Repository navigation
Description
[Bug] Shared() dependencies become request-scoped without pydocket, and direct call_tool crashes with pydocket
Summary
Shared() is app-scoped: a dependency is resolved once and reused across calls. The repo's own tests pin this (tests/server/test_dependencies.py::TestSharedDependencies::test_shared_sync_function asserts call_count == 1 after two client calls; test_shared_async_context_manager asserts the context manager is entered once).
Context.__aenter__ decides whether to create a fallback SharedContext from pydocket availability, not from whether an app-scoped context is already active (fastmcp_slim/fastmcp/server/context.py:286):
if not is_docket_available():
# Without docket, the lifespan won't provide a SharedContext,
# so create one scoped to this Context for Shared() dependencies.
self._shared_context = SharedContext()
await self._shared_context.__aenter__()The comment's premise is false in both directions:
- The server lifespan always enters an app-scoped
SharedContext(fastmcp_slim/fastmcp/server/mixins/lifespan.py:80), andFastMCPServerMiddleware._apply_shared_contextre-applies that snapshot for every request (fastmcp_slim/fastmcp/server/low_level.py:303). On a default install,is_docket_available()isFalse— the publishedfastmcpdepends onfastmcp-slim[client,server]; pydocket only comes with thetasksextra — so every request shadows the app-scoped context with a fresh per-request one. - With pydocket installed the branch is skipped. A direct
await mcp.call_tool(...)(documented as "the public API for executing tools",fastmcp_slim/fastmcp/server/server.py:1365-1367) that runs without a server lifespan then has noSharedContext;Shared()resolution raisesLookupErroron theshared_resolvedContextVar, surfaced asToolError: Failed to resolve dependency ....
User impact. On the default published install, "shared" dependencies (DB pools, HTTP clients, context managers) are re-created and torn down on every request. With the tasks extra installed, calling a tool directly (as middleware and tools-calling-tools do) crashes — the same code works when pydocket is absent. The behavior depends on an unrelated optional dependency.
This also shows up in the repo's own suite: with is_docket_available() forced to False (the value computed on a default install), tests/server/test_dependencies.py::TestSharedDependencies is 7 failed, 1 passed; test_shared_sync_function fails at assert call_count == 1 with assert 2 == 1.
Repro
# repro_shared.py
import asyncio
from contextlib import asynccontextmanager
from fastmcp import Client, FastMCP
from fastmcp.dependencies import Shared
from fastmcp.server.dependencies import is_docket_available
class Connection:
def __init__(self, n: int) -> None:
self.n = n
self.open = False
async def __aenter__(self):
self.open = True
return self
async def __aexit__(self, *exc):
self.open = False
counts = {"factory": 0, "enter": 0, "exit": 0}
def build_server() -> FastMCP:
mcp = FastMCP("shared-repro")
def get_config() -> dict[str, str]:
counts["factory"] += 1
return {"key": f"value-{counts['factory']}"}
@asynccontextmanager
async def get_connection():
counts["enter"] += 1
conn = Connection(counts["enter"])
async with conn:
yield conn
counts["exit"] += 1
@mcp.tool()
async def factory_tool(config: dict[str, str] = Shared(get_config)) -> str:
return config["key"]
@mcp.tool()
async def cm_tool(conn: Connection = Shared(get_connection)) -> str:
return f"conn-{conn.n}"
return mcp
async def main() -> None:
print(f"is_docket_available(): {is_docket_available()}")
async with Client(build_server()) as client:
print("factory_tool:", (await client.call_tool("factory_tool", {})).content[0].text)
print("factory_tool:", (await client.call_tool("factory_tool", {})).content[0].text)
print("cm_tool:", (await client.call_tool("cm_tool", {})).content[0].text)
print("cm_tool:", (await client.call_tool("cm_tool", {})).content[0].text)
print(f"factory invocations for 2 requests: {counts['factory']}")
print(f"shared context-manager enter/exit for 2 requests: {counts['enter']}/{counts['exit']}")
# Public API for executing a tool; no server lifespan was entered.
try:
await build_server().call_tool("factory_tool", {})
print("direct call_tool: OK")
except Exception as exc:
chain = []
cur: BaseException | None = exc
while cur is not None:
chain.append(f"{type(cur).__name__}: {cur}")
cur = cur.__cause__ or cur.__context__
print("direct call_tool: RAISED " + " <- ".join(chain))
if __name__ == "__main__":
asyncio.run(main())Run once in an environment without pydocket (default install), and once with it (dev install / fastmcp[tasks]):
# no pydocket
uv venv .venv-nodocket
uv pip install --python .venv-nodocket/bin/python -e "fastmcp_slim[server,client]"
.venv-nodocket/bin/python repro_shared.py
# pydocket installed
.venv/bin/python repro_shared.pyACTUAL output
No pydocket (default install):
is_docket_available(): False
factory_tool: value-1
factory_tool: value-2
cm_tool: conn-1
cm_tool: conn-2
factory invocations for 2 requests: 2
shared context-manager enter/exit for 2 requests: 2/2
direct call_tool: OK
With pydocket installed:
is_docket_available(): True
factory_tool: value-1
factory_tool: value-1
cm_tool: conn-1
cm_tool: conn-1
factory invocations for 2 requests: 1
shared context-manager enter/exit for 2 requests: 1/1
direct call_tool: RAISED ToolError: Error calling tool 'factory_tool': Failed to resolve dependency 'config' for factory_tool <- RuntimeError: Failed to resolve dependency 'config' for factory_tool <- LookupError: <ContextVar name='shared_resolved' at 0x...>
Expected: the same app-scoped behavior in both installs (2 requests -> 1 factory invocation, 1/1 enter/exit), and direct call_tool working in both.
Suggested fix direction
Choose the fallback by whether a SharedContext is active rather than by is_docket_available() — e.g. try SharedContext.resolved.get() and only create/enter a fresh context on LookupError. That preserves the lifespan's app scope on no-pydocket installs and self-heals direct calls in both installs.
Environment: origin/main at 7f3c53eadf6bb1b7194e00c42551e4db380b3f67.
Activity
Preserve shared dependency scopes without optional tasks (PrefectHQ#5817