-
Notifications
You must be signed in to change notification settings - Fork 173
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: add request cancellation and cleanup #167
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
888bdd3
tests for issue 88
dsp-ant 827e494
feat: add request cancellation and in-flight request tracking
dsp-ant 08cfbe5
fix: improve error handling and request cancellation for issue #88
dsp-ant 733db0c
fix: enforce context manager usage for RequestResponder
dsp-ant File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
"""Test to reproduce issue #88: Random error thrown on response.""" | ||
|
||
from datetime import timedelta | ||
from pathlib import Path | ||
from typing import Sequence | ||
|
||
import anyio | ||
import pytest | ||
|
||
from mcp.client.session import ClientSession | ||
from mcp.server.lowlevel import Server | ||
from mcp.shared.exceptions import McpError | ||
from mcp.types import ( | ||
EmbeddedResource, | ||
ImageContent, | ||
TextContent, | ||
) | ||
|
||
|
||
@pytest.mark.anyio | ||
async def test_notification_validation_error(tmp_path: Path): | ||
"""Test that timeouts are handled gracefully and don't break the server. | ||
|
||
This test verifies that when a client request times out: | ||
1. The server task stays alive | ||
2. The server can still handle new requests | ||
3. The client can make new requests | ||
4. No resources are leaked | ||
""" | ||
|
||
server = Server(name="test") | ||
request_count = 0 | ||
slow_request_started = anyio.Event() | ||
slow_request_complete = anyio.Event() | ||
|
||
@server.call_tool() | ||
async def slow_tool( | ||
name: str, arg | ||
) -> Sequence[TextContent | ImageContent | EmbeddedResource]: | ||
nonlocal request_count | ||
request_count += 1 | ||
|
||
if name == "slow": | ||
# Signal that slow request has started | ||
slow_request_started.set() | ||
# Long enough to ensure timeout | ||
await anyio.sleep(0.2) | ||
# Signal completion | ||
slow_request_complete.set() | ||
return [TextContent(type="text", text=f"slow {request_count}")] | ||
elif name == "fast": | ||
# Fast enough to complete before timeout | ||
await anyio.sleep(0.01) | ||
return [TextContent(type="text", text=f"fast {request_count}")] | ||
return [TextContent(type="text", text=f"unknown {request_count}")] | ||
|
||
async def server_handler(read_stream, write_stream): | ||
await server.run( | ||
read_stream, | ||
write_stream, | ||
server.create_initialization_options(), | ||
raise_exceptions=True, | ||
) | ||
|
||
async def client(read_stream, write_stream): | ||
# Use a timeout that's: | ||
# - Long enough for fast operations (>10ms) | ||
# - Short enough for slow operations (<200ms) | ||
# - Not too short to avoid flakiness | ||
async with ClientSession( | ||
read_stream, write_stream, read_timeout_seconds=timedelta(milliseconds=50) | ||
) as session: | ||
await session.initialize() | ||
|
||
# First call should work (fast operation) | ||
result = await session.call_tool("fast") | ||
assert result.content == [TextContent(type="text", text="fast 1")] | ||
assert not slow_request_complete.is_set() | ||
|
||
# Second call should timeout (slow operation) | ||
with pytest.raises(McpError) as exc_info: | ||
await session.call_tool("slow") | ||
assert "Timed out while waiting" in str(exc_info.value) | ||
|
||
# Wait for slow request to complete in the background | ||
with anyio.fail_after(1): # Timeout after 1 second | ||
await slow_request_complete.wait() | ||
|
||
# Third call should work (fast operation), | ||
# proving server is still responsive | ||
result = await session.call_tool("fast") | ||
assert result.content == [TextContent(type="text", text="fast 3")] | ||
|
||
# Run server and client in separate task groups to avoid cancellation | ||
server_writer, server_reader = anyio.create_memory_object_stream(1) | ||
client_writer, client_reader = anyio.create_memory_object_stream(1) | ||
|
||
server_ready = anyio.Event() | ||
|
||
async def wrapped_server_handler(read_stream, write_stream): | ||
server_ready.set() | ||
await server_handler(read_stream, write_stream) | ||
|
||
async with anyio.create_task_group() as tg: | ||
tg.start_soon(wrapped_server_handler, server_reader, client_writer) | ||
# Wait for server to start and initialize | ||
with anyio.fail_after(1): # Timeout after 1 second | ||
await server_ready.wait() | ||
# Run client in a separate task to avoid cancellation | ||
async with anyio.create_task_group() as client_tg: | ||
client_tg.start_soon(client, client_reader, server_writer) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm quite allergic to actually sleeping in tests, due to the flakiness and slowness. Is there any other way we can exercise these? Would a timeout of 0 work? Or a timeout in the past vs. a timeout in the far future?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let me fix this. This was Claude written. After a lot of back and forth, the right way is to use events and wait for them to trigger.