Skip to content

feat(mcp): read client identity from request _meta - #803

Draft
gesh wants to merge 7 commits into
mainfrom
posthog-code/mcp-meta-client-identity
Draft

feat(mcp): read client identity from request _meta#803
gesh wants to merge 7 commits into
mainfrom
posthog-code/mcp-meta-client-identity

Conversation

@gesh

@gesh gesh commented Jul 30, 2026

Copy link
Copy Markdown
Member

The MCP 2026-07-28 spec revision removes the initialize handshake and the Mcp-Session-Id header (SEP-2575 / SEP-2567). Client identity now travels in every request's params._meta, under io.modelcontextprotocol/clientInfo and io.modelcontextprotocol/protocolVersion.

We only read client info from initialize (or from the session token minted there), so under the new spec both sources vanish and $mcp_client_name, $mcp_client_version, and $mcp_protocol_version would silently go null.

This adds support for those _meta fields: a new _client_identity module reads them off whatever each call site has (a FastMCP Context, a low-level RequestContext, a request object, or a plain dict), layered into the shared resolve_session_and_client() so all four adapter call sites pick it up with a one-line change each.

_meta takes precedence over the transport values and the session token, since it's the per-request truth under the new spec. When it's absent nothing changes — legacy clients behave exactly as before.

Parity with the TypeScript SDK, which shipped this in @posthog/mcp 0.10.1 (PostHog/posthog-js#4237).

Testing

18 new tests: the reader, precedence against a real encoded session token, and end-to-end passes through both adapters. Full MCP suite green (159).

Note

check_public_api.py fails on this branch, but it fails identically on a clean main — pre-existing posthog.ai.prompts.config snapshot drift from #801, unrelated to this PR.


Created with PostHog Code

The MCP 2026-07-28 stateless revision removes the initialize handshake and
the Mcp-Session-Id header (SEP-2575 / SEP-2567). Client name/version and the
protocol version now travel in every request's params._meta under
io.modelcontextprotocol/clientInfo and /protocolVersion.

Python previously derived client identity only from client_params.clientInfo
(i.e. from initialize) or from the session token it mints during initialize.
Under the new revision both sources disappear, so $mcp_client_name,
$mcp_client_version and $mcp_protocol_version would all go silently null.

Add a _client_identity module that reads those keys off whatever the call
site has on hand (a FastMCP Context, a low-level RequestContext, a request or
params object, or a plain dict) and layer it into resolve_session_and_client,
which all four adapter call sites already share. _meta takes precedence over
both the transport values and the session token, since it is the per-request
truth under the new revision; when it is absent nothing changes, so legacy
clients behave exactly as before.

Identity is resolved per request rather than in server-wide state, so a
server multiplexing concurrent requests from different clients cannot
cross-attribute them — a real hazard under the stateless spec.

Closes a parity gap with the TypeScript SDK, which shipped this in
@posthog/mcp 0.10.1 (PostHog/posthog-js#4237).

Generated-By: PostHog Code
Task-Id: 14a95eda-2573-4c9a-9191-d5eecb8e8d44
@github-actions

github-actions Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-07-30 15:06:38 UTC
Duration: 338821ms

✅ All Tests Passed!

111/111 tests passed


Capture_V1 Tests

94/94 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint 515ms
Endpoint And Method.Does Not Use Legacy Endpoints 1010ms
Required Headers.Has Authorization Bearer Header 1009ms
Required Headers.Has Content Type Json 1009ms
Required Headers.Has Posthog Sdk Info Format 1009ms
Required Headers.Has Posthog Attempt Header 1009ms
Required Headers.Has Posthog Request Id 1009ms
Required Headers.Has Posthog Request Timestamp 1009ms
Required Headers.Has User Agent 1009ms
Body Format.Body Has Created At And Batch 1009ms
Body Format.No Api Key In Body 1009ms
Body Format.No Sent At In Body 1009ms
Event Format.Event Has Required Root Fields 1009ms
Event Format.Event Uuid Is Valid 1010ms
Event Format.Event Timestamp Is Rfc3339 1008ms
Event Format.Distinct Id Is String 1010ms
Event Format.Distinct Id At Root Not Properties 1009ms
Event Format.Custom Properties Preserved 1009ms
Event Format.Set Properties Preserved 1009ms
Event Format.Set Once Properties Preserved 1009ms
Event Format.Groups Properties Preserved 1009ms
Event Format.Sdk Generates Uuid If Not Provided 1009ms
Event Format.Event Has Required Root Fields Batch 1012ms
Event Format.Event Uuid Is Valid Batch 1013ms
Event Format.Event Timestamp Is Rfc3339 Batch 1013ms
Event Format.Distinct Id Is String Batch 1013ms
Event Format.Distinct Id At Root Not Properties Batch 1012ms
Event Format.Custom Properties Preserved Batch 1012ms
Event Format.Set Properties Preserved Batch 1012ms
Event Format.Set Once Properties Preserved Batch 1012ms
Event Format.Groups Properties Preserved Batch 1013ms
Event Format.Sdk Generates Uuid If Not Provided Batch 1012ms
Batch Behavior.Multiple Events In Single Batch 1507ms
Batch Behavior.Batch Envelope Smoke 1014ms
Batch Behavior.Flush With No Events Sends Nothing 1005ms
Batch Behavior.Flush At Triggers Batch 1509ms
Batch Behavior.Created At Reflects Batch Creation Time 1011ms
Deduplication.Generates Unique Uuids 1506ms
Deduplication.Different Events Same Content Different Uuids 1507ms
Deduplication.Preserves Uuid On Retry 7513ms
Deduplication.Preserves Timestamp On Retry 7512ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 7512ms
Deduplication.No Duplicate Events In Batch 1504ms
Header Behavior On Retry.Attempt Header Starts At One 1008ms
Header Behavior On Retry.Attempt Header Increments On Retry 14522ms
Header Behavior On Retry.Request Id Preserved On Retry 7509ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3515ms
Header Behavior On Retry.Request Timestamp Changes On Retry 7511ms
Response Format Validation.Success Response Has Uuid Keyed Results 1009ms
Response Format Validation.Success Response Has Ok For Each Event 1507ms
Response Format Validation.Success No Retry After When All Ok 1507ms
Response Format Validation.Success Retry After Present When Retry Events 2510ms
Response Format Validation.Success No Retry After When Drop Only 1507ms
Response Format Validation.Response Echoes Request Id 1009ms
Retry Behavior.Retries On 408 7514ms
Retry Behavior.Retries On 500 7510ms
Retry Behavior.Retries On 503 9514ms
Retry Behavior.Retries On 504 7513ms
Retry Behavior.Retryable Errors Have Retry After 4509ms
Retry Behavior.Respects Retry After On Retryable Error 12511ms
Retry Behavior.Does Not Retry On 400 3508ms
Retry Behavior.Does Not Retry On 401 3509ms
Retry Behavior.Does Not Retry On 402 3506ms
Retry Behavior.Does Not Retry On 413 3509ms
Retry Behavior.Does Not Retry On 415 3507ms
Retry Behavior.Non Retryable Errors Have No Retry After 3508ms
Retry Behavior.Implements Backoff 23530ms
Retry Behavior.Max Retries Respected 23510ms
Partial Batch Handling.Handles 200 Full Success 3012ms
Partial Batch Handling.Handles 200 With All Ok 4508ms
Partial Batch Handling.Does Not Retry Dropped Events 4509ms
Partial Batch Handling.Does Not Retry Limited Events 4507ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 7514ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 7511ms
Partial Batch Handling.Retries Only Retry Events From Partial 7511ms
Partial Batch Handling.Partial Retry Preserves Uuids 7512ms
Partial Batch Handling.Partial Retry Attempt Header Increments 7512ms
Partial Batch Handling.Partial Retry Request Id Preserved 7512ms
Partial Batch Handling.Respects Retry After On Partial 9511ms
Partial Batch Handling.Unknown Result Treated As Terminal 4505ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry 4509ms
Compression.Sends Gzip Content Encoding 1007ms
Compression.No Content Encoding When Disabled 1009ms
Compression.Compressed Body Is Decompressible 1008ms
Error Handling.Does Not Retry On Unknown 4Xx 3510ms
Event Options.Cookieless Mode Override 1008ms
Event Options.Disable Skew Correction Override 1009ms
Event Options.Process Person Profile Override 1009ms
Event Options.Product Tour Id Override 1009ms
Event Options.Unset Options Omitted 1009ms
Event Options.Options Override In Batch 1011ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties 1009ms
Geoip And Historical Migration.Historical Migration Set In Body 1009ms
Geoip And Historical Migration.Historical Migration Absent By Default 1009ms

Feature_Flags Tests

17/17 tests passed

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

gesh added 6 commits July 30, 2026 17:09
The first cut generalized over shapes that never reach it: a recursive walk
with a depth cap, plain-dict handling, an attribute-based fallback for
clientInfo, and a MetaClientInfo dataclass fronted by a second function.

Only two shapes actually arrive — a RequestContext (carries `.meta`) and a
request object (nests it under `.params`) — and both expose the reverse-DNS
keys as a plain dict via `model_extra`. Collapse to a single
apply_meta_client_info() over those two, dropping the module from 136 to 68
lines and the tests from 18 to 15 without losing a real case.

Also fixes a bug the simplification surfaced: the FastMCP call site used
getattr(context, "request_context", None), but that property *raises* when a
Context is used off-request, and a getattr default only covers
AttributeError. The ValueError propagated into the caller's tool call.
Route it through a try/except accessor instead, matching the file's other
defensive accessors, and cover it with a regression test (verified failing
against the old call site).

Generated-By: PostHog Code
Task-Id: 14a95eda-2573-4c9a-9191-d5eecb8e8d44
Once the reverse-DNS keys are in hand, reading them is dict access; the
surrounding structure wasn't earning its keep. Drop `_meta_entries()` and the
isinstance ladder for a single try/except around three `meta.get(...)` calls.

The one genuinely load-bearing step is that `_meta` is not a dict when it
reaches us: it arrives as a `RequestParams.Meta`, and because that model is
`extra="allow"` the reverse-DNS keys land in `model_extra` rather than on the
model. That's one getattr, now commented in place.

`_meta` is arbitrary client-controlled JSON, so a `clientInfo` that isn't an
object would raise on `.get`; the try/except covers every malformed shape at
once instead of type-checking each field, and is pinned by a test.

Module is 136 -> 54 lines across the two passes.

Generated-By: PostHog Code
Task-Id: 14a95eda-2573-4c9a-9191-d5eecb8e8d44
Separate the two concerns visually: three lines to get from the pydantic
model to the dict, then plain `.get()` reads. No behavior change.

Records why `model_extra` rather than the more obvious
`params.model_dump(by_alias=True)["_meta"]`: the latter serializes the entire
params payload — tool arguments included — to read two fields, measured 80x
slower on a 20KB argument.

Generated-By: PostHog Code
Task-Id: 14a95eda-2573-4c9a-9191-d5eecb8e8d44
Verified the two key strings against the 2026-07-28 schema and against
mcp 2.0.0, which exports them as CLIENT_INFO_META_KEY and
PROTOCOL_VERSION_META_KEY; they match exactly.

But mcp 2.0.0 (released 2026-07-28, stable) drops RequestParams.Meta and
hands `_meta` over as a plain dict, so `model_extra` doesn't exist there and
the reader returned nothing on the very generation that speaks the revision
it was written for. Take the dict when we're given one and only unwrap
`model_extra` on 1.x.

Also corrects the module docstring, which described v2 as "still beta" — it
is the stable line, and `pip install mcp` now resolves to it.

Generated-By: PostHog Code
Task-Id: 14a95eda-2573-4c9a-9191-d5eecb8e8d44
`dict()` handles both SDK generations in one expression: mcp>=2 hands `_meta`
over as a plain dict, and on 1.x pydantic model iteration yields the
undeclared reverse-DNS keys just the same. Drops the isinstance branch and
the `model_extra` unwrap; verified against both mcp 1.29.0 and 2.0.0.

Generated-By: PostHog Code
Task-Id: 14a95eda-2573-4c9a-9191-d5eecb8e8d44
Tested against mcp 2.0.0, the release that speaks the 2026-07-28 revision.
Three things were wrong there:

- `posthog.mcp` failed to import at all: `_compatibility` did a hard
  `from mcp.server.fastmcp import FastMCP`, and that module is renamed
  `mcp.server.mcpserver` in 2.x. Import both tolerantly and accept either.
- Client identity read `client_params.clientInfo` / `.protocolVersion`;
  2.x spells these `client_info` and puts the negotiated version on the
  request context. Read the new names, falling back to the old.
- `is_tool_result_error` only checked `isError`, spelled `is_error` in 2.x,
  so every tool error on 2.x was recorded as a success.

The tool-call seam itself (`_tool_manager.call_tool`) is unchanged between
majors, so wrapping still works. End to end on 2.0.0 we now capture
$mcp_initialize, $mcp_tool_call and $exception, each carrying
$mcp_client_name, $mcp_client_version and $mcp_protocol_version.

Note the SDK reads `_meta` itself on 2.x and hands back a synthesized
`client_params`, so `_client_identity` only does work on 1.x, which ignores
`_meta` entirely. Both paths are covered.

tools/list is still not captured on 2.x: that release replaces the
`request_handlers` dispatch the listing seam hooks. The version guard now
says so instead of warning the whole major is untested.

Generated-By: PostHog Code
Task-Id: 14a95eda-2573-4c9a-9191-d5eecb8e8d44
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.

1 participant