Skip to content

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

Merged
gesh merged 13 commits into
mainfrom
georgis/mcp-initialize-real-handshake
Oct 23, 2026
Merged

gesh merged 13 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. Until now, it sent $mcp_initialize on the first request of each session, once per process.
  • That count was wrong in three cases. A stateless fleet sent one event for each pod that a session reached. A client that connected and left sent none. On MCP SDK 2.x, 2026-07-28 requests sent one, but that spec has no initialize.
  • The MCP analytics spec allows $mcp_initialize only for an initialize that the client sent.

Changes

The SDK now sends one $mcp_initialize for each initialize request, in the session that the client's later requests use.

Setup Where the SDK sees the handshake
MCP SDK 2.x, any transport A hook in Server.middleware. The SDK hands it the parsed initialize.
MCP SDK 1.x over HTTP PostHogMcpStatelessSessionMiddleware. It parses each request with no Mcp-Session-Id as JSON, as it already did to mint the token. It records the event when the response starts.
MCP SDK 1.x over stdio or SSE No change. The first request of the session stands in.
  • instrument() binds the middleware on the apps that it autowires. If you mount the middleware by hand, pass the new optional server= argument. Without it, each pod still sends the event on its first request.
  • identify and event_properties run inline in the handshake request, the same as on a tool call. The capture runs in the background, and analytics.flush() waits for it.
  • The event now has $mcp_parameters with the handshake request. On MCP SDK 2.x, it also has $mcp_response with the server reply.
  • A session that an echoed conversation_id anchors no longer gets its own $mcp_initialize.
  • Fix: a client that disconnects mid-body now reaches the app as a disconnect, not as a complete partial request.

Check in review

  • On MCP SDK 2.x, a stateful server keeps its session id on the private ServerSession._connection. A guard handles it, and the stateful tests fail if the SDK renames it.
  • On MCP SDK 1.x, the middleware reads only the response status and Mcp-Session-Id. So the event has the protocol version that the client asked for, and an initialize that fails with a JSON-RPC error still counts.
  • On MCP SDK 1.x, extra["ctx"] for the handshake callbacks has only .request. 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.

Known limits

  • A middleware without server= keeps the per-pod event.
  • On MCP SDK 1.x, an initialize that reuses an existing Mcp-Session-Id gets no event. The middleware does not read requests that carry one, so tool calls stay unread.
  • On MCP SDK 1.x over stdio or SSE, a client that sends initialize and nothing else gets no event.
  • Where the first request stands in, a first request that echoes a conversation_id gets no event.

💚 How did you test it?

  • test_initialize_handshake.py drives real apps with raw JSON-RPC and counts the events. Two pods with round-robin requests stand in for a fleet.
  • It covers the SDK high-level server, standalone fastmcp, and a low-level Server on both majors. It also runs real stdio and SSE servers, and a PostHogMCP dispatcher.
  • Count cases: one handshake across pods, reconnects, a bare handshake, and stateful transports.
  • Other cases: OAuth context in identify, a hung identify, flush(), an escaped or nested method, and the 2026-07-28 spec.
  • Against main, 23 of the new tests fail on SDK 1.x and 28 fail on SDK 2.x.
  • The MCP suites pass on Python 3.10 and 3.14. SDK 1.x runs mcp 1.30.0 with fastmcp 3.x, and SDK 2.x runs mcp 2.3.0 with fastmcp 4.1.0.
  • Manual run on 0773e32 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.

📝 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).
  • On SDK 2.x, it uses the hook that the SDK gives for initialize. SDK 1.x has no such hook, so the ASGI middleware observes the handshake over HTTP, and stdio 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 <[email protected]>
@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-10-23T12:02:36.488961+00:00
Duration: 259289ms

✅ 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 ✅ 510ms
Required Headers.Has Authorization Bearer Header ✅ 508ms
Required Headers.Has Content Type Json ✅ 509ms
Required Headers.Has Posthog Sdk Info Format ✅ 508ms
Required Headers.Has Posthog Attempt Header ✅ 508ms
Required Headers.Has Posthog Request Id ✅ 508ms
Required Headers.Has Posthog Request Timestamp ✅ 509ms
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 ✅ 509ms
Event Format.Event Has Required Root Fields ✅ 508ms
Event Format.Event Uuid Is Valid ✅ 508ms
Event Format.Event Timestamp Is Rfc3339 ✅ 509ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 526ms
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 ✅ 507ms
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 ✅ 510ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 511ms
Event Format.Custom Properties Preserved Batch ✅ 511ms
Event Format.Set Properties Preserved Batch ✅ 510ms
Event Format.Set Once Properties Preserved Batch ✅ 511ms
Event Format.Groups Properties Preserved Batch ✅ 510ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 510ms
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 ✅ 1008ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 509ms
Deduplication.Generates Unique Uuids ✅ 513ms
Deduplication.Different Events Same Content Different Uuids ✅ 510ms
Deduplication.Preserves Uuid On Retry ✅ 6517ms
Deduplication.Preserves Timestamp On Retry ✅ 6514ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6515ms
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 ✅ 6517ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 3015ms
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 ✅ 511ms
Response Format Validation.Success No Retry After When All Ok ✅ 510ms
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 ✅ 8519ms
Retry Behavior.Retries On 504 ✅ 6513ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3514ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11520ms
Retry Behavior.Does Not Retry On 400 ✅ 2511ms
Retry Behavior.Does Not Retry On 401 ✅ 2511ms
Retry Behavior.Does Not Retry On 402 ✅ 2509ms
Retry Behavior.Does Not Retry On 413 ✅ 2511ms
Retry Behavior.Does Not Retry On 415 ✅ 2511ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2511ms
Retry Behavior.Implements Backoff ✅ 22531ms
Retry Behavior.Max Retries Respected ✅ 22521ms
Partial Batch Handling.Handles 200 Full Success ✅ 2511ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3514ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3514ms
Partial Batch Handling.Does Not Retry Limited Events ✅ 3513ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6518ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6518ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6517ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6518ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6518ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6519ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8514ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3513ms
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 ✅ 508ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2511ms
Event Options.Cookieless Mode Override ✅ 509ms
Event Options.Disable Skew Correction Override ✅ 508ms
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 ✅ 510ms
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 ✅ 508ms
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 ✅ 9ms
Request Payload.Flags Request Uses V2 Query Param ✅ 6ms
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 ✅ 6ms
Request Payload.Groups Round Trip ✅ 7ms
Request Payload.Groups Default To Empty Object ✅ 6ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 7ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 8ms
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 ✅ 310ms
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 ✅ 46ms
Versioned Boolean Matching.Matching Version 1 ✅ 46ms
Versioned Boolean Matching.Matching Version 2 ✅ 45ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 25ms

@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
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 <[email protected]>
- 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 <[email protected]>
@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 Outdated
@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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
@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 <[email protected]>
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 <[email protected]>
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 <[email protected]>

@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.

Comment thread posthog/mcp/_instrument_v2.py Outdated
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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks, good catch. The detached recorder was the real problem, so I removed it instead of capping it.

20c1243 runs identify and event_properties inline in the handshake request on both hooks, the same as on a tool call. A hung callback now holds that one request, where the host sees it, and leaves no analytics task behind. The capture still goes out in the background afterwards.

test_a_hung_identify_leaves_no_task_behind runs your scenario on all three server types and both SDK majors. It sends 5 handshakes against an identify that never returns, then asserts 0 pending tasks and that flush() returns. After the callback recovers, the SDK records the next handshake. On bb21c6a the test fails on the pending recorder tasks.

The trade-off: on both SDK majors the handshake reply now waits for identify, as a tool call already does. Since 132eaef the v1 middleware records it when the response starts, inside the request context.

Both handshake hooks ran identify and event_properties in a detached
background task. If a callback never returned, each handshake left one
more task pending, with no bound, and flush() waited for all of them.
The spec requires pending state to be bounded by count.

The hooks now run the callbacks inline, the same as a tool call does. A
hung callback holds that request, where the host sees it, and leaves no
task behind. The capture still runs in the background after the
callbacks, as for every other event.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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 20c1243: 2 Should fix.

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.

Comment thread posthog/mcp/asgi.py Outdated
Comment thread posthog/mcp/asgi.py Outdated
gesh and others added 2 commits October 23, 2026 11:41
The session middleware sits outside FastMCP's AuthContextMiddleware. It
ran identify after the app returned, when that middleware had already
reset the authenticated user. An identify that calls get_access_token()
got None, so $mcp_initialize stayed anonymous under OAuth. The
middleware now records the handshake when the response starts, while
the app still handles the request.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The 4 KB peek stopped when "initialize" was not in the first 4 KB. JSON
key order is arbitrary, so an initialize with large params before its
method got no event. The peek now stops only when the prefix shows a
"method" and no "initialize". Without a method yet, it reads up to the
full cap.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@marandaneto

Copy link
Copy Markdown
Member

already approved so wont approve again, left 2 new comments tho, address them if they make sense

@marandaneto marandaneto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Two reproduced blocking findings from the review. The complete patch was revalidated before posting.

Comment thread posthog/mcp/asgi.py Outdated
if not peeked and total >= _PEEK_BODY:
peeked = True
prefix = b"".join(chunks)
if b'"method"' in prefix and b'"initialize"' not in prefix:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

blocking: A nested method can still hide the actual initialize method. The latest cutoff handles a missing method in the prefix, but it also matches nested keys: an initialize with an existing session header and params first can contain capabilities.experimental.vendor = {"method": "custom", "padding": ...} before its top-level method. With over 4 KB of parameters, buffering stops at that nested key, so SDK 1.x successfully answers the handshake but emits no $mcp_initialize; the bound middleware also suppresses the fallback. Only the top-level RPC method can establish that the request is not initialize. Reproduction: reproduced — test_nested_method_before_top_level_initialize_is_counted received HTTP 200 with a successful result but zero initialize events on the reviewed head; disabling the premature cutoff made it pass.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good catch, thanks. Both of your findings came from the same byte checks, so 0773e32 removes them instead of patching them again.

On SDK 1.x the middleware no longer reads requests that carry an Mcp-Session-Id. Nothing guesses at the method from raw bytes now. The cost is that on SDK 1.x an initialize that reuses an existing session id gets no event. The README lists that limit. SDK 2.x still counts it, because Server.middleware gets the parsed method from the SDK.

Your case is now test_a_nested_method_before_the_top_level_initialize_is_counted. It runs on SDK 2.x for all three server types.

Comment thread posthog/mcp/asgi.py Outdated
"""The JSON-RPC message in ``body`` if it is an ``initialize`` request, else
``None`` (never raises)."""
# Cheap first: with a bound middleware this runs on every tool call too.
if not body or b'"initialize"' not in body:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

blocking: Preserve JSON-escaped initialize methods. The valid JSON method string "\u0069nitialize" decodes to initialize, but this new raw-byte filter rejects it before JSON parsing. This regresses session-token minting even for unbound middleware, losing cross-pod session correlation, and prevents bound SDK 1.x middleware from observing the handshake. Reproduction: reproduced — test_escaped_initialize_still_mints_a_session returned HTTP 200 without Mcp-Session-Id on the reviewed head under both SDK majors, while the identical test passed on the merge base.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed, that one broke behavior that worked on main. Fixed in 0773e32: the middleware parses the body as JSON again before it checks the method, as main does, so "initialize" gets its token and its event.

Your case is now test_an_escaped_initialize_still_mints_a_session, on both SDK majors for all three server types. It fails on 23a0677.

The middleware guessed from raw bytes whether a request was initialize.
A nested "method" key in params stopped the 4 KB peek too early, and a
JSON-escaped "initialize" failed the quick byte check. That second
case also stopped the token mint, which worked before this PR.

The middleware now parses the body as JSON, as main does, and reads
only requests with no Mcp-Session-Id. On MCP SDK 1.x, an initialize
that reuses an existing session id is not captured. The README lists
this limit. MCP SDK 2.x still captures it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@gesh
gesh merged commit 8cd8eb5 into main Oct 23, 2026
44 of 45 checks passed
@gesh
gesh deleted the georgis/mcp-initialize-real-handshake branch October 23, 2026 12:10
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.

3 participants