Skip to content

feat(mcp): group sessions by ChatGPT, Codex and VS Code conversation ids - #1193

Open
lucasheriques wants to merge 5 commits into
mainfrom
lucas/mcp-client-meta-session
Open

lucasheriques wants to merge 5 commits into
mainfrom
lucas/mcp-client-meta-session

Conversation

@lucasheriques

@lucasheriques lucasheriques commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Servers that need tool schemas and results left unchanged turn conversation IDs off. On a stateless server that builds a fresh instance per request, every tool call then gets its own $session_id (PostHog/posthog#119784).

Some clients already name the conversation in each tool call's _meta. sdk-specs main defines which keys the SDKs read, from which clients, and in what order: "Session identity", from PostHog/sdk-specs#175 and #176. This PR implements those rules exactly. It is the twin of PostHog/posthog-js#5577.

Changes

  • _client_conversation.CLIENT_CONVERSATION_ROWS mirrors the spec table:

    • ChatGPT openai/session: 1 to 128 printable ASCII characters. Handle-free.
    • Codex sessionId: a UUID. Keeps the handle as a fallback.
    • VS Code vscode.conversationId: a UUID. Keeps the handle as a fallback.

    UUIDs are lowercased and the nil UUID is rejected.

  • Recognition. A key is read only from a request whose User-Agent or client name matches its row. The client name comes from the request's _meta clientInfo first, then the name the adapter resolved.

  • The client's id is session source 1 on tool calls, ahead of the handle and the transport. tools/list, resource requests, and initialize no longer read it. A handle echoed alongside it is stripped but ignored.

  • Handle-free (ChatGPT). Its client-facing tools/list has no conversation_id or _mcp_instructions, and it is minted no handle. The SDK's internal tool-cache pass still injects, so validation stays the same for every client.

  • Connection activity. On a one-client connection (stdio), a client-grouped call counts as activity, so the session doesn't rotate early.

  • $mcp_session_source on every instrument() event. The spec addition for it is docs(mcp-analytics): record which source grouped each session as $mcp_session_source sdk-specs#185.

  • PostHogMCP. prepare_tool_list and prepare_tool_call take headers, and prepare_tool_call also takes client_info. capture_tool_call takes request_meta. A ChatGPT prepare_tool_list still records conversation_id ownership.

  • On mcp 2.x low-level servers, the SDK's internal tools/list dispatch (Mcp-Param header validation) emits no event. That part is unchanged from the earlier version of this PR.

Not verified against real clients

  • Does openai/session stay the same for a whole ChatGPT conversation? Not verified. I have no ChatGPT connector session to log from. One way to confirm is to log _meta across a multi-turn chat.
  • Do the Codex versions in use today send sessionId? Partly verified, from source only. Codex adds it to tool-call _meta starting at rust-v0.156.0 (2026-09-22). Older installs fall back to the handle.

How I tested

  • pytest posthog/test/mcp: 745 passed on mcp 1.30.0 and 603 passed on mcp 2.3.0.
    • test_client_conversation_session.py covers every spec scenario and vector, and recognition examples.
    • It covers the manual API and connection rotation.
    • It covers real HTTP fleets over the official, FastMCP, and low-level server kinds: listings, and ChatGPT calls across pods.
  • ruff, mypy (CI mode with baseline), and the public API snapshot pass.
  • Pre-PR gate: two adversarial reviewers (Opus and Sonnet), on both mcp majors.
    • Fixed: counting client-grouped calls as activity also ran on shared stateless HTTP pods. There it kept the instance session alive and merged two unrelated clients. It now applies only to a one-client connection.
    • Fixed: a ChatGPT prepare_tool_list skipped recording ownership, so prepare_tool_call passed an echoed handle to the handler.
    • Both fixes have tests that fail on the previous commit.
    • Dismissed: the inactivity clock is reset by any request, not only tool calls, and is measured from arrival with >. It predates this PR and matches posthog-js, so it's a follow-up.
    • Dismissed: on mcp 1.x, a ChatGPT listing populates the tool cache without the analytics fields. A later client on that instance then gets the handle only as a text block, not mirrored into structuredContent. Mirroring is a MAY and the handle is still delivered.
    • Dismissed: the manual capture methods set $mcp_session_source only for a recognized client id (spec MAY, follow-up).

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

Built with Claude Code (pstack poteto-mode) at Lucas's direction. An earlier version ranked openai/session below the transport session, with no recognition rules. Lucas decided the merged sdk-specs rules win, so this version implements them as written.

Read ChatGPT's `_meta["openai/session"]` conversation id as a session source
for calls with no conversation handle and no transport session, and stamp
`$mcp_session_source` (conversation, transport, client_metadata, generated)
on every event whose session the SDK resolves.

Why: on per-request stateless servers with `enable_conversation_id=False`
(common for ChatGPT/Claude directory submissions) every call got its own
`$session_id` (PostHog/posthog#119784). ChatGPT already sends a
per-conversation id, so grouping needs no schema or result change. Order is
handle, transport (token or mcp id), client id, generated, so it only groups
calls that fragment today. A call carrying it mints no handle and gets no
prompt-back. Same rule in `PostHogMCP.prepare_tool_call` via `request_meta`,
after an explicit `session_id`. Twin of posthog-js 3eb19d9 and ADR-0014; the
derivation `ses_35e4cc45ea3e5e1282c3f091de632132` is a cross-SDK contract.

Internals: `resolve_session_id_with_source` / `prepare_request` return a
`ResolvedSession(session_id, source)`, which the record_* functions take, so
the source reaches every event. `token`/`mcp` map to `transport` at the
property boundary. `handshake_session_id` becomes `handshake_session`. A
client-conversation session never stands in for an unobserved `initialize`,
like a conversation one.

Tested: `pytest posthog/test/mcp` -> 699 passed, 10 skipped on mcp 1.30.0 and
557 passed, 42 skipped on mcp 2.3.0 (incl. new parameterized
test_client_conversation_session.py plus a v1 FastMCP and a v2 wire-level
fresh-instance test); `ruff format --check`, `ruff check`, `mypy`,
`make public_api_check` clean.
Pre-PR gate findings on the TypeScript twin (posthog-js 26d720abd), applied
here:
- tools/list, resources/list|read and initialize resolved sessions without
  the client conversation id, which the spec's session order covers for every
  event. Each call site now passes it (`params.meta` on request handlers,
  `_meta` of the initialize params through `handshake_session`). Still
  per-request, never written to shared state, and it still does not stand in
  for an unobserved initialize.
- Custom events from `McpAnalytics.capture()` now carry `$mcp_session_source`,
  the instance's own source (`generated`, or `transport` for a token or mcp
  session id).
- `prepare_tool_call(session_id="")` already treated an empty id as absent;
  a regression case now pins it.

Tested: `pytest posthog/test/mcp` -> 714 passed, 11 skipped on mcp 1.30.0 and
570 passed, 45 skipped on mcp 2.3.0 (fastmcp uninstalled); new parameterized
cases failed before the fix (12 on mcp 2.3.0); `ruff format --check`,
`ruff check`, `mypy`, `make public_api_check` clean.
…ernal tools/list

What
- ToolCallLifecycle.prime_session now passes the request's client conversation to
  resolve_session_id, so a call carrying only openai/session returns at the
  client_metadata step before the memory branch. It no longer refreshes
  data.last_activity or rotates data.session_id, so ChatGPT calls cannot keep the
  instance's generated session alive past its inactivity window.
- The v2 tools/list wrapper skips analytics when the SDK calls the handler itself.
  On the 2026-07-28 streamable-HTTP path, mcp 2.3.0 runs tools/list during every
  tools/call (Mcp-Param-* validation) on a server without get_tool_input_schema
  (the low-level Server; MCPServer provides it). That call has no _meta, resolved
  to a fresh generated session, and emitted a phantom $mcp_tools_list. It is
  detected by the shared HTTP request's required Mcp-Method header naming a
  different method than the handler's own.

Why
Pre-PR gate findings on the client-metadata session work; the spec limits
events to requests the client sent.

Tested
- pytest posthog/test/mcp: mcp 1.30.0 716 passed, 11 skipped; mcp 2.3.0 576
  passed, 45 skipped (fastmcp uninstalled)
- ruff format --check, ruff check, mypy | mypy-baseline filter, make
  public_api_check: clean
- New tests failed before the fixes (instance state moved; phantom event emitted).
  A real tools/list still emits on both MCPServer and low-level Server.

@posthog posthog Bot left a comment

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.

PostHog Review · Standard · reviewed 208707d: 1 Must fix.

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.

Comment on lines +409 to +411
await resolve_session_id(
data, mcp_session_id, token=token, client_conversation=client_conversation
)

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.

P1 · Isolate custom-event identity for metadata-only requests

When Alice's token-bearing request precedes Bob's metadata-only request on a shared server, client_conversation makes this resolver return without clearing Alice's shared session. An in-tool McpAnalytics.capture() then sends Bob's properties with Alice's session, cached distinct_id, and $set. Use request-local session and identity for custom capture.

@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-11-05T21:02:34.528282+00:00
Duration: 259313ms

✅ All Tests Passed!

121/121 tests passed


Capture_V1 Tests

✅ 95/95 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint ✅ 514ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 508ms
Required Headers.Has Authorization Bearer Header ✅ 509ms
Required Headers.Has Content Type Json ✅ 508ms
Required Headers.Has Posthog Sdk Info Format ✅ 508ms
Required Headers.Has Posthog Attempt Header ✅ 508ms
Required Headers.Has Posthog Request Id ✅ 507ms
Required Headers.Has Posthog Request Timestamp ✅ 508ms
Required Headers.Has User Agent ✅ 508ms
Body Format.Body Has Created At And Batch ✅ 508ms
Body Format.No Api Key In Body ✅ 508ms
Body Format.No Sent At In Body ✅ 508ms
Event Format.Event Has Required Root Fields ✅ 508ms
Event Format.Event Uuid Is Valid ✅ 508ms
Event Format.Event Timestamp Is Rfc3339 ✅ 507ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 519ms
Event Format.Distinct Id Is String ✅ 508ms
Event Format.Distinct Id At Root Not Properties ✅ 508ms
Event Format.Custom Properties Preserved ✅ 508ms
Event Format.Set Properties Preserved ✅ 508ms
Event Format.Set Once Properties Preserved ✅ 508ms
Event Format.Groups Properties Preserved ✅ 507ms
Event Format.Sdk Generates Uuid If Not Provided ✅ 508ms
Event Format.Event Has Required Root Fields Batch ✅ 511ms
Event Format.Event Uuid Is Valid Batch ✅ 510ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 510ms
Event Format.Distinct Id Is String Batch ✅ 510ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 509ms
Event Format.Custom Properties Preserved Batch ✅ 511ms
Event Format.Set Properties Preserved Batch ✅ 510ms
Event Format.Set Once Properties Preserved Batch ✅ 510ms
Event Format.Groups Properties Preserved Batch ✅ 510ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 511ms
Batch Behavior.Multiple Events In Single Batch ✅ 512ms
Batch Behavior.Batch Envelope Smoke ✅ 512ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 506ms
Batch Behavior.Flush At Triggers Batch ✅ 1007ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 509ms
Deduplication.Generates Unique Uuids ✅ 512ms
Deduplication.Different Events Same Content Different Uuids ✅ 509ms
Deduplication.Preserves Uuid On Retry ✅ 6512ms
Deduplication.Preserves Timestamp On Retry ✅ 6516ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6517ms
Deduplication.No Duplicate Events In Batch ✅ 514ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 507ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 13525ms
Header Behavior On Retry.Request Id Preserved On Retry ✅ 6512ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 3016ms
Header Behavior On Retry.Request Timestamp Changes On Retry ✅ 6517ms
Response Format Validation.Success Response Has Uuid Keyed Results ✅ 509ms
Response Format Validation.Success Response Has Ok For Each Event ✅ 510ms
Response Format Validation.Success No Retry After When All Ok ✅ 509ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 1512ms
Response Format Validation.Success No Retry After When Drop Only ✅ 510ms
Response Format Validation.Response Echoes Request Id ✅ 507ms
Retry Behavior.Retries On 408 ✅ 6516ms
Retry Behavior.Retries On 500 ✅ 6517ms
Retry Behavior.Retries On 503 ✅ 8520ms
Retry Behavior.Retries On 504 ✅ 6518ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3514ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11519ms
Retry Behavior.Does Not Retry On 400 ✅ 2512ms
Retry Behavior.Does Not Retry On 401 ✅ 2511ms
Retry Behavior.Does Not Retry On 402 ✅ 2511ms
Retry Behavior.Does Not Retry On 413 ✅ 2511ms
Retry Behavior.Does Not Retry On 415 ✅ 2509ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2512ms
Retry Behavior.Implements Backoff ✅ 22532ms
Retry Behavior.Max Retries Respected ✅ 22521ms
Partial Batch Handling.Handles 200 Full Success ✅ 2508ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3517ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3513ms
Partial Batch Handling.Does Not Retry Limited Events ✅ 3512ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6513ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6519ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6518ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6514ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6514ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6515ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8517ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3516ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry ✅ 3515ms
Compression.Sends Gzip Content Encoding ✅ 509ms
Compression.No Content Encoding When Disabled ✅ 508ms
Compression.Compressed Body Is Decompressible ✅ 508ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2509ms
Event Options.Cookieless Mode Override ✅ 508ms
Event Options.Disable Skew Correction Override ✅ 507ms
Event Options.Process Person Profile Override ✅ 507ms
Event Options.Product Tour Id Override ✅ 508ms
Event Options.Unset Options Omitted ✅ 508ms
Event Options.Options Override In Batch ✅ 510ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties ✅ 507ms
Geoip And Historical Migration.Historical Migration Set In Body ✅ 509ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 507ms

Capture_Ai Tests

✅ 5/5 tests passed

View Details
Test Status Duration
Routing.Capture Ai Posts To Ai Endpoint ✅ 508ms
Routing.Capture Does Not Reroute Ai Named Events ✅ 508ms
Identity.Capture Ai Event Has Uuid ✅ 508ms
Identity.Capture Ai Keeps Supplied Uuid ✅ 507ms
Timestamp Format.Non Utc Event Timestamp Is Converted To Utc ✅ 509ms

Feature_Flags Tests

✅ 17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 8ms
Request Payload.Flags Request Uses V4 Query Param ✅ 6ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 6ms
Request Payload.Flags Request Omits Authorization Header ✅ 6ms
Request Payload.Token In Flags Body Matches Init ✅ 6ms
Request Payload.Groups Round Trip ✅ 6ms
Request Payload.Groups Default To Empty Object ✅ 5ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 6ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 6ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 6ms
Request Lifecycle.No Flags Request On Init Alone ✅ 3ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 506ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 10ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 6ms
Retry Behavior.Retries Flags On 502 ✅ 309ms
Retry Behavior.Retries Flags On 504 ✅ 310ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 509ms

Feature_Flags_Local_Evaluation Tests

✅ 4/4 tests passed

View Details
Test Status Duration
Versioned Boolean Matching.Matching Version Missing ✅ 44ms
Versioned Boolean Matching.Matching Version 1 ✅ 42ms
Versioned Boolean Matching.Matching Version 2 ✅ 44ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 22ms

@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

SDK performance: posthog-python

Benchmarks 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
Test Measurement Before PR With PR Change Assessment
Capture and deliver events (32-byte payload, burst)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (32-byte payload, steady)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Queue an event (32-byte payload)
Shard: capture
Allocated memory per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Queue an event (32-byte payload)
Shard: capture
Allocations per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Queue an event (4,096-byte payload)
Shard: capture
Allocated memory per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Queue an event (4,096-byte payload)
Shard: capture
Allocations per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Refresh 1,000 flag definitions
Shard: flags-memory
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (32-byte payload, burst)
Shard: capture
Allocated memory per operation 113.54 KiB/op 113.54 KiB/op <0.1% less memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Allocations per operation 1,096.61 count/op 1,096.6 count/op <0.1% fewer Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Time per operation 112.54 µs/op 118.99 µs/op 5.7% more time Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Idle process memory (RSS) 36 MiB 36.01 MiB <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Observed peak process memory (RSS) 37.75 MiB 37.76 MiB <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Process memory after settling (RSS) 37.75 MiB 37.76 MiB <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Process CPU time per operation 112.84 µs/op 121.42 µs/op 7.6% more time Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Lifetime peak process memory (RSS) 40.32 MiB 40.32 MiB No observed change Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Allocated memory per operation 166.1 KiB/op 166.11 KiB/op <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Allocations per operation 1,089.63 count/op 1,089.64 count/op <0.1% more Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Time per operation 147.98 µs/op 160.51 µs/op 8.5% more time Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Idle process memory (RSS) 40.82 MiB 40.76 MiB 0.2% less memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Observed peak process memory (RSS) 45.93 MiB 45.85 MiB 0.2% less memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Process memory after settling (RSS) 45.93 MiB 45.85 MiB 0.2% less memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Process CPU time per operation 140.94 µs/op 155.47 µs/op 10.3% more time Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Lifetime peak process memory (RSS) 50.76 MiB 50.59 MiB 0.3% less memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Allocated memory per operation 117.68 KiB/op 117.68 KiB/op <0.1% less memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Allocations per operation 1,136.59 count/op 1,136.58 count/op <0.1% fewer Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Time per operation 126.99 µs/op 130.93 µs/op 3.1% more time Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Idle process memory (RSS) 35.84 MiB 35.87 MiB <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Observed peak process memory (RSS) 35.95 MiB 35.97 MiB <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Process memory after settling (RSS) 35.95 MiB 35.97 MiB <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Process CPU time per operation 125.16 µs/op 129.95 µs/op 3.8% more time Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Lifetime peak process memory (RSS) 40.32 MiB 40.32 MiB No observed change Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Allocated memory per operation 170.57 KiB/op 170.57 KiB/op <0.1% less memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Allocations per operation 1,129.5 count/op 1,129.47 count/op <0.1% fewer Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Time per operation 161.57 µs/op 153.52 µs/op 5% less time Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Idle process memory (RSS) 40.69 MiB 40.73 MiB <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Observed peak process memory (RSS) 40.7 MiB 40.74 MiB 0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Process memory after settling (RSS) 40.7 MiB 40.74 MiB 0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Process CPU time per operation 154.92 µs/op 145.87 µs/op 5.8% less time Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Lifetime peak process memory (RSS) 40.96 MiB 40.96 MiB <0.1% less memory Not flagged
Queue an event (32-byte payload)
Shard: capture
Caller-thread CPU time per operation 82.27 µs/op 84.96 µs/op 3.3% more time Not flagged
Queue an event (32-byte payload)
Shard: capture
Time per operation 86.26 µs/op 87.36 µs/op 1.3% more time Not flagged
Queue an event (4,096-byte payload)
Shard: capture
Caller-thread CPU time per operation 81.12 µs/op 88.58 µs/op 9.2% more time Not flagged
Queue an event (4,096-byte payload)
Shard: capture
Time per operation 88.46 µs/op 91.86 µs/op 3.8% more time Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Allocated memory per operation 200.98 KiB/op 200.98 KiB/op No observed change Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Allocations per operation 2,339.33 count/op 2,339.33 count/op No observed change Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Time per operation 107.42 µs/op 106.86 µs/op 0.5% less time Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Process CPU time per operation 107.42 µs/op 106.86 µs/op 0.5% less time Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Allocated memory per operation 1.93 MiB/op 1.93 MiB/op No observed change Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Allocations per operation 23,013.56 count/op 23,013.56 count/op No observed change Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Time per operation 1.01 ms/op 1.02 ms/op 1.6% more time Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Process CPU time per operation 1.01 ms/op 1.02 ms/op 1.6% more time Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Allocated memory per operation 19.24 MiB/op 19.24 MiB/op No observed change Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Allocations per operation 229,654.94 count/op 229,654.94 count/op No observed change Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Time per operation 10.24 ms/op 10.61 ms/op 3.6% more time Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Process CPU time per operation 10.24 ms/op 10.61 ms/op 3.6% more time Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Idle process memory (RSS) 41.64 MiB 41.63 MiB <0.1% less memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Observed peak process memory (RSS) 41.94 MiB 41.97 MiB <0.1% more memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Process memory after settling (RSS) 41.94 MiB 41.97 MiB <0.1% more memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Lifetime peak process memory (RSS) 42.57 MiB 42.53 MiB <0.1% less memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Idle process memory (RSS) 42.07 MiB 41.46 MiB 1.5% less memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Observed peak process memory (RSS) 42.14 MiB 42.18 MiB <0.1% more memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Process memory after settling (RSS) 42.14 MiB 41.84 MiB 0.7% less memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Lifetime peak process memory (RSS) 42.51 MiB 42.57 MiB 0.1% more memory Not flagged
Evaluate one boolean flag
Shard: flags-single
Allocated memory per operation 15.05 KiB/op 15.05 KiB/op No observed change Not flagged
Evaluate one boolean flag
Shard: flags-single
Allocations per operation 173.76 count/op 173.76 count/op No observed change Not flagged
Evaluate one boolean flag
Shard: flags-single
Time per operation 12.56 µs/op 12.55 µs/op <0.1% less time Not flagged
Evaluate one boolean flag
Shard: flags-single
Process CPU time per operation 12.56 µs/op 12.55 µs/op <0.1% less time Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Allocated memory per operation 23.12 KiB/op 23.12 KiB/op No observed change Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Allocations per operation 270.27 count/op 270.27 count/op No observed change Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Time per operation 16.79 µs/op 16.73 µs/op 0.4% less time Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Process CPU time per operation 16.79 µs/op 16.73 µs/op 0.4% less time Not flagged
Evaluate a flag (early match)
Shard: flags-single
Allocated memory per operation 35.71 KiB/op 35.71 KiB/op No observed change Not flagged
Evaluate a flag (early match)
Shard: flags-single
Allocations per operation 387.27 count/op 387.27 count/op No observed change Not flagged
Evaluate a flag (early match)
Shard: flags-single
Time per operation 24.2 µs/op 24 µs/op 0.8% less time Not flagged
Evaluate a flag (early match)
Shard: flags-single
Process CPU time per operation 24.2 µs/op 24 µs/op 0.8% less time Not flagged
Evaluate a flag (late match)
Shard: flags-single
Allocated memory per operation 53.59 KiB/op 53.59 KiB/op No observed change Not flagged
Evaluate a flag (late match)
Shard: flags-single
Allocations per operation 576.27 count/op 576.27 count/op No observed change Not flagged
Evaluate a flag (late match)
Shard: flags-single
Time per operation 34.46 µs/op 34.11 µs/op 1% less time Not flagged
Evaluate a flag (late match)
Shard: flags-single
Process CPU time per operation 34.45 µs/op 34.1 µs/op 1% less time Not flagged
Evaluate a flag (no match)
Shard: flags-single
Allocated memory per operation 52.14 KiB/op 52.14 KiB/op No observed change Not flagged
Evaluate a flag (no match)
Shard: flags-single
Allocations per operation 556.77 count/op 556.77 count/op No observed change Not flagged
Evaluate a flag (no match)
Shard: flags-single
Time per operation 32.9 µs/op 32.4 µs/op 1.5% less time Not flagged
Evaluate a flag (no match)
Shard: flags-single
Process CPU time per operation 32.9 µs/op 32.4 µs/op 1.5% less time Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Allocated memory per operation 17.84 KiB/op 17.84 KiB/op No observed change Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Allocations per operation 198.27 count/op 198.27 count/op No observed change Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Time per operation 13.86 µs/op 14.08 µs/op 1.6% more time Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Process CPU time per operation 13.86 µs/op 14.08 µs/op 1.6% more time Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Allocated memory per operation 19.23 KiB/op 19.23 KiB/op No observed change Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Allocations per operation 210.77 count/op 210.77 count/op No observed change Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Time per operation 14.89 µs/op 14.9 µs/op <0.1% more time Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Process CPU time per operation 14.89 µs/op 14.9 µs/op <0.1% more time Not flagged
Evaluate a rollout flag
Shard: flags-single
Allocated memory per operation 14.04 KiB/op 14.04 KiB/op No observed change Not flagged
Evaluate a rollout flag
Shard: flags-single
Allocations per operation 160.76 count/op 160.76 count/op No observed change Not flagged
Evaluate a rollout flag
Shard: flags-single
Time per operation 11.78 µs/op 11.74 µs/op 0.3% less time Not flagged
Evaluate a rollout flag
Shard: flags-single
Process CPU time per operation 11.78 µs/op 11.74 µs/op 0.3% less time Not flagged
Evaluate a multivariate flag
Shard: flags-single
Allocated memory per operation 15.21 KiB/op 15.21 KiB/op No observed change Not flagged
Evaluate a multivariate flag
Shard: flags-single
Allocations per operation 177.77 count/op 177.77 count/op No observed change Not flagged
Evaluate a multivariate flag
Shard: flags-single
Time per operation 13.04 µs/op 13.08 µs/op 0.3% more time Not flagged
Evaluate a multivariate flag
Shard: flags-single
Process CPU time per operation 13.04 µs/op 13.08 µs/op 0.3% more time Not flagged

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 5febc73aa74b38376a9d9cac895552686cefaca2 → 3cbcd29b479ff2e47473a169c206b154b4c30378.

Full report and diagnostics

102 metric rows; 102 rows shown in all results. Omitted or shortened data remain in comparison.json, including per-runner environments, resource limits, measurement methods, samples and checkpoints.

@dustinbyrne dustinbyrne left a comment

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.

Reproduced a custom-event attribution regression: after a token-bearing request, a metadata-only caller’s in-tool capture can inherit the previous caller’s session and person. The same public-entry test passes on base and fails on this head.

The metadata policy also needs reconciliation with the current canonical MCP specification; the linked spec proposal remains open. Details and executed evidence are inline.

AI-assisted review.

await resolve_session_id(data, mcp_session_id, token=token)
await resolve_session_id(
data, mcp_session_id, token=token, client_conversation=client_conversation
)

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.

1. [P1] Metadata-only priming leaves the previous caller’s identity available to custom capture

IMPORTANT · REQUIRED · Introduced regression
Location / inline: posthog/mcp/_instrumentation.py:409–411, RIGHT; resolver branch posthog/mcp/session.py:188–194.

After Alice’s token-bearing request, Bob’s metadata-only request can send an in-tool custom event under Alice’s session and person. Expected: Bob’s event must not inherit another caller’s session, identity or cached person properties. Bob’s automatic tool-call event is correctly attributed, so the custom-event error can be missed.

A supported sequential caller is sufficient:

@server.tool()
async def probe(marker: str) -> str:
    await analytics.capture("inside_tool", {"marker": marker})
    return marker

The executed harness uses a shared FastMCP(stateless_http=True) instrumented with conversation anchoring disabled and an identify callback returning the request’s user. It sends actual JSON-RPC tools/call requests through httpx.ASGITransport, flushing after each:

  1. Alice: a valid encoded PostHog token with session_id="ses_alice"; identify returns Alice and {"owner":"alice"}.
  2. Bob: no session header, _meta={"openai/session":"bob-chat"}; identify returns Bob. His tool calls public analytics.capture().

On head, Bob’s custom event contains:

{
  "event": "inside_tool",
  "distinct_id": "alice",
  "properties": {
    "$session_id": "ses_alice",
    "$mcp_session_source": "transport",
    "$set": {"owner": "alice"},
    "marker": "bob"
  }
}

On base, the identical event has a fresh generated session, $process_person_profile: false, and no Alice $set. Removing only Bob’s metadata makes the head control pass too. No concurrency, private-state mutation or malformed input is needed; the token is a session carrier, not an authentication credential.

The new priming argument takes the metadata resolver’s early return before the old token-clearing path. McpAnalytics.capture() still reads shared data.session_id; _capture.py then retrieves Alice’s cached actor using that id. This violates the canonical session-isolation requirement and the existing preceding-caller isolation invariant tested in test_conversation_session.py:301–356.

Executed regression: regression_identity.py retains these assertions:

assert bob["properties"]["$session_id"] != "ses_alice"
assert bob["distinct_id"] != "alice"
assert bob["properties"].get("$set", {}).get("owner") != "alice"

Executed regression commands (local paths represented by environment variables):

E="$REVIEW_EVIDENCE_DIR"
V="$REVIEW_VALIDATION_DIR"
PY=python3.11 # Python 3.11.13
cd "$V"
for rev in base 208707d; do
  env -i HOME="$PWD" TMPDIR="$PWD" PATH=/usr/bin:/bin \
    PYTHONDONTWRITEBYTECODE=1 /usr/bin/sandbox-exec -f "$E/sandbox.sb" \
    "$PY" -S "$E/regression_identity.py" \
    "$REVIEW_WORKTREE_ROOT/python-1193-$rev"
done

Results: base exit 0; head exit 1 at the session assertion. Printed output independently confirms the wrong actor and $set. Appending no-metadata to the head command gives exit 0. Full setup and stdout are retained in the evidence directory.

Consider restoring custom-capture isolation for metadata-only execution and adding this regression plus its negative control. An isolated anonymous fallback is sufficient; custom events need not acquire the metadata-derived session or resolve Bob’s identity earlier. Do not persist metadata globally or refresh an unrelated instance session’s inactivity window.

Impact is wrong attribution within the receiving PostHog project. This does not demonstrate an authentication bypass, cross-project disclosure, backend profile mutation or incorrect attribution of Bob’s automatic tool-call event. No fix was applied or tested.

Comment thread posthog/mcp/session.py Outdated

# Printable ASCII only, so every SDK hashes the same characters.
_CLIENT_CONVERSATION_ID_SHAPE = re.compile(r"[\x20-\x7e]{1,256}")

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.

2. [P2/design] Reconcile the new metadata policy with the current canonical specification

QUESTION · REQUIRED acceptance decision · Intentional new behavior following a conflicting proposal
Suggested inline: posthog/mcp/session.py:46–60, RIGHT. Also affects resolution at 183–194 and manual preparation at posthog_mcp.py:608–629.

This implements sdk-specs#185, but that proposal is still open, at ed40d1a9bbef88393bf8279c61d629384021a278. The current canonical specification requires different behavior:

Rule This PR Canonical spec at ffe38baa…
Recognize openai/session Any caller carrying it Recognized ChatGPT HTTP User-Agent only
Printable ASCII length 1–256 1–128
Precedence Handle → token/transport → metadata Client metadata → handle → transport
Client id plus echoed handle Keep handle authoritative Ignore handle for session and $mcp_conversation_id

The canonical contract evolved after this PR snapshot; this is not a claim that the author misimplemented the earlier proposal. Nevertheless, the pending JS twin is not authority to override the current contract.

Executed public-path checks in test_contract.py use actual instrumented FastMCP/ASGI requests:

Input / expected canonical behavior Base Head
Valid ChatGPT metadata groups calls Fails: feature absent Passes
Metadata wins over echoed handle Fails current contract Fails: handle-derived session
example-client/1.0 carrying the key is ignored Passes Fails: metadata groups it and suppresses handle
Identical 129-character values on fresh instances do not group Passes Fails: same derived session

For the precedence case, the request carries recognized ChatGPT UA, _meta={"openai/session":"v1/conv-example-0001"} and handle 0190f0e8-7a6b-7c3d-9e4f-5a6b7c8d9e0f. Expected session is ses_2f5d35b7108d17c807766f2f769a1e8c; head instead uses handle-derived ses_6df45f0102a182bcd5e8dd5dad6c65a0.

These map to “Session identity” and its acceptance scenarios in the pinned spec. The precedence gap is not a passing-base regression: base lacks the capability. The other cases demonstrate changed input boundaries, not observed malicious production traffic. The overlength assertion checks session separation, not whether ChatGPT receives a handle.

The exact base/head command is the sandbox command above, replacing the script invocation with:

"$PY" -S "$E/run_pytest.py" "$REVIEW_WORKTREE_ROOT/python-1193-$rev" \
  "$E/test_contract.py" --rootdir="$E" --confcutdir="$E" \
  -o asyncio_mode=auto -q -s

Set PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 as recorded in commands.sh. Base: 2 passed / 2 failed / 1 skipped; head: 1 passed / 3 failed / 1 skipped. The manual conformance sketch is explicitly skipped because the current helper lacks recognition context; no executed manual result is claimed.

Consider aligning this changed capability with the named canonical contract, or obtaining an explicit cross-SDK decision documenting the intentional divergence and its consequences. Keep Python, JS, tests, documentation and release wording consistent. This does not require expanding the PR into unrelated pre-existing Codex/VS Code support, handle-free listings or broader manual-API redesign.

…x, VS Code)

Rework the openai/session change to the merged sdk-specs rules
(PostHog/sdk-specs 2026-11-04-mcp-client-conversation-ids and
-codex-vscode-conversation-ids), matching posthog-js#5577:

- _client_conversation.CLIENT_CONVERSATION_ROWS mirrors the spec table:
  openai/session (1-128 printable ASCII, handle-free), Codex sessionId and
  VS Code vscode.conversationId (UUID, lowercased, non-nil, handle kept).
- A key is read only from a request its row recognizes by User-Agent or
  client name (_meta clientInfo first, then the adapter's resolved name).
- The client id is session source 1, ahead of the handle and transport, on
  tool calls only (tools/list, resources and initialize no longer read it).
  A handle echoed with it is stripped but ignored.
- A handle-free client's client-facing listing has no conversation_id or
  _mcp_instructions, and it is minted no handle. The SDK's internal cache
  pass still injects, so validation stays client-agnostic.
- Client- and handle-grouped calls count as connection activity, so a
  stdio session does not rotate early (gate finding from the JS port).
- PostHogMCP: prepare_tool_list/prepare_tool_call take headers
  (+client_info), capture_tool_call takes request_meta.

Tested: pytest posthog/test/mcp 743 passed on mcp 1.30.0, 601 passed on
mcp 2.3.0; the new tests cover every spec scenario and vector, including
real HTTP fleets over official, fastmcp and lowlevel servers. ruff, mypy
(CI mode with baseline) and the public API snapshot pass.

@posthog posthog Bot left a comment

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.

PostHog Review · Standard · reviewed 02a4815: 1 Must fix, 1 Should fix. This pull request is large, so the review ran in 4 parts with less depth than usual.

server,
data,
tools,
advertise_conversation_id=lifecycle.advertises_conversation_id,

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.

P1 · Keep the shared validation cache compatible with both client listings

On MCP 1.30.0, a ChatGPT listing after another client's listing replaces the shared _tool_cache output schema without _mcp_instructions. The other client's next call still mirrors that property, so tools with additionalProperties: false return an output validation error instead of their result. Keep the shared validation schema compatible with both clients' results.

Comment thread posthog/mcp/posthog_mcp.py Outdated
Comment on lines +532 to +533
if client is None or not client.handle_free:
prepared = self._inject_conversation(prepared, conversation_ownership)

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 · Cache application ownership when suppressing conversation injection

With ChatGPT headers, prepare_tool_list() skips caching conversation ownership. A later prepare_tool_call() without original_tool, when client metadata is absent or invalid, treats an application-owned UUIDv7 conversation_id as an SDK handle and overrides the supplied session. Preserve application ownership even when conversation schema injection is suppressed.

"""
await resolve_session_id(data, mcp_session_id, token=token)
await resolve_session_id(
data, mcp_session_id, token=token, client_conversation=client_conversation

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Medium: Custom events inherit the previous caller's identity

On a shared server, passing client_conversation here makes the resolver return before updating data.session_id: after Alice's token-backed request, Bob's recognized metadata call leaves Alice's session in place even when Bob supplies a different token, so an in-tool McpAnalytics.capture() emits Bob's payload with Alice's distinct_id, $set, and $groups. Prime only the request's transport/memory session here, keeping client-conversation grouping on request-scoped event resolution.

Suggested change
data, mcp_session_id, token=token, client_conversation=client_conversation
data, mcp_session_id, token=token

@veria-ai

veria-ai Bot commented Nov 5, 2026

Copy link
Copy Markdown

PR overview

The PR groups stateless ChatGPT MCP calls by the OpenAI session identifier, updating how MCP instrumentation resolves conversation and session context.

One issue remains open: on a shared server, a caller's custom analytics events can retain the previous caller's identity despite supplying a different token. This can attribute one user's event payload to another user's identity, properties, and groups. No issues have been addressed yet.

Open issues (1)

Fixed/addressed: 0 · PR risk: 6/10

- Count a client-grouped call as connection activity only on a one-client
  connection (no HTTP request, no token, no transport id). On a shared
  stateless HTTP pod, ChatGPT calls kept the instance session alive and
  merged two unrelated clients into one $session_id.
- PostHogMCP.prepare_tool_list for a handle-free client still records
  conversation_id ownership, so prepare_tool_call strips an echoed handle
  like the automatic path does.

Tested: both regressions have tests that fail on 02a4815 and pass now;
pytest posthog/test/mcp 745 passed on mcp 1.30.0 and 603 on mcp 2.3.0;
ruff, mypy (CI mode) and the public API check pass.
@lucasheriques lucasheriques changed the title feat(mcp): group stateless ChatGPT calls by openai/session feat(mcp): group sessions by ChatGPT, Codex and VS Code conversation ids Nov 5, 2026

@posthog posthog Bot left a comment

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.

PostHog Review · Standard · reviewed 3cbcd29: 1 Must fix, 2 Should fix. This pull request is large, so the review ran in 4 parts with less depth than usual.

This is review round 3 on this pull request. When findings keep coming back in the same code, the approach is usually the problem. Before the next fix, check whether a different design would remove the whole class of findings.

elif minted and (
token is not None
or bool(mcp_session_id)
or (client is not None and client.handle_free)

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.

P1 · Isolate handle-free HTTP requests without valid conversation metadata

When ChatGPT requests omit valid openai/session on a shared stateless HTTP server, this branch suppresses handles and prepare_request() reuses the process session. Separate users then share cached identity: handle_identify() merges Alice's properties into Bob's events and profile. Allocate a fresh request-local fallback session for sessionless HTTP calls.

Comment on lines +903 to +907
if not advertise:
self._conversation_ownership.update(
{
name: _ConversationOwnership(owned.conversation_id, False)
for name, owned in ownership.items()

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 · Keep client-specific output suppression out of ownership state

After a ChatGPT listing, cached output_instructions=False permanently suppresses declarations on later ordinary listings through the ownership merge. Using the documented prepare_tool_call(original_tool=...) still mirrors _mcp_instructions, so results fail schemas with additionalProperties: false. Keep listing-specific suppression separate from cached ownership.

Comment on lines +600 to +601
if self.client_conversation is not None and on_one_client_connection:
await touch_connection_session(self.data)

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 · Refresh connection activity when metadata-grouped calls finish

On stdio, a metadata-grouped call lasting over 30 minutes updates last_activity only at entry. Completion bypasses updates, so the next metadata-free call immediately rotates the connection session, violating the completion-based timeout contract required by AGENTS.md:21. Refresh connection activity when the call finishes.

@dustinbyrne dustinbyrne left a comment

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.

The earlier recognition, bounds and precedence feedback is addressed. The custom-event attribution regression remains and now also reproduces when the second caller supplies its own token.

I also reproduced session/identity merging for handle-free HTTP calls without usable metadata, output-validation failures after mixed-client FastMCP listings, and schema-invalid results after mixed manual listings. The corresponding base controls pass; details are inline.

AI-assisted review.

await resolve_session_id(data, mcp_session_id, token=token)
await resolve_session_id(
data, mcp_session_id, token=token, client_conversation=client_conversation
)

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.

1. [P1] Metadata priming leaves the previous caller’s identity available to custom capture

IMPORTANT · REQUIRED · Introduced regression, persisting and amplified
Location: posthog/mcp/_instrumentation.py:415–417. Related resolver: session.py:153–157.

After Alice’s token-bearing request, Bob’s recognized metadata request sends an in-tool custom event under Alice’s session and person—even when Bob supplies his own valid token. Expected: Bob’s custom event must not inherit another caller’s cached identity.

A supported tool suffices:

@server.tool()
async def probe(marker: str) -> str:
    await analytics.capture("inside_tool", {"marker": marker})
    return marker

The executed public-entry harness uses a shared FastMCP(stateless_http=True), conversation anchoring disabled, request-based identification and actual JSON-RPC requests through ASGI:

  1. Alice sends encoded token sid="ses_alice"; identification caches Alice and {"owner":"alice"}.
  2. Bob sends recognized ChatGPT UA and _meta={"openai/session":"bob-chat"}.
  3. Bob’s tool invokes public analytics.capture().

Head emits:

{
  "event": "inside_tool",
  "distinct_id": "alice",
  "properties": {
    "$session_id": "ses_alice",
    "$mcp_session_source": "transport",
    "$set": {"owner": "alice"},
    "marker": "bob"
  }
}

Base/head comparison: without a Bob token, base uses an isolated anonymous generated session; with Bob’s own ses_bob token, base uses that session anonymously. Both head variants inherit Alice. Removing Bob’s metadata makes the head control pass. Bob’s automatic tool-call event is correctly attributed; this failure concerns earlier custom capture.

Passing client_conversation into priming takes the resolver’s early return before transport/memory priming and previous-token clearing. McpAnalytics.capture() still reads shared data.session_id (__init__.py:163–176); _capture.py:32–33 retrieves Alice’s cached actor under it.

This violates canonical session/person isolation and the preceding-caller invariant in test_conversation_session.py:301–356.

Executed regression: regression_identity.py, default and bob-token modes. Both pass base and fail head:

assert bob["properties"]["$session_id"] != "ses_alice"
assert bob["distinct_id"] != "alice"
assert bob["properties"].get("$set", {}).get("owner") != "alice"

The first assertion fails; printed payloads independently confirm the wrong person and $set.

Consider separating custom-capture priming from request-local metadata grouping so metadata selection cannot bypass caller isolation. A safe anonymous fallback is sufficient; this need not introduce earlier identification or globally persist metadata sessions. Retain both token variants and the no-metadata control.

Impact limits: sequential valid requests suffice; no concurrency, private-state mutation or malformed input. Wrong attribution is within the receiving PostHog project. No authentication bypass, cross-project disclosure or live backend mutation was demonstrated.

Executed regression commands

Base: 5febc73aa74b38376a9d9cac895552686cefaca2; reviewed head: 3cbcd29b479ff2e47473a169c206b154b4c30378.

These are executed tests, not unexecuted sketches. Both pinned snapshots used Python 3.11.13 / MCP 1.28.1 with the same dependencies and sandbox. Local paths are represented by environment variables:

E="$REVIEW_EVIDENCE_DIR"
V="$REVIEW_VALIDATION_DIR"
PY="$REVIEW_PYTHON"
cd "$V"
for S in "$BASE_WORKTREE" "$HEAD_WORKTREE"; do
  for MODE in default bob-token; do
    env -i HOME="$V" TMPDIR="$V" PATH=/usr/bin:/bin PYTHONDONTWRITEBYTECODE=1 \
      /usr/bin/sandbox-exec -f "$E/sandbox.sb" \
      "$PY" -S "$E/regression_identity.py" "$S" "$MODE"
  done
  env -i HOME="$V" TMPDIR="$V" PATH=/usr/bin:/bin PYTHONDONTWRITEBYTECODE=1 \
    PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 /usr/bin/sandbox-exec -f "$E/sandbox.sb" \
    "$PY" -S "$E/run_pytest.py" "$S" "$E/test_followup_regressions.py" \
    --rootdir="$E" --confcutdir="$E" -o asyncio_mode=auto -q -s
done

Identity variants: base exit 0, head exit 1. Follow-up harness: base 6 passed, head 4 failed / 2 passed. No fixes were applied or tested.

elif minted and (
token is not None
or bool(mcp_session_id)
or (client is not None and client.handle_free)

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.

2. [P1] Handle-free HTTP requests without usable metadata share a session and person properties

IMPORTANT · REQUIRED · Existing fallback defect newly exposed by handle suppression
Location: posthog/mcp/_instrumentation.py:744–749. Related fallback: session.py:189–197.

On a shared stateless HTTP server, two recognized ChatGPT calls without valid openai/session receive the same process session. With request-based identification, Bob’s automatic event also receives Alice-only properties.

Minimal traffic, with default conversation anchoring enabled:

Alice: ChatGPT UA, no session header, tools/call, _meta={}
Bob:   ChatGPT UA, no session header, tools/call, _meta={}

The same occurs with _meta={"openai/session":""}. Identification returns disjoint properties:

return UserIdentity(
    distinct_id=who,
    properties={who + "_only": "present"},
)

Observed head output:

Alice: session S, distinct_id alice, $set {alice_only: present}
Bob:   session S, distinct_id bob,   $set {alice_only: present, bob_only: present}

Base mints distinct handles, derives separate sessions and keeps the properties separate.

The new branch suppresses handles as required, but falls back to shared process memory intended for one-client connections. Identity properties then merge under that shared session (_internal.py:158–168,201–204).

Canonical “Session identity” rule 4 requires a fresh session for sessionless HTTP; the explicit invalid handle-free-ID scenario requires different sessions. The new test checks fresh pods, masking shared-pod reuse.

Executed regression: test_handle_free_http_requests_stay_isolated[missing] and [empty] in test_followup_regressions.py; both pass base and fail head:

assert calls[0]["properties"]["$session_id"] != calls[1]["properties"]["$session_id"]
assert "alice_only" not in calls[1]["properties"].get("$set", {})

Printed events independently establish copied properties after the first assertion fails.

Consider a fresh request-local generated fallback for sessionless HTTP, consistently reused throughout that request, while retaining connection-scoped fallback for stdio/in-memory transports. Do not restore ChatGPT handles or mint a different ID at every resolver invocation.

Impact limits: missing/invalid metadata is an explicit contract boundary; its live ChatGPT frequency is unknown. Normal valid metadata is not claimed to merge automatic events. Cross-user $set emission is observed; deployed person updates were not executed.

Executed regression commands

Base: 5febc73aa74b38376a9d9cac895552686cefaca2; reviewed head: 3cbcd29b479ff2e47473a169c206b154b4c30378.

These are executed tests, not unexecuted sketches. Both pinned snapshots used Python 3.11.13 / MCP 1.28.1 with the same dependencies and sandbox. Local paths are represented by environment variables:

E="$REVIEW_EVIDENCE_DIR"
V="$REVIEW_VALIDATION_DIR"
PY="$REVIEW_PYTHON"
cd "$V"
for S in "$BASE_WORKTREE" "$HEAD_WORKTREE"; do
  for MODE in default bob-token; do
    env -i HOME="$V" TMPDIR="$V" PATH=/usr/bin:/bin PYTHONDONTWRITEBYTECODE=1 \
      /usr/bin/sandbox-exec -f "$E/sandbox.sb" \
      "$PY" -S "$E/regression_identity.py" "$S" "$MODE"
  done
  env -i HOME="$V" TMPDIR="$V" PATH=/usr/bin:/bin PYTHONDONTWRITEBYTECODE=1 \
    PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 /usr/bin/sandbox-exec -f "$E/sandbox.sb" \
    "$PY" -S "$E/run_pytest.py" "$S" "$E/test_followup_regressions.py" \
    --rootdir="$E" --confcutdir="$E" -o asyncio_mode=auto -q -s
done

Identity variants: base exit 0, head exit 1. Follow-up harness: base 6 passed, head 4 failed / 2 passed. No fixes were applied or tested.

server,
data,
tools,
advertise_conversation_id=lifecycle.advertises_conversation_id,

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.

3. [P1] Mixed-client listings turn successful FastMCP results into validation errors

IMPORTANT · REQUIRED · Introduced regression
Location: posthog/mcp/_instrument_fastmcp.py:296–300. Related mirroring/state: :182–185, _instrumentation.py:1270–1273.

Ordinary sequential requests on one official MCP 1.x FastMCP instance turn a successful strict-schema tool result into an error:

1. Ordinary client: tools/list
2. ChatGPT client:  tools/list
3. Ordinary client: tools/call

Example tool:

class StrictResult(BaseModel):
    model_config = ConfigDict(extra="forbid")
    value: int

@server.tool()
def probe() -> StrictResult:
    return StrictResult(value=7)

Head returns:

{
  "content": [{
    "type": "text",
    "text": "Output validation error: Additional properties are not allowed ('_mcp_instructions' was unexpected)"
  }],
  "isError": true
}

Expected: the successful application result reaches the caller. Base does so.

The first listing sets shared tool_output_instructions["probe"]=True. The ChatGPT listing replaces the framework’s cached Tool with a strict schema lacking _mcp_instructions, but leaves that flag true. The next ordinary call mirrors the forbidden property; the outer framework validator rejects it.

Installed official MCP source confirms listings populate _tool_cache and call results are validated against it. PostHog’s FastMCP mirror executes inside that validator’s call path.

Canonical observer-only instrumentation forbids converting a successful result into failure. Optional mirroring still requires compatible declarations; official MCP requires structured results to conform to their output schema.

Executed regression: test_automatic_mixed_client_listings_keep_output_validation[other-then-chatgpt]; base passes, head fails:

assert not result.get("isError"), result
assert result["structuredContent"]["value"] == 7

The head’s ChatGPT-first-only control passes. The PR’s dismissal of that simpler ordering does not cover this failure.

Consider separating client-specific advertisements from a framework validation cache compatible with every result instrumentation can write, preserving ChatGPT’s unchanged listing. Retain both ordering cases.

Impact limits: reproduced on official MCP 1.28.1, shared instance, anchoring enabled and strict structured output. No new-regression execution claim is made for MCP 2.x or standalone FastMCP. This is actual response failure, not merely loss of optional mirroring.

Executed regression commands

Base: 5febc73aa74b38376a9d9cac895552686cefaca2; reviewed head: 3cbcd29b479ff2e47473a169c206b154b4c30378.

These are executed tests, not unexecuted sketches. Both pinned snapshots used Python 3.11.13 / MCP 1.28.1 with the same dependencies and sandbox. Local paths are represented by environment variables:

E="$REVIEW_EVIDENCE_DIR"
V="$REVIEW_VALIDATION_DIR"
PY="$REVIEW_PYTHON"
cd "$V"
for S in "$BASE_WORKTREE" "$HEAD_WORKTREE"; do
  for MODE in default bob-token; do
    env -i HOME="$V" TMPDIR="$V" PATH=/usr/bin:/bin PYTHONDONTWRITEBYTECODE=1 \
      /usr/bin/sandbox-exec -f "$E/sandbox.sb" \
      "$PY" -S "$E/regression_identity.py" "$S" "$MODE"
  done
  env -i HOME="$V" TMPDIR="$V" PATH=/usr/bin:/bin PYTHONDONTWRITEBYTECODE=1 \
    PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 /usr/bin/sandbox-exec -f "$E/sandbox.sb" \
    "$PY" -S "$E/run_pytest.py" "$S" "$E/test_followup_regressions.py" \
    --rootdir="$E" --confcutdir="$E" -o asyncio_mode=auto -q -s
done

Identity variants: base exit 0, head exit 1. Follow-up harness: base 6 passed, head 4 failed / 2 passed. No fixes were applied or tested.

self._conversation_ownership.update(
{
name: _ConversationOwnership(owned.conversation_id, False)
for name, owned in ownership.items()

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.

4. [P1] A ChatGPT manual listing suppresses later declarations while ordinary results still mirror them

IMPORTANT · REQUIRED · Introduced regression
Location: posthog/mcp/posthog_mcp.py:903–907. Related ownership merge: 899–901.

A shared manual dispatcher can advertise a strict schema and then return data violating it after serving ChatGPT followed by an ordinary client:

chatgpt = {"user-agent": "openai-mcp/1.0.0 (ChatGPT)"}
other = {"user-agent": "example-client/1.0"}

client.prepare_tool_list([original], context=False, headers=chatgpt)
[listed] = client.prepare_tool_list([original], context=False, headers=other)
call = client.prepare_tool_call(
    "probe", {}, original_tool=original, headers=other,
)
prepared = client.prepare_tool_result(
    {"content": [{"type": "text", "text": "ok"}],
     "structuredContent": {"value": 7}},
    call,
)

For an original plain-object output schema declaring integer value and additionalProperties: false, head’s ordinary listing does not declare _mcp_instructions, but its result contains it. Expected: the schema and returned structured content remain compatible.

The new non-advertising branch stores output_instructions=False in persistent ownership. The monotonic AND merge keeps it false for later ordinary listings. However, recommended prepare_tool_call(original_tool=...) independently recognizes the extendable original schema and enables mirroring.

This follows the documented original-tool preparation path. Canonical conversation rules permit mirroring only with a declaration; official MCP requires schema-conforming structured results.

Executed regression: test_manual_client_specific_listing_does_not_poison_ownership[chatgpt-then-other]; base passes and head fails:

jsonschema.validate(
    prepared.result["structuredContent"], listed["outputSchema"]
)
# ValidationError: '_mcp_instructions' was unexpected

The head’s ordinary-only control passes. Base lacks headers, so the harness uses equivalent supported helpers without those new arguments; this is not a signature/import failure.

Consider keeping per-client suppression separate from persistent application-field ownership, so an ordinary listing advertises the declaration its ordinary result path will use. Preserve genuine application ownership and the two regression controls.

Impact limits: actual public preparation methods and returned schema/result were exercised. Strict validating clients can reject the response; no end-to-end MCP client was run for this manual case. This is a forbidden returned field, not merely an omitted optional mirror.

Executed regression commands

Base: 5febc73aa74b38376a9d9cac895552686cefaca2; reviewed head: 3cbcd29b479ff2e47473a169c206b154b4c30378.

These are executed tests, not unexecuted sketches. Both pinned snapshots used Python 3.11.13 / MCP 1.28.1 with the same dependencies and sandbox. Local paths are represented by environment variables:

E="$REVIEW_EVIDENCE_DIR"
V="$REVIEW_VALIDATION_DIR"
PY="$REVIEW_PYTHON"
cd "$V"
for S in "$BASE_WORKTREE" "$HEAD_WORKTREE"; do
  for MODE in default bob-token; do
    env -i HOME="$V" TMPDIR="$V" PATH=/usr/bin:/bin PYTHONDONTWRITEBYTECODE=1 \
      /usr/bin/sandbox-exec -f "$E/sandbox.sb" \
      "$PY" -S "$E/regression_identity.py" "$S" "$MODE"
  done
  env -i HOME="$V" TMPDIR="$V" PATH=/usr/bin:/bin PYTHONDONTWRITEBYTECODE=1 \
    PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 /usr/bin/sandbox-exec -f "$E/sandbox.sb" \
    "$PY" -S "$E/run_pytest.py" "$S" "$E/test_followup_regressions.py" \
    --rootdir="$E" --confcutdir="$E" -o asyncio_mode=auto -q -s
done

Identity variants: base exit 0, head exit 1. Follow-up harness: base 6 passed, head 4 failed / 2 passed. No fixes were applied or tested.

@dustinbyrne
dustinbyrne requested a review from a team November 5, 2026 22:28

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants