-
Notifications
You must be signed in to change notification settings - Fork 2.3k
SDK Parity: Avoid Parsing Server Response for non-JsonRPCMessage Requests #1290
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
Open
justin-yi-wang
wants to merge
11
commits into
modelcontextprotocol:main
Choose a base branch
from
justin-yi-wang:no-responses-for-notifs
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+163
−11
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
3a98694
parity with ts sdk
justin-yi-wang e6cdb23
test
justin-yi-wang 1f5e0f3
fixup test
justin-yi-wang 1d8464a
ruff
justin-yi-wang 34c782d
ruff ruff
justin-yi-wang 8fc8d3f
cleanup comment
justin-yi-wang 9f6f0b1
pyright
justin-yi-wang b51026c
comment abt notifications
justin-yi-wang 4048bfc
comment for test
justin-yi-wang c6c2cc5
address comments
justin-yi-wang 954db09
ruff
justin-yi-wang 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 hidden or 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 hidden or 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,150 @@ | ||
""" | ||
Tests for StreamableHTTP client transport with non-SDK servers. | ||
|
||
These tests verify client behavior when interacting with servers | ||
that don't follow SDK conventions. | ||
""" | ||
|
||
import json | ||
import multiprocessing | ||
import socket | ||
import time | ||
from collections.abc import Generator | ||
|
||
import pytest | ||
import uvicorn | ||
from starlette.applications import Starlette | ||
from starlette.requests import Request | ||
from starlette.responses import JSONResponse, Response | ||
from starlette.routing import Route | ||
|
||
from mcp import ClientSession, types | ||
from mcp.client.streamable_http import streamablehttp_client | ||
from mcp.shared.session import RequestResponder | ||
from mcp.types import ClientNotification, RootsListChangedNotification | ||
|
||
|
||
def create_non_sdk_server_app() -> Starlette: | ||
"""Create a minimal server that doesn't follow SDK conventions.""" | ||
|
||
async def handle_mcp_request(request: Request) -> Response: | ||
"""Handle MCP requests with non-standard responses.""" | ||
try: | ||
body = await request.body() | ||
data = json.loads(body) | ||
|
||
# Handle initialize request normally | ||
if data.get("method") == "initialize": | ||
response_data = { | ||
"jsonrpc": "2.0", | ||
"id": data["id"], | ||
"result": { | ||
"serverInfo": {"name": "test-non-sdk-server", "version": "1.0.0"}, | ||
"protocolVersion": "2024-11-05", | ||
"capabilities": {}, | ||
}, | ||
} | ||
return JSONResponse(response_data) | ||
|
||
# For notifications, return 204 No Content (non-SDK behavior) | ||
if "id" not in data: | ||
return Response(status_code=204, headers={"Content-Type": "application/json"}) | ||
|
||
# Default response for other requests | ||
return JSONResponse( | ||
{"jsonrpc": "2.0", "id": data.get("id"), "error": {"code": -32601, "message": "Method not found"}} | ||
) | ||
|
||
except Exception as e: | ||
return JSONResponse({"error": f"Server error: {str(e)}"}, status_code=500) | ||
|
||
app = Starlette( | ||
debug=True, | ||
routes=[ | ||
Route("/mcp", handle_mcp_request, methods=["POST"]), | ||
], | ||
) | ||
return app | ||
|
||
|
||
def run_non_sdk_server(port: int) -> None: | ||
"""Run the non-SDK server in a separate process.""" | ||
app = create_non_sdk_server_app() | ||
config = uvicorn.Config( | ||
app=app, | ||
host="127.0.0.1", | ||
port=port, | ||
log_level="error", # Reduce noise in tests | ||
) | ||
server = uvicorn.Server(config=config) | ||
server.run() | ||
|
||
|
||
@pytest.fixture | ||
def non_sdk_server_port() -> int: | ||
"""Get an available port for the test server.""" | ||
with socket.socket() as s: | ||
s.bind(("127.0.0.1", 0)) | ||
return s.getsockname()[1] | ||
|
||
|
||
@pytest.fixture | ||
def non_sdk_server(non_sdk_server_port: int) -> Generator[None, None, None]: | ||
"""Start a non-SDK server for testing.""" | ||
proc = multiprocessing.Process(target=run_non_sdk_server, kwargs={"port": non_sdk_server_port}, daemon=True) | ||
proc.start() | ||
|
||
# Wait for server to be ready | ||
start_time = time.time() | ||
while time.time() - start_time < 10: | ||
try: | ||
with socket.create_connection(("127.0.0.1", non_sdk_server_port), timeout=0.1): | ||
break | ||
except (TimeoutError, ConnectionRefusedError): | ||
time.sleep(0.1) | ||
else: | ||
proc.kill() | ||
proc.join(timeout=2) | ||
pytest.fail("Server failed to start within 10 seconds") | ||
|
||
yield | ||
|
||
proc.kill() | ||
proc.join(timeout=2) | ||
|
||
|
||
@pytest.mark.anyio | ||
async def test_non_compliant_notification_response(non_sdk_server: None, non_sdk_server_port: int) -> None: | ||
""" | ||
This test verifies that the client ignores unexpected responses to notifications: the spec states they should | ||
either be 202 + no response body, or 4xx + optional error body | ||
(https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#sending-messages-to-the-server), | ||
but some servers wrongly return other 2xx codes (e.g. 204). For now we simply ignore unexpected responses | ||
(aligning behaviour w/ the TS SDK). | ||
""" | ||
server_url = f"http://127.0.0.1:{non_sdk_server_port}/mcp" | ||
returned_exception = None | ||
|
||
async def message_handler( | ||
message: RequestResponder[types.ServerRequest, types.ClientResult] | types.ServerNotification | Exception, | ||
): | ||
nonlocal returned_exception | ||
if isinstance(message, Exception): | ||
returned_exception = message | ||
|
||
async with streamablehttp_client(server_url) as (read_stream, write_stream, _): | ||
async with ClientSession( | ||
read_stream, | ||
write_stream, | ||
message_handler=message_handler, | ||
) as session: | ||
# Initialize should work normally | ||
await session.initialize() | ||
|
||
# The test server returns a 204 instead of the expected 202 | ||
await session.send_notification( | ||
ClientNotification(RootsListChangedNotification(method="notifications/roots/list_changed")) | ||
) | ||
|
||
if returned_exception: | ||
pytest.fail(f"Server encountered an exception: {returned_exception}") |
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.
Uh oh!
There was an error while loading. Please reload this page.