Skip to content

fix(mcp): await async resource and tool handlers - #311

Merged
andrevanzuydam merged 1 commit into
v3from
fix/mcp-await-async-handlers
Nov 13, 2026
Merged

andrevanzuydam merged 1 commit into
v3from
fix/mcp-await-async-handlers

Conversation

@andrevanzuydam

@andrevanzuydam andrevanzuydam commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

What was wrong

McpServer._handle_resources_read and _handle_tools_call called the registered handler and serialised whatever came back, without awaiting it. An async def resource or tool returned a coroutine that never ran, and that coroutine was sent back as text. Probe on origin/v3 with a real McpServer and real JSON-RPC messages (async def rows(): return {"rows": [1,2,3]}, async def add(a: int, b: int): return a + b):

resources/read -> <coroutine object rows at 0x...>
tools/call     -> <coroutine object add at 0x...>

The fix

The dispatch chain is synchronous (handle_message ← dispatch_http / dispatch_sse_message), but it is called from async def routes. An event loop is already running there, so the sync path cannot simply asyncio.run() the coroutine. handle_message is public API, so its return type stays str.

  • When the user handler returns an awaitable, _handle_tools_call and _handle_resources_read now return a private _Deferred instead of formatting the result straight away. Formatting moved into _tool_content / _resource_contents, unchanged, and runs after the await.
  • New handle_message_async, dispatch_http_async and dispatch_sse_message_async await 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.
  • The async routes from register_routes() and the dev-admin /__dev/mcp and /__dev/mcp/message endpoints now use the async variants.
  • Sync handle_message with an async handler:
    • No running loop (scripts, CLI, sync tests): the handler runs to completion on a private loop. It uses new_event_loop rather than asyncio.run, so the thread's current-loop setting is left as the caller had it.
    • Inside a running loop: the coroutine is closed (so no "never awaited" warning) and the reply is a -32603 error that names handle_message_async(). It no longer returns a coroutine string.
  • Sync handlers return byte-identical replies. Checked by hashing handle_message output for 16 message shapes (str/dict/list/int results, raising handlers, unknown tool/resource, bad arguments, notification, parse error, ping, tools/list, dispatch_http) on origin/v3 and 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 use handle_message_async().
  • dev_admin._api_mcp_call (the REST shim) is unchanged. It already awaited async def tools via inspect.iscoroutinefunction.

Tests

New tests/test_mcp_async_handlers.py (17 tests). No mocks: it uses a real McpServer and real JSON-RPC messages, and drives the real ASGI front controller through TestClient, both for the routes register_routes() mounts (POST {path} and {path}/message) and for the dev-admin /__dev/mcp endpoints. Covered:

  • async resource and async tool return their real values (async path, sync path with no loop, HTTP routes, dev-admin)
  • rejecting async resource and tool give -32603 with the handler's message, with no unawaited-coroutine RuntimeWarning
  • sync resource and tool output unchanged, on both entry points and over HTTP
  • sync handle_message with an async handler and no running loop works, and leaves the thread's event loop alone
  • sync handle_message inside a running loop returns the clear -32603 error
  • an async notification gets no reply

Mutation 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. On origin/v3, the 6 TestHandleMessageAsync failures are only because handle_message_async does not exist yet. The other 10 (sync handle_message, the register_routes HTTP 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 on origin/v3 and on this branch (375 passed, 10 failed, 11 skipped, 2 errors), with identical failing test ids. Those failures are Windows-environment issues already present on v3 (preexec_fn not supported, backslash migration paths, symlinks, port binding). ruff check on the new test file is clean. The changed source files show the same 14 pre-existing findings as on v3, none on changed lines.

Python sibling of tina4-nodejs#193.

🤖 Generated with Claude Code

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>
@andrevanzuydam
andrevanzuydam merged commit 8b1bf1b into v3 Nov 13, 2026
15 of 16 checks passed
@andrevanzuydam
andrevanzuydam deleted the fix/mcp-await-async-handlers branch November 13, 2026 11:24
@andrevanzuydam andrevanzuydam mentioned this pull request Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant