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
10 changes: 10 additions & 0 deletions .sampo/changesets/mcp-session-transport-rules.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
pypi/posthog: patch
---

MCP analytics sessions now follow the transport rules of the sdk-specs "Session identity" requirement:

- Every sessionless HTTP request gets a `$session_id` of its own. That covers a stateless server without the session middleware, and a request that sends no `Mcp-Session-Id` after another client's request did. Before, these requests shared the process session with every other caller, and an unwired stateless route reported each pod's first request as an `$mcp_initialize`. That fallback is gone, so such a server reports one session per request until the middleware is added. The runtime warning names the fix, and no longer fires for 2026-07-28 requests, which no middleware can group.
- A call's events all use the session resolved when the call arrived, so a stdio call longer than 30 minutes no longer changes session midway.
- A one-client connection's session rotates once 30 or more minutes pass between the end of one tool call and the arrival of the next. A `tools/list` or resource request no longer keeps the session alive.
- The deprecated SSE transport groups a connection's requests by its `session_id` query parameter, read only on a connection that completed a handshake.
17 changes: 8 additions & 9 deletions posthog/mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,8 @@ The MCP SDK answers `initialize` itself, so the SDK observes it from outside:
- **MCP SDK 1.x.x over HTTP**: through `PostHogMcpStatelessSessionMiddleware`, which
`instrument()` adds to the apps it autowires. If you mount the middleware
yourself, pass the server: `app.add_middleware(PostHogMcpStatelessSessionMiddleware, server=mcp)`.
Without it, each pod reports the session's first request as its initialize.
The deprecated SSE transport also uses the session's first request.
Without it, each request is a session of its own and reports no initialize.
The deprecated SSE transport uses the session's first request.
The middleware reads only requests that carry no `Mcp-Session-Id`, so an
`initialize` that reuses an existing session id reports none.
- **MCP SDK 1.x.x over stdio**: from the session's first request. A stdio server
Expand Down Expand Up @@ -497,8 +497,8 @@ server.run(transport="streamable-http") # already wired

Autowiring only affects an app built **after** `instrument()` runs. If you build or
mount the ASGI app before `instrument()`, or in a different module (the common
FastAPI case), the running app gets **no** middleware and every session falls back to
a fragmented per-process id. Add the middleware to your app explicitly:
FastAPI case), the running app gets **no** middleware and every request gets a
`$session_id` of its own. Add the middleware to your app explicitly:

```python
from posthog.mcp import PostHogMcpStatelessSessionMiddleware, get_mcp_session
Expand Down Expand Up @@ -537,8 +537,8 @@ The failure used to be silent. It now surfaces two ways:

- **At `instrument()`**: if `streamable_http_app()` was already called before
`instrument()` ran, so the live app has no middleware.
- **At runtime, once**: the first time a tool call arrives over streamable HTTP and the
session still has to come from this process's memory.
- **At runtime, once**: the first time a request arrives over streamable HTTP with no
session, so it gets a session of its own.

Both go to the logger you pass via `MCPAnalyticsOptions(logger=...)` **and** to the
`posthog.mcp` standard-library logger, so you see them without opting in. Silence them
Expand All @@ -564,6 +564,5 @@ The same installation code continues to support standalone FastMCP 2.x.x and 3.x

Two gaps worth knowing: jlowin's `fastmcp` 2.x.x and 3.x.x don't expose the attribute the
instrument-time check reads, so those servers get the runtime warning only. And the
deprecated SSE transport is excluded. It keys sessions off a query parameter, and the
mint sets a response header an SSE client never replays, so the middleware wouldn't
help it.
deprecated SSE transport needs no middleware: its connection's `session_id` query
parameter groups its requests.
31 changes: 3 additions & 28 deletions posthog/mcp/_instrument_fastmcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
from ._output_instructions import mirror_instructions_into_structured_content
from ._tool_input import get_registered_tool_input_schema
from .logger import log
from .request_headers import read_transport_session_id
from .tools import get_more_tools_result_text

_WRAPPED_FLAG = "__posthog_mcp_wrapped__"
Expand Down Expand Up @@ -91,7 +92,7 @@ async def wrapped(
) -> Any:
client_name, client_version = _client_info(context)
protocol_version = _protocol_version(context)
mcp_session_id = _mcp_session_id(context)
mcp_session_id = read_transport_session_id(_tool_call_request_context(context))
token, client_name, client_version, protocol_version = (
resolve_session_and_client(
mcp_session_id, client_name, client_version, protocol_version
Expand Down Expand Up @@ -263,7 +264,7 @@ async def list_handler(req: Any) -> Any:

client_name, client_version = _low_level_client_info(server)
protocol_version = _low_level_protocol_version(server)
mcp_session_id = _low_level_session_id(server)
mcp_session_id = read_transport_session_id(_low_level_request_context(server))
token, client_name, client_version, protocol_version = (
resolve_session_and_client(
mcp_session_id, client_name, client_version, protocol_version
Expand Down Expand Up @@ -437,18 +438,6 @@ def _low_level_client_info(server: Any) -> Tuple[Optional[str], Optional[str]]:
return None, None


def _low_level_session_id(server: Any) -> Optional[str]:
ctx = _low_level_request_context(server)
try:
request = getattr(ctx, "request", None)
headers = getattr(request, "headers", None)
if headers is not None:
return headers.get("mcp-session-id")
except Exception: # noqa: BLE001
pass
return None


def _low_level_protocol_version(server: Any) -> Optional[str]:
ctx = _low_level_request_context(server)
try:
Expand Down Expand Up @@ -478,17 +467,3 @@ def _protocol_version(context: Any) -> Optional[str]:
except Exception: # noqa: BLE001
pass
return None


def _mcp_session_id(context: Any) -> Optional[str]:
"""Best-effort transport session id (e.g. the ``Mcp-Session-Id`` header on the
streamable-HTTP transport). Returns ``None`` for stdio, where the SDK-generated
session is used instead."""
try:
request = getattr(context.request_context, "request", None)
headers = getattr(request, "headers", None)
if headers is not None:
return headers.get("mcp-session-id")
except Exception: # noqa: BLE001
pass
return None
19 changes: 4 additions & 15 deletions posthog/mcp/_instrument_lowlevel.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
from ._output_instructions import mirror_instructions_into_structured_content
from ._raised_tool_error import raised_tool_error, wrap_error_result
from .logger import log, warn
from .request_headers import read_transport_session_id
from .tools import get_more_tools_result_text

_WRAPPED_FLAG = "__posthog_mcp_wrapped__"
Expand Down Expand Up @@ -127,7 +128,7 @@ def _wrap_resource_request(
async def handler(req: Any) -> Any:
client_name, client_version = _client_info(server)
protocol_version = _protocol_version(server)
mcp_session_id = _mcp_session_id(server)
mcp_session_id = read_transport_session_id(_request_context(server))
token, client_name, client_version, protocol_version = (
resolve_session_and_client(
mcp_session_id, client_name, client_version, protocol_version
Expand Down Expand Up @@ -214,7 +215,7 @@ async def handler(req: Any) -> Any:
)
client_name, client_version = _client_info(server)
protocol_version = _protocol_version(server)
mcp_session_id = _mcp_session_id(server)
mcp_session_id = read_transport_session_id(_request_context(server))
token, client_name, client_version, protocol_version = (
resolve_session_and_client(
mcp_session_id, client_name, client_version, protocol_version
Expand Down Expand Up @@ -495,7 +496,7 @@ async def handler(req: Any) -> Any:

client_name, client_version = _client_info(server)
protocol_version = _protocol_version(server)
mcp_session_id = _mcp_session_id(server)
mcp_session_id = read_transport_session_id(_request_context(server))
token, client_name, client_version, protocol_version = (
resolve_session_and_client(
mcp_session_id, client_name, client_version, protocol_version
Expand Down Expand Up @@ -945,18 +946,6 @@ def _protocol_version(server: Any) -> Optional[str]:
return None


def _mcp_session_id(server: Any) -> Optional[str]:
ctx = _request_context(server)
try:
request = getattr(ctx, "request", None)
headers = getattr(request, "headers", None)
if headers is not None:
return headers.get("mcp-session-id")
except Exception: # noqa: BLE001
pass
return None


def _resolve_local_pointer(schema: Dict[str, Any], ref: str) -> Any:
target: Any = schema
for part in ref[2:].split("/"):
Expand Down
38 changes: 12 additions & 26 deletions posthog/mcp/_instrument_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@
advertised_tool_names,
apply_virtual_tool_injection,
collect_listed_tools,
_is_sse_request,
_to_jsonable,
copy_tools_list_result,
is_first_listing_page,
Expand Down Expand Up @@ -80,9 +79,9 @@
from ._tool_input import get_registered_tool_input_schema
from .asgi import get_mcp_session
from .logger import log
from .request_headers import get_request_headers
from .request_headers import get_request, read_transport_session_id
from .session import handshake_session
from .session_token import SessionTokenPayload, read_mcp_session_header
from .session_token import SessionTokenPayload, decode_session_id
from .tools import (
get_more_tools_result_text,
)
Expand Down Expand Up @@ -184,21 +183,17 @@ def _initialize_session(
A stateful transport has already assigned the id it returns in the
``Mcp-Session-Id`` header; ``ServerSession`` keeps it on its connection and
exposes no public accessor. A stateless one has none: the session comes from
the ``Mcp-Session-Id`` the client sent, which it keeps sending, read the way
:func:`_resolve_ctx` reads it for every later request, or else from the token
our ASGI middleware minted for this response. stdio has neither and resolves
to this process's own session, as its later requests do."""
if _is_sse_request({"ctx": ctx}):
# The SSE transport keys its session on a query parameter that later
# requests do not resolve from: they land in this process's own session.
return None, None
the ``Mcp-Session-Id`` the client sent, which it keeps sending, or the SSE
transport's query parameter, or else from the token our ASGI middleware minted
for this response. stdio has neither and resolves to this process's own
session, as its later requests do."""
connection = getattr(getattr(ctx, "session", None), "_connection", None)
transport_session_id = getattr(connection, "session_id", None)
if isinstance(transport_session_id, str) and transport_session_id:
return transport_session_id, None
token, _, _, _, incoming = _resolve_ctx(ctx)
incoming = read_transport_session_id(ctx, handshake=True)
if incoming:
return incoming, token
return incoming, decode_session_id(incoming)
Comment on lines +194 to +196

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 · Validate the SSE transport before accepting its query session

On MCP 2.x, a stateless Streamable HTTP initialize carrying ?session_id=chosen reaches _initialize_session, where handshake=True accepts the unvalidated query and overrides the middleware-minted token. The handshake uses a caller-chosen analytics session while later calls use the returned token, violating the session identity contract; restrict query reads to verified SSE transport sessions.

request = getattr(ctx, "request", None)
return None, get_mcp_session(request) if request is not None else None

Expand All @@ -211,7 +206,9 @@ async def _record_v2_initialize(
params = dict(ctx.params) if isinstance(ctx.params, Mapping) else {}
await record_initialize(
data,
session=await handshake_session(data, mcp_session_id, token),
session=await handshake_session(
data, mcp_session_id, token, over_http=get_request(ctx) is not None
),
params=params,
result=_to_jsonable(result),
extra={"session_id": mcp_session_id, "ctx": ctx},
Expand Down Expand Up @@ -297,17 +294,6 @@ def _ctx_protocol_version(ctx: Any) -> Optional[str]:
return None


def _ctx_mcp_session_id(ctx: Any) -> Optional[str]:
"""Best-effort transport session id (the ``Mcp-Session-Id`` header on the
legacy era — 2026-07-28 removed it). ``ctx.request`` carries the transport's
HTTP request when there is one; ``None`` on stdio.

Reuses the same header-bag normalisation and case-insensitive lookup the
public ``get_request_headers``/``read_mcp_session_header`` helpers already
provide, instead of a second hand-rolled ``ctx.request.headers`` read."""
return read_mcp_session_header(get_request_headers(ctx))


def _is_internal_dispatch(ctx: Any) -> bool:
"""True when the SDK invoked this handler itself, not for a client request.

Expand All @@ -331,7 +317,7 @@ def _resolve_ctx(
for a request, with token-carried identity backfilled for stateless pods."""
client_name, client_version = _ctx_client_info(ctx)
protocol_version = _ctx_protocol_version(ctx)
mcp_session_id = _ctx_mcp_session_id(ctx)
mcp_session_id = read_transport_session_id(ctx)
token, client_name, client_version, protocol_version = resolve_session_and_client(
mcp_session_id, client_name, client_version, protocol_version
)
Expand Down
Loading
Loading