Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Scope FileUpload and session visibility to a stable client on MCP 2026-07-28 (#5651)

nate nowack4ecb5ab7f220
diff --git a/docs/apps/providers/file-upload.mdx b/docs/apps/providers/file-upload.mdx
index f47d2794c..dcd0cb7aa 100644
--- a/docs/apps/providers/file-upload.mdx
+++ b/docs/apps/providers/file-upload.mdx
@@ -69,9 +69,11 @@ Both options default to `None`, keeping files for the server process's lifetime
## Storage scoping
-By default, files are stored in memory and scoped by MCP session ID. Each session gets its own isolated file store β€” files uploaded in one conversation aren't visible in another.
+By default, files are stored in memory and scoped to the client that uploaded them, so one client's files aren't visible to another. How FastMCP identifies that client depends on the protocol version the connection negotiated.
-This works with **stdio**, **SSE**, and **stateful HTTP** transports, where sessions persist across requests.
+On a handshake-era connection (`mode="legacy"`, or a client that predates MCP 2026-07-28), files are scoped by MCP session ID. This works with **stdio**, **SSE**, and **stateful HTTP** transports, where sessions persist across requests.
+
+MCP 2026-07-28 connections, which FastMCP clients negotiate by default, have no session. Files are scoped to the authenticated user instead, the same identity [`UserSession`](/servers/sessions) uses. Without authentication, stdio servers keep one store for the process, because a stdio server serves a single client. An unauthenticated HTTP request carries nothing that identifies its client between requests, so the default storage rejects it with an error rather than sharing files across clients. Add [authentication](/servers/auth/authentication) to the server, or override `_get_scope_key`.
<Warning>
In **stateless HTTP** mode, each request creates a new session object with a new ID. Files stored during one request (e.g. the UI upload) will be invisible to the next request (e.g. the LLM calling `list_files`). You **must** override `_get_scope_key` to use a stable identifier like a user ID from your auth token.
diff --git a/docs/servers/visibility.mdx b/docs/servers/visibility.mdx
index 6b013257b..376424c08 100644
--- a/docs/servers/visibility.mdx
+++ b/docs/servers/visibility.mdx
@@ -386,6 +386,10 @@ async def enable_recent_tools(ctx: Context) -> str:
return "Recent tools enabled"
```
+### Sessions on MCP 2026-07-28
+
+MCP 2026-07-28 connections, which FastMCP clients negotiate by default, have no session. On those connections, session rules are scoped to the authenticated user, the same identity [`UserSession`](/servers/sessions) uses, so they apply to every connection that user makes. Without authentication, stdio servers keep one set of rules for the process, because a stdio server serves a single client. An unauthenticated HTTP request carries nothing that identifies its client between requests, so `enable_components()`, `disable_components()`, and `reset_visibility()` raise an error rather than changing what every client sees.
+
### Automatic Notifications
When session visibility changes, FastMCP automatically sends notifications to that session. Clients receive `ToolListChangedNotification`, `ResourceListChangedNotification`, and `PromptListChangedNotification` so they can refresh their component lists. These notifications go only to the affected session.
diff --git a/fastmcp_slim/fastmcp/apps/file_upload.py b/fastmcp_slim/fastmcp/apps/file_upload.py
index e7edec74b..de6ab0d28 100644
--- a/fastmcp_slim/fastmcp/apps/file_upload.py
+++ b/fastmcp_slim/fastmcp/apps/file_upload.py
@@ -67,6 +67,7 @@ from time import monotonic
from typing import Any
from fastmcp.apps.app import FastMCPApp
+from fastmcp.exceptions import ToolError
from fastmcp.server.context import Context
_TEXT_EXTENSIONS = frozenset(
@@ -118,12 +119,15 @@ class FileUpload(FastMCPApp):
the current ``Context``, giving access to session ID, auth tokens,
and request metadata for partitioning and authorization.
- **Session scoping:** The default storage uses ``ctx.session_id`` to
- isolate files by session. This works with stdio, SSE, and stateful
- HTTP transports. In **stateless HTTP** mode, each request creates a
- new session, so files won't persist across requests. For stateless
- deployments, override the storage methods to partition by a stable
- identifier from the auth context::
+ **Session scoping:** The default storage isolates files by MCP session
+ on handshake-era connections. MCP 2026-07-28 connections have no
+ session, so files are scoped to the authenticated user instead, or
+ shared by the server process on stdio. Unauthenticated 2026-07-28 HTTP
+ requests carry no client identity, so the default storage rejects them.
+ In **stateless HTTP** mode, each request creates a new session, so
+ files won't persist across requests. For stateless deployments,
+ override the storage methods to partition by a stable identifier from
+ the auth context::
class UserScopedUpload(FileUpload):
def on_store(self, files, ctx):
@@ -184,9 +188,13 @@ class FileUpload(FastMCPApp):
def _get_scope_key(self, ctx: Context) -> str:
"""Return the key used to partition file storage.
- Defaults to ``ctx.session_id``, which is stable for stdio, SSE,
- and stateful HTTP. The default ``on_store``/``on_list``/``on_read``
- implementations call this to partition the in-memory store.
+ Defaults to the MCP session on handshake-era connections. A 2026-07-28
+ connection has no session, so files are scoped to the authenticated
+ user, or shared by the server process on stdio, which serves a single
+ client. An unauthenticated 2026-07-28 HTTP request has nothing to scope
+ files to and raises a `ToolError`. The default
+ ``on_store``/``on_list``/``on_read`` implementations call this to
+ partition the in-memory store.
Override to scope by user, tenant, or any other dimension::
@@ -194,9 +202,17 @@ class FileUpload(FastMCPApp):
return ctx.access_token["sub"]
"""
try:
- return ctx.session_id
+ scope = ctx._session_scope_key()
except RuntimeError:
return "__default__"
+ if scope is None:
+ raise ToolError(
+ "File uploads are scoped to a client, and this unauthenticated "
+ "request carries no client identity: MCP 2026-07-28 HTTP "
+ "connections have no session. Add authentication to the server, "
+ "or override FileUpload._get_scope_key."
+ )
+ return scope
def _prune_expired(self, now: float) -> None:
"""Remove expired files while holding the default storage lock."""
diff --git a/fastmcp_slim/fastmcp/server/context.py b/fastmcp_slim/fastmcp/server/context.py
index 921e69a07..5a8ebf3c1 100644
--- a/fastmcp_slim/fastmcp/server/context.py
+++ b/fastmcp_slim/fastmcp/server/context.py
@@ -795,6 +795,31 @@ class Context:
session._fastmcp_state_prefix = session_id # type: ignore[attr-defined] # ty:ignore[unresolved-attribute]
return session_id
+ def _session_scope_key(self) -> str | None:
+ """Key for data that follows one client across requests.
+
+ On a handshake-era connection this is `session_id`. A 2026-07-28
+ connection has no session, so the scope is the authenticated user (the
+ identity `UserSession` keys on) or, on stdio and in-memory transports,
+ the server process, which serves a single client. Returns None for an
+ unauthenticated 2026-07-28 HTTP request, where nothing identifies the
+ client from one request to the next.
+
+ Raises:
+ RuntimeError if no session is available.
+ """
+ if not self._is_modern_protocol():
+ return self.session_id
+
+ from fastmcp.server.sessions import _principal_segment, current_principal
+
+ principal = current_principal()
+ if principal is not None:
+ return f"user:{_principal_segment(principal)}"
+ if self.transport in ("sse", "streamable-http"):
+ return None
+ return "process"
+
@property
def session(self) -> ServerSession:
"""Access to the underlying session for advanced usage.
diff --git a/fastmcp_slim/fastmcp/server/transforms/visibility.py b/fastmcp_slim/fastmcp/server/transforms/visibility.py
index 0e6a7fe5a..664ccd3f4 100644
--- a/fastmcp_slim/fastmcp/server/transforms/visibility.py
+++ b/fastmcp_slim/fastmcp/server/transforms/visibility.py
@@ -311,9 +311,33 @@ if TYPE_CHECKING:
from fastmcp.server.context import Context
+def _visibility_rules_key(context: Context) -> str | None:
+ """State-store key for this client's visibility rules.
+
+ None when the request carries no client identity to scope rules to (an
+ unauthenticated MCP 2026-07-28 HTTP request). Raises RuntimeError when no
+ session is available.
+ """
+ scope = context._session_scope_key()
+ if scope is None:
+ return None
+ return f"{scope}:_visibility_rules"
+
+
async def get_visibility_rules(context: Context) -> list[dict[str, Any]]:
- """Load visibility rule dicts from session state."""
- return await context.get_state("_visibility_rules") or []
+ """Load visibility rule dicts from session state.
+
+ Returns no rules when there is no session or no client identity to scope
+ them to.
+ """
+ try:
+ key = _visibility_rules_key(context)
+ except RuntimeError:
+ return []
+ if key is None:
+ return []
+ result = await context.fastmcp._state_store.get(key=key)
+ return result.value if result is not None else []
async def save_visibility_rules(
@@ -331,7 +355,21 @@ async def save_visibility_rules(
If None, sends notifications for all types (safe default).
If provided, only sends notifications for specified types.
"""
- await context.set_state("_visibility_rules", rules)
+ from fastmcp.server.server import StateValue
+
+ key = _visibility_rules_key(context)
+ if key is None:
+ raise RuntimeError(
+ "Session visibility rules are scoped to a client, and this "
+ "unauthenticated request carries no client identity: MCP "
+ "2026-07-28 HTTP connections have no session. Add authentication "
+ "to the server to scope rules to each user."
+ )
+ await context.fastmcp._state_store.put(
+ key=key,
+ value=StateValue(value=rules),
+ ttl=context._STATE_TTL_SECONDS,
+ )
# Send notifications based on components hint
# Note: MCP has no separate template notification - templates use ResourceListChangedNotification
@@ -373,12 +411,6 @@ def create_visibility_transforms(rules: list[dict[str, Any]]) -> list[Visibility
async def get_session_transforms(context: Context) -> list[Visibility]:
"""Get session-specific Visibility transforms from state store."""
- try:
- # Will raise RuntimeError if no session available
- _ = context.session_id
- except RuntimeError:
- return []
-
rules = await get_visibility_rules(context)
return create_visibility_transforms(rules)
diff --git a/tests/apps/test_file_upload_retention.py b/tests/apps/test_file_upload_retention.py
index 29aaefebf..2ba93dfbf 100644
--- a/tests/apps/test_file_upload_retention.py
+++ b/tests/apps/test_file_upload_retention.py
@@ -23,7 +23,9 @@ def clock(monkeypatch: pytest.MonkeyPatch) -> list[float]:
def scope(name: str) -> Context:
- return Mock(spec=Context, session_id=name)
+ context = Mock(spec=Context, session_id=name)
+ context._session_scope_key.return_value = name
+ return context
async def test_total_size_uses_payload_sizes():
diff --git a/tests/server/test_session_scope.py b/tests/server/test_session_scope.py
new file mode 100644
index 000000000..76436e3b9
--- /dev/null
+++ b/tests/server/test_session_scope.py
@@ -0,0 +1,160 @@
+"""Session-scoped features on MCP 2026-07-28 connections.
+
+A 2026-07-28 connection has no session, so `FileUpload` and per-session
+visibility scope their data to the authenticated user, or to the server
+process on stdio and in-memory transports. An unauthenticated HTTP request
+carries no client identity and is rejected rather than losing data.
+"""
+
+import base64
+
+import pytest
+from mcp.shared.exceptions import MCPError
+
+from fastmcp import Client, Context, FastMCP
+from fastmcp.apps.file_upload import FileUpload
+from fastmcp.exceptions import ToolError
+from fastmcp.server.auth.providers.jwt import StaticTokenVerifier
+from fastmcp.utilities.tests import run_server_async
+
+UPLOAD = {
+ "name": "a.txt",
+ "size": 5,
+ "type": "text/plain",
+ "data": base64.b64encode(b"hello").decode(),
+}
+
+
+def build_server(auth: StaticTokenVerifier | None = None) -> FastMCP:
+ server = FastMCP("scope", auth=auth)
+ server.add_provider(FileUpload())
+
+ @server.tool
+ async def hide_secret(ctx: Context) -> str:
+ await ctx.disable_components(names={"secret"})
+ return "hidden"
+
+ @server.tool
+ def secret() -> str:
+ return "s"
+
+ return server
+
+
+async def upload_tool_names(client: Client) -> tuple[str, str]:
+ names = {t.name for t in await client.list_tools()}
+ store = next(n for n in names if n.endswith("store_files"))
+ list_files = next(n for n in names if n.endswith("list_files"))
+ return store, list_files
+
+
+async def listed_files(client: Client, list_files: str) -> list[dict]:
+ result = await client.call_tool(list_files, {})
+ assert result.structured_content is not None
+ return result.structured_content["result"]
+
+
+async def secret_visible(client: Client) -> bool:
+ return "secret" in {t.name for t in await client.list_tools()}
+
+
+class TestInMemory:
+ async def test_uploaded_files_persist_across_calls(self):
+ async with Client(build_server()) as client:
+ store, list_files = await upload_tool_names(client)
+ await client.call_tool(store, {"files": [UPLOAD]})
+
+ files = await listed_files(client, list_files)
+
+ assert [f["name"] for f in files] == ["a.txt"]
+
+ async def test_disabled_components_stay_hidden(self):
+ async with Client(build_server()) as client:
+ await client.call_tool("hide_secret", {})
+
+ assert not await secret_visible(client)
+
+
+class TestUnauthenticatedHttp:
+ async def test_upload_is_rejected(self):
+ async with run_server_async(build_server()) as url:
+ async with Client(url) as client:
+ store, _ = await upload_tool_names(client)
+
+ with pytest.raises(ToolError, match="no client identity"):
+ await client.call_tool(store, {"files": [UPLOAD]})
+
+ async def test_disable_components_is_rejected(self):
+ async with run_server_async(build_server()) as url:
+ async with Client(url) as client:
+ with pytest.raises(ToolError, match="no client identity"):
+ await client.call_tool("hide_secret", {})
+
+ assert await secret_visible(client)
+
+ async def test_legacy_session_still_scopes_by_session(self):
+ async with run_server_async(build_server()) as url:
+ async with Client(url, mode="legacy") as client:
+ store, list_files = await upload_tool_names(client)
+ await client.call_tool(store, {"files": [UPLOAD]})
+ await client.call_tool("hide_secret", {})
+
+ files = await listed_files(client, list_files)
+ visible = await secret_visible(client)
+
+ assert [f["name"] for f in files] == ["a.txt"]
+ assert not visible
+
+
+class TestAuthenticatedHttp:
+ @pytest.fixture
+ def verifier(self) -> StaticTokenVerifier:
+ return StaticTokenVerifier(
+ {
+ "token-a": {"client_id": "c", "scopes": [], "sub": "user-a"},
+ "token-b": {"client_id": "c", "scopes": [], "sub": "user-b"},
+ }
+ )
+
+ async def test_uploads_are_scoped_to_the_user(self, verifier: StaticTokenVerifier):
+ async with run_server_async(build_server(auth=verifier)) as url:
+ async with Client(url, auth="token-a") as user_a:
+ store, list_files = await upload_tool_names(user_a)
+ await user_a.call_tool(store, {"files": [UPLOAD]})
+ files_a = await listed_files(user_a, list_files)
+
+ async with Client(url, auth="token-b") as user_b:
+ files_b = await listed_files(user_b, list_files)
+
+ assert [f["name"] for f in files_a] == ["a.txt"]
+ assert files_b == []
+
+ async def test_visibility_rules_are_scoped_to_the_user(
+ self, verifier: StaticTokenVerifier
+ ):
+ async with run_server_async(build_server(auth=verifier)) as url:
+ async with Client(url, auth="token-a") as user_a:
+ await user_a.call_tool("hide_secret", {})
+ visible_to_a = await secret_visible(user_a)
+
+ async with Client(url, auth="token-b") as user_b:
+ visible_to_b = await secret_visible(user_b)
+
+ assert not visible_to_a
+ assert visible_to_b
+
+
+async def test_state_store_failure_is_not_read_as_no_rules(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ server = build_server()
+
+ async def broken_get(**kwargs):
+ raise RuntimeError("store down")
+
+ async with Client(server) as client:
+ await client.call_tool("hide_secret", {})
+ monkeypatch.setattr(server._state_store, "get", broken_get)
+
+ with pytest.raises(MCPError, match="Internal server error"):
+ await client.list_tools()