Something went wrong. Try again.
mirror of github.com/PrefectHQ/fastmcp
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640---title: dependenciessidebarTitle: dependencies---
# `fastmcp.server.dependencies`
Dependency injection for FastMCP.
DI features (Depends, CurrentContext, CurrentFastMCP) work without pydocketusing the uncalled-for DI engine. Only task-related dependencies (CurrentDocket,CurrentWorker) and background task execution require fastmcp[tasks].
## Functions
### `get_task_context` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/dependencies.py#L104" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonget_task_context() -> TaskContextInfo | None```
Get the current task context if running inside a background task worker.
This function extracts task information from the Docket execution context.Returns None if not running in a task context (e.g., foreground execution).
**Returns:**- TaskContextInfo with task_id and session_id, or None if not in a task.
### `register_task_session` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/dependencies.py#L142" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonregister_task_session(session_id: str, session: ServerSession) -> None```
Register a session for Context access in background tasks.
Called automatically when a task is submitted to Docket. The session isstored as a weakref so it doesn't prevent garbage collection when theclient disconnects.
**Args:**- `session_id`: The session identifier- `session`: The ServerSession instance
### `get_task_session` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/dependencies.py#L156" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonget_task_session(session_id: str) -> ServerSession | None```
Get a registered session by ID if still alive.
**Args:**- `session_id`: The session identifier
**Returns:**- The ServerSession if found and alive, None otherwise
### `register_task_server` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/dependencies.py#L191" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonregister_task_server(task_id: str, server: FastMCP) -> None```
Register the server for a background task.
Called at task-submission time (inside the child server's call_toolcontext) so that background workers can resolve CurrentFastMCP() andctx.fastmcp to the child server for mounted tasks.
The map is bounded to avoid unbounded growth in long-lived servers.Evicted entries fall back to the ContextVar (parent server).
### `is_docket_available` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/dependencies.py#L221" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonis_docket_available() -> bool```
Check if pydocket is installed.
### `require_docket` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/dependencies.py#L234" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonrequire_docket(feature: str) -> None```
Raise ImportError with install instructions if docket not available.
**Args:**- `feature`: Description of what requires docket (e.g., "`task=True`", "CurrentDocket()"). Will be included in the error message.
### `transform_context_annotations` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/dependencies.py#L259" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythontransform_context_annotations(fn: Callable[..., Any]) -> Callable[..., Any]```
Transform ctx: Context into ctx: Context = CurrentContext().
Transforms ALL params typed as Context to use Docket's DI system,unless they already have a Dependency-based default (like CurrentContext()).
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/src/fastmcp/server/dependencies.py#L400" 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/src/fastmcp/server/dependencies.py#L410" 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, checks the task-server map first so thatmounted-child tasks resolve to the child server (not the parent thatstarted the worker).
**Returns:**- The active FastMCP server
**Raises:**- `RuntimeError`: If no server in context
### `get_http_request` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/dependencies.py#L444" 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.In background tasks, returns a synthetic request populated with thesnapshotted headers from the originating HTTP request.
### `get_http_headers` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/dependencies.py#L489" 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 `authorization`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 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/src/fastmcp/server/dependencies.py#L546" 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. In background tasks (Docket workers), falls back to thetoken snapshot stored in Redis at task submission time.
**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/src/fastmcp/server/dependencies.py#L618" 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
**Returns:**- Async wrapper function without injected parameters
### `resolve_dependencies` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/dependencies.py#L767" 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.
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/src/fastmcp/server/dependencies.py#L1022" 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/src/fastmcp/server/dependencies.py#L1047" 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.
### `CurrentDocket` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/dependencies.py#L1075" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonCurrentDocket() -> Docket```
Get the current Docket instance managed by FastMCP.
This dependency provides access to the Docket instance that FastMCPautomatically creates for background task scheduling.
**Returns:**- A dependency that resolves to the active Docket instance
**Raises:**- `RuntimeError`: If not within a FastMCP server context- `ImportError`: If fastmcp[tasks] not installed
### `CurrentWorker` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/dependencies.py#L1125" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonCurrentWorker() -> Worker```
Get the current Docket Worker instance managed by FastMCP.
This dependency provides access to the Worker instance that FastMCPautomatically creates for background task processing.
**Returns:**- A dependency that resolves to the active Worker instance
**Raises:**- `RuntimeError`: If not within a FastMCP server context- `ImportError`: If fastmcp[tasks] not installed
### `CurrentFastMCP` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/dependencies.py#L1166" 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/src/fastmcp/server/dependencies.py#L1220" 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/src/fastmcp/server/dependencies.py#L1271" 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 header. Returns an empty dictionary when no HTTPrequest is available, making it safe to use in code that might run over anytransport.
**Returns:**- A dependency that resolves to a dictionary of header name -> value
### `CurrentAccessToken` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/dependencies.py#L1505" 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/src/fastmcp/server/dependencies.py#L1562" 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
### `TaskContextInfo` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/dependencies.py#L90" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Information about the current background task context.
Returned by ``get_task_context()`` when running inside a Docket worker.Contains identifiers needed to communicate with the MCP session.
### `ProgressLike` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/dependencies.py#L1299" 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/src/fastmcp/server/dependencies.py#L1307" 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/src/fastmcp/server/dependencies.py#L1312" 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/src/fastmcp/server/dependencies.py#L1317" 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/src/fastmcp/server/dependencies.py#L1321" 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/src/fastmcp/server/dependencies.py#L1325" 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/src/fastmcp/server/dependencies.py#L1329" 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/src/fastmcp/server/dependencies.py#L1334" 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/src/fastmcp/server/dependencies.py#L1359" 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/src/fastmcp/server/dependencies.py#L1363" 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/src/fastmcp/server/dependencies.py#L1367" 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/src/fastmcp/server/dependencies.py#L1370" 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/src/fastmcp/server/dependencies.py#L1376" 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/src/fastmcp/server/dependencies.py#L1385" 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/src/fastmcp/server/dependencies.py#L1390" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
FastMCP Progress dependency that works in both server and worker contexts.
Handles three execution modes:- In Docket worker: Uses the execution's progress (observable via Redis)- In FastMCP server with Docket: Falls back to in-memory progress- In FastMCP server without Docket: Uses in-memory progress
This allows tools to use Progress() regardless of whether they're calledimmediately or as background tasks, and regardless of whether pydocketis installed.
**Methods:**
#### `current` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/dependencies.py#L1432" 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/src/fastmcp/server/dependencies.py#L1438" 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/src/fastmcp/server/dependencies.py#L1444" 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/src/fastmcp/server/dependencies.py#L1449" 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/src/fastmcp/server/dependencies.py#L1454" 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/src/fastmcp/server/dependencies.py#L1459" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonset_message(self, message: str | None) -> None```
Update the progress status message.