Skip to content

fix(mcp): send one $mcp_initialize per initialize request - #1103

Open
gesh wants to merge 9 commits into
mainfrom
georgis/mcp-initialize-real-handshake
Open

gesh wants to merge 9 commits into
mainfrom
georgis/mcp-initialize-real-handshake

Conversation

@gesh

@gesh gesh commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

💡 Motivation and Context

  • The Python MCP SDK answers initialize itself, so posthog.mcp cannot wrap it the way @posthog/mcp does. Until now, the SDK sent $mcp_initialize on the first request of each session, once per process.
  • That count is wrong in three cases:
    • A stateless fleet sends one event for each pod that a session reaches. Two pods send two events per connection.
    • A client that connects and sends no other request sends no event. Probes and health checkers do this.
    • On MCP SDK 2.x, each 2026-07-28 request can send one, but that spec has no initialize.
  • The MCP analytics spec allows $mcp_initialize only for an initialize request that the client sent.

Changes

  • MCP SDK 2.x: instrument() adds a hook to Server.middleware. The hook sees each initialize, on every transport.
  • MCP SDK 1.x over HTTP: PostHogMcpStatelessSessionMiddleware already reads the initialize body to mint the session token. Now it also sends the event after the response. The event uses the Mcp-Session-Id that the client sends back, so the event and the later requests share one $session_id.
  • The apps that instrument() autowires bind the middleware to the server. If you mount the middleware by hand, pass the new optional server= argument. Without it, nothing changes: each pod sends the event on the first request.
  • The bound middleware marks each request that it passes on. The first-request fallback stops only for marked requests, so a route without the middleware keeps the fallback.
  • The deprecated SSE transport keeps its session in a query parameter. On SDK 1.x, its first request still stands in for initialize. On SDK 2.x, the hook puts the event in the session that the SSE calls use.
  • The hooks compute the handshake session without a write to the server's shared session, which McpAnalytics.capture() reads.
  • An initialize that carries an existing Mcp-Session-Id gets an event in that session. On SDK 1.x, a bound middleware reads up to 4 KB of such a POST. If "initialize" is not in it, the rest of the body streams to the app unread.
  • A client that disconnects while it sends the body now reaches the app as a disconnect, not as a complete partial request.
  • analytics.flush() waits for the handshake capture.
  • MCP SDK 1.x over stdio: no change. The first request still stands in for initialize. A stdio server has one client, so the count stays correct.
  • A session that an echoed conversation_id anchors no longer gets its own $mcp_initialize.
  • The event now has $mcp_parameters with the handshake request. On MCP SDK 2.x, it also has $mcp_response with the server reply, the same as @posthog/mcp.

Check in review

  • On MCP SDK 2.x, a stateful server keeps its session id on ServerSession._connection, which is private. The code reads it with a guard, and a test covers it.
  • On MCP SDK 1.x, the hook reads only the status and the Mcp-Session-Id header of the response, not the body. So the event has the protocol version that the client asked for, and no $mcp_response. An initialize that fails with a JSON-RPC error still counts, because that error comes back as HTTP 200.
  • On MCP SDK 1.x, the identify and event_properties callbacks for the handshake get an extra["ctx"] that has only .request. The SDK has no request context at that point. get_request_headers(extra) works as before.
  • The $mcp_initialize count goes down for stateless Python fleets. The default MCP dashboard counts users and sessions from this event.
  • These cases still differ from the spec:
    • A middleware without server= keeps the old per-pod event.
    • On MCP SDK 1.x over stdio or SSE, a client that sends initialize and then nothing else gets no event.
    • A batched initialize gets no event. The spec does not allow one.
    • Where the first request stands in, a client whose first request already echoes a conversation_id gets no event.

💚 How did you test it?

  • The new file test_initialize_handshake.py sends raw JSON-RPC over HTTP to real apps and counts the events. Two pods with round-robin requests stand in for a fleet.
    • Server types: SDK FastMCP or MCPServer, standalone fastmcp (3.x on SDK 1.x, 4.x on SDK 2.x), and a low-level Server.
    • Count cases: one handshake across pods, reconnects, a handshake with no other request, and a stateful transport.
    • Other cases: identify, a failed initialize (SDK 2.x), an echoed conversation, and the 2026-07-28 spec.
    • Middleware cases: a route without the middleware, the shared session after a handshake, and a server= value that cannot be bound.
    • Lifecycle cases: flush() with a slow before_send, and an initialize with an existing session header.
    • stdio: a real server process, with JSON-RPC on its stdin and stdout.
    • SSE: a real uvicorn server and a client that reads the event stream.
    • A PostHogMCP dispatcher behind a middleware without server= sends only its own event.
  • Against main, 19 of the new tests fail on SDK 1.x and 20 fail on SDK 2.x.
  • The MCP suites pass on Python 3.10 and 3.14, on both SDK majors. v1 uses mcp 1.30.0 with fastmcp 3.x. v2 uses mcp 2.3.0 with fastmcp 4.1.0.
  • Manual run with real uvicorn servers and a client that reconnects 3 times. The table shows the $mcp_initialize count. The main column is posthog 7.75.4 on SDK 1.x.
Setup main This PR
One pod, handshake only 0 3
One pod, handshake and tools/list 3 3
Two pods, handshake and tools/list 3 3
Two pods, handshake, tools/list, and 2 tool calls 6 3

On this PR, the counts are the same for stateful and stateless servers, on both SDK majors. Each event is in the same $session_id as the tool calls of its connection.

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran sampo add to generate a changeset file

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

  • Written with Claude Code, model Claude Opus 5.5 (claude-opus-5-5).
  • Uses the hooks that the SDKs give, not private session code: Server.middleware on SDK 2.x and the ASGI middleware on SDK 1.x. SDK 1.x over stdio has no such hook, so it keeps the first-request fallback.

🤖 Generated with Claude Code

The Python MCP SDK answers initialize itself, so posthog.mcp sent the
event on the first request of each session, once per process. A
stateless fleet sent one event per pod. A client that sent only
initialize sent no event.

Now MCP SDK 2.x reports the event from Server.middleware, on every
transport. MCP SDK 1.x over HTTP reports it from
PostHogMcpStatelessSessionMiddleware, which takes a new optional
server= argument. MCP SDK 1.x over stdio keeps the first-request
fallback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-10-22T15:57:21.774376+00:00
Duration: 259392ms

✅ 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 ✅ 515ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 508ms
Required Headers.Has Authorization Bearer Header ✅ 508ms
Required Headers.Has Content Type Json ✅ 510ms
Required Headers.Has Posthog Sdk Info Format ✅ 508ms
Required Headers.Has Posthog Attempt Header ✅ 508ms
Required Headers.Has Posthog Request Id ✅ 509ms
Required Headers.Has Posthog Request Timestamp ✅ 508ms
Required Headers.Has User Agent ✅ 508ms
Body Format.Body Has Created At And Batch ✅ 509ms
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 ✅ 509ms
Event Format.Event Timestamp Is Rfc3339 ✅ 508ms
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 ✅ 509ms
Event Format.Groups Properties Preserved ✅ 508ms
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 ✅ 511ms
Event Format.Distinct Id Is String Batch ✅ 511ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 511ms
Event Format.Custom Properties Preserved Batch ✅ 510ms
Event Format.Set Properties Preserved Batch ✅ 512ms
Event Format.Set Once Properties Preserved Batch ✅ 511ms
Event Format.Groups Properties Preserved Batch ✅ 511ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 511ms
Batch Behavior.Multiple Events In Single Batch ✅ 514ms
Batch Behavior.Batch Envelope Smoke ✅ 512ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 505ms
Batch Behavior.Flush At Triggers Batch ✅ 1010ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 508ms
Deduplication.Generates Unique Uuids ✅ 514ms
Deduplication.Different Events Same Content Different Uuids ✅ 510ms
Deduplication.Preserves Uuid On Retry ✅ 6517ms
Deduplication.Preserves Timestamp On Retry ✅ 6518ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6515ms
Deduplication.No Duplicate Events In Batch ✅ 515ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 508ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 13521ms
Header Behavior On Retry.Request Id Preserved On Retry ✅ 6518ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 3016ms
Header Behavior On Retry.Request Timestamp Changes On Retry ✅ 6513ms
Response Format Validation.Success Response Has Uuid Keyed Results ✅ 509ms
Response Format Validation.Success Response Has Ok For Each Event ✅ 511ms
Response Format Validation.Success No Retry After When All Ok ✅ 511ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 1513ms
Response Format Validation.Success No Retry After When Drop Only ✅ 510ms
Response Format Validation.Response Echoes Request Id ✅ 508ms
Retry Behavior.Retries On 408 ✅ 6517ms
Retry Behavior.Retries On 500 ✅ 6517ms
Retry Behavior.Retries On 503 ✅ 8516ms
Retry Behavior.Retries On 504 ✅ 6517ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3514ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11521ms
Retry Behavior.Does Not Retry On 400 ✅ 2512ms
Retry Behavior.Does Not Retry On 401 ✅ 2511ms
Retry Behavior.Does Not Retry On 402 ✅ 2512ms
Retry Behavior.Does Not Retry On 413 ✅ 2511ms
Retry Behavior.Does Not Retry On 415 ✅ 2512ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2512ms
Retry Behavior.Implements Backoff ✅ 22529ms
Retry Behavior.Max Retries Respected ✅ 22522ms
Partial Batch Handling.Handles 200 Full Success ✅ 2510ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3516ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3513ms
Partial Batch Handling.Does Not Retry Limited Events ✅ 3514ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6518ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6515ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6516ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6516ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6519ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6519ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8518ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3514ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry ✅ 3516ms
Compression.Sends Gzip Content Encoding ✅ 509ms
Compression.No Content Encoding When Disabled ✅ 508ms
Compression.Compressed Body Is Decompressible ✅ 509ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2510ms
Event Options.Cookieless Mode Override ✅ 508ms
Event Options.Disable Skew Correction Override ✅ 509ms
Event Options.Process Person Profile Override ✅ 508ms
Event Options.Product Tour Id Override ✅ 508ms
Event Options.Unset Options Omitted ✅ 508ms
Event Options.Options Override In Batch ✅ 511ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties ✅ 508ms
Geoip And Historical Migration.Historical Migration Set In Body ✅ 508ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 508ms

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 ✅ 509ms
Identity.Capture Ai Event Has Uuid ✅ 508ms
Identity.Capture Ai Keeps Supplied Uuid ✅ 508ms
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 V2 Query Param ✅ 7ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 7ms
Request Payload.Flags Request Omits Authorization Header ✅ 7ms
Request Payload.Token In Flags Body Matches Init ✅ 7ms
Request Payload.Groups Round Trip ✅ 7ms
Request Payload.Groups Default To Empty Object ✅ 7ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 7ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 7ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 8ms
Request Lifecycle.No Flags Request On Init Alone ✅ 2ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 508ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 11ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 7ms
Retry Behavior.Retries Flags On 502 ✅ 311ms
Retry Behavior.Retries Flags On 504 ✅ 311ms
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 ✅ 52ms
Versioned Boolean Matching.Matching Version 1 ✅ 51ms
Versioned Boolean Matching.Matching Version 2 ✅ 51ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 28ms

@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 57d8dc6: 3 Should fix.

This is the only automatic review while this pull request is a draft. Comment @posthog review to review new changes sooner. Otherwise, a review of the new changes runs when you mark it ready for review.

Comment thread posthog/mcp/asgi.py Outdated
Comment thread posthog/mcp/_instrumentation.py Outdated
Comment thread posthog/mcp/_instrumentation.py Outdated
gesh and others added 2 commits October 22, 2026 16:09
The mcp 1.x hook now keeps only the status and the Mcp-Session-Id header
of the initialize response. It no longer parses the JSON or SSE body.
The event uses the protocol version that the client asked for.

record_initialize now reads the client name, version, and protocol from
the initialize params and reply, so both hooks pass them through. The
new tests share their request helpers and drop the SSE body case.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- SSE transport: the initialize event now lands in the session that the
  SSE calls use. On SDK 1.x the middleware leaves SSE requests to the
  first-request fallback. On SDK 2.x the hook uses the process session.
- The bound middleware marks each request that it passes on. The fallback
  now stops only for marked requests, not for every HTTP request.
- The hooks compute the handshake session without a write to the shared
  session that McpAnalytics.capture() reads.
- A server= value that cannot be bound no longer breaks requests.
- Remove the unused _mint_token_if_initialize.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@gesh
gesh marked this pull request as ready for review October 22, 2026 14:56
@gesh
gesh requested a review from a team as a code owner October 22, 2026 14:56
@gesh
gesh removed the request for review from a team October 22, 2026 14:56
@gesh gesh added the reviewhog label Oct 22, 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 1b0fe8f: 2 Should fix.

This Standard review started from the posthog-review label. Comment @posthog review --deep for a Deep review, or @posthog help to see all commands.

Comment thread posthog/mcp/_instrument_v2.py
Comment thread posthog/mcp/_instrument_v2.py
@posthog posthog Bot removed the reviewhog label Oct 22, 2026
gesh and others added 3 commits October 22, 2026 18:29
Both handshake hooks run record_initialize in a tracked background task.
It started the capture as a second task, after flush() took its snapshot
of pending tasks. With a slow before_send, flush() returned early and
shutdown dropped $mcp_initialize. The handshake task now awaits the
capture itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On MCP SDK 2.x, a stateless client can send initialize with an existing
Mcp-Session-Id and keep sending it. Its later calls resolve their
session from that header, but the handshake hook read only the
connection id and the minted token. The event landed in a generated
session. The hook now falls back to the incoming header.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On MCP SDK 1.x, the middleware read the body only of a POST with no
Mcp-Session-Id, because only those need a token. A client that sent
initialize with an existing session id got no event: the middleware
marked the request, so the first-request fallback did not run either.

A middleware bound to a server now reads those bodies too, behind a
cheap check for "initialize". It still mints only without a header. The
event uses the header that the client keeps sending.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@posthog

posthog Bot commented Oct 22, 2026

Copy link
Copy Markdown
Contributor

PostHog Review · Standard · couldn't review da925d5

Something went wrong and the review didn't finish. Push a new commit to run it again.

@posthog

posthog Bot commented Oct 22, 2026

Copy link
Copy Markdown
Contributor

PostHog Review · Standard · couldn't review 0a7a6a4

Something went wrong and the review didn't finish. Push a new commit to run it again.

@gesh
gesh requested review from a team October 22, 2026 15:46
gesh and others added 3 commits October 22, 2026 18:49
When the client disconnected while it sent the body, the middleware
stopped its read and replayed the partial body as a complete request.
The app parsed half a request and never saw the disconnect. The
middleware now replays the partial body with more_body set, then hands
the app the disconnect.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A bound middleware reads the body of a POST that carries a session id,
to catch an initialize that reuses one. That held every tool call in
memory, up to 256 KB, before the app saw it. The middleware now stops
after 4 KB when "initialize" is not in it, and streams the rest.
JSON-RPC clients put "method" before "params", so a handshake shows up
in that window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The v2 handshake hook read the Mcp-Session-Id header and decoded the
token itself. Every later request gets the same pair from _resolve_ctx.
The hook now calls it, so the handshake and later requests follow one
rule and cannot drift apart into two sessions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@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 handshake-count fixes are well covered and reproduce correctly against the base. One optional resource-safety follow-up is noted inline.

AI-assisted review.

return await call_next(ctx)
started = datetime.now(timezone.utc)
result = await call_next(ctx)
fire_and_forget(_record_v2_initialize(data, ctx, result, started), 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] Optional follow-up: bound detached handshake recorder admission

Consider adding a finite, nonblocking per-server admission cap before creating handshake recorder tasks, including the equivalent v1 HTTP path in asgi.py:186–194.

This matters when a configured async identify or event_properties callback stays pending—for example, an identity lookup using httpx.AsyncClient(timeout=None) against a service that accepts the connection but never replies. Each successful handshake can then leave another analytics task waiting after the request finishes and the client disconnects.

With the same gated-callback test on base e17a8be and head bb21c6a, both MCP majors retained 0 tasks on base versus 16, 32, and 1,056 on head after that many completed handshakes. Head flush waited for callback release; releasing the gate drained everything to zero. The regression used an illustrative 1,024-task threshold, not a specification-prescribed number; unconditional scheduling in source establishes the missing bound.

The MCP observer-only contract explicitly calls for count-bounded pending state. Sensible caller-side timeouts and cached lookups substantially mitigate this, though, so I’m treating it as optional hardening rather than a merge requirement. This is not an ordinary-operation leak or a demonstrated production OOM.

A saturation regression should exceed the chosen cap, verify successful unchanged handshake responses and bounded work after disconnect, then verify recording resumes once callbacks finish. An unlimited semaphore wait queue would not bound retained tasks. An admission cap also would not, by itself, guarantee flush termination for a callback that never returns; callback-deadline policy can remain separate.

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.

kind of a stretch, fwiw, given this is only truly unbounded if the caller allows an infinite timeout period - i left this in considering the reference to sdk-specs, but it seems pretty benign to me overall

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