Skip to main content
When defining FastMCP tools, resources, resource templates, or prompts, your functions might need to interact with the underlying MCP session or access advanced server capabilities. FastMCP provides the Context object for this purpose.
FastMCP uses Docket’s dependency injection system for managing runtime dependencies. This page covers Context and the built-in dependencies; see Custom Dependencies for creating your own.

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: List and read data from resources registered with the server
  • Prompt Access: List and retrieve prompts 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 between middleware and the handler within a single request
  • Request Information: Access metadata about the current request
  • Server Access: When needed, access the underlying FastMCP server instance

Accessing the Context

New in version 2.14 The preferred way to access context is using the CurrentContext() dependency:
This works with tools, resources, and prompts:
Key Points:
  • 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. Context is scoped to a single request; state or data set in one request will not be available in subsequent requests.
  • 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 the Context type hint. FastMCP will automatically inject the context instance:
This approach still works for tools, resources, and prompts. The parameter name doesn’t matter—only the Context type hint is important. The type hint can also be a union (Context | None) or use Annotated[].

Via get_context() Function

New in version 2.2.11 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:
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 a RuntimeError.
  • 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.
See Server Logging for complete documentation and examples.

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.
See User Elicitation for detailed examples and supported response types.

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.
See LLM Sampling for comprehensive usage and advanced techniques.

Progress Reporting

Update clients on the progress of long-running operations, enabling progress indicators and better user experience.
See Progress Reporting for detailed patterns and examples.

Resource Access

List and read data from resources registered with your FastMCP server, allowing access to files, configuration, or dynamic content.
Method signatures:
  • ctx.list_resources() -> list[MCPResource]: New in version 2.13.0 Returns list of all available resources
  • ctx.read_resource(uri: str | AnyUrl) -> list[ReadResourceContents]: Returns a list of resource content parts

Prompt Access

New in version 2.13.0 List and retrieve prompts registered with your FastMCP server, allowing tools and middleware to discover and use available prompts programmatically.
Method signatures:
  • ctx.list_prompts() -> list[MCPPrompt]: Returns list of all available prompts
  • ctx.get_prompt(name: str, arguments: dict[str, Any] | None = None) -> GetPromptResult: Get a specific prompt with optional arguments

State Management

New in version 2.11.0 Store and share data between middleware and handlers within a single MCP request. Each MCP request (such as calling a tool, reading a resource, listing tools, or listing resources) receives its own context object with isolated state. Context state is particularly useful for passing information from middleware to your handlers. To store a value in the context state, use ctx.set_state(key, value). To retrieve a value, use ctx.get_state(key).
Context state is scoped to a single MCP request. Each operation (tool call, resource read, list operation, etc.) receives a new context object. State set during one request will not be available in subsequent requests. For persistent data storage across requests, use external storage mechanisms like databases, files, or in-memory caches.
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:
Method signatures:
  • ctx.set_state(key: str, value: Any) -> None: Store a value in the context state
  • ctx.get_state(key: str) -> Any: Retrieve a value from the context state (returns None if not found)
State Inheritance: When a new context is created (nested contexts), it inherits a copy of its parent’s state. This ensures that:
  • 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
This makes state management predictable and prevents unexpected side effects between nested operations.

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:
These methods are primarily used internally by FastMCP’s automatic notification system and most users will not need to invoke them directly.

FastMCP Server

To access the underlying FastMCP server instance, you can use the ctx.fastmcp property:

MCP Request

Access metadata about the current request and client.
Available Properties:
  • ctx.request_id -> str: Get the unique ID for the current MCP request
  • ctx.client_id -> str | None: Get the ID of the client making the request, if provided during initialization
  • ctx.session_id -> str | None: Get the MCP session ID for session-based data sharing (HTTP transports only)

Request Context Availability

New in version 2.13.1 The ctx.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_request hook before the MCP handshake completes
  • During the initialization phase of client connections
The MCP request context is distinct from the HTTP request. For HTTP transports, HTTP request data may be available even when the MCP session is not yet established. To safely access the request context in situations where it may not be available:
For HTTP request access that works regardless of MCP session availability (when using HTTP transports), use the HTTP request helpers like get_http_request() and get_http_headers().

Client Metadata

New in version 2.13.1 Clients can send contextual information with their requests using the meta 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.
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:
This approach works anywhere within a request’s execution flow, not just within your MCP function. It’s useful when:
  1. You need access to HTTP information in helper functions
  2. You’re calling nested functions that need HTTP request data
  3. 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:
By default, 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:
This is particularly useful when you need to:
  1. Access user identification - Get the client_id or subject from token claims
  2. Check permissions - Verify scopes or custom claims before performing operations
  3. Multi-tenant applications - Extract tenant information from token claims
  4. Audit logging - Track which user performed which actions

Working with Token Claims

The claims field contains all the data from the original token (JWT claims for JWT tokens, or custom data for other token types):

Custom Dependencies

New in version 2.14 FastMCP’s dependency injection is powered by Docket, which provides a flexible system for injecting values into your functions. Beyond the built-in dependencies like CurrentContext(), you can create your own.

Using Depends()

The simplest way to create a custom dependency is with Depends(). Pass any callable (sync or async function, or async context manager) and its return value will be injected:
Dependencies using Depends() are automatically excluded from the MCP schema—clients never see them as parameters.

Resource Management with Context Managers

For dependencies that need cleanup (database connections, file handles, etc.), use an async context manager:
The context manager’s cleanup code runs after your function completes, even if an error occurs.

Nested Dependencies

Dependencies can depend on other dependencies:

Advanced: Subclassing Dependency

For more complex dependency patterns—like dependencies that need access to Docket’s execution context or require custom lifecycle management—you can subclass Docket’s Dependency class. See the Docket documentation on dependencies for details.