Depends() and CurrentContext() work without installing Docket. Background task execution and task-specific dependencies such as CurrentDocket() and CurrentWorker() require fastmcp[tasks]. For comprehensive coverage of dependency patterns, see the Docket dependency documentation.
Dependency parameters are automatically excluded from the MCP schema—clients never see them as callable parameters. This separation keeps your function signatures clean while giving you access to the runtime context you need.
How Dependency Injection Works
Dependency injection in FastMCP follows a simple pattern: declare a parameter with a recognized type annotation or a dependency default value, and FastMCP injects the resolved value at runtime.my_tool, they only see query as a parameter. The ctx parameter is injected automatically because it has a Context type annotation—FastMCP recognizes this and provides the active context for the request.
This works identically for tools, resources, resource templates, and prompts.
Explicit Dependencies with CurrentContext
For more explicit code, you can useCurrentContext() as a default value instead of relying on the type annotation:
CurrentContext() approach makes the dependency injection visible in the signature.
Built-in Dependencies
MCP Context
The MCP Context provides logging, progress reporting, resource access, and other request-scoped operations. See MCP Context for the full API. Dependency injection: Use aContext type annotation (FastMCP injects automatically) or CurrentContext():
get_context() in helper functions or middleware:
Server Instance
Access the FastMCP server instance for introspection or server-level configuration. Dependency injection: UseCurrentFastMCP():
get_server():
HTTP Request
Access the Starlette Request when running over HTTP transports (SSE or Streamable HTTP). Dependency injection: UseCurrentRequest():
get_http_request():
Both raise
RuntimeError when called outside an HTTP context (e.g., STDIO transport,
or inside a background task — there is no live request object to reconstruct there).
Use HTTP Headers below if you need graceful fallback, including inside background tasks.HTTP Headers
Access HTTP headers with graceful fallback. When a background task originates from an HTTP request, FastMCP restores the originating headers inside the worker. When no HTTP request is available, this returns an empty dictionary, making it safe for code that might run over any transport. Dependency injection: UseCurrentHeaders():
get_http_headers():
host and content-length are excluded. Use get_http_headers(include_all=True) to include all headers.
Access Token
Access the authenticated user’s token when your server uses authentication. Dependency injection: UseCurrentAccessToken() (raises if not authenticated):
get_access_token() (returns None if not authenticated):
AccessToken object provides:
client_id: The OAuth client identifierscopes: List of granted permission scopesexpires_at: Token expiration timestamp (if available)claims: Dictionary of all token claims (JWT claims or provider-specific data)
Token Claims
When you need just one specific value from the token—like a user ID or tenant identifier—TokenClaim() extracts it directly without needing the full token object.
TokenClaim() raises a RuntimeError if the claim doesn’t exist, listing available claims to help with debugging.
Common claims vary by identity provider:
Background Task Dependencies
For background task execution, FastMCP provides dependencies that integrate with Docket.CurrentDocket() and CurrentWorker() require installing fastmcp[tasks]; Progress() also works during immediate foreground execution with an in-memory tracker, and delegates to Docket progress when a Docket worker context is active.
CurrentDocket(): Access the Docket instance for scheduling additional background workCurrentWorker(): Access the worker processing tasks (name, concurrency settings)Progress(): Track task progress with atomic updates
CurrentDocket() and CurrentWorker() require pip install 'fastmcp[tasks]'. They resolve once the server lifespan has initialized Docket, which happens as soon as any component on the server is task-enabled — so regular foreground tools, resources, and prompts can inject them too, not only task-enabled components. Progress() can be injected anywhere regardless, though cross-process task progress requires Docket. For comprehensive task patterns, see the Docket documentation.Custom Dependencies
Beyond the built-in dependencies, you can create your own to inject configuration, database connections, API clients, or any other values your functions need.Using Depends()
TheDepends() function wraps any callable and injects its return value. This works with synchronous functions, async functions, and async context managers.
Caching
Dependencies are cached per-request. If multiple parameters use the same dependency, or if nested dependencies share a common dependency, it’s resolved once and the same instance is reused.Resource Management
For dependencies that need cleanup—database connections, file handles, HTTP clients—use an async context manager. The cleanup code runs after your function completes, even if an error occurs.Nested Dependencies
Dependencies can depend on other dependencies. FastMCP resolves them in the correct order and applies caching across the dependency tree.Call Arguments
A dependency factory can read the arguments of the function it serves. Declare the reference withCallArgument():
show_account, the factory receives the same user_id value the tool receives. The bare form takes the name of the parameter it is declared on. CallArgument("user_id") names the parameter explicitly. The reference also sees a value that another dependency on the tool’s signature produced. CallArgument("tenant", optional=True) yields None when the function has no such parameter. References that form a cycle raise CycleError, importable from fastmcp.dependencies.
Clients still cannot override dependencies this way: an argument whose name collides with a dependency parameter is stripped before resolution, so a CallArgument reference to that parameter resolves the dependency itself.
Bindings
Depends() accepts keyword bindings, so you can wire up a factory without changing it:
Dependency, such as CallArgument(...) or another Depends(...), resolves first and the factory receives its value. Any other value passes through as it is. A binding replaces the default of the factory’s own parameter, which is then never resolved. Two dependencies on the same factory share one cached result only when their bindings match. See the Docket dependency documentation for more detail on call arguments and bindings.
For advanced dependency patterns—like TaskArgument() for accessing task parameters, or custom Dependency subclasses—see the Docket dependency documentation.
