MCP Context
Access MCP capabilities like logging, progress, and resources within your MCP objects.
When defining FastMCP tools, resources, resource templates, or prompts, your functions might need to interact with the underlying MCP session or access server capabilities. FastMCP provides the Context
object for this purpose.
What Is Context?
The Context
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
- 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 as Context
. 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 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:
Important Notes:
- 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
Logging
Send log messages back to the MCP client. This is useful for debugging and providing visibility into function execution during a request.
Available Logging Methods:
ctx.debug(message: str)
: Low-level details useful for debuggingctx.info(message: str)
: General information about executionctx.warning(message: str)
: Potential issues that didn’t prevent executionctx.error(message: str)
: Errors that occurred during executionctx.log(level: Literal["debug", "info", "warning", "error"], message: str, logger_name: str | None = None)
: Generic log method supporting custom logger names
Progress Reporting
For long-running operations, notify the client about the progress. This allows clients to display progress indicators and provide a better user experience.
Method signature:
ctx.report_progress(progress: float, total: float | None = None)
progress
: Current progress value (e.g., 24)total
: Optional total value (e.g., 100). If provided, clients may interpret this as a percentage.
Progress reporting requires the client to have sent a progressToken
in the initial request. If the client doesn’t support progress reporting, these calls will have no effect.
Resource Access
Read data from resources registered with your FastMCP server. This allows functions to access files, configuration, or dynamically generated content.
Method signature:
ctx.read_resource(uri: str | AnyUrl) -> list[ReadResourceContents]
uri
: The resource URI to read- Returns a list of resource content parts (usually containing just one item)
The returned content is typically accessed via content_list[0].content
and can be text or binary data depending on the resource.
LLM Sampling
New in version: 2.0.0
Request the client’s LLM to generate text based on provided messages. This is useful when your function needs to leverage the LLM’s capabilities to process data or generate responses.
Method signature:
ctx.sample(messages: str | list[str | SamplingMessage], system_prompt: str | None = None, temperature: float | None = None, max_tokens: int | None = None) -> TextContent | ImageContent
messages
: A string or list of strings/message objects to send to the LLMsystem_prompt
: Optional system prompt to guide the LLM’s behaviortemperature
: Optional sampling temperature (controls randomness)max_tokens
: Optional maximum number of tokens to generate (defaults to 512)- Returns the LLM’s response as TextContent or ImageContent
When providing a simple string, it’s treated as a user message. For more complex scenarios, you can provide a list of messages with different roles.
See Client Sampling for more details on how clients handle these requests.
Request Information
Access metadata about the current request and client.
Available Properties:
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 initialization
Advanced Access
FastMCP Server and Sessions
HTTP Requests
New in version: 2.2.7
The ctx.get_http_request()
method is deprecated and will be removed in a future version.
Please use the get_http_request()
dependency function instead.
See the HTTP Requests pattern for more details.
For web applications, you can access the underlying HTTP request:
Advanced Properties Reference
ctx.fastmcp -> FastMCP
: Access the server instance the context belongs toctx.session
: Access the rawmcp.server.session.ServerSession
objectctx.request_context
: Access the rawmcp.shared.context.RequestContext
object
Direct use of session
or request_context
requires understanding the low-level MCP Python SDK and may be less stable than using the methods provided directly on the Context
object.