Context
object for this purpose.
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: Read data from resources registered with the server
- LLM Sampling: Request the client’s LLM to generate text based on provided messages
- User Elicitation: Request structured input from users during tool execution
- State Management: Store and share data across middleware and tool calls within a request
- Request Information: Access metadata about the current request
- Server Access: When needed, access the underlying FastMCP server instance
Accessing the Context
Via Dependency Injection
To use the context object within any of your functions, simply add a parameter to your function signature and type-hint it asContext
. FastMCP will automatically inject the context instance when your function is called.
Key Points:
- The parameter name (e.g.,
ctx
,context
) doesn’t matter, only the type hintContext
is important. - The context parameter can be placed anywhere in your function’s signature; it will not be exposed to MCP clients as a valid parameter.
- The context is optional - functions that don’t need it can omit the parameter entirely.
- Context methods are async, so your function usually needs to be async as well.
- The type hint can be a union (
Context | None
) or useAnnotated[]
and it will still work properly. - Context is only available during a request; attempting to use context methods outside a request will raise errors. If you need to debug or call your context methods outside of a request, you can type your variable as
Context | None=None
to avoid missing argument errors.
Tools
Resources and Templates
New in version: 2.2.5
Prompts
New in version: 2.2.5
Via Runtime Dependency Function
New in version: 2.2.11
While the simplest way to access context is through function parameter injection as shown above, there are cases where you need to access the context in code that may not be easy to modify to accept a context parameter, or that is nested deeper within your function calls.
FastMCP provides dependency functions that allow you to retrieve the active context from anywhere within a server 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
New in version: 2.10.0
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.
LLM Sampling
New in version: 2.0.0
Request the client’s LLM to generate text based on provided messages, useful for leveraging AI capabilities within your tools.
Progress Reporting
Update clients on the progress of long-running operations, enabling progress indicators and better user experience.Resource Access
Read data from resources registered with your FastMCP server, allowing access to files, configuration, or dynamic content.ctx.read_resource(uri: str | AnyUrl) -> list[ReadResourceContents]
: Returns a list of resource content parts
State Management
New in version: 2.11.0
Store and share data across middleware and tool calls within a request. Context objects maintain a state dictionary that’s especially useful for passing information from middleware to your tools.
To store a value in the context state, use ctx.set_state(key, value)
. To retrieve a value, use ctx.get_state(key)
.
This simplified example shows how to use MCP middleware to store user info in the context state, and how to access that state in a tool:
ctx.set_state(key: str, value: Any) -> None
: Store a value in the context statectx.get_state(key: str) -> Any
: Retrieve a value from the context state (returns None if not found)
- State set on a child context never affects the parent context
- State set on a parent context after the child context is initialized is not propagated to the child context
Change Notifications
New in version: 2.9.1
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 methods:
FastMCP Server
To access the underlying FastMCP server instance, you can use thectx.fastmcp
property:
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 | None
: Get the MCP session ID for session-based data sharing (HTTP transports only)
The MCP request is part of the low-level MCP SDK and intended for advanced use cases. Most users will not need to use it directly.
Runtime Dependencies
HTTP Requests
New in version: 2.2.11
The recommended way to access the current HTTP request is through the get_http_request()
dependency function:
- You need access to HTTP information in helper functions
- You’re calling nested functions that need HTTP request data
- You’re working with middleware or other request processing code
HTTP Headers
New in version: 2.2.11
If you only need request headers and want to avoid potential errors, you can use the get_http_headers()
helper:
get_http_headers()
excludes problematic headers like host
and content-length
. To include all headers, use get_http_headers(include_all=True)
.
Access Tokens
New in version: 2.11.0
When using authentication with your FastMCP server, you can access the authenticated user’s access token information using the get_access_token()
dependency function:
- Access user identification - Get the
client_id
or subject from token claims - Check permissions - Verify scopes or custom claims before performing operations
- Multi-tenant applications - Extract tenant information from token claims
- Audit logging - Track which user performed which actions
Working with Token Claims
Theclaims
field contains all the data from the original token (JWT claims for JWT tokens, or custom data for other token types):