Skip to content

[Bug] ctx.debug/info/warning/error raise RuntimeError in background tasks (session is not available) #5799

Closed

Description

@BlueX888

Summary

In a background task (task=True tool running on a SEP-2663 worker), any call to ctx.debug() / ctx.info() / ctx.warning() / ctx.error() raises RuntimeError and aborts the tool body, so the task completes with isError=True and the tool's work is discarded. The worker's Context is built by fastmcp_tasks/context.py::make_task_context as Context(fastmcp=server, session=None, ...) — no live session — but Context.log() (fastmcp_slim/fastmcp/server/context.py:633) unconditionally dereferences self.session to resolve the per-session logging/setLevel gate:

RuntimeError: session is not available because the MCP session has not been established yet. Check `context.request_context` for None before accessing this attribute.

This is an in-class inconsistency: report_progress degrades gracefully in a worker (it flows through the Docket execution), and session_id / set_state / get_state degrade by keying off the submitting session's snapshotted id in _background_task_session_id — only log() raises. So a background task can update state and report progress but cannot log a single line.

Repro

from fastmcp import Context, FastMCP
from fastmcp_tasks import TasksExtension

mcp = FastMCP("repro")
mcp.add_extension(TasksExtension())


@mcp.tool(task=True)
async def double(x: int, ctx: Context) -> int:
    await ctx.info("starting work")  # first logging call aborts the task body
    return x * 2


# Drive it the way a tasks-opted-in client does (same helpers the repo's own
# tests use): enter the lifespan (Docket backend + worker), submit the
# tools/call with the tasks extension, wait for the task.
from tests.tasks.task_helpers import submit_task, wait_for_task

async with mcp._lifespan_manager():
    created = await submit_task(mcp, "double", {"x": 21})
    final = await wait_for_task(mcp, created.task_id)
    print("isError:", final.result["isError"])
    print("content:", final.result["content"][0]["text"])

Output on current main (commit 7f3c53e):

isError: True
content: Error calling tool 'double': session is not available because the MCP session has not been established yet. Check `context.request_context` for None before accessing this attribute.

(Remove the await ctx.info(...) line and the same task completes normally; ctx.report_progress(...) and await ctx.set_state(...) also work fine in the same worker context — only logging raises.)

The fix shape that matches the existing precedents: resolve the session defensively; when none exists, key the level gate on _background_task_session_id (exactly what session_id/set_state/get_state already do), keep mirroring the record to the fastmcp.server.context.to_client logger with the same gating, and skip only the client send_log_message — a worker has no back-channel. In-session logging stays byte-for-byte unchanged.

Activity

  1. added
    bugSomething isn't working. Reports of errors, unexpected behavior, or broken functionality.
    serverRelated to FastMCP server implementation or server-side functionality.
    tasksRelated to background tasks, Docket, SEP-1686.
    on Oct 17, 2026
  2. BlueX888 commented on Oct 19, 2026

    @BlueX888
    ContributorAuthor

    Update: I have an independently verified fix for this at BlueX888:fix/ctx-log-background-session @ ff3c7879, and it now includes the exact logging/setLevel key alignment raised on #5806:

    • TaskContextSnapshot captures _log_level_session_key(live submitting session) — the same key setLevel wrote (connection.session_id, else "__no_session__"), carried forward across nested task capture.
    • The worker restores that exact key via a dedicated ContextVar; a legacy snapshot or hand-built worker Context without it falls back to _log_level_session_key(None) = "__no_session__". HTTP keys stay matched and the live-session path is unchanged.
    • The session-less mirror now reads Logging {LEVEL} server-side: ... instead of claiming to send to a client.
    • Regression tests cover the diverging-snapshot-id scenario (gate registered under __no_session__ but ctx.session_id snapshots a UUID): sub-threshold logs are suppressed with no client-send claim; red at base, green at head. The broader suites pass (441 passed across tasks/server, server context/logs and protocol eras), with ty and ruff clean.

    #5806 covers the base fix but is currently blocked on this same key mismatch. I'm not opening a duplicate PR while it is under review — happy to open a linked PR with this branch if maintainers prefer, or to have the key-capture/test changes carried into #5806 if that's easier.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working. Reports of errors, unexpected behavior, or broken functionality.serverRelated to FastMCP server implementation or server-side functionality.tasksRelated to background tasks, Docket, SEP-1686.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions