Repository navigation
fix(mcp): await async resource and tool handlers - #311
Merged
Merged
Conversation
resources/read and tools/call called the registered handler and serialised its return value without awaiting it, so an `async def` resource or tool answered with "<coroutine object ... at 0x...>" and never ran. The method handlers now hand back a deferred result when the user handler returns an awaitable. handle_message_async() and the new dispatch_http_async() / dispatch_sse_message_async() await it; the async routes from register_routes() and the dev-admin /__dev/mcp endpoints use them. A raising async handler becomes JSON-RPC -32603 with its message. The synchronous handle_message() keeps its str return type: with no running loop it awaits the handler on a private event loop; inside a running loop it closes the coroutine and returns -32603 naming handle_message_async(). Sync handlers produce byte-identical replies. Python sibling of tina4-nodejs#193. Signed-off-by: Andre van Zuydam <andrevanzuydam@gmail.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-Authored-By: Tina4 <82961293+tina4stack@users.noreply.github.com>
Merged
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
What was wrong
McpServer._handle_resources_readand_handle_tools_callcalled the registered handler and serialised whatever came back, without awaiting it. Anasync defresource or tool returned a coroutine that never ran, and that coroutine was sent back as text. Probe onorigin/v3with a realMcpServerand real JSON-RPC messages (async def rows(): return {"rows": [1,2,3]},async def add(a: int, b: int): return a + b):The fix
The dispatch chain is synchronous (
handle_message←dispatch_http/dispatch_sse_message), but it is called fromasync defroutes. An event loop is already running there, so the sync path cannot simplyasyncio.run()the coroutine.handle_messageis public API, so its return type staysstr._handle_tools_calland_handle_resources_readnow return a private_Deferredinstead of formatting the result straight away. Formatting moved into_tool_content/_resource_contents, unchanged, and runs after the await.handle_message_async,dispatch_http_asyncanddispatch_sse_message_asyncawait the deferred result. A raising async handler becomes JSON-RPC -32603 (INTERNAL_ERROR) with the exception message, the same mapping a raising sync handler already gets.register_routes()and the dev-admin/__dev/mcpand/__dev/mcp/messageendpoints now use the async variants.handle_messagewith an async handler:new_event_looprather thanasyncio.run, so the thread's current-loop setting is left as the caller had it.handle_message_async(). It no longer returns a coroutine string.handle_messageoutput for 16 message shapes (str/dict/list/int results, raising handlers, unknown tool/resource, bad arguments, notification, parse error, ping, tools/list,dispatch_http) onorigin/v3and on this branch: the hashes match.Limits
handle_message()(sync) called from inside a running event loop still cannot run an async handler. It now returns a clear -32603 error instead of a coroutine string. Async callers should usehandle_message_async().dev_admin._api_mcp_call(the REST shim) is unchanged. It already awaitedasync deftools viainspect.iscoroutinefunction.Tests
New
tests/test_mcp_async_handlers.py(17 tests). No mocks: it uses a realMcpServerand real JSON-RPC messages, and drives the real ASGI front controller throughTestClient, both for the routesregister_routes()mounts (POST {path}and{path}/message) and for the dev-admin/__dev/mcpendpoints. Covered:RuntimeWarninghandle_messagewith an async handler and no running loop works, and leaves the thread's event loop alonehandle_messageinside a running loop returns the clear -32603 errorMutation check (source reverted to
origin/v3, tests kept): 16 failed, 1 passed. The one that passes is the sync-handler-over-HTTP control. With the fix: 17 passed. Onorigin/v3, the 6TestHandleMessageAsyncfailures are only becausehandle_message_asyncdoes not exist yet. The other 10 (synchandle_message, theregister_routesHTTP routes, dev-admin) fail on behaviour: the reply is a coroutine string.Existing MCP-related tests (
git grep -l -i mcp tests/): the same result onorigin/v3and on this branch (375 passed, 10 failed, 11 skipped, 2 errors), with identical failing test ids. Those failures are Windows-environment issues already present onv3(preexec_fnnot supported, backslash migration paths, symlinks, port binding).ruff checkon the new test file is clean. The changed source files show the same 14 pre-existing findings as onv3, none on changed lines.Python sibling of tina4-nodejs#193.
🤖 Generated with Claude Code