Skip to content

Commit 7570ba3

Browse files
authored
Make sure RequestId is not coerced as int (#1178)
1 parent 0b1b52b commit 7570ba3

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

src/mcp/types.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
ProgressToken = str | int
3737
Cursor = str
3838
Role = Literal["user", "assistant"]
39-
RequestId = Annotated[int | str, Field(union_mode="left_to_right")]
39+
RequestId = Annotated[int, Field(strict=True)] | str
4040
AnyFunction: TypeAlias = Callable[..., Any]
4141

4242

@@ -849,7 +849,7 @@ class Tool(BaseMetadata):
849849
"""A JSON Schema object defining the expected parameters for the tool."""
850850
outputSchema: dict[str, Any] | None = None
851851
"""
852-
An optional JSON Schema object defining the structure of the tool's output
852+
An optional JSON Schema object defining the structure of the tool's output
853853
returned in the structuredContent field of a CallToolResult.
854854
"""
855855
annotations: ToolAnnotations | None = None

tests/shared/test_sse.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -466,12 +466,21 @@ async def test_request_context_isolation(context_server: None, server_url: str)
466466

467467

468468
def test_sse_message_id_coercion():
469-
"""Test that string message IDs that look like integers are parsed as integers.
469+
"""Previously, the `RequestId` would coerce a string that looked like an integer into an integer.
470470
471471
See <https://github.com/modelcontextprotocol/python-sdk/pull/851> for more details.
472+
473+
As per the JSON-RPC 2.0 specification, the id in the response object needs to be the same type as the id in the
474+
request object. In other words, we can't perform the coercion.
475+
476+
See <https://www.jsonrpc.org/specification#response_object> for more details.
472477
"""
473478
json_message = '{"jsonrpc": "2.0", "id": "123", "method": "ping", "params": null}'
474479
msg = types.JSONRPCMessage.model_validate_json(json_message)
480+
assert msg == snapshot(types.JSONRPCMessage(root=types.JSONRPCRequest(method="ping", jsonrpc="2.0", id="123")))
481+
482+
json_message = '{"jsonrpc": "2.0", "id": 123, "method": "ping", "params": null}'
483+
msg = types.JSONRPCMessage.model_validate_json(json_message)
475484
assert msg == snapshot(types.JSONRPCMessage(root=types.JSONRPCRequest(method="ping", jsonrpc="2.0", id=123)))
476485

477486

0 commit comments

Comments
 (0)