Skip to content

🚀 The fast, Pythonic way to build MCP servers and clients.

Let context list calls run outside a request (#5903)

Asem ahmed531411e5e176
diff --git a/docs/servers/context.mdx b/docs/servers/context.mdx
index 84c8188a3..ce53dfb37 100644
--- a/docs/servers/context.mdx
+++ b/docs/servers/context.mdx
@@ -70,7 +70,7 @@ async def data_analysis_request(dataset: str, ctx: Context = CurrentContext()) -
- Dependency parameters are automatically excluded from the MCP schema—clients never see them.
- Context methods are async, so your function usually needs to be async as well.
- **Each MCP request receives a new context object.** State set with `ctx.set_state()` is scoped to that request and is not available in subsequent ones. To persist state across requests, use [Session State](/servers/sessions).
-- Context is only available during a request; attempting to use context methods outside a request will raise errors.
+- Context is only available during a request; most context methods raise errors outside a request. `ctx.list_resources()` and `ctx.list_prompts()` are the exceptions: they also work from a bare `Context(fastmcp=server)` or a direct `server.call_tool()` call, where they list every component visible without a session.
### Legacy Type-Hint Injection
diff --git a/fastmcp_slim/fastmcp/server/context.py b/fastmcp_slim/fastmcp/server/context.py
index 4e043b8cc..86d202c22 100644
--- a/fastmcp_slim/fastmcp/server/context.py
+++ b/fastmcp_slim/fastmcp/server/context.py
@@ -339,7 +339,13 @@ class Context:
return await call_next(context)
```
"""
- return fastmcp_request_ctx.get()
+ request_ctx = fastmcp_request_ctx.get()
+ # Outside a live request, _paginate_list binds a stand-in request
+ # context with no session. That is not an MCP session, so report it
+ # as no request context to session consumers.
+ if request_ctx is None or request_ctx.session is None:
+ return None
+ return request_ctx
def client_extension_settings(self, identifier: str) -> dict[str, Any] | None:
"""This request's per-request opt-in settings for an MCP extension.
diff --git a/tests/server/test_context.py b/tests/server/test_context.py
index 17c4544a6..2ec1871b6 100644
--- a/tests/server/test_context.py
+++ b/tests/server/test_context.py
@@ -82,6 +82,32 @@ class TestSessionId:
finally:
fastmcp_request_ctx.reset(token)
+ def test_session_id_raises_when_request_context_has_no_session(self, context):
+ """A request context without a session is not a session: raise RuntimeError."""
+ from fastmcp.server.dependencies import (
+ FastMCPRequestContext,
+ fastmcp_request_ctx,
+ )
+
+ token = fastmcp_request_ctx.set(
+ FastMCPRequestContext(
+ session=None, # ty: ignore[invalid-argument-type]
+ request_id=None,
+ meta=None,
+ request=None,
+ protocol_version="2025-06-18",
+ close_sse_stream=None,
+ lifespan_context={},
+ _srctx=MagicMock(meta=None),
+ )
+ )
+
+ try:
+ with pytest.raises(RuntimeError, match="no session exists"):
+ context.session_id
+ finally:
+ fastmcp_request_ctx.reset(token)
+
class TestContextState:
"""Test suite for Context state functionality."""
@@ -494,6 +520,64 @@ class TestTransportIntegration:
assert result.data == "streamable-http"
+class TestListComponentsOutsideRequest:
+ """`Context.list_resources` and `list_prompts` without a live MCP request."""
+
+ @pytest.fixture
+ def server(self) -> FastMCP:
+ mcp = FastMCP("test")
+
+ @mcp.resource("docs://readme")
+ def readme() -> str:
+ return "readme"
+
+ @mcp.prompt
+ def summarize(text: str) -> str:
+ return f"Summarize: {text}"
+
+ return mcp
+
+ async def test_tool_run_by_call_tool(self, server: FastMCP):
+ @server.tool
+ async def catalog(ctx: Context) -> dict[str, list[str]]:
+ return {
+ "resources": [str(r.uri) for r in await ctx.list_resources()],
+ "prompts": [p.name for p in await ctx.list_prompts()],
+ }
+
+ result = await server.call_tool("catalog", {})
+
+ assert result.structured_content == {
+ "resources": ["docs://readme"],
+ "prompts": ["summarize"],
+ }
+
+ async def test_bare_context(self, server: FastMCP):
+ async with Context(fastmcp=server) as ctx:
+ resources = await ctx.list_resources()
+ prompts = await ctx.list_prompts()
+
+ assert [str(r.uri) for r in resources] == ["docs://readme"]
+ assert [p.name for p in prompts] == ["summarize"]
+
+ async def test_session_middleware_sees_no_request_context(self, server: FastMCP):
+ """The stand-in request context has no session, so PingMiddleware must
+ not start a keepalive task for it."""
+ from fastmcp.server.middleware.ping import PingMiddleware
+
+ ping = PingMiddleware(interval_ms=50)
+ server.add_middleware(ping)
+
+ @server.tool
+ async def catalog(ctx: Context) -> list[str]:
+ return [str(r.uri) for r in await ctx.list_resources()]
+
+ result = await server.call_tool("catalog", {})
+
+ assert result.structured_content == {"result": ["docs://readme"]}
+ assert ping._active_sessions == set()
+
+
class TestContextLogExtra:
async def test_log_extra_with_log_record_attribute_names(self):
"""`extra` keys that collide with LogRecord attributes must not fail the call."""