server
MCP Server Module
This module provides a framework for creating an MCP (Model Context Protocol) server. It allows you to easily define and handle various types of requests and notifications using constructor-based handler registration.
Usage: 1. Define handler functions: async def my_list_tools(ctx, params): return types.ListToolsResult(tools=[...])
async def my_call_tool(ctx, params): return types.CallToolResult(content=[...])
-
Create a Server instance with on_* handlers: server = Server( "your_server_name", on_list_tools=my_list_tools, on_call_tool=my_call_tool, )
-
Run the server: async def main(): async with mcp.server.stdio.stdio_server() as (read_stream, write_stream): await server.run( read_stream, write_stream, server.create_initialization_options(), )
asyncio.run(main())
The Server class dispatches incoming requests and notifications to registered handler callables by method string.
RequestHandler
module-attribute
RequestHandler = Callable[
[ServerRequestContext[LifespanResultT], _ParamsT],
Awaitable[HandlerResult],
]
A registered request handler: (ctx, params) -> result.
NotificationHandler
module-attribute
NotificationHandler = Callable[
[ServerRequestContext[LifespanResultT], _ParamsT],
Awaitable[None],
]
A registered notification handler: (ctx, params) -> None.
HandlerEntry
dataclass
Bases: Generic[LifespanResultT]
A registered handler and the params model to validate incoming params against.
Stored in Server._request_handlers / _notification_handlers and consumed
by ServerRunner to validate, build Context, and invoke. The handler's
second-argument type is erased to Any in storage (each entry has a
different concrete params type and Callable parameters are contravariant);
the precise type is recoverable via params_type. The correlation is
enforced at registration time by Server.add_request_handler.
Source code in src/mcp/server/lowlevel/server.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 | |
lifespan
async
Default lifespan context manager that does nothing.
Returns:
| Type | Description |
|---|---|
AsyncIterator[dict[str, Any]]
|
An empty context object |
Source code in src/mcp/server/lowlevel/server.py
106 107 108 109 110 111 112 113 | |
Server
Bases: Generic[LifespanResultT]
Source code in src/mcp/server/lowlevel/server.py
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 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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 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 | |
add_request_handler
add_request_handler(
method: str,
params_type: type[_ParamsT],
handler: RequestHandler[LifespanResultT, _ParamsT],
) -> None
Register a request handler for method.
params_type is the model incoming params are validated against
before the handler is invoked. It should subclass RequestParams so
_meta parses uniformly. A message with no params member validates
{} against params_type: models with required fields reject it as
INVALID_PARAMS, all-optional models reach the handler with their
defaults - the handler never receives None. Replaces any existing
handler for the same method, except initialize, which is reserved:
the runner owns the handshake, so registering it raises ValueError.
Use Server.middleware to observe or wrap initialization.
Source code in src/mcp/server/lowlevel/server.py
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | |
add_notification_handler
add_notification_handler(
method: str,
params_type: type[_ParamsT],
handler: NotificationHandler[LifespanResultT, _ParamsT],
) -> None
Register a notification handler for method.
params_type should subclass NotificationParams so _meta
parses uniformly. Absent params follow the same contract as requests:
{} is validated, so the handler receives the model with its defaults,
never None. Replaces any existing handler. A handler for
notifications/initialized runs after the runner has marked the
connection initialized.
Source code in src/mcp/server/lowlevel/server.py
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 | |
get_request_handler
get_request_handler(
method: str,
) -> HandlerEntry[LifespanResultT] | None
Return the registered entry for a request method, or None.
Source code in src/mcp/server/lowlevel/server.py
293 294 295 | |
get_notification_handler
get_notification_handler(
method: str,
) -> HandlerEntry[LifespanResultT] | None
Return the registered entry for a notification method, or None.
Source code in src/mcp/server/lowlevel/server.py
297 298 299 | |
create_initialization_options
create_initialization_options(
notification_options: NotificationOptions | None = None,
experimental_capabilities: (
dict[str, dict[str, Any]] | None
) = None,
) -> InitializationOptions
Create initialization options from this server instance.
Source code in src/mcp/server/lowlevel/server.py
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 | |
get_capabilities
get_capabilities(
notification_options: NotificationOptions,
experimental_capabilities: dict[str, dict[str, Any]],
) -> ServerCapabilities
Convert existing handlers to a ServerCapabilities object.
Source code in src/mcp/server/lowlevel/server.py
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 | |
session_manager
property
session_manager: StreamableHTTPSessionManager
Get the StreamableHTTP session manager.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called before streamable_http_app() has been called. |
streamable_http_app
streamable_http_app(
*,
streamable_http_path: str = "/mcp",
json_response: bool = False,
stateless_http: bool = False,
event_store: EventStore | None = None,
retry_interval: int | None = None,
transport_security: (
TransportSecuritySettings | None
) = None,
host: str = "127.0.0.1",
auth: AuthSettings | None = None,
token_verifier: TokenVerifier | None = None,
auth_server_provider: (
OAuthAuthorizationServerProvider[Any, Any, Any]
| None
) = None,
custom_starlette_routes: list[Route] | None = None,
debug: bool = False
) -> Starlette
Return an instance of the StreamableHTTP server app.
Source code in src/mcp/server/lowlevel/server.py
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 | |