{"record":{"id":"612401d2efc3446e","repo":"PrefectHQ/fastmcp","slug":"no-active-context-found-this-can-happen-if-c","errorCode":null,"errorMessage":"No active context found. This can happen if:\n  - Called outside an MCP request handler\n  - Called in a background task before the context was established\nCheck `context.request_context` for None before accessing.","messagePattern":"No active context found\\. This can happen if:\n  - Called outside an MCP request handler\n  - Called in a background task before the context was established\nCheck `context\\.request_context` for None before accessing\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"fastmcp_slim/fastmcp/server/dependencies.py","lineNumber":907,"sourceCode":"    async def __aenter__(self) -> Context:\n        from fastmcp.server.context import _current_context\n\n        # Try foreground context first (normal MCP request)\n        context = _current_context.get()\n        if context is not None:\n            return context\n\n        # In a background-task worker there is no foreground context; the tasks\n        # extension installs a factory that builds and enters a worker Context\n        # from the restored task snapshot. Core has no task engine of its own,\n        # so this is None unless the extension is active.\n        factory = _background_context_factory\n        if factory is not None:\n            background = await factory()\n            if background is not None:\n                return background\n\n        raise RuntimeError(\n            \"No active context found. This can happen if:\\n\"\n            \"  - Called outside an MCP request handler\\n\"\n            \"  - Called in a background task before the context was established\\n\"\n            \"Check `context.request_context` for None before accessing.\"\n        )\n\n    async def __aexit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_value: BaseException | None,\n        traceback: TracebackType | None,\n    ) -> None:\n        from fastmcp.server.context import _current_context\n\n        ctx = _current_context.get()\n        if ctx is not None and ctx.is_background_task:\n            await ctx.__aexit__(exc_type, exc_value, traceback)\n","sourceCodeStart":889,"sourceCodeEnd":925,"githubUrl":"https://github.com/PrefectHQ/fastmcp/blob/1f021142978e0861cd910c8df4e8074bc7cf3978/fastmcp_slim/fastmcp/server/dependencies.py#L889-L925","documentation":"FastMCP exposes a Context dependency that resolves the active per-request MCP context from a contextvar; in background tasks it first consults a snapshot factory (_background_context_factory) captured when the task was spawned. If neither a live request context nor a captured background context exists, entering the context manager raises this RuntimeError. The library throws it because there is genuinely no MCP request in flight, so request-scoped data (session, request_context) cannot be provided.","triggerScenarios":"Calling `with Context() as ctx:` (async) from code running outside an MCP request handler — e.g. in a plain asyncio task, at module import, in tests, or in a background worker spawned without capturing the context.","commonSituations":"Scheduling asyncio.create_task from a tool without the context snapshot mechanism; unit tests calling tool functions directly instead of through a client; logging/telemetry code that touches ctx after the request ended.","solutions":["Only access Context inside code executed as part of an MCP request (tool/resource/prompt handler invoked via a client)","If you must run background work, capture the context snapshot before spawning (FastMCP's background context factory) or pass needed data explicitly as arguments","Guard with `if ctx.request_context is not None` where the API allows, or check availability before entering","In tests, use fastmcp's in-memory Client fixture so handlers run inside a real request context"],"exampleFix":"// before\nasync def cleanup():\n    with Context() as ctx:\n        await ctx.info(\"done\")\n// after\nasync def my_tool(ctx: Context) -> str:\n    await ctx.info(\"done\")  # ctx provided by the request\n    return \"ok\"","handlingStrategy":"type-guard","validationCode":"from fastmcp.server.dependencies import get_http_request, _current_request\n# availability probe\nin_request = _current_request.get() is not None","typeGuard":"def has_active_context() -> bool:\n    from fastmcp.server import dependencies\n    ctx = dependencies._current_context.get(None)\n    return ctx is not None or dependencies._background_context_factory is not None","tryCatchPattern":"try:\n    async with Context() as ctx:\n        await ctx.info(\"working\")\nexcept RuntimeError as e:\n    if \"No active context\" in str(e):\n        logger.warning(\"context unavailable; skipping request-scoped logging\")","preventionTips":["Never construct Context outside request handlers; take it as an injected parameter","For background tasks, capture the context snapshot before spawning the task","Guard optional context use with `ctx.request_context is not None`","In tests, always run handlers through a fastmcp Client fixture"],"tags":["context","asyncio","fastmcp"],"backgroundTag":"no-active-request-context","analyzedSha":"1f021142978e0861cd910c8df4e8074bc7cf3978","analyzedAt":"2026-08-29T14:31:16.082Z","schemaVersion":2},"datasetVersion":"2026-08-29T17:17:51.833Z"}