Skip to content

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

Add session_id property to Context for session-based data sharing

Jeremiah Lowin942fd5c13e2d
diff --git a/src/fastmcp/server/context.py b/src/fastmcp/server/context.py
index 145b127fe..bbd164515 100644
--- a/src/fastmcp/server/context.py
+++ b/src/fastmcp/server/context.py
@@ -171,6 +171,36 @@ class Context:
"""Get the unique ID for this request."""
return str(self.request_context.request_id)
+ @property
+ def session_id(self) -> str | None:
+ """Get the MCP session ID for HTTP transports.
+
+ Returns the session ID that can be used as a key for session-based
+ data storage (e.g., Redis) to share data between tool calls within
+ the same client session.
+
+ Returns:
+ The session ID for HTTP transports (SSE, StreamableHTTP), or None
+ for stdio and in-memory transports which don't use session IDs.
+
+ Example:
+ ```python
+ @server.tool
+ def store_data(data: dict, ctx: Context) -> str:
+ if session_id := ctx.session_id:
+ redis_client.set(f"session:{session_id}:data", json.dumps(data))
+ return f"Data stored for session {session_id}"
+ return "No session ID available (stdio/memory transport)"
+ ```
+ """
+ try:
+ from fastmcp.server.dependencies import get_http_headers
+ headers = get_http_headers(include_all=True)
+ return headers.get("mcp-session-id")
+ except RuntimeError:
+ # No HTTP context available (stdio/in-memory transport)
+ return None
+
@property
def session(self):
"""Access to the underlying session for advanced usage."""
diff --git a/tests/server/test_context.py b/tests/server/test_context.py
index a41b8b6e3..2c45ddb60 100644
--- a/tests/server/test_context.py
+++ b/tests/server/test_context.py
@@ -86,3 +86,40 @@ class TestParseModelPreferences:
def test_parse_model_preferences_invalid_type(self, context):
with pytest.raises(ValueError):
context._parse_model_preferences(123)
+
+
+class TestSessionId:
+ def test_session_id_with_http_headers(self, context):
+ """Test that session_id returns the value from mcp-session-id header."""
+ mock_headers = {"mcp-session-id": "test-session-123"}
+
+ with patch(
+ "fastmcp.server.dependencies.get_http_headers", return_value=mock_headers
+ ):
+ assert context.session_id == "test-session-123"
+
+ def test_session_id_without_http_headers(self, context):
+ """Test that session_id returns None when no HTTP headers are available."""
+ with patch(
+ "fastmcp.server.dependencies.get_http_headers",
+ side_effect=RuntimeError("No active HTTP request found.")
+ ):
+ assert context.session_id is None
+
+ def test_session_id_with_missing_header(self, context):
+ """Test that session_id returns None when mcp-session-id header is missing."""
+ mock_headers = {"other-header": "value"}
+
+ with patch(
+ "fastmcp.server.dependencies.get_http_headers", return_value=mock_headers
+ ):
+ assert context.session_id is None
+
+ def test_session_id_with_empty_header(self, context):
+ """Test that session_id returns None when mcp-session-id header is empty."""
+ mock_headers = {"mcp-session-id": ""}
+
+ with patch(
+ "fastmcp.server.dependencies.get_http_headers", return_value=mock_headers
+ ):
+ assert context.session_id == "" # Empty string is still returned as-is