Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/fastmcp/client/transports.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ def __init__(
if isinstance(sse_read_timeout, int | float):
sse_read_timeout = datetime.timedelta(seconds=float(sse_read_timeout))
self.sse_read_timeout = sse_read_timeout
self.get_session_id_cb = None

def _set_auth(self, auth: httpx.Auth | Literal["oauth"] | str | None):
if auth == "oauth":
Expand Down Expand Up @@ -287,12 +288,18 @@ async def connect_session(
auth=self.auth,
**client_kwargs,
) as transport:
read_stream, write_stream, _ = transport
read_stream, write_stream, get_session_id = transport
self.get_session_id_cb = get_session_id
async with ClientSession(
read_stream, write_stream, **session_kwargs
) as session:
yield session

def get_session_id(self) -> str | None:
if self.get_session_id_cb:
return self.get_session_id_cb()
return None

Comment on lines +298 to +302
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Guard against missing get_session_id_cb to avoid AttributeError before connection

get_session_id assumes self.get_session_id_cb always exists. If a caller invokes get_session_id() before any connect_session() has run, this will raise AttributeError instead of cleanly returning None, which contradicts the intended “id or None” API.

Initialize the callback on construction and check it explicitly:

@@ class StreamableHttpTransport(ClientTransport):
     def __init__(
         self,
         url: str | AnyUrl,
         headers: dict[str, str] | None = None,
         auth: httpx.Auth | Literal["oauth"] | str | None = None,
         sse_read_timeout: datetime.timedelta | float | int | None = None,
         httpx_client_factory: McpHttpClientFactory | None = None,
     ):
@@
         if isinstance(sse_read_timeout, int | float):
             sse_read_timeout = datetime.timedelta(seconds=float(sse_read_timeout))
         self.sse_read_timeout = sse_read_timeout
+        # Session id callback provided by underlying streamablehttp_client transport
+        self.get_session_id_cb = None
@@
     def get_session_id(self) -> str | None:
-        if self.get_session_id_cb:
-            return self.get_session_id_cb()
-        return None
+        """
+        Return the current MCP session id, or None if no session has been established yet.
+        """
+        cb = self.get_session_id_cb
+        if cb is None:
+            return None
+        return cb()

If you want stricter typing, you can additionally annotate the attribute in __init__:

from typing import Callable  # at top of file

self.get_session_id_cb: Callable[[], str | None] | None = None

This keeps the method safe to call at any time while preserving the desired str | None return contract.

🤖 Prompt for AI Agents
In src/fastmcp/client/transports.py around lines 297 to 301, get_session_id()
assumes self.get_session_id_cb exists and can raise AttributeError if called
before connect_session(); initialize self.get_session_id_cb = None in __init__
(and optionally annotate it as Callable[[], str | None] | None after importing
Callable) and change get_session_id() to explicitly check "if
self.get_session_id_cb is not None:" before calling it, returning None otherwise
so the method always returns str | None without raising.

def __repr__(self) -> str:
return f"<StreamableHttpTransport(url='{self.url}')>"

Expand Down
9 changes: 9 additions & 0 deletions tests/client/test_streamable_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,15 @@ async def test_http_headers(streamable_http_server: str):
assert json_result["x-demo-header"] == "ABC"


async def test_session_id_callback(streamable_http_server: str):
"""Test getting mcp-session-id from the transport."""
transport = StreamableHttpTransport(streamable_http_server)
assert transport.get_session_id() is None
async with Client(transport=transport):
session_id = transport.get_session_id()
assert session_id is not None


@pytest.mark.parametrize("streamable_http_server", [True, False], indirect=True)
async def test_greet_with_progress_tool(streamable_http_server: str):
"""Test calling the greet tool."""
Expand Down
Loading