jsonrpc_dispatcher
JSON-RPC Dispatcher over the SessionMessage stream contract all transports speak.
Owns the receive loop and per-request task isolation over a duplex stream
pair; request-id correlation, cancellation/progress wiring, and the single
exception-to-wire boundary live in the shared RequestCorrelator so the
streamable-HTTP transport (which has no stream pair) applies the same
semantics. Methods and params are otherwise opaque strings and dicts.
cancelled_request_id_from_params
Read params.requestId from a notifications/cancelled (as_request_id shape rules).
Source code in src/mcp/shared/jsonrpc_dispatcher.py
92 93 94 | |
handler_exception_to_error_data
handler_exception_to_error_data(
exc: BaseException,
) -> ErrorData | None
Map a handler-raised exception to its wire ErrorData.
The two rungs every peer shares: an MCPError carries its own
ErrorData; a pydantic ValidationError is the spec's INVALID_PARAMS
with empty data (no pydantic text on the wire). Returns None for
any other exception so each caller applies its own catch-all -
serve_inbound currently pins code=0 for v1 compat,
the modern HTTP entry uses INTERNAL_ERROR.
Source code in src/mcp/shared/_correlation.py
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | |
JSONRPCDispatcher
Bases: Dispatcher[TransportT]
Dispatcher over the SessionMessage stream contract.
Explicit Protocol base so pyright checks conformance at the class definition.
Source code in src/mcp/shared/jsonrpc_dispatcher.py
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 | |
__init__
__init__(
read_stream: ReadStream[SessionMessage | Exception],
write_stream: WriteStream[SessionMessage],
*,
transport_builder: (
Callable[[MessageMetadata], TransportT] | None
) = None,
peer_cancel_mode: PeerCancelMode = "interrupt",
raise_handler_exceptions: bool = False,
inline_methods: frozenset[str] = frozenset(),
on_stream_exception: (
Callable[[Exception], Awaitable[None]] | None
) = None
) -> None
Wire a dispatcher over a transport's SessionMessage stream pair.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transport_builder
|
Callable[[MessageMetadata], TransportT] | None
|
Builds each message's |
None
|
raise_handler_exceptions
|
bool
|
Re-raise handler exceptions out of
|
False
|
inline_methods
|
frozenset[str]
|
Methods awaited in the read loop before the next
message is dequeued (e.g. |
frozenset()
|
on_stream_exception
|
Callable[[Exception], Awaitable[None]] | None
|
Observer for |
None
|
Source code in src/mcp/shared/jsonrpc_dispatcher.py
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | |
on_stream_exception
instance-attribute
on_stream_exception = on_stream_exception
Observer for Exception items on the read stream. Mutable so a session can
bind it after the dispatcher is built (e.g. ClientSession routing into
message_handler); only consulted inside run() so pre-enter assignment is safe.
send_raw_request
async
send_raw_request(
method: str,
params: Mapping[str, Any] | None,
opts: CallOptions | None = None,
*,
_related_request_id: RequestId | None = None
) -> dict[str, Any]
Send a JSON-RPC request and await its response.
_related_request_id is set only by _JSONRPCDispatchContext so that
mid-handler requests route onto the inbound request's SSE stream.
Raises:
| Type | Description |
|---|---|
MCPError
|
Peer error response; |
RuntimeError
|
Called before |
Source code in src/mcp/shared/jsonrpc_dispatcher.py
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 | |
notify
async
notify(
method: str,
params: Mapping[str, Any] | None,
opts: CallOptions | None = None,
*,
_related_request_id: RequestId | None = None
) -> None
Send a fire-and-forget notification.
Fire-and-forget all the way: a post-close send or a write onto a
torn-down transport drops the notification with a debug log instead
of raising (same policy as the response writes and ctx.notify).
Source code in src/mcp/shared/jsonrpc_dispatcher.py
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | |
run
async
run(
on_request: OnRequest,
on_notify: OnNotify,
on_notify_intercept: OnNotifyIntercept | None = None,
*,
task_status: TaskStatus[None] = TASK_STATUS_IGNORED
) -> None
Drive the receive loop until the read stream closes.
task_status.started() fires once send_raw_request is usable.
Single-shot: once the loop ends the dispatcher stays closed and cannot be restarted.
Source code in src/mcp/shared/jsonrpc_dispatcher.py
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 | |
PeerCancelMode
module-attribute
PeerCancelMode = Literal['interrupt', 'signal']
How notifications/cancelled is applied: "interrupt" (default) cancels
the handler's scope; "signal" only sets ctx.cancel_requested and lets the
handler run to completion. Either way the cancelled request is never
answered - the handler's eventual result or error is dropped, not written.
progress_token_from_params
progress_token_from_params(
params: Mapping[str, Any] | None,
) -> ProgressToken | None
Read params._meta.progressToken; reject bool (bool subclasses int, so True would alias 1).
Source code in src/mcp/shared/jsonrpc_dispatcher.py
83 84 85 86 87 88 89 | |
Classes
JSONRPCDispatcher—Dispatcherover theSessionMessagestream contract.
Functions
cancelled_request_id_from_params— Readparams.requestIdfrom anotifications/cancelled(as_request_idshape rules).handler_exception_to_error_data— Map a handler-raised exception to its wireErrorData.progress_token_from_params— Readparams._meta.progressToken; reject bool (bool subclasses int, so True would alias 1).
Attributes
PeerCancelMode— Hownotifications/cancelledis applied:"interrupt"(default) cancels the handler's scope;"signal"only setsctx.cancel_requestedand lets the handler run to completion. Either way the cancelled request is never answered - the handler's eventual result or error is dropped, not written.