diff --git a/.sampo/changesets/mcp-session-transport-rules.md b/.sampo/changesets/mcp-session-transport-rules.md new file mode 100644 index 000000000..f4e91089e --- /dev/null +++ b/.sampo/changesets/mcp-session-transport-rules.md @@ -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. diff --git a/posthog/mcp/README.md b/posthog/mcp/README.md index ec4fa667f..d512a2fbe 100644 --- a/posthog/mcp/README.md +++ b/posthog/mcp/README.md @@ -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 @@ -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 @@ -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 @@ -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. diff --git a/posthog/mcp/_instrument_fastmcp.py b/posthog/mcp/_instrument_fastmcp.py index 907f997a3..72c1a04b9 100644 --- a/posthog/mcp/_instrument_fastmcp.py +++ b/posthog/mcp/_instrument_fastmcp.py @@ -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__" @@ -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 @@ -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 @@ -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: @@ -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 diff --git a/posthog/mcp/_instrument_lowlevel.py b/posthog/mcp/_instrument_lowlevel.py index 7ca9caead..c1f3902ba 100644 --- a/posthog/mcp/_instrument_lowlevel.py +++ b/posthog/mcp/_instrument_lowlevel.py @@ -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__" @@ -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 @@ -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 @@ -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 @@ -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("/"): diff --git a/posthog/mcp/_instrument_v2.py b/posthog/mcp/_instrument_v2.py index 9628a43f1..471d2fa0e 100644 --- a/posthog/mcp/_instrument_v2.py +++ b/posthog/mcp/_instrument_v2.py @@ -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, @@ -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, ) @@ -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) request = getattr(ctx, "request", None) return None, get_mcp_session(request) if request is not None else None @@ -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}, @@ -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. @@ -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 ) diff --git a/posthog/mcp/_instrumentation.py b/posthog/mcp/_instrumentation.py index 5e72e7461..e9a590638 100644 --- a/posthog/mcp/_instrumentation.py +++ b/posthog/mcp/_instrumentation.py @@ -66,6 +66,7 @@ ) from ._output_instructions import add_instructions_to_output_schema from .logger import log, warn +from .constants import SESSIONLESS_PROTOCOL_VERSION from .request_headers import get_request from ._sanitization import build_captured_mcp_parameters from ._transport_identity import stamp_transport_identity @@ -82,7 +83,6 @@ PendingCustomEvents, bind_in_tool_session, resolve_anchored_session, - new_session_id, resolve_session_id_with_source, touch_connection_session, ) @@ -429,46 +429,6 @@ def resolve_session_and_client( return token, client_name, client_version, protocol_version -async def prime_session( - data: MCPAnalyticsData, - *, - mcp_session_id: Optional[str], - token: Optional[SessionTokenPayload] = None, - request_session_id: Optional[str] = None, -) -> ResolvedSession: - """Point the shared per-server session at *this* request before the tool body runs. - - ``McpAnalytics.capture()`` reads ``data.session_id`` for custom in-tool - events. The conversation anchor can only be resolved after the call (we - don't know until then whether the agent received the handle), so without - this the tool body would read whatever the *previous* request left behind - and attribute a custom event to the wrong caller. Emits nothing — it only - settles the transport/memory session an in-tool event should belong to. - - A client conversation id never reaches this shared state: it names one chat, - and a concurrent request would read it. A call that carries one is primed - like any other, which also counts its arrival on a one-client connection. - """ - return await resolve_session_id_with_source( - data, mcp_session_id, token=token, request_session_id=request_session_id - ) - - -def _is_sse_request(extra: Optional[Dict[str, Any]]) -> bool: - """True for the deprecated SSE transport, which carries its session as a - ``session_id`` query parameter rather than a header. - - Such a request resolves to a ``generated`` session for a reason the stateless - mint cannot fix -- the mint sets a response header an SSE client never replays -- - so :func:`_warn_stateless_session_not_wired` would be recommending a remedy that - does not apply.""" - try: - params = getattr(get_request(extra), "query_params", None) - return bool(params is not None and params.get("session_id")) - except Exception: # noqa: BLE001 - a transport probe must never break a tool call - return False - - def _warn_stateless_session_not_wired(data: MCPAnalyticsData) -> None: """Warn once per server when a tool call/listing arrives over HTTP but the session still had to come from this process's memory. @@ -483,8 +443,9 @@ def _warn_stateless_session_not_wired(data: MCPAnalyticsData) -> None: data.warned_no_stateless_session = True warn( "Warning: an MCP tool request arrived over streamable HTTP with no session id, so " - "PostHog generated a per-process $session_id that will fragment across requests " - "and pods. This usually means PostHogMcpStatelessSessionMiddleware never attached " + "PostHog generated a $session_id for that request alone, so the client's " + "requests fragment into one session each. This usually means " + "PostHogMcpStatelessSessionMiddleware never attached " "— e.g. the ASGI app was built or mounted before instrument() ran. If you build " "the app yourself, add the middleware explicitly: " "app.add_middleware(PostHogMcpStatelessSessionMiddleware). " @@ -506,7 +467,6 @@ async def prepare_request( protocol_version: Optional[str] = None, conversation_id: Optional[str] = None, client_conversation: Optional[ClientConversation] = None, - request_session_id: Optional[str] = None, ) -> ResolvedSession: """Resolve the session, run identify, then emit initialize if this request has to stand in for an unobserved handshake. Returns the session to stamp on @@ -536,31 +496,41 @@ async def prepare_request( Where a seam observes the real handshake (:func:`record_initialize`), nothing is synthesized here. - A request that reached us over HTTP yet still resolved to this process's memory - has nothing correlating it across pods, which on a stateless server means the - mint middleware never attached — warn once rather than fragment silently.""" + A request that reached us over HTTP with no session has nothing correlating it + with the client's other requests, which on a stateless server means the mint + middleware never attached — warn once rather than fragment silently.""" session = await resolve_session_id_with_source( data, mcp_session_id, token=token, conversation_id=conversation_id, client_conversation=client_conversation, - request_session_id=request_session_id, + over_http=get_request(extra) is not None, ) - if ( - session.source in ("generated", "request") - and get_request(extra) is not None - and not _is_sse_request(extra) - ): + await _open_request( + data, session, client_name, client_version, request, extra, protocol_version + ) + return session + + +async def _open_request( + data: MCPAnalyticsData, + session: ResolvedSession, + client_name: Optional[str], + client_version: Optional[str], + request: Dict[str, Any], + extra: Optional[Dict[str, Any]], + protocol_version: Optional[str], +) -> None: + if session.source == "request" and protocol_version != SESSIONLESS_PROTOCOL_VERSION: _warn_stateless_session_not_wired(data) await handle_identify(data, session.session_id, request, extra) await _maybe_emit_initialize( data, session, client_name, client_version, extra, protocol_version ) - return session -@dataclass(frozen=True) +@dataclass class ToolCallLifecycle: """Common analytics policy for one tool call. @@ -575,7 +545,6 @@ class ToolCallLifecycle: request_meta: Optional[Dict[str, Any]] client: Optional[ClientConversationRow] client_conversation: Optional[ClientConversation] - request_session_id: Optional[str] allow_self_reported_model: bool analytics_owned_parameters: Optional[FrozenSet[str]] request: Dict[str, Any] @@ -599,6 +568,7 @@ class ToolCallLifecycle: pending_custom_events: PendingCustomEvents = field( default_factory=PendingCustomEvents ) + arrival: Optional[ResolvedSession] = None @property def is_missing_capability(self) -> bool: @@ -609,34 +579,47 @@ def is_feedback(self) -> bool: return self.feedback_name is not None and self.name == self.feedback_name async def prepare_session(self, conversation_id: Optional[str]) -> ResolvedSession: - on_one_client_connection = ( - get_request(self.extra) is None - and self.token is None - and not self.mcp_session_id - ) - if self.client_conversation is not None and on_one_client_connection: + arrival = await self.prime_session() + if arrival.source == "generated": await touch_connection_session(self.data) - return await prepare_request( + session = ( + resolve_anchored_session(conversation_id, self.client_conversation) + or arrival + ) + await _open_request( self.data, - mcp_session_id=self.mcp_session_id, - client_name=self.client_name, - client_version=self.client_version, - protocol_version=self.protocol_version, - request=self.request, - extra=self.extra, - token=self.token, - conversation_id=conversation_id, - client_conversation=self.client_conversation, - request_session_id=self.request_session_id, + session, + self.client_name, + self.client_version, + self.request, + self.extra, + self.protocol_version, ) + return session async def prime_session(self) -> ResolvedSession: - return await prime_session( - self.data, - mcp_session_id=self.mcp_session_id, - token=self.token, - request_session_id=self.request_session_id, - ) + """Point the shared per-server session at *this* request before the tool body runs. + + ``McpAnalytics.capture()`` reads ``data.session_id`` for custom in-tool + events. The conversation anchor can only be resolved after the call (we + don't know until then whether the agent received the handle), so without + this the tool body would read whatever the *previous* request left behind + and attribute a custom event to the wrong caller. Emits nothing — it only + settles the transport/memory session an in-tool event should belong to. + + A client conversation id never reaches this shared state: it names one chat, + and a concurrent request would read it. A call that carries one is primed + like any other, which also counts its arrival on a one-client connection. + """ + if self.arrival is None: + self.arrival = await resolve_session_id_with_source( + self.data, + self.mcp_session_id, + token=self.token, + over_http=get_request(self.extra) is not None, + tool_call=True, + ) + return self.arrival @contextmanager def in_tool(self, primed: ResolvedSession) -> Iterator[None]: @@ -858,18 +841,6 @@ def start_tool_call_lifecycle( client_conversation = read_client_conversation(client, request_meta) carries_session = token is not None or bool(mcp_session_id) handle_free = client is not None and client.handle_free - # Over HTTP the process session would mix this call with other clients': one - # its client id groups (an in-tool event reads it before the call), or one a - # handle-free client sends without its id and so with no handle either. Only - # stdio, which has no request, keeps the process session; an SSE-style - # `session_id` query parameter is the caller's to set, so it earns no exemption. - request_session_id = ( - new_session_id() - if (client_conversation is not None or handle_free) - and not carries_session - and get_request(extra) is not None - else None - ) # The client's own id wins, so a handle the agent echoes alongside it is # ignored. A carried session stays stable until the agent supplies its own # handle, and a handle-free client names its conversation itself, so neither @@ -885,7 +856,6 @@ def start_tool_call_lifecycle( request_meta=request_meta, client=client, client_conversation=client_conversation, - request_session_id=request_session_id, allow_self_reported_model=allow_self_reported_model, analytics_owned_parameters=analytics_owned_parameters, request=build_tool_call_request(name, arguments), diff --git a/posthog/mcp/_internal.py b/posthog/mcp/_internal.py index fdbcf3688..b43f5c428 100644 --- a/posthog/mcp/_internal.py +++ b/posthog/mcp/_internal.py @@ -60,7 +60,6 @@ class MCPAnalyticsData: sink: Optional[McpEventSink] = None session_id: str = "" session_source: str = "generated" # "generated" | "mcp" | "token" - last_mcp_session_id: Optional[str] = None # Set once we've warned that an HTTP request resolved with no session id — the # signature of a stateless server whose mint middleware never attached. Warned # a single time per server so the log isn't flooded on every request. diff --git a/posthog/mcp/asgi.py b/posthog/mcp/asgi.py index 8aa34e31a..09fdf43c0 100644 --- a/posthog/mcp/asgi.py +++ b/posthog/mcp/asgi.py @@ -349,7 +349,9 @@ async def _record_initialize( params = _initialize_params(message)[0] await record_initialize( data, - session=await _handshake_session(data, header, decode_session_id(header)), + session=await _handshake_session( + data, header, decode_session_id(header), over_http=True + ), params=params, result=None, extra={"session_id": header, "ctx": _InitializeContext(Request(scope))}, diff --git a/posthog/mcp/constants.py b/posthog/mcp/constants.py index da0225f8d..c06c2c659 100644 --- a/posthog/mcp/constants.py +++ b/posthog/mcp/constants.py @@ -17,6 +17,8 @@ INACTIVITY_TIMEOUT_IN_MINUTES = 30 +SESSIONLESS_PROTOCOL_VERSION = "2026-07-28" + DEFAULT_CONTEXT_PARAMETER_DESCRIPTION = ( "A few words on why you are calling this tool, for the server developer's " 'analytics. Describe people and things by role, such as "a customer". Do not ' diff --git a/posthog/mcp/request_headers.py b/posthog/mcp/request_headers.py index abb478722..09b7f9576 100644 --- a/posthog/mcp/request_headers.py +++ b/posthog/mcp/request_headers.py @@ -33,6 +33,9 @@ def identify(request, extra): from typing import Any, Dict, Optional +from .constants import SESSIONLESS_PROTOCOL_VERSION +from .session_token import read_mcp_session_header + __all__ = ["get_request_headers"] RequestHeaderBag = Dict[str, str] @@ -51,9 +54,7 @@ def get_request(extra: Any) -> Optional[Any]: (e.g. query params) -- one place that knows how to unwrap ``extra``/``ctx`` down to the request, instead of each caller re-deriving it. """ - ctx = extra - if isinstance(extra, dict): - ctx = extra.get("ctx") + ctx = _request_context(extra) if ctx is None: return None return getattr(ctx, "request", None) @@ -72,6 +73,39 @@ def get_request_headers(extra: Any) -> Optional[RequestHeaderBag]: return _to_header_bag(source) +def read_transport_session_id(extra: Any, *, handshake: bool = False) -> Optional[str]: + """The SSE transport checks the ``session_id`` query parameter against its open + streams, while a stateless request never completes a handshake, so adding the + parameter to a request picks no session.""" + header = read_mcp_session_header(get_request_headers(extra)) + if header is not None: + return header + ctx = _request_context(extra) + try: + if not (handshake or _completed_a_handshake(ctx)): + return None + params = getattr(get_request(ctx), "query_params", None) + value = params.get("session_id") if params is not None else None + except Exception: # noqa: BLE001 - a transport probe must never break a tool call + return None + return value if isinstance(value, str) and value else None + + +def _completed_a_handshake(ctx: Any) -> bool: + params = getattr(getattr(ctx, "session", None), "client_params", None) + if params is None: + return False + # mcp 2.x builds client params from a 2026-07-28 request's own envelope. + version = getattr(params, "protocol_version", None) or getattr( + params, "protocolVersion", None + ) + return version != SESSIONLESS_PROTOCOL_VERSION + + +def _request_context(extra: Any) -> Any: + return extra.get("ctx") if isinstance(extra, dict) else extra + + def _to_header_bag(source: Any) -> Optional[RequestHeaderBag]: """Flatten a Starlette ``Headers``, a mapping, or anything iterable of pairs into a lowercase-keyed dict. Never raises: a header read must not take a diff --git a/posthog/mcp/session.py b/posthog/mcp/session.py index 0bc6a3684..de6b8c3c3 100644 --- a/posthog/mcp/session.py +++ b/posthog/mcp/session.py @@ -199,7 +199,6 @@ async def resolve_session_id( token: Optional[SessionTokenPayload] = None, conversation_id: Optional[str] = None, client_conversation: Optional[ClientConversation] = None, - request_session_id: Optional[str] = None, ) -> str: """The session id for this request. See :func:`resolve_session_id_with_source`, which this wraps -- callers that need to know *where* the session came from @@ -210,7 +209,6 @@ async def resolve_session_id( token=token, conversation_id=conversation_id, client_conversation=client_conversation, - request_session_id=request_session_id, ) return session_id @@ -219,6 +217,7 @@ async def handshake_session( data: MCPAnalyticsData, mcp_session_id: Optional[str], token: Optional[SessionTokenPayload], + over_http: bool = False, ) -> ResolvedSession: """The session an ``initialize`` belongs to: the one the client's later requests resolve to through :func:`resolve_session_id_with_source`. @@ -226,14 +225,14 @@ async def handshake_session( A token or a transport session id gives it directly, so this leaves the server's shared session alone. One server serves many clients, and a handshake must not move the session that ``McpAnalytics.capture()`` reads. Without either, the - session is this process's own, which only the resolver can hand out.""" + session is the connection's own, which only the resolver can hand out.""" if token is not None: return ResolvedSession(token.session_id, "token") if mcp_session_id: return ResolvedSession( derive_session_id_from_mcp_session(mcp_session_id), "mcp" ) - return await resolve_session_id_with_source(data, None) + return await resolve_session_id_with_source(data, None, over_http=over_http) async def handshake_session_id( @@ -270,7 +269,8 @@ async def resolve_session_id_with_source( token: Optional[SessionTokenPayload] = None, conversation_id: Optional[str] = None, client_conversation: Optional[ClientConversation] = None, - request_session_id: Optional[str] = None, + over_http: bool = False, + tool_call: bool = False, ) -> ResolvedSession: """Resolve the session id for a request. Mutates per-server state under a lock so concurrent async requests can't race on session rotation. @@ -303,10 +303,6 @@ async def resolve_session_id_with_source( for a request that didn't replay the token would merge unrelated clients under one ``$session_id``. A compliant client replays the header on every request, so a genuine token session never needs the fallback. - - ``request_session_id`` is a session the caller reserved for one HTTP request - in place of process memory, which belongs to a one-client connection and on a - shared HTTP server would group unrelated clients. """ anchored = resolve_anchored_session(conversation_id, client_conversation) if anchored is not None: @@ -326,42 +322,39 @@ async def resolve_session_id_with_source( if mcp_session_id: data.session_id = derive_session_id_from_mcp_session(mcp_session_id) - data.last_mcp_session_id = mcp_session_id data.session_source = "mcp" data.last_activity = now return ResolvedSession(data.session_id, "mcp") - if request_session_id: + if over_http: # One request's own: leaving it out of shared state keeps it from the # next request and from custom events captured outside any call. - return ResolvedSession(request_session_id, "request") - - # Once a session is MCP-derived, keep it even if a later request arrives - # without the MCP session id, so the session doesn't fragment. - if data.session_source == "mcp" and data.last_mcp_session_id: - data.last_activity = now - return ResolvedSession(data.session_id, "mcp") + return ResolvedSession(new_session_id(), "request") # Memory fallback (single-owner transports like stdio). A leftover token # session must NOT leak to a credential-less request, so anything that # isn't already a generated session starts fresh; generated sessions - # persist and roll over on inactivity. - if data.session_source != "generated" or _is_stale(data, now): + # persist and roll over on inactivity between tool calls. + rotate = data.session_source != "generated" or ( + tool_call and _is_stale(data, now) + ) + if rotate: data.session_id = new_session_id() data.session_source = "generated" - data.last_activity = now + if rotate or tool_call: + data.last_activity = now return ResolvedSession(data.session_id, "generated") def _is_stale(data: MCPAnalyticsData, now: datetime) -> bool: timeout_seconds = INACTIVITY_TIMEOUT_IN_MINUTES * 60 - return (now - data.last_activity).total_seconds() > timeout_seconds + return (now - data.last_activity).total_seconds() >= timeout_seconds async def touch_connection_session(data: MCPAnalyticsData) -> None: - """Count a finished call grouped by the client as connection activity, so a - later call without an id does not rotate a live one-client connection's id. - Rotation itself happens when a call arrives (see ``prime_session``). + """Count a finished call as connection activity: idle time runs from the end + of the previous call. Rotation itself happens when a call arrives (see + ``prime_session``). Only for a one-client connection (stdio): on a shared HTTP instance, keeping the instance's own session alive would group unrelated clients' requests.""" diff --git a/posthog/test/mcp/test_client_conversation_session.py b/posthog/test/mcp/test_client_conversation_session.py index 726922bea..32af00116 100644 --- a/posthog/test/mcp/test_client_conversation_session.py +++ b/posthog/test/mcp/test_client_conversation_session.py @@ -686,7 +686,7 @@ async def test_sessionless_http_calls_without_a_client_id_get_their_own_sessions assert bob["properties"]["$set"] == {"bob_only": "present"} assert bob["properties"]["$mcp_session_source"] == "generated" assert _events(client, "$mcp_initialize") == [] - assert data.warned_no_stateless_session is (query is None) + assert data.warned_no_stateless_session is True async def test_a_one_client_connection_keeps_its_session_without_a_client_id(): @@ -1057,12 +1057,11 @@ async def test_a_request_session_leaves_a_transport_session_in_place(): data = MCPAnalyticsData(options=MCPAnalyticsOptions(), session_id="ses_init") transport = await resolve_session_id_with_source(data, "mcp-1") - one_request = await resolve_session_id_with_source( - data, None, request_session_id="ses_one_request" - ) + one_request = await resolve_session_id_with_source(data, None, over_http=True) - assert one_request == ("ses_one_request", "request") - assert await resolve_session_id_with_source(data, None) == transport + assert one_request.source == "request" + assert one_request.session_id != transport.session_id + assert (data.session_id, data.session_source) == transport @pytest.mark.parametrize( diff --git a/posthog/test/mcp/test_initialize_handshake.py b/posthog/test/mcp/test_initialize_handshake.py index 87fe29d78..40576524d 100644 --- a/posthog/test/mcp/test_initialize_handshake.py +++ b/posthog/test/mcp/test_initialize_handshake.py @@ -731,11 +731,9 @@ async def send(method, params, request_id=None): # --- the middleware is per request and fail-safe ----------------------------------- -@pytest.mark.skipif(MCP_MAJOR >= 2, reason="mcp 2.x has no first-request fallback") -async def test_a_route_without_the_middleware_keeps_the_fallback(): +async def test_a_route_without_the_middleware_gives_each_request_its_own_session(): # One process, one server, two routes: the autowired app with the bound - # middleware, and the session manager mounted by hand without it. Each route - # reports its own handshakes, once. + # middleware, and the session manager mounted by hand without it. client = FakeClient() app, lifespan, server = make_pod(client) async with lifespan: @@ -750,12 +748,14 @@ async def test_a_route_without_the_middleware_keeps_the_fallback(): await call_add(lb, headers, 4) await _flush() - inits = _events(client, "$mcp_initialize") - assert len(inits) == 2 + inits = {e["properties"]["$session_id"] for e in _events(client, "$mcp_initialize")} calls = _events(client, "$mcp_tool_call") - assert {c["properties"]["$session_id"] for c in calls} == { - e["properties"]["$session_id"] for e in inits - } + wired, unwired = calls[:2], calls[2:] + (wired_session,) = {c["properties"]["$session_id"] for c in wired} + assert wired_session in inits + unwired_sessions = {c["properties"]["$session_id"] for c in unwired} + assert len(unwired_sessions - inits) == 2 + assert {c["properties"]["$mcp_session_source"] for c in unwired} == {"generated"} async def test_handshake_session_id_keeps_its_public_contract(): diff --git a/posthog/test/mcp/test_session_rules.py b/posthog/test/mcp/test_session_rules.py new file mode 100644 index 000000000..67b6aadf5 --- /dev/null +++ b/posthog/test/mcp/test_session_rules.py @@ -0,0 +1,222 @@ +from datetime import timedelta +from types import SimpleNamespace +from unittest import mock + +import pytest +from freezegun import freeze_time + +from posthog.mcp import McpAnalytics +from posthog.mcp._instrumentation import start_tools_list_lifecycle +from posthog.mcp._internal import set_server_tracking_data +from posthog.mcp import request_headers +from posthog.mcp.session import derive_session_id_from_mcp_session +from posthog.test.mcp._helpers import ( + MCP_MAJOR, + FakeClient, + events_named as _events, + flush_background as _flush, +) +from posthog.test.mcp.test_client_conversation_session import ( + CHATGPT, + CODEX, + OTHER, + FakeServer, + fresh_data, + http_extra, + run_call, + shared_http_server, + start_call, +) + + +def _sessions(client, name="$mcp_tool_call"): + return [ + (e["properties"]["$session_id"], e["properties"]["$mcp_session_source"]) + for e in _events(client, name) + ] + + +@pytest.mark.parametrize("user_agent", [OTHER, CHATGPT, CODEX]) +@pytest.mark.parametrize( + "earlier_transport", [None, "transport-a"], ids=["first", "after a transport call"] +) +async def test_sessionless_http_calls_each_get_their_own_session( + user_agent, earlier_transport +): + client = FakeClient() + _, data = shared_http_server(client, enable_conversation_id=False) + if earlier_transport: + await run_call(data, user_agent=OTHER, mcp_session_id=earlier_transport) + + for user in ("alice", "bob"): + await run_call(data, user_agent=user_agent, user=user) + await _flush() + + alice, bob = _sessions(client)[-2:] + assert alice[0] != bob[0] + assert {alice[1], bob[1]} == {"generated"} + assert derive_session_id_from_mcp_session("transport-a") not in (alice[0], bob[0]) + + +async def test_sessionless_http_listings_each_get_their_own_session(): + client = FakeClient() + _, data = shared_http_server(client) + + for _ in range(2): + lifecycle = await start_tools_list_lifecycle( + data, + request={"method": "tools/list", "params": {}}, + extra=http_extra(OTHER), + mcp_session_id=None, + token=None, + client_name=None, + client_version=None, + protocol_version=None, + ) + await lifecycle.record_result( + names=["search_docs"], result={"tools": []}, duration_ms=1.0, is_empty=False + ) + await _flush() + + first, second = _sessions(client, "$mcp_tools_list") + assert first[0] != second[0] + + +@pytest.mark.parametrize("outcome", ["result", "error"]) +async def test_every_event_of_a_long_call_keeps_its_arrival_session(outcome): + client = FakeClient() + key = FakeServer() + data = fresh_data(client, enable_conversation_id=False) + set_server_tracking_data(key, data) + + call = start_call(data) + arrival = await call.prime_session() + with call.in_tool(arrival): + await McpAnalytics(key).capture("inside_tool") + data.last_activity -= timedelta(minutes=40) + if outcome == "result": + await call.record_result({"content": []}, 1.0, conversation_id_delivered=False) + else: + await call.record_error(RuntimeError("boom"), 1.0) + await _flush() + + assert _sessions(client) == [(arrival.session_id, "generated")] + assert _sessions(client, "inside_tool") == [(arrival.session_id, "generated")] + + +@pytest.mark.parametrize( + ("call_minutes", "idle_minutes", "rotated"), + [(20, 29, False), (0, 29, False), (0, 30, True), (20, 30, True)], + ids=[ + "idle counts from the call's end", + "under 30 idle minutes keeps it", + "30 idle minutes rotates", + "30 idle minutes after a long call rotates", + ], +) +async def test_a_one_client_connection_rotates_after_30_idle_minutes( + call_minutes, idle_minutes, rotated +): + client = FakeClient() + data = fresh_data(client, enable_conversation_id=False) + + with freeze_time("2026-11-25 12:00:00", real_asyncio=True) as clock: + first = start_call(data) + await first.prime_session() + clock.tick(timedelta(minutes=call_minutes)) + await first.record_result({"content": []}, 1.0, conversation_id_delivered=False) + clock.tick(timedelta(minutes=idle_minutes)) + await run_call(data) + await _flush() + + (first_session, _), (second_session, _) = _sessions(client) + assert (first_session != second_session) is rotated + + +async def test_a_listing_does_not_keep_an_idle_connection_alive(): + client = FakeClient() + data = fresh_data(client, enable_conversation_id=False) + + with freeze_time("2026-11-25 12:00:00", real_asyncio=True) as clock: + await run_call(data) + clock.tick(timedelta(minutes=29)) + await start_tools_list_lifecycle( + data, + request={"method": "tools/list", "params": {}}, + extra={}, + mcp_session_id=None, + token=None, + client_name=None, + client_version=None, + protocol_version=None, + ) + clock.tick(timedelta(minutes=29)) + await run_call(data) + await _flush() + + (first, _), (second, _) = _sessions(client) + assert first != second + + +@pytest.mark.skipif(MCP_MAJOR < 2, reason="2026-07-28 requests need mcp 2.x") +async def test_a_2026_07_28_request_does_not_ask_for_the_session_middleware(): + from posthog.test.mcp._helpers_v2 import modern_headers, modern_meta + from posthog.test.mcp.test_initialize_handshake import BASE_HEADERS, call_add, fleet + + client = FakeClient() + headers = {**BASE_HEADERS, **modern_headers("tools/call", "add")} + with mock.patch("posthog.mcp._instrumentation.warn") as warn: + async with fleet(client, pods=1) as lb: + await call_add(lb, headers, 1, _meta=modern_meta()) + await _flush() + + assert _sessions(client)[0][1] == "generated" + warn.assert_not_called() + + +def _request_context(query=None, headers=None, client_params=None): + return SimpleNamespace( + request=SimpleNamespace(headers=headers or {}, query_params=query or {}), + session=SimpleNamespace(client_params=client_params), + ) + + +HANDSHAKE = SimpleNamespace(protocolVersion="2025-06-18") +SSE_ID = "0f1e2d3c4b5a69788796a5b4c3d2e1f0" + + +@pytest.mark.parametrize( + ("ctx", "expected"), + [ + (_request_context(headers={"mcp-session-id": "header-id"}), "header-id"), + (_request_context({"session_id": SSE_ID}, client_params=HANDSHAKE), SSE_ID), + ( + _request_context( + {"session_id": SSE_ID}, + client_params=SimpleNamespace(protocol_version="2025-11-25"), + ), + SSE_ID, + ), + (_request_context({"session_id": SSE_ID}), None), + ( + _request_context( + {"session_id": SSE_ID}, + client_params=SimpleNamespace(protocol_version="2026-07-28"), + ), + None, + ), + (SimpleNamespace(request=None, session=None), None), + (None, None), + ], + ids=[ + "the Mcp-Session-Id header", + "an SSE connection's query parameter", + "an SSE connection's query parameter on mcp 2.x", + "a query parameter on a stateless request", + "a query parameter on a 2026-07-28 request", + "stdio", + "no context", + ], +) +def test_the_transport_session_of_a_request(ctx, expected): + assert request_headers.read_transport_session_id(ctx) == expected diff --git a/posthog/test/mcp/test_session_token.py b/posthog/test/mcp/test_session_token.py index 6e6f9995f..9405c178f 100644 --- a/posthog/test/mcp/test_session_token.py +++ b/posthog/test/mcp/test_session_token.py @@ -19,6 +19,7 @@ from posthog.mcp import logger as logger_module from posthog.mcp._instrumentation import prepare_request from posthog.mcp.logger import set_logger +from posthog.mcp.request_headers import read_transport_session_id from posthog.mcp.session import new_session_id, resolve_session_id from posthog.mcp.session_token import ( MCP_SESSION_HEADER, @@ -803,16 +804,17 @@ async def test_no_warning_when_session_is_anchored_by_conversation_id(): async def test_no_warning_for_sse_transport(): - """The deprecated SSE transport carries its session as a query param, and the - mint sets a response header an SSE client never replays -- so the middleware we - would be recommending cannot help. Stay quiet rather than give wrong advice.""" + """The deprecated SSE transport carries its session as a query param.""" ctx = _http_ctx() ctx.request.query_params = {"session_id": "sse-session-1"} + ctx.session = SimpleNamespace( + client_params=SimpleNamespace(protocolVersion="2025-06-18") + ) with _captured_logs() as logs: await prepare_request( _data(), - mcp_session_id=None, + mcp_session_id=read_transport_session_id(ctx), client_name=None, client_version=None, request={"method": "tools/call", "params": {}}, diff --git a/posthog/test/mcp/test_units.py b/posthog/test/mcp/test_units.py index f5a3546c3..513f45530 100644 --- a/posthog/test/mcp/test_units.py +++ b/posthog/test/mcp/test_units.py @@ -34,6 +34,7 @@ derive_session_id_from_mcp_session, new_session_id, resolve_session_id, + resolve_session_id_with_source, ) from posthog.mcp.types import ( CollectFeedbackOptions, @@ -360,13 +361,6 @@ async def test_resolve_session_id_uses_mcp_session(): assert data.session_source == "mcp" -async def test_resolve_session_id_keeps_mcp_session_without_fragmenting(): - data = _session_data() - first = await resolve_session_id(data, "mcp-abc") - # a later request with no MCP session id must not fragment the session - assert await resolve_session_id(data, None) == first - - async def test_resolve_session_id_no_rollover_within_timeout(): data = _session_data() before = data.session_id @@ -377,8 +371,8 @@ async def test_resolve_session_id_rolls_over_after_inactivity(): data = _session_data() before = data.session_id data.last_activity = datetime.now(timezone.utc) - timedelta(minutes=31) - after = await resolve_session_id(data, None) - assert after != before and data.session_source == "generated" + after = await resolve_session_id_with_source(data, None, tool_call=True) + assert after.session_id != before and data.session_source == "generated" # --- identity cache / merge --------------------------------------------------