Repository navigation
fix(mcp): follow the spec's transport session rules - #1308
lucasheriques wants to merge 4 commits into
Conversation
Aligns posthog.mcp with sdk-specs "Session identity" rules 3 and 4 and the manual call step: - Every sessionless HTTP request gets its own session (rule 4). Before, only client-id and handle-free calls did; the rest shared the process session, and the sticky "mcp" branch handed one client's Mcp-Session-Id session to later sessionless callers. The resolver now takes over_http and the sticky branch and last_mcp_session_id are gone. - A tool call resolves its transport/connection session once, on arrival, and every event of the call uses it; a >30-min stdio call no longer rotates midway. - A one-client connection rotates at >= 30 idle minutes, counted from the end of the previous call (every stdio call now touches the connection when it ends). - SSE keeps one session per connection: its session_id query parameter is the transport session, read only on a connection that completed a handshake, so a forged ?session_id on a stateless request still gets a fresh session. - prepare_tool_call(session_id=...) derives the raw transport id or decodes a PostHog token, as instrument() does. Customer-visible: an unwired stateless route no longer reports a first-request $mcp_initialize; each request is its own session (see changeset). Tested: uv run --frozen --extra test pytest posthog/test/mcp -> 996 passed (mcp 1.30); same suite with mcp 2.3 bare -> 798 passed; ruff format/check and mypy baseline clean. New posthog/test/mcp/test_session_rules.py fails before.
…API as is Pre-PR gate fixes (two adversaries, Opus and Sonnet): - A tools/list or resource request on stdio no longer resets or rotates the one-client connection's idle clock: resolve_session_id_with_source takes tool_call, and only a tool call's arrival and end count. - The stateless-wiring warning skips 2026-07-28 requests, which no middleware can group. - Revert the manual prepare_tool_call(session_id=...) derivation: capture_* still sent the raw id, so one dispatcher's events split across two sessions. The manual step API (derivation plus tracked connection keys) is a follow-up. Tested: new tests in test_session_rules.py fail before (listing between calls, 2026-07-28 warning). uv run --frozen --extra test pytest posthog/test/mcp -> 994 passed; mcp 2.3 bare -> 797 passed; ruff, mypy baseline, public API clean.
…t check /simplify pass: SESSIONLESS_PROTOCOL_VERSION replaces two literals, the connection touch reads the arrival's source alone, resolve_session_id keeps its earlier signature, and request_headers unwraps the context in one place. Tested: pytest posthog/test/mcp 994 passed (mcp 1.30), 797 passed (mcp 2.3); ruff, mypy baseline, public API clean.
PR overviewNo security issues were found in this pull request. Reviews
|
There was a problem hiding this comment.
Not approved — this change needs a human reviewer.
Adding the stamphog label gives the same result unless the changed files change.
The deny-list gate refused this pull request because it touches posthog/test/mcp/test_session_token.py, which matches the auth pattern. Because of that match, the tier gate placed the whole change in the never-auto-review tier. The size gate passed, so splitting is not needed for size. The author can ask a human reviewer to look at it. If the session-token test change can stand on its own, it could go in a separate pull request so the rest of the work is reviewed on its own merits.
Gate mechanics and policy version
| Gate | Result | |
|---|---|---|
| prerequisites | ✓ | all clear |
| deny-list | ✗ | matches: auth in posthog/test/mcp/test_session_token.py |
| every_file_attested | ✓ | not a bot PR |
| size | ✓ | 332L, 9F substantive, 632L/16F incl. docs/generated/snapshots — within ceiling |
| tier | ✗ | T2-never because the deny-list matched auth |
| stamphog 2.9.1 | .stamphog/policy.yml @ unknown · reviewed head 5c6cb5a |
There was a problem hiding this comment.
PostHog Review · Standard · reviewed 5c6cb5a: 1 Should fix.
New pushes to this pull request won't start an automatic review. Comment @posthog review to review new changes.
See this review and its findings in PostHog Review. Comment @posthog review --deep for a Deep review. A Deep review takes longer and looks deeper than a Standard review.
| incoming = read_transport_session_id(ctx, handshake=True) | ||
| if incoming: | ||
| return incoming, token | ||
| return incoming, decode_session_id(incoming) |
There was a problem hiding this comment.
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.
SDK performance: posthog-pythonBenchmarks completed. No changes flagged for review. Flags require at least a 5% change in the median and all six pairs agreeing on direction. This is a noise filter, not proof of a performance change or a CI gate. View all results
Values are medians of paired measurements. Not flagged does not mean unchanged. Unavailable means a measurement could not be provided, not zero. Estimated allocation measurements retain their instrumentation uncertainty. RSS measures the whole process, not just SDK allocations; observed peaks are sampled checkpoints. Paired ranges in the diagnostics describe variability, not confidence intervals. Each shard uses its own runner; compare Before PR against With PR within a row, not across shards. Compared 102 metric rows; 102 rows shown in all results. Omitted or shortened data remain in |
💡 Motivation and Context
Every PostHog MCP SDK should follow the sdk-specs "Session identity" requirement (PostHog/sdk-specs#225, merged 2026-11-23). #1193 adds client conversation ids. This PR, stacked on it, aligns the transport rules it left alone.
Mcp-Session-Id, a sticky branch handed that client's session to later sessionless callers.$mcp_tool_calldisagreed.>and counted from any request's arrival, includingtools/list.session_idquery parameter is the transport session, read only on a connection that completed a handshake. A forged?session_idon a stateless request still gets a fresh session, so the veria-ai finding fixed in feat(mcp): group sessions by ChatGPT, Codex and VS Code conversation ids #1193 (3a6d34d) stays fixed.Changes
session.resolve_session_id_with_sourcetakesover_httpandtool_call. A sessionless HTTP request returns a fresh"request"session and never touches shared state. The sticky"mcp"branch andlast_mcp_session_idare gone. Only a tool call's arrival rotates or stamps the stdio clock._is_staleuses>=.ToolCallLifecycle.prime_sessionresolves once and cachesarrival.prepare_sessionlayers the client id or delivered handle on top, and touches the connection when the call ends.request_headers.read_transport_session_idreplaces four per-adapterMcp-Session-Idreaders and adds the handshake-gated SSE query read._is_sse_requestis gone.Customer-visible. A stateless server without
PostHogMcpStatelessSessionMiddlewarenow reports one session per request. It no longer reports a first-request$mcp_initialize. The changeset says so.Dropped from the audit, and why
merge_identitieskeeps a cached identity when identify returns null. posthog-jshandleIdentifydoes the same, so this is cross-SDK behavior, not a python gap. Changing one SDK would split a session across two persons. It belongs in an sdk-specs clarification.prepare_tool_call(session_id=...)passes the raw id through. I implemented derivation, then reverted it.capture_initializeandcapture_tools_liststill send the id unchanged, so one dispatcher's events split across two sessions. The spec's manual step API also wants connection keys the SDK tracks and rotates. Both belong in one follow-up.Known gaps (follow-ups)
initializeposted with a forged?session_idlands its$mcp_initializein a session derived from that value. At the initialize seam an SSE handshake looks the same, since the middleware mints a token for both. Base put that initialize in the process session every client shared.initializeposted with?session_idis not observed by the middleware, which predates this change.💚 How did you test it?
uv run --frozen --extra test pytest posthog/test/mcp: 994 passed on mcp 1.30. The same suite with mcp 2.3 (no fastmcp): 797 passed. CI covers fastmcp 2 and 4.posthog/test/mcp/test_session_rules.py, parameterized. It covers rule 4 per client and after a transport call, listings, arrival sessions on result and error, rotation at the 30-minute boundary measured from the call's end, a listing between calls, SSE query handling per transport shape, and the 2026-07-28 warning. Each fails on 3a6d34d.ruff,mypy(baseline), and the public API snapshot pass.tools/listkept an idle stdio connection alive, the warning fired on 2026-07-28 requests, and the manual API split sessions./simplifynamed the sessionless revision once.📝 Checklist
If releasing new changes
sampo addto generate a changeset file🤖 Agent context
Autonomy: Human-driven (agent-assisted)
Claude Code (Opus) wrote this from a read-only spec-alignment audit across the MCP SDKs, verifying each gap before fixing it. An earlier attempt gated rule 4 on "has a request" and was reverted in #1193, because real SSE lost its session. Reading the SSE query parameter as a transport session, only on a handshaked connection, resolves both that and the forged-parameter case. Pre-PR adversaries ran on Opus and Sonnet. The comment and
/simplifypasses ran on Sonnet.