{"record":{"id":"db27cecac1eeaa6e","repo":"PrefectHQ/fastmcp","slug":"fastmcp-server-instance-is-no-longer-available","errorCode":null,"errorMessage":"FastMCP server instance is no longer available","messagePattern":"FastMCP server instance is no longer available","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"fastmcp_slim/fastmcp/server/dependencies.py","lineNumber":481,"sourceCode":"\n    Returns:\n        The active FastMCP server\n\n    Raises:\n        RuntimeError: If no server in context\n    \"\"\"\n    resolver = _worker_server_resolver\n    if resolver is not None:\n        worker_server = resolver()\n        if worker_server is not None:\n            return worker_server\n\n    server_ref = _current_server.get()\n    if server_ref is None:\n        raise RuntimeError(\"No FastMCP server instance in context\")\n    server = server_ref()\n    if server is None:\n        raise RuntimeError(\"FastMCP server instance is no longer available\")\n    return server\n\n\nasync def get_session(session_id: str) -> Session:\n    \"\"\"Resolve and validate a `Session` for an explicit `session_id`.\n\n    Pair with a `session_id: SessionId` tool argument (the agent obtains an id\n    from `create_session` and passes it back). For a single per-user bucket with\n    nothing for the agent to pass, inject `session: UserSession` instead.\n\n    State is keyed by `(principal, session_id)`: the authenticated principal is\n    the isolation wall and `session_id` organizes sessions within it. The id must\n    have been minted by `create_session` under the current principal; an id that\n    was never created, or created under a different principal, raises\n    `InvalidSession` rather than resolving to a fresh empty bucket (the specific\n    reason is logged at debug level, never returned to the caller).\n\n    Like `get_server()`, this resolves through the task-aware server, so it needs","sourceCodeStart":463,"sourceCodeEnd":499,"githubUrl":"https://github.com/PrefectHQ/fastmcp/blob/1f021142978e0861cd910c8df4e8074bc7cf3978/fastmcp_slim/fastmcp/server/dependencies.py#L463-L499","documentation":"get_server() stores the server as a weak reference. This RuntimeError is thrown when the reference exists but the referent has been garbage-collected — i.e. the server was set in the contextvar and later deleted while code still holds the context. It is distinct from the 'no server in context' case: a server was active, but its lifetime ended.","triggerScenarios":"Calling get_server() after the FastMCP instance that set _current_server was garbage-collected — e.g. a temporary server object created inside a function went out of scope while an async task referencing it continues running.","commonSituations":"Background tasks outliving a short-lived server instance; building a server in a local scope and returning only a reference to a handler; holding contextvars across server teardown in tests.","solutions":["Keep a strong reference to the FastMCP instance for as long as dependent code runs (module-level or app-lifetime variable).","Ensure background tasks complete (await them) before the server object goes out of scope.","Set the server contextvar again around the work if it must run after the original context ended."],"exampleFix":"// before\ndef make():\n    mcp = FastMCP(\"x\")\n    asyncio.create_task(worker())  # mcp can be GC'd\n    return None\n// after\nMCP = FastMCP(\"x\")  # module-level strong ref\nasyncio.create_task(worker())","handlingStrategy":"type-guard","validationCode":null,"typeGuard":"server = None\ntry:\n    server = get_server()\nexcept RuntimeError:\n    server = None\nif server is None:\n    # weakref died or no context: rebuild or fail explicitly\n    raise RuntimeError(\"server unavailable; keep a strong reference\")","tryCatchPattern":"try:\n    server = get_server()\nexcept RuntimeError:\n    server = default_server  # module-level strong reference","preventionTips":["Hold a strong module-level reference to the FastMCP instance","Await background tasks before the server scope ends","Avoid creating servers in local scopes consumed elsewhere"],"tags":["context","lifecycle","garbage-collection"],"backgroundTag":"weakref-target-collected","analyzedSha":"1f021142978e0861cd910c8df4e8074bc7cf3978","analyzedAt":"2026-08-29T14:31:16.082Z","schemaVersion":2},"datasetVersion":"2026-08-29T17:17:51.833Z"}