Skip to content

Commit 029680c

Browse files
committed
client(streamable_http): raise JSON-RPC error on unexpected content-type so ClientSession receives McpError; keep fallback exception if no request id; add request id plumbing
1 parent ca34666 commit 029680c

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

src/mcp/client/streamable_http.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -288,9 +288,11 @@ async def _handle_post_request(self, ctx: RequestContext) -> None:
288288
elif content_type.startswith(SSE):
289289
await self._handle_sse_response(response, ctx, is_initialization)
290290
else:
291+
# Propagate an error bound to the originating request id so callers get McpError
291292
await self._handle_unexpected_content_type(
292293
content_type,
293294
ctx.read_stream_writer,
295+
message.root.id,
294296
)
295297

296298
async def _handle_json_response(
@@ -343,11 +345,22 @@ async def _handle_unexpected_content_type(
343345
self,
344346
content_type: str,
345347
read_stream_writer: StreamWriter,
348+
request_id: RequestId | None,
346349
) -> None:
347350
"""Handle unexpected content type in response."""
348351
error_msg = f"Unexpected content type: {content_type}"
349352
logger.error(error_msg)
350-
await read_stream_writer.send(ValueError(error_msg))
353+
if request_id is not None:
354+
jsonrpc_error = JSONRPCError(
355+
jsonrpc="2.0",
356+
id=request_id,
357+
error=ErrorData(code=32600, message=error_msg),
358+
)
359+
session_message = SessionMessage(JSONRPCMessage(jsonrpc_error))
360+
await read_stream_writer.send(session_message)
361+
else:
362+
# Fallback: send as exception if we somehow lack a request id
363+
await read_stream_writer.send(ValueError(error_msg))
351364

352365
async def _send_session_terminated_error(
353366
self,

0 commit comments

Comments
 (0)