context
fastmcp.server.context
Functions
set_context
Classes
Context
Context object providing access to MCP capabilities.
This provides a cleaner interface to MCP’s RequestContext functionality. It gets injected into tool and resource functions that request it via type hints.
To use context in a tool function, add a parameter with the Context type annotation:
The context parameter name can be anything as long as it’s annotated with Context. The context is optional - tools that don’t need it can omit the parameter.
Methods:
request_context
Access to the underlying request context.
If called outside of a request context, this will raise a ValueError.
client_id
Get the client ID if available.
request_id
Get the unique ID for this request.
session_id
Get the MCP session ID for HTTP transports.
Returns the session ID that can be used as a key for session-based data storage (e.g., Redis) to share data between tool calls within the same client session.
Returns:
- The session ID for HTTP transports (SSE, StreamableHTTP), or None
- for stdio and in-memory transports which don’t use session IDs.
session
Access to the underlying session for advanced usage.
get_http_request
Get the active starlette request.