Something went wrong. Try again.
mirror of github.com/PrefectHQ/fastmcp
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618---title: dependenciessidebarTitle: dependencies---
# `fastmcp.server.dependencies`
Dependency injection for FastMCP.
DI features (Depends, CurrentContext, CurrentFastMCP) work without pydocketusing 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` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L113" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonbind_request_context(ctx: ServerRequestContext) -> Generator[FastMCPRequestContext, None, None]```
Bind a ``FastMCPRequestContext`` for the duration of a handler.
Constructs the wrapper from the SDK's per-request context and sets/resetsthe ``fastmcp_request_ctx`` ContextVar. Every request adapter and theinitialize middleware enters this so ``Context`` and dependency helpers canread the active request from the ContextVar.
### `extract_version_spec` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L140" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonextract_version_spec(meta: dict[str, Any] | None) -> str | None```
Extract the FastMCP component version from a lifted ``_meta`` block.
### `set_background_context_factory` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L194" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonset_background_context_factory(factory: Callable[[], Awaitable[Context | None]] | None) -> None```
Install (or clear) the background-task ``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 isno task context. Passing ``None`` restores core's no-worker-fallbackbehavior.
### `set_worker_server_resolver` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L216" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonset_worker_server_resolver(resolver: Callable[[], FastMCP | None] | None) -> None```
Install (or clear) the worker-server resolver used by ``get_server()``.
### `is_docket_available` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L308" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonis_docket_available() -> bool```
Check if a compatible pydocket (>= 0.19.0) is installed and importable.
Three things have to be true for fastmcp's task features to work: 1. pydocket distribution metadata is discoverable 2. its version is at least ``_MIN_DOCKET_VERSION`` (older versions are missing symbols like ``docket.dependencies.current_execution``, which fastmcp imports on the request hot path) 3. the package actually imports — guards against broken/partial installs where metadata exists but ``import docket`` blows up
Any of those failing means we treat docket as unavailable and fall backto the no-tasks code paths instead of crashing deep inside a request.
### `transform_context_annotations` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L340" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythontransform_context_annotations(fn: Callable[..., Any]) -> Callable[..., Any]```
Transform injected-by-type params into Dependency-defaulted params.
Transforms ALL params typed as Context (into ``= CurrentContext()``) and asUserSession (into ``= CurrentSession()``) to use Docket's DI system, unlessthey 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 defaultsafter those without). KEYWORD_ONLY parameters keep their position since Pythonallows them to have defaults in any order.
**Args:**- `fn`: Function to transform
**Returns:**- Function with modified signature (same function object, updated __signature__)
### `get_context` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L506" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonget_context() -> Context```
Get the current FastMCP Context instance directly.
### `get_server` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L516" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonget_server() -> FastMCP```
Get the current FastMCP server instance directly.
In a background-task worker the tasks extension's resolver is consultedfirst, so a mounted-child task resolves to the child server rather than theroot that started the worker (#3571).
**Returns:**- The active FastMCP server
**Raises:**- `RuntimeError`: If no server in context
### `get_session` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L544" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonget_session(session_id: str) -> Session```
Resolve and validate a `Session` for an explicit `session_id`.
Pair with a `session_id: SessionId` tool argument (the agent obtains an idfrom `create_session` and passes it back). For a single per-user bucket withnothing for the agent to pass, inject `session: UserSession` instead.
State is keyed by `(principal, session_id)`: the authenticated principal isthe isolation wall and `session_id` organizes sessions within it. The id musthave been minted by `create_session` under the current principal; an id thatwas never created, or created under a different principal, raises`InvalidSession` rather than resolving to a fresh empty bucket (the specificreason is logged at debug level, never returned to the caller).
Like `get_server()`, this resolves through the task-aware server, so it needsno foreground context — it works from a `task=True` tool's Docket worker aswell as a normal request.
### `get_http_request` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L579" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonget_http_request() -> Request```
Get the current HTTP request.
Tries MCP SDK's request_ctx first, then falls back to FastMCP's HTTP context.
### `get_http_headers` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L600" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonget_http_headers(include_all: bool = False, include: set[str] | None = None) -> dict[str, str]```
Extract headers from the current HTTP request if available.
Never raises an exception, even if there is no active HTTP request (in which casean empty dict is returned).
By default, strips problematic headers like `content-length`, and credentialheaders like `authorization` and `cookie`, that cause issues if forwarded todownstream services. If `include_all` is True, all headers are returned.
The `include` parameter allows specific headers to be included even if they wouldnormally be excluded. This is useful for proxy transports that need to forwardauthorization headers to upstream MCP servers.
### `get_access_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L665" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonget_access_token() -> AccessToken | None```
Get the FastMCP access token from the current context.
This function first tries to get the token from the current HTTP request's scope,which is more reliable for long-lived connections where the SDK's auth_context_varmay become stale after token refresh. Falls back to the SDK's context var if norequest is available.
**Returns:**- The access token if an authenticated user is available, None otherwise.
### `without_injected_parameters` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L724" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonwithout_injected_parameters(fn: Callable[..., Any]) -> Callable[..., Any]```
Create a wrapper function without injected parameters.
Returns a wrapper that excludes Context and Docket dependency parameters,making it safe to use with Pydantic TypeAdapter for schema generation andvalidation. The wrapper internally handles all dependency resolution andContext injection when called.
Handles:- Legacy Context injection (always works)- Depends() injection (always works - uses docket or vendored DI engine)
**Args:**- `fn`: Original function with Context and/or dependencies- `run_in_thread`: For sync ``fn``, whether to dispatch the call to a workerthread after resolving dependencies. Defaults to True. Set to Falseto call ``fn`` inline on the event loop thread — required forthread-affinity libraries (e.g. Windows COM). Ignored for async fns.
**Returns:**- Async wrapper function without injected parameters
### `resolve_dependencies` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L893" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonresolve_dependencies(fn: Callable[..., Any], arguments: dict[str, Any]) -> AsyncGenerator[dict[str, Any], None]```
Resolve dependencies for a FastMCP function.
This function:1. Filters out any dependency parameter names from user arguments (security)2. Resolves Depends() parameters via the DI system
The filtering prevents external callers from overriding injected parameters byproviding values for dependency parameter names. This is a security feature.The filtered arguments also feed the resolution frame, so a CallArgument()reference to a dependency parameter resolves the dependency and never acaller-supplied value.
Note: Context injection is handled via transform_context_annotations() whichconverts `ctx: Context` to `ctx: Context = Depends(get_context)` at registrationtime, so all injection goes through the unified DI system.
**Args:**- `fn`: The function to resolve dependencies for- `arguments`: User arguments (may contain keys that match dependency names, which will be filtered out)
### `CurrentContext` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1021" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonCurrentContext() -> Context```
Get the current FastMCP Context instance.
This dependency provides access to the active FastMCP Context for thecurrent MCP operation (tool/resource/prompt call).
**Returns:**- A dependency that resolves to the active Context instance
**Raises:**- `RuntimeError`: If no active context found (during resolution)
### `OptionalCurrentContext` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1046" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonOptionalCurrentContext() -> Context | None```
Get the current FastMCP Context, or None when no context is active.
### `CurrentFastMCP` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1066" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonCurrentFastMCP() -> FastMCP```
Get the current FastMCP server instance.
This dependency provides access to the active FastMCP server.
**Returns:**- A dependency that resolves to the active FastMCP server
**Raises:**- `RuntimeError`: If no server in context (during resolution)
### `CurrentRequest` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1106" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonCurrentRequest() -> Request```
Get the current HTTP request.
This dependency provides access to the Starlette Request object for thecurrent HTTP request. Only available when running over HTTP transports(SSE or Streamable HTTP).
**Returns:**- A dependency that resolves to the active Starlette Request
**Raises:**- `RuntimeError`: If no HTTP request in context (e.g., STDIO transport)
### `CurrentHeaders` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1150" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonCurrentHeaders() -> dict[str, str]```
Get the current HTTP request headers.
This dependency provides access to the HTTP headers for the current request,including the `authorization` and `cookie` headers, which `get_http_headers()`withholds by default. Returns an empty dictionary when no HTTP request isavailable, 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` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1368" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonCurrentAccessToken() -> AccessToken```
Get the current access token for the authenticated user.
This dependency provides access to the AccessToken for the currentauthenticated request. Raises an error if no authentication is present.
**Returns:**- A dependency that resolves to the active AccessToken
**Raises:**- `RuntimeError`: If no authenticated user (use get_access_token() for optional)
### `TokenClaim` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1425" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonTokenClaim(name: str) -> str```
Get a specific claim from the access token.
This dependency extracts a single claim value from the current access token.It's useful for getting user identifiers, roles, or other token claimswithout needing the full token object.
**Args:**- `name`: The name of the claim to extract (e.g., "oid", "sub", "email")
**Returns:**- A dependency that resolves to the claim value as a string
**Raises:**- `RuntimeError`: If no access token is available or claim is missing
## Classes
### `FastMCPRequestContext` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L64" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
FastMCP-owned wrapper around the SDK's per-request context.
The SDK v2 runner hands each handler a fresh ``ServerRequestContext`` as anargument rather than exposing it through a ContextVar. FastMCP owns thisContextVar (``fastmcp_request_ctx``) and each request adapter binds a``FastMCPRequestContext`` at the top of the handler (and the initializemiddleware binds it too).
A wrapper rather than the raw context because the SDK's``ServerRequestContext.meta`` is a bare ``RequestParamsMeta`` TypedDict thatonly carries ``progress_token`` — it does not carry ``_meta.fastmcp`` or thedistributed-trace parent. Those live in the raw params dict under ``_meta``,which this wrapper lifts once so downstream consumers have a stable surface.
### `ProgressLike` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1178" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Protocol for progress tracking interface.
Defines the common interface between InMemoryProgress (server context)and Docket's Progress (worker context).
**Methods:**
#### `current` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1186" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythoncurrent(self) -> int | None```
Current progress value.
#### `total` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1191" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythontotal(self) -> int```
Total/target progress value.
#### `message` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1196" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonmessage(self) -> str | None```
Current progress message.
#### `set_total` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1200" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonset_total(self, total: int) -> None```
Set the total/target value for progress tracking.
#### `increment` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1204" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonincrement(self, amount: int = 1) -> None```
Atomically increment the current progress value.
#### `set_message` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1208" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonset_message(self, message: str | None) -> None```
Update the progress status message.
### `InMemoryProgress` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1213" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
In-memory progress tracker for immediate tool execution.
Provides the same interface as Docket's Progress but stores state in memoryinstead of Redis. Useful for testing and immediate execution whereprogress doesn't need to be observable across processes.
**Methods:**
#### `current` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1238" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythoncurrent(self) -> int | None```
#### `total` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1242" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythontotal(self) -> int```
#### `message` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1246" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonmessage(self) -> str | None```
#### `set_total` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1249" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonset_total(self, total: int) -> None```
Set the total/target value for progress tracking.
#### `increment` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1255" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonincrement(self, amount: int = 1) -> None```
Atomically increment the current progress value.
#### `set_message` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1264" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonset_message(self, message: str | None) -> None```
Update the progress status message.
### `Progress` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1269" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
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 nevershare mutable state.
**Methods:**
#### `current` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1310" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythoncurrent(self) -> int | None```
Current progress value.
#### `total` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1316" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythontotal(self) -> int```
Total/target progress value.
#### `message` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1322" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonmessage(self) -> str | None```
Current progress message.
#### `set_total` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1327" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonset_total(self, total: int) -> None```
Set the total/target value for progress tracking.
#### `increment` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1332" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonincrement(self, amount: int = 1) -> None```
Atomically increment the current progress value.
#### `set_message` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1337" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonset_message(self, message: str | None) -> None```
Update the progress status message.