Context object for this purpose.
You access Context through FastMCP’s dependency injection system. For other injectable values like HTTP requests, access tokens, and custom dependencies, see Dependency Injection.
What Is Context?
TheContext object provides a clean interface to access MCP features within your functions, including:
- Logging: Send debug, info, warning, and error messages back to the client
- Progress Reporting: Update the client on the progress of long-running operations
- Resource Access: List and read data from resources registered with the server
- Prompt Access: List and retrieve prompts registered with the server
- User Elicitation: Request structured input from users during tool execution
- Request State: Pass values and non-serializable resources between middleware and handlers within a request (for state that persists across requests, see Session State)
- Session Visibility: Control which components are visible to the current session
- Request Information: Access metadata about the current request
- Server Access: When needed, access the underlying FastMCP server instance
Accessing the Context
The preferred way to access context is using theCurrentContext() dependency:
- Dependency parameters are automatically excluded from the MCP schema—clients never see them.
- Context methods are async, so your function usually needs to be async as well.
- Each MCP request receives a new context object. State set with
ctx.set_state()is scoped to that request and is not available in subsequent ones. To persist state across requests, use Session State. - Context is only available during a request; attempting to use context methods outside a request will raise errors.
Legacy Type-Hint Injection
For backwards compatibility, you can still access context by simply adding a parameter with theContext type hint. FastMCP will automatically inject the context instance:
Context type hint is important. The type hint can also be a union (Context | None) or use Annotated[].
Via get_context() Function
For code nested deeper within your function calls where passing context through parameters is inconvenient, use get_context() to retrieve the active context from anywhere within a request’s execution flow:
- The
get_context()function should only be used within the context of a server request. Calling it outside of a request will raise aRuntimeError. - The
get_context()function is server-only and should not be used in client code.
Context Capabilities
FastMCP provides several advanced capabilities through the context object. Each capability has dedicated documentation with comprehensive examples and best practices:Logging
Send debug, info, warning, and error messages back to the MCP client for visibility into function execution.Client Elicitation
Request structured input from clients during tool execution, enabling interactive workflows and progressive disclosure. This is a new feature in the 6/18/2025 MCP spec.Sampling and Roots
Neither capability has aContext method. Both used to push a request into a live client connection, which the modern MCP protocol has no channel to carry, so a tool now asks for them by returning the request and reading the answer on the next round — the same guard pattern elicitation uses on modern connections. That route is the natural one for roots; for generation, call an LLM directly from your server.
Progress Reporting
Update clients on the progress of long-running operations, enabling progress indicators and better user experience.Resource Access
List and read data from resources registered with your FastMCP server, allowing access to files, configuration, or dynamic content.ctx.list_resources() -> list[mcp.types.Resource]: Returns list of all available resourcesctx.read_resource(uri: str | AnyUrl) -> ResourceResult: Returns aResourceResultwhose.contentslist contains the resource content parts
Prompt Access
List and retrieve prompts registered with your FastMCP server, allowing tools and middleware to discover and use available prompts programmatically.ctx.list_prompts() -> list[MCPPrompt]: Returns list of all available promptsctx.get_prompt(name: str, arguments: dict[str, Any] | None = None) -> GetPromptResult: Get a specific prompt with optional arguments
Request State
Request state carries values within a single request, across the middleware → handler pipeline. A request runs through any middleware you’ve added and then the handler — separate functions that don’t share a stack frame, so a plain local variable can’t pass anything between them.ctx.set_state / ctx.get_state is that channel.
The common case is a middleware that resolves something once and every tool reads it, rather than each tool recomputing it:
await ctx.set_state(key, value, *, serializable=True)— store a valueawait ctx.get_state(key)— retrieve a value (returnsNoneif not set)await ctx.delete_state(key)— remove a value
Non-serializable resources
The most useful thing request state holds is objects you can’t persist — a database connection or an HTTP client that a middleware or the lifespan opens and a handler uses. Passserializable=False:
serializable=False value lives on the request context for the current call only. It is inherently request-scoped — a live connection can’t be serialized and stored — which is exactly why it belongs here rather than in a persistent store.
Persisting across requests
Request state does not survive from one call to the next. When you need a cart, a conversation, or any state that outlives a single request, use Session State — it stores server-side, keyed by the authenticated user, and works on every protocol era. (On session-based, handshake-era connections, serializable request state also persists across the session, but Session State is the deliberate, cross-era way to do it.)Session Visibility
Tools can customize which components are visible to their current session usingctx.enable_components(), ctx.disable_components(), and ctx.reset_visibility(). They accept the same filters as the server-level methods, so names={"search"} targets a component by name and tags targets a group. These methods apply visibility rules that affect only the calling session, leaving other sessions unchanged. See Per-Session Visibility for complete documentation, filter criteria, and patterns like namespace activation.
Change Notifications
FastMCP automatically sends list change notifications when components (such as tools, resources, or prompts) are added, removed, enabled, or disabled. In rare cases where you need to manually trigger these notifications, you can use the context’s notification methods:FastMCP Server
To access the underlying FastMCP server instance, you can use thectx.fastmcp property:
Transport
Thectx.transport property indicates which transport is being used to run the server. This is useful when your tool needs to behave differently depending on whether the server is running over STDIO, SSE, or Streamable HTTP. For example, you might want to return shorter responses over STDIO or adjust timeout behavior based on transport characteristics.
The transport type is set once when the server starts and remains constant for the server’s lifetime. It returns None when called outside of a server context (for example, in unit tests or when running code outside of an MCP request).
ctx.transport -> Literal["stdio", "sse", "streamable-http"] | None
MCP Request
Access metadata about the current request and client.ctx.request_id -> str: Get the unique ID for the current MCP requestctx.client_id -> str | None: Get the ID of the client making the request, if provided during initializationctx.session_id -> str: Get the MCP session ID for session-based data sharing. RaisesRuntimeErrorif the MCP session is not yet established.
Request Context Availability
Thectx.request_context property provides access to the underlying MCP request context, but returns None when the MCP session has not been established yet. This typically occurs:
- During middleware execution in the
on_requesthook before the MCP handshake completes - During the initialization phase of client connections
get_http_request() and get_http_headers().
Client Metadata
Clients can send contextual information with their requests using themeta parameter. This metadata is accessible through ctx.request_context.meta and is available for all MCP operations (tools, resources, prompts).
The meta field is None when clients don’t provide metadata. When provided, metadata is accessible via attribute access (e.g., meta.user_id) rather than dictionary access. The structure of metadata is determined by the client making the request.

