π The fast, Pythonic way to build MCP servers and clients.
Session-in-task Context API, task telemetry, settings dotenv, guard fail-loud
Jeremiah Lowin76c6f1a64e6a
diff --git a/docs/more/settings.mdx b/docs/more/settings.mdxindex e602f0c0d..8395b8900 100644--- a/docs/more/settings.mdx+++ b/docs/more/settings.mdx@@ -63,7 +63,7 @@ These control how the server listens when running with an HTTP transport.|---|---|---|---|| `FASTMCP_CLIENT_INIT_TIMEOUT` | `float \| None` | None | Timeout in seconds for the client initialization handshake. Set to `0` or leave unset to disable. || `FASTMCP_CLIENT_DISCONNECT_TIMEOUT` | `float` | `5` | Maximum time in seconds to wait for a clean disconnect before giving up. |-| `FASTMCP_CLIENT_TASK_POLL_INTERVAL` | `float` | `0.5` | Ceiling in seconds for the fallback poll backoff while waiting on a [background task](/servers/tasks). Applies **only** when the server does not advertise its own `pollInterval`: in that case `Task.wait()` starts polling fast (~20ms) and doubles up to this ceiling rather than polling at a fixed cadence. When the server advertises a `pollInterval`, that interval is honored exactly and this setting is ignored. |+| `FASTMCP_TASKS_CLIENT_POLL_INTERVAL` | `float` | `0.5` | Ceiling in seconds for the fallback poll backoff while waiting on a [background task](/servers/tasks). Requires the `fastmcp-tasks` package. Applies **only** when the server does not advertise its own `pollInterval`: in that case `Task.wait()` starts polling fast (~20ms) and doubles up to this ceiling rather than polling at a fixed cadence. When the server advertises a `pollInterval`, that interval is honored exactly and this setting is ignored. || `FASTMCP_CLIENT_RAISE_FIRST_EXCEPTIONGROUP_ERROR` | `bool` | `true` | When an `ExceptionGroup` is raised, re-raise the first error directly instead of the group. Simplifies debugging but may mask secondary errors. |## CLI & Displaydiff --git a/fastmcp_slim/fastmcp/server/context.py b/fastmcp_slim/fastmcp/server/context.pyindex 34067a8fa..c0977e7aa 100644--- a/fastmcp_slim/fastmcp/server/context.py+++ b/fastmcp_slim/fastmcp/server/context.py@@ -793,6 +793,15 @@ class Context:elif self._session is not None:session = self._sessionelse:+ # Background task: no live session, but the submitting request's+ # stable session id was captured in the task snapshot. Use it so+ # session-scoped state (session_id / get_state / set_state) keeps+ # working in a worker, keyed to the same client that submitted.+ from fastmcp.server.dependencies import _background_task_session_id++ task_session_id = _background_task_session_id.get()+ if task_session_id is not None:+ return task_session_idraise RuntimeError("session_id is not available because no session exists. ""This typically means you're outside a request context."diff --git a/fastmcp_slim/fastmcp/server/dependencies.py b/fastmcp_slim/fastmcp/server/dependencies.pyindex 291e63f2b..32d8ba183 100644--- a/fastmcp_slim/fastmcp/server/dependencies.py+++ b/fastmcp_slim/fastmcp/server/dependencies.py@@ -223,6 +223,16 @@ _background_task_headers: ContextVar[dict[str, str] | None] = ContextVar()+#: The originating request's stable session id, carried into a background task.+#: A worker has no live session, so ``Context.session_id`` (and the session-scoped+#: ``get_state``/``set_state`` built on it) would otherwise raise. The tasks+#: extension sets this from the task snapshot so session-scoped state keyed by the+#: submitting client survives into the worker.+_background_task_session_id: ContextVar[str | None] = ContextVar(+ "fastmcp_background_task_session_id", default=None+)++# --- Docket availability check ---_DOCKET_AVAILABLE: bool | None = Nonediff --git a/fastmcp_tasks/fastmcp_tasks/client.py b/fastmcp_tasks/fastmcp_tasks/client.pyindex 78744acb1..82c9041d2 100644--- a/fastmcp_tasks/fastmcp_tasks/client.py+++ b/fastmcp_tasks/fastmcp_tasks/client.py@@ -33,7 +33,9 @@ from mcp.client.session import ClientRequestContext, ClientSession, ElicitationFfrom mcp_types import CallToolResultfrom mcp_types.version import MODERN_PROTOCOL_VERSIONS+from fastmcp.client.telemetry import client_spanfrom fastmcp.exceptions import ToolError+from fastmcp.telemetry import inject_trace_contextfrom fastmcp.utilities.logging import get_loggerfrom fastmcp.utilities.tasks import TASKS_EXTENSION_IDfrom fastmcp.utilities.timeout import normalize_timeout_to_seconds@@ -69,16 +71,31 @@ _TERMINAL_STATES = frozenset({"completed", "failed", "cancelled"})# ---------------------------------------------------------------------------+def _trace_meta() -> mcp_types.RequestParamsMeta | None:+ """Trace context for a task management request, for the current client span.++ Task management calls (`tasks/get`/`update`/`cancel`) use ordinary+ client-to-server trace propagation, so their server-side spans nest under+ the client span rather than becoming disconnected trace roots.+ """+ return cast("mcp_types.RequestParamsMeta | None", inject_trace_context(None))++async def _send_get(session: ClientSession,task_id: str,read_timeout_seconds: float | None = None,) -> ClientGetTaskResult:"""Send `tasks/get` and parse the detailed task response."""- request = GetTaskRequest(params=GetTaskRequestParams(task_id=task_id))- return await session.send_request(- request, ClientGetTaskResult, request_read_timeout_seconds=read_timeout_seconds- )+ with client_span("tasks/get", "tasks/get", task_id):+ request = GetTaskRequest(+ params=GetTaskRequestParams(task_id=task_id, meta=_trace_meta())+ )+ return await session.send_request(+ request,+ ClientGetTaskResult,+ request_read_timeout_seconds=read_timeout_seconds,+ )async def _send_update(@@ -88,12 +105,15 @@ async def _send_update(read_timeout_seconds: float | None = None,) -> None:"""Send `tasks/update` delivering the caller's answers to a parked task."""- request = UpdateTaskRequest(- params=UpdateTaskRequestParams(task_id=task_id, input_responses=input_responses)- )- await session.send_request(- request, mcp_types.Result, request_read_timeout_seconds=read_timeout_seconds- )+ with client_span("tasks/update", "tasks/update", task_id):+ request = UpdateTaskRequest(+ params=UpdateTaskRequestParams(+ task_id=task_id, input_responses=input_responses, meta=_trace_meta()+ )+ )+ await session.send_request(+ request, mcp_types.Result, request_read_timeout_seconds=read_timeout_seconds+ )async def _send_cancel(@@ -102,10 +122,13 @@ async def _send_cancel(read_timeout_seconds: float | None = None,) -> None:"""Send `tasks/cancel` to cooperatively cancel a task."""- request = CancelTaskRequest(params=CancelTaskRequestParams(task_id=task_id))- await session.send_request(- request, mcp_types.Result, request_read_timeout_seconds=read_timeout_seconds- )+ with client_span("tasks/cancel", "tasks/cancel", task_id):+ request = CancelTaskRequest(+ params=CancelTaskRequestParams(task_id=task_id, meta=_trace_meta())+ )+ await session.send_request(+ request, mcp_types.Result, request_read_timeout_seconds=read_timeout_seconds+ )# ---------------------------------------------------------------------------@@ -522,16 +545,19 @@ async def call_tool_task(fastmcp_meta = dict(combined_meta.get("fastmcp") or {})fastmcp_meta["version"] = versioncombined_meta["fastmcp"] = fastmcp_meta- request_meta = cast("mcp_types.RequestParamsMeta | None", combined_meta or None)- raw = await client._await_with_session_monitoring(- client.session.call_tool(- name=name,- arguments=arguments or {},- read_timeout_seconds=read_timeout_seconds,- meta=request_meta,- allow_claimed=True,+ with client_span("tools/call", "tools/call", name, tool_name=name):+ # Propagate the trace into the tasked submission, like a foreground call.+ propagated = inject_trace_context(combined_meta)+ request_meta = cast("mcp_types.RequestParamsMeta | None", propagated or None)+ raw = await client._await_with_session_monitoring(+ client.session.call_tool(+ name=name,+ arguments=arguments or {},+ read_timeout_seconds=read_timeout_seconds,+ meta=request_meta,+ allow_claimed=True,+ ))- )if isinstance(raw, ClientCreateTaskResult):return ToolTask(client, name, raw, raise_on_error=raise_on_error)raise ToolError(diff --git a/fastmcp_tasks/fastmcp_tasks/context.py b/fastmcp_tasks/fastmcp_tasks/context.pyindex 8a9c421b7..6a4c8b514 100644--- a/fastmcp_tasks/fastmcp_tasks/context.py+++ b/fastmcp_tasks/fastmcp_tasks/context.py@@ -489,7 +489,10 @@ def _apply_snapshot_to_context(snapshot: TaskContextSnapshot) -> None:from mcp.server.auth.middleware.bearer_auth import AuthenticatedUserfrom fastmcp.server.auth import AccessToken- from fastmcp.server.dependencies import _background_task_headers+ from fastmcp.server.dependencies import (+ _background_task_headers,+ _background_task_session_id,+ )user: AuthenticatedUser | None = Noneif snapshot.access_token_json is not None:@@ -505,6 +508,7 @@ def _apply_snapshot_to_context(snapshot: TaskContextSnapshot) -> None:_background_task_headers.set(dict(snapshot.http_headers) if snapshot.http_headers else None)+ _background_task_session_id.set(snapshot.session_id)async def make_task_context() -> Context | None:diff --git a/fastmcp_tasks/fastmcp_tasks/input_loop.py b/fastmcp_tasks/fastmcp_tasks/input_loop.pyindex c8a9f1740..07145d5bf 100644--- a/fastmcp_tasks/fastmcp_tasks/input_loop.py+++ b/fastmcp_tasks/fastmcp_tasks/input_loop.py@@ -151,10 +151,25 @@ def reentrant_task_fn(requests = input_required.input_requests or {}request_state = input_required.request_state- if not requests and request_state is None:- # A leg that asks nothing and carries nothing can never be answered;- # treat it as the terminal result rather than an unanswerable park.- return result+ if not requests:+ if request_state is None:+ # Asks nothing and carries nothing β terminal, not a park.+ return result+ # State-only round: foreground re-invokes the tool after a backoff,+ # carrying `request_state` forward with no client interaction. The+ # tasked path has no self-continuation for that yet, so parking it+ # (with no requests for the client to answer) would strand the task.+ # Fail loudly rather than silently report a wrong completed result.+ return _error_result(+ tool_name,+ FastMCPError(+ "A background task returned a state-only "+ "InputRequiredResult (request_state with no input_requests). "+ "Checkpoint-style rounds that carry state without asking the "+ "client anything are not yet supported for tasks; include at "+ "least one input request, or run the tool synchronously."+ ),+ )task_context = get_task_context()docket = _resolve_docket()diff --git a/fastmcp_tasks/fastmcp_tasks/settings.py b/fastmcp_tasks/fastmcp_tasks/settings.pyindex 294f0d280..b836b0f67 100644--- a/fastmcp_tasks/fastmcp_tasks/settings.py+++ b/fastmcp_tasks/fastmcp_tasks/settings.py@@ -139,6 +139,7 @@ class TasksClientSettings(BaseSettings):model_config = SettingsConfigDict(env_prefix="FASTMCP_TASKS_CLIENT_",+ env_file=_ENV_FILE,extra="ignore",)diff --git a/tests/tasks/client/test_task_tracing.py b/tests/tasks/client/test_task_tracing.pynew file mode 100644index 000000000..6d9c9bd70--- /dev/null+++ b/tests/tasks/client/test_task_tracing.py@@ -0,0 +1,32 @@+"""Client OpenTelemetry tracing for the task management wire calls.++Task submission and the `tasks/get`/`update`/`cancel` polling requests each get+a FastMCP client span and propagate trace context, so a tasked call is traced+end to end the same way a synchronous one is β its server spans nest under the+client spans rather than starting fresh trace roots.+"""++from __future__ import annotations++from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter++from fastmcp import Client, FastMCP+from fastmcp_tasks import TasksExtension+++async def test_tasked_call_creates_client_spans(trace_exporter: InMemorySpanExporter):+ mcp = FastMCP("traced-tasks")+ mcp.add_extension(TasksExtension())++ @mcp.tool(task=True)+ async def double(n: int) -> int:+ return n * 2++ async with Client(mcp, mode="auto") as client:+ result = await client.call_tool("double", {"n": 21})+ assert result.data == 42++ names = [s.name for s in trace_exporter.get_finished_spans()]+ # The tasked submission and at least one poll each produced a client span.+ assert "tools/call double" in names+ assert "tasks/get" in namesdiff --git a/tests/tasks/server/test_guard_reentrant.py b/tests/tasks/server/test_guard_reentrant.pyindex 463de404b..5adad9c32 100644--- a/tests/tasks/server/test_guard_reentrant.py+++ b/tests/tasks/server/test_guard_reentrant.py@@ -217,3 +217,30 @@ def test_reentrant_wrapper_preserves_signature():wrapped = reentrant_task_fn(fn, "fn")assert list(inspect.signature(wrapped).parameters) == ["n", "ctx"]+++async def test_state_only_guard_round_fails_clearly():+ """A state-only guard round (request_state, no input_requests) fails loudly.++ Foreground, the client re-invokes such a round after a backoff. The tasked+ path has no self-continuation for it, so rather than silently completing with+ a wrong result it surfaces an actionable error.+ """+ mcp = FastMCP("guard-state-only")+ mcp.add_extension(TasksExtension())++ @mcp.tool(task=True)+ async def checkpoint(ctx: Context) -> str | mcp_types.InputRequiredResult:+ if ctx.request_state is None:+ return _input_required({}, request_state="carried")+ return "done"++ async with running_task_server(mcp):+ final = await wait_for_task(+ mcp, (await submit_task(mcp, "checkpoint", {})).task_id+ )++ assert final.status == "completed"+ assert final.result is not None+ assert final.result["isError"] is True+ assert "state-only" in final.result["content"][0]["text"]diff --git a/tests/tasks/server/test_task_dependencies.py b/tests/tasks/server/test_task_dependencies.pyindex 0eec0e8b5..847b902d5 100644--- a/tests/tasks/server/test_task_dependencies.py+++ b/tests/tasks/server/test_task_dependencies.py@@ -17,7 +17,7 @@ import pytestfrom fastmcp_tasks.dependencies import CurrentDocketfrom uncalled_for import Depends-from fastmcp import FastMCP+from fastmcp import Context, FastMCPfrom fastmcp.server.auth import AccessTokenfrom fastmcp.server.dependencies import CurrentFastMCPfrom fastmcp.server.sessions import UserSession@@ -246,3 +246,31 @@ async def test_user_session_state_persists_across_task_calls():assert second.result["structuredContent"]["result"] == ["apples", "pears"]# Bob is a distinct principal β isolated bucket.assert other.result["structuredContent"]["result"] == ["figs"]+++async def test_ctx_session_state_works_in_background_task():+ """`ctx.session_id` and `ctx.get_state`/`set_state` work inside a worker.++ A worker has no live session, so the Context-level session API falls back to+ the stable session id captured in the task snapshot. Session-scoped state a+ task writes is therefore keyed to the submitting client and readable back.+ """+ mcp = FastMCP("ctx-session-task")+ mcp.add_extension(TasksExtension())++ @mcp.tool(task=True)+ async def stash(value: str, ctx: Context) -> dict[str, object]:+ await ctx.set_state("stashed", value)+ return {+ "session_id": ctx.session_id,+ "read_back": await ctx.get_state("stashed"),+ }++ async with running_task_server(mcp):+ final = await run_task(mcp, "stash", {"value": "hello"})++ assert final.status == "completed"+ assert final.result is not None+ structured = final.result["structuredContent"]+ assert structured["read_back"] == "hello"+ assert isinstance(structured["session_id"], str) and structured["session_id"]