Something went wrong. Try again.
mirror of github.com/PrefectHQ/fastmcp
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193---title: contextsidebarTitle: context---
# `fastmcp.server.tasks.context`
Task context and scoping for background task execution.
Determines authorization scope (``get_task_scope``), manages the contextsnapshot that is captured at task submission and restored in workers(``TaskContextSnapshot``), and maintains in-process registries for livesessions and servers.
## Functions
### `get_task_scope` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/tasks/context.py#L42" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonget_task_scope() -> str | None```
Get the authorization scope for task isolation.
Returns the raw scope identifier for the current access token, or``None`` when no auth context is present (anonymous tasks).
The scope is composed as ``client_id|sub`` when the token carries a``sub`` claim — necessary for fixed-OAuth servers where ``client_id`` isshared across all users — and falls back to ``client_id`` alone forDCR/CIMD flows where the client identity is already per-user.
Encoding for Redis/Docket keys happens at the boundary in ``keys.py``;this function returns the raw value.
### `get_task_context` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/tasks/context.py#L82" 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 task_scope, or None if not in a task.
### `get_task_session_id` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/tasks/context.py#L220" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonget_task_session_id() -> str | None```
Get the session_id for the current background task, if available.
Reads the cached snapshot set by the worker-level restore dependency.Returns None if not in a task context or the snapshot wasn't restored.
### `restore_task_snapshot` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/tasks/context.py#L233" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonrestore_task_snapshot(key: str = TaskKey()) -> None```
Worker-level Docket dependency that restores the task-context snapshot.
Runs before each fastmcp-owned task, populating the snapshot ContextVarso user code — and any task-scoped dependency like ``_CurrentContext`` —sees a ready snapshot without touching Redis itself. All Redis I/Ogoes through Docket's async client, so cluster URLs and the memory://backend work transparently (#3897). Failures are non-fatal: the taskstill runs, and sync helpers return ``None`` as they would have beforethe snapshot was captured.
### `register_task_session` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/tasks/context.py#L286" 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 in-process background task access.
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.
### `get_task_session` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/tasks/context.py#L296" 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.
Returns None in distributed workers where the session lives in anotherprocess — callers must handle this gracefully.
### `register_task_server` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/tasks/context.py#L315" 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 so that background workers can resolvethe correct (child) server for mounted tasks.
### `get_task_server` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/tasks/context.py#L326" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonget_task_server(task_id: str) -> FastMCP | None```
Get the registered server for a background task, if still alive.
## Classes
### `TaskContextInfo` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/tasks/context.py#L68" 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.
### `TaskContextSnapshot` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/tasks/context.py#L112" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
All context data snapshotted at task-submission time.
Stored as a single Redis key per task, restored once in the worker.
**Methods:**
#### `capture` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/tasks/context.py#L124" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythoncapture(cls) -> TaskContextSnapshot```
Capture current context for background task execution.
#### `from_json` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/tasks/context.py#L151" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonfrom_json(cls, raw: str | bytes) -> TaskContextSnapshot```
Deserialize from JSON stored in Redis.
#### `to_json` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/tasks/context.py#L166" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonto_json(self) -> str```
Serialize to JSON for Redis storage.
#### `save` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/tasks/context.py#L177" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonsave(self, docket: Docket, task_scope: str | None, task_id: str, ttl_seconds: int) -> None```
Store this snapshot as a single Redis key.