fastmcp.server.dependencies
Dependency injection for FastMCP.
DI features (Depends, CurrentContext, CurrentFastMCP) work without pydocket
using the uncalled-for DI engine. The docket-specific dependencies
(CurrentDocket, CurrentWorker) and background task execution live in the
fastmcp-tasks package.
Functions
bind_request_context
FastMCPRequestContext for the duration of a handler.
Constructs the wrapper from the SDK’s per-request context and sets/resets
the fastmcp_request_ctx ContextVar. Every request adapter and the
initialize middleware enters this so Context and dependency helpers can
read the active request from the ContextVar.
extract_version_spec
_meta block.
set_background_context_factory
Context factory.
The factory returns an already-entered Context (so _current_context
is set for cleanup) when called inside a worker, or None when there is
no task context. Passing None restores core’s no-worker-fallback
behavior.
set_worker_server_resolver
get_server().
is_docket_available
- pydocket distribution metadata is discoverable
- its version is at least
_MIN_DOCKET_VERSION(older versions are missing symbols likedocket.dependencies.current_execution, which fastmcp imports on the request hot path) - the package actually imports — guards against broken/partial
installs where metadata exists but
import docketblows up
transform_context_annotations
= CurrentContext()) and as
UserSession (into = CurrentSession()) to use Docket’s DI system, unless
they already have a Dependency-based default.
This unifies the legacy type annotation DI with Docket’s Depends() system,
allowing both patterns to work through a single resolution path.
Note: Only POSITIONAL_OR_KEYWORD parameters are reordered (params with defaults
after those without). KEYWORD_ONLY parameters keep their position since Python
allows them to have defaults in any order.
Args:
fn: Function to transform
- Function with modified signature (same function object, updated signature)
get_context
get_server
- The active FastMCP server
RuntimeError: If no server in context
get_session
Session for an explicit session_id.
Pair with a session_id: SessionId tool argument (the agent obtains an id
from create_session and passes it back). For a single per-user bucket with
nothing for the agent to pass, inject session: UserSession instead.
State is keyed by (principal, session_id): the authenticated principal is
the isolation wall and session_id organizes sessions within it. The id must
have been minted by create_session under the current principal; an id that
was never created, or created under a different principal, raises
InvalidSession rather than resolving to a fresh empty bucket (the specific
reason is logged at debug level, never returned to the caller).
Like get_server(), this resolves through the task-aware server, so it needs
no foreground context — it works from a task=True tool’s Docket worker as
well as a normal request.
get_http_request
get_http_headers
content-length, and credential
headers like authorization and cookie, that cause issues if forwarded to
downstream services. If include_all is True, all headers are returned.
The include parameter allows specific headers to be included even if they would
normally be excluded. This is useful for proxy transports that need to forward
authorization headers to upstream MCP servers.
get_access_token
- The access token if an authenticated user is available, None otherwise.
without_injected_parameters
- Legacy Context injection (always works)
- Depends() injection (always works - uses docket or vendored DI engine)
fn: Original function with Context and/or dependenciesrun_in_thread: For syncfn, whether to dispatch the call to a worker thread after resolving dependencies. Defaults to True. Set to False to callfninline on the event loop thread — required for thread-affinity libraries (e.g. Windows COM). Ignored for async fns.
- Async wrapper function without injected parameters
resolve_dependencies
- Filters out any dependency parameter names from user arguments (security)
- Resolves Depends() parameters via the DI system
ctx: Context to ctx: Context = Depends(get_context) at registration
time, so all injection goes through the unified DI system.
Args:
fn: The function to resolve dependencies forarguments: User arguments (may contain keys that match dependency names, which will be filtered out)
CurrentContext
- A dependency that resolves to the active Context instance
RuntimeError: If no active context found (during resolution)
OptionalCurrentContext
CurrentFastMCP
- A dependency that resolves to the active FastMCP server
RuntimeError: If no server in context (during resolution)
CurrentRequest
- A dependency that resolves to the active Starlette Request
RuntimeError: If no HTTP request in context (e.g., STDIO transport)
CurrentHeaders
authorization and cookie headers, which get_http_headers()
withholds by default. Returns an empty dictionary when no HTTP request is
available, making it safe to use in code that might run over any transport.
Returns:
- A dependency that resolves to a dictionary of header name -> value
CurrentAccessToken
- A dependency that resolves to the active AccessToken
RuntimeError: If no authenticated user (use get_access_token() for optional)
TokenClaim
name: The name of the claim to extract (e.g., “oid”, “sub”, “email”)
- A dependency that resolves to the claim value as a string
RuntimeError: If no access token is available or claim is missing
Classes
FastMCPRequestContext
FastMCP-owned wrapper around the SDK’s per-request context.
The SDK v2 runner hands each handler a fresh ServerRequestContext as an
argument rather than exposing it through a ContextVar. FastMCP owns this
ContextVar (fastmcp_request_ctx) and each request adapter binds a
FastMCPRequestContext at the top of the handler (and the initialize
middleware binds it too).
A wrapper rather than the raw context because the SDK’s
ServerRequestContext.meta is a bare RequestParamsMeta TypedDict that
only carries progress_token — it does not carry _meta.fastmcp or the
distributed-trace parent. Those live in the raw params dict under _meta,
which this wrapper lifts once so downstream consumers have a stable surface.
ProgressLike
Protocol for progress tracking interface.
Defines the common interface between InMemoryProgress (server context)
and Docket’s Progress (worker context).
Methods:
current
total
message
set_total
increment
set_message
InMemoryProgress
In-memory progress tracker for immediate tool execution.
Provides the same interface as Docket’s Progress but stores state in memory
instead of Redis. Useful for testing and immediate execution where
progress doesn’t need to be observable across processes.
Methods:
current
total
message
set_total
increment
set_message
Progress
Progress dependency that works in both server and worker contexts.
In a Docket worker, delegates to the execution’s Redis-backed progress
(observable across processes). Otherwise, uses in-memory tracking.
The shared default instance acts as a stateless factory — __aenter__
creates a fresh Progress per invocation so concurrent tasks never
share mutable state.
Methods:

