Skip to content

feat: JSONRPCDispatcher#2458

Draft
maxisbey wants to merge 7 commits intomaxisbey/v2-dispatcher-protocolfrom
maxisbey/v2-jsonrpc-dispatcher
Draft

feat: JSONRPCDispatcher#2458
maxisbey wants to merge 7 commits intomaxisbey/v2-dispatcher-protocolfrom
maxisbey/v2-jsonrpc-dispatcher

Conversation

@maxisbey
Copy link
Copy Markdown
Contributor

Stacked on #2452. The production Dispatcher implementation over the existing SessionMessage stream contract.

Motivation and Context

JSONRPCDispatcher is the JSON-RPC implementation of the Dispatcher Protocol from #2452. It owns request-id correlation, the receive loop, per-request task isolation, cancellation/progress wiring, and the single exception-to-wire boundary. The MCP type layer (ServerRunner, Context, Client — later PRs) sits above it and sees only (ctx, method, params) -> dict; transports sit below and see only SessionMessage reads/writes.

The dispatcher is mostly MCP-agnostic — methods/params are opaque — but it intercepts notifications/cancelled (must, since it owns the handler task scopes) and notifications/progress (chosen, to avoid duplicating the correlation table in every run() caller). Those wire shapes are extracted with structural match patterns; a malformed payload simply fails to match and the correlation is skipped.

How Has This Been Tested?

The 9 contract tests from #2452 are now parametrized over both DirectDispatcher and JSONRPCDispatcher (via crossed in-memory streams) — same behavioral assertions, two implementations. tests/shared/test_jsonrpc_dispatcher.py adds 21 JSON-RPC-specific tests for correlation, the exception boundary, peer-cancel in both modes, CONNECTION_CLOSED fan-out, late-response handling, raise_handler_exceptions, contextvar propagation via _spawn, and the metadata routing. 43 tests total, 100% coverage on the new module, 0.15s wall-clock.

Breaking Changes

None. New code only; nothing existing is wired in yet. Dispatcher.run() gained a task_status kwarg (Protocol-level guarantee that send_request is usable once run() has started); DirectDispatcher updated to match.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

Additional context

Stack:

  1. feat: add Dispatcher Protocol and DirectDispatcher #2452 — Dispatcher Protocol + DirectDispatcher
  2. (this PR) JSONRPCDispatcher
  3. BaseContext / Context / Peer / Connection
  4. ServerRunner

Notable design points (see commit messages for detail): _Pending buffer is 1 not unbounded (a WouldBlock means the waiter already has an outcome and dropping is correct); _dispatch is fully synchronous (no awaits — send_nowait/_spawn only) to avoid head-of-line blocking; _spawn propagates the sender's contextvars via Context.run(tg.start_soon, ...) so auth/OTel set by ASGI middleware reach handler tasks.

AI Disclaimer

Chunk (a) of JSONRPCDispatcher: constructor, _Pending/_InFlight/_JSONRPCDispatchContext,
send_request/notify and helpers. run() is stubbed.

The Dispatcher contract tests are now parametrized over a pair_factory fixture
(direct + jsonrpc). The 9 jsonrpc cases are strict-xfail until run()/
_handle_request land in the next commits; once those pass, strict xfail flips
to XPASS and forces removal of the marker.

Factories return (client, server, close) so running_pair can shut down any
implementation uniformly.
run() drives the receive loop in a per-request task group;
task_status.started() fires once send_request is usable. _dispatch routes each
inbound message synchronously (no awaits — send_nowait/_spawn only) to avoid
head-of-line blocking. _spawn propagates the sender's contextvars via
Context.run(tg.start_soon, ...) so auth/OTel set by ASGI middleware survive.
_fan_out_closed wakes pending send_request waiters with CONNECTION_CLOSED on
shutdown (called both post-EOF and in finally; idempotent).

Wire-param extraction (progressToken, cancelled.requestId, progress fields)
uses structural match patterns — runtime narrowing, no casts, no mcp.types
model coupling; malformed input fails to match and the correlation is skipped.

_handle_request is happy-path only here (run on_request, write response); the
exception-to-wire boundary lands in the next commit.

Dispatcher.run() Protocol gained a task_status kwarg (it's a contract-level
guarantee). DirectDispatcher.run() updated to match. running_pair now uses
tg.start so the test body runs only once the dispatcher is ready.

20 contract tests pass; the 2 needing the exception boundary are strict-xfail.
_handle_request is now the single exception-to-wire boundary:
- MCPError -> JSONRPCError(e.error)
- pydantic ValidationError -> INVALID_PARAMS
- Exception -> INTERNAL_ERROR(str(e)), logged, optionally re-raised
- outer-cancel (run() TG shutdown) -> shielded REQUEST_CANCELLED write, re-raise
- peer-cancel (notifications/cancelled) -> scope swallows, no response written

dctx.close() runs in an inner finally so the back-channel shuts the moment the
handler exits. _write_result/_write_error swallow Broken/ClosedResourceError so
a dropped connection during the response write doesn't crash the dispatcher.

All 22 contract tests now pass against both DirectDispatcher and
JSONRPCDispatcher; chunk-c xfail markers removed.
Covers behaviors with no DirectDispatcher analog: out-of-order response
correlation, INTERNAL_ERROR over the wire, peer-cancel in interrupt and signal
modes, CONNECTION_CLOSED on stream EOF mid-await, late-response drop,
raise_handler_exceptions propagation, ServerMessageMetadata tagging on
ctx.send_request, null-id JSONRPCError drop, ValidationError->INVALID_PARAMS,
contextvar propagation via _spawn, and the defensive Broken/Closed/WouldBlock
catches.

Two small src tweaks for coverage:
- _cancel_outbound: combine the two except arms into one tuple
- _dispatch: pragma no-branch on the final case (match is exhaustive over
  JSONRPCMessage; the no-match arc is unreachable)

43 tests, 100% coverage on all PR2 modules, 0.15s wall-clock.
The pull_request branch filter meant the test/lint/coverage matrix only ran
on PRs targeting main or v1.x. Stacked PRs (targeting feature branches) only
got the conformance checks, which are continue-on-error and don't exercise
unit tests. Removing the filter so the full matrix runs on every PR.
3.14: nested async-with arc misreporting on three create_task_group lines
(the documented AGENTS.md case) — pragma: no branch.

3.11: lines after async-CM exit with pytest.raises mis-traced in one test —
moved the asserts inside the context manager.
Follows the Outbound Protocol rename in the previous commit. Mechanical rename
across JSONRPCDispatcher, _JSONRPCDispatchContext, and tests.
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