runner
ServerRunner - the per-connection handler kernel.
ServerRunner bridges the dispatch layer (on_request / on_notify, untyped
dicts) and the user's handler layer (typed Context, typed params). It is a
pure kernel: it holds a pre-populated Connection and reads
connection.protocol_version / connection.outbound as facts. Driving a
dispatcher loop and tearing down the connection live in the free-function
drivers (serve_connection, serve_loop, serve_one); the entry constructs
the Connection, the driver tears it down.
ServerRunner holds a Server directly - Server is the registry.
CallNext
module-attribute
CallNext = Callable[
["ServerRequestContext[Any, Any]"],
Awaitable[HandlerResult],
]
Invokes the rest of the chain. Pass the ctx through; rewrite method or
params with dataclasses.replace(ctx, ...) to alter what the handler sees.
ServerMiddleware
Bases: Protocol[_MwLifespanT]
Context-tier middleware: (ctx, call_next) -> result.
Runs at the top of ServerRunner._on_request / _on_notify after ctx
is built but before any validation, lookup, or handshake. Wraps every
inbound request and notification: initialize, the pre-init gate,
METHOD_NOT_FOUND, params validation, the handler call, and
notifications/initialized all run inside call_next(ctx).
notifications/cancelled is observed too; the dispatcher applies the
cancellation itself, then forwards the notification. A request-side
failure reaches the middleware as a raised MCPError (or
ValidationError for malformed params) so observation/logging middleware
can record it. Listed outermost-first on Server.middleware.
The method and the raw inbound params are ctx.method and ctx.params (no
model validation has happened yet). To rewrite either before the handler
runs, pass an adjusted context: await call_next(replace(ctx, params=...)).
ctx.request_id is None distinguishes a notification from a request. For
notifications call_next(ctx) returns None (a dropped or unhandled
notification also returns None) and the middleware's own return value is
discarded.
Warning
initialize is handled inline - the dispatcher does not read
further inbound messages until the middleware chain returns. Awaiting a
server-to-client request (ctx.session.send_request, send_ping, ...)
while handling initialize therefore deadlocks the connection: the
response can never be dequeued. Send-and-forget notifications are safe.
initialize is observed but not rewritable: the post-chain handshake
commit reads the wire params, so to veto the handshake raise before
call_next().
Server[L].middleware holds ServerMiddleware[L], so an app-specific
middleware sees ctx.lifespan_context: L. While the context is the
mutable ServerRequestContext dataclass it is invariant in L, so a
reusable middleware should be typed ServerMiddleware[Any] to register on
any Server[L].
Source code in src/mcp/server/context.py
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 | |
otel_middleware
Dispatch-tier middleware that wraps each request in an OpenTelemetry span.
Mirrors the span shape of the existing Server._handle_request: span name
"MCP handle <method> [<target>]", mcp.method.name attribute, W3C
trace context extracted from params._meta (SEP-414), and an ERROR
status if the handler raises.
Source code in src/mcp/server/runner.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | |
aclose_shielded
async
aclose_shielded(connection: Connection) -> None
Unwind connection.exit_stack under a shielded, bounded scope.
Called from a driver's finally: the shield lets per-connection cleanup
callbacks run even when the driver itself is being cancelled, the
_EXIT_STACK_CLOSE_TIMEOUT bound stops a hung callback wedging shutdown,
and a raising callback is logged-and-swallowed so it never masks the
driver's own exception.
Source code in src/mcp/server/runner.py
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | |
to_jsonrpc_response
async
to_jsonrpc_response(
request_id: RequestId, coro: Awaitable[dict[str, Any]]
) -> JSONRPCResponse | JSONRPCError
Await coro and wrap its outcome as the JSON-RPC reply for request_id.
The exception-to-wire boundary for the request-per-call drivers
(serve_one, the modern HTTP entry). MCPError and ValidationError
map via the shared handler_exception_to_error_data ladder; any other
exception is logged and surfaced as INTERNAL_ERROR so handler internals
never reach the wire.
Source code in src/mcp/server/runner.py
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | |
ServerRunner
dataclass
Bases: Generic[LifespanT]
Per-connection handler kernel. One instance per client connection.
Source code in src/mcp/server/runner.py
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 | |
init_options
class-attribute
instance-attribute
init_options: InitializationOptions | None = None
InitializeResult payload. Defaults to server.create_initialization_options().
on_request
cached
property
on_request: OnRequest
_on_request wrapped in dispatch_middleware, outermost-first.
Dispatch-tier middleware sees raw (dctx, method, params) -> dict and
wraps everything - initialize, METHOD_NOT_FOUND, validation failures
included.
serve_connection
async
serve_connection(
server: Server[LifespanT],
dispatcher: Dispatcher[Any],
*,
connection: Connection,
lifespan_state: LifespanT,
init_options: InitializationOptions | None = None,
task_status: TaskStatus[None] = TASK_STATUS_IGNORED
) -> None
Drive dispatcher until the underlying channel closes.
The loop-mode driver: builds the kernel, hands on_request/on_notify
to dispatcher.run(), and tears down connection.exit_stack (shielded)
on the way out. The entry constructs the Connection; this only consumes
it.
Source code in src/mcp/server/runner.py
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 | |
serve_loop
async
serve_loop(
server: Server[LifespanT],
read_stream: ReadStream[SessionMessage | Exception],
write_stream: WriteStream[SessionMessage],
*,
lifespan_state: LifespanT,
session_id: str | None = None,
init_options: InitializationOptions | None = None,
raise_exceptions: bool = False
) -> None
Drive server in loop mode over a stream pair until the channel closes.
Builds the loop-mode JSONRPCDispatcher + Connection and hands them to
serve_connection, so loop-mode callers share one dispatcher-construction
recipe (notably the inline_methods={"initialize"} rule). Callers that own
a lifespan (the streamable-HTTP manager) pass it in; callers that don't
(Server.run for stdio/memory) enter the lifespan and then call this.
Source code in src/mcp/server/runner.py
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 | |
serve_one
async
serve_one(
server: Server[LifespanT],
request: JSONRPCRequest,
*,
connection: Connection,
dctx: DispatchContext[TransportContext],
lifespan_state: LifespanT
) -> JSONRPCResponse | JSONRPCError
Handle a single request and return its JSON-RPC reply.
The single-exchange driver: builds the kernel, runs on_request once for
request under dctx, maps the outcome to a JSONRPCResponse /
JSONRPCError via to_jsonrpc_response, and tears down
connection.exit_stack (shielded) on the way out. The entry constructs
the (born-ready) Connection and the dctx; this only consumes them.
Source code in src/mcp/server/runner.py
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 | |