Skip to content

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

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

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

@geshgesh 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-actionsBot 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
TestStatusDuration
Endpoint And Method.Targets V1 Endpoint515ms
Endpoint And Method.Does Not Use Legacy Endpoints1010ms
Required Headers.Has Authorization Bearer Header1009ms
Required Headers.Has Content Type Json1009ms
Required Headers.Has Posthog Sdk Info Format1009ms
Required Headers.Has Posthog Attempt Header1009ms
Required Headers.Has Posthog Request Id1009ms
Required Headers.Has Posthog Request Timestamp1009ms
Required Headers.Has User Agent1009ms
Body Format.Body Has Created At And Batch1009ms
Body Format.No Api Key In Body1009ms
Body Format.No Sent At In Body1009ms
Event Format.Event Has Required Root Fields1009ms
Event Format.Event Uuid Is Valid1010ms
Event Format.Event Timestamp Is Rfc33391008ms
Event Format.Distinct Id Is String1010ms
Event Format.Distinct Id At Root Not Properties1009ms
Event Format.Custom Properties Preserved1009ms
Event Format.Set Properties Preserved1009ms
Event Format.Set Once Properties Preserved1009ms
Event Format.Groups Properties Preserved1009ms
Event Format.Sdk Generates Uuid If Not Provided1009ms
Event Format.Event Has Required Root Fields Batch1012ms
Event Format.Event Uuid Is Valid Batch1013ms
Event Format.Event Timestamp Is Rfc3339 Batch1013ms
Event Format.Distinct Id Is String Batch1013ms
Event Format.Distinct Id At Root Not Properties Batch1012ms
Event Format.Custom Properties Preserved Batch1012ms
Event Format.Set Properties Preserved Batch1012ms
Event Format.Set Once Properties Preserved Batch1012ms
Event Format.Groups Properties Preserved Batch1013ms
Event Format.Sdk Generates Uuid If Not Provided Batch1012ms
Batch Behavior.Multiple Events In Single Batch1507ms
Batch Behavior.Batch Envelope Smoke1014ms
Batch Behavior.Flush With No Events Sends Nothing1005ms
Batch Behavior.Flush At Triggers Batch1509ms
Batch Behavior.Created At Reflects Batch Creation Time1011ms
Deduplication.Generates Unique Uuids1506ms
Deduplication.Different Events Same Content Different Uuids1507ms
Deduplication.Preserves Uuid On Retry7513ms
Deduplication.Preserves Timestamp On Retry7512ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry7512ms
Deduplication.No Duplicate Events In Batch1504ms
Header Behavior On Retry.Attempt Header Starts At One1008ms
Header Behavior On Retry.Attempt Header Increments On Retry14522ms
Header Behavior On Retry.Request Id Preserved On Retry7509ms
Header Behavior On Retry.Different Requests Have Different Request Ids3515ms
Header Behavior On Retry.Request Timestamp Changes On Retry7511ms
Response Format Validation.Success Response Has Uuid Keyed Results1009ms
Response Format Validation.Success Response Has Ok For Each Event1507ms
Response Format Validation.Success No Retry After When All Ok1507ms
Response Format Validation.Success Retry After Present When Retry Events2510ms
Response Format Validation.Success No Retry After When Drop Only1507ms
Response Format Validation.Response Echoes Request Id1009ms
Retry Behavior.Retries On 4087514ms
Retry Behavior.Retries On 5007510ms
Retry Behavior.Retries On 5039514ms
Retry Behavior.Retries On 5047513ms
Retry Behavior.Retryable Errors Have Retry After4509ms
Retry Behavior.Respects Retry After On Retryable Error12511ms
Retry Behavior.Does Not Retry On 4003508ms
Retry Behavior.Does Not Retry On 4013509ms
Retry Behavior.Does Not Retry On 4023506ms
Retry Behavior.Does Not Retry On 4133509ms
Retry Behavior.Does Not Retry On 4153507ms
Retry Behavior.Non Retryable Errors Have No Retry After3508ms
Retry Behavior.Implements Backoff23530ms
Retry Behavior.Max Retries Respected23510ms
Partial Batch Handling.Handles 200 Full Success3012ms
Partial Batch Handling.Handles 200 With All Ok4508ms
Partial Batch Handling.Does Not Retry Dropped Events4509ms
Partial Batch Handling.Does Not Retry Limited Events4507ms
Partial Batch Handling.Prunes Ok Events On Partial Retry7514ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry7511ms
Partial Batch Handling.Retries Only Retry Events From Partial7511ms
Partial Batch Handling.Partial Retry Preserves Uuids7512ms
Partial Batch Handling.Partial Retry Attempt Header Increments7512ms
Partial Batch Handling.Partial Retry Request Id Preserved7512ms
Partial Batch Handling.Respects Retry After On Partial9511ms
Partial Batch Handling.Unknown Result Treated As Terminal4505ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry4509ms
Compression.Sends Gzip Content Encoding1007ms
Compression.No Content Encoding When Disabled1009ms
Compression.Compressed Body Is Decompressible1008ms
Error Handling.Does Not Retry On Unknown 4Xx3510ms
Event Options.Cookieless Mode Override1008ms
Event Options.Disable Skew Correction Override1009ms
Event Options.Process Person Profile Override1009ms
Event Options.Product Tour Id Override1009ms
Event Options.Unset Options Omitted1009ms
Event Options.Options Override In Batch1011ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties1009ms
Geoip And Historical Migration.Historical Migration Set In Body1009ms
Geoip And Historical Migration.Historical Migration Absent By Default1009ms

Feature_Flags Tests

17/17 tests passed

View Details
TestStatusDuration
Request Payload.Request With Person Properties Device Id1006ms
Request Payload.Flags Request Uses V2 Query Param1007ms
Request Payload.Flags Request Hits Flags Path Not Decide1007ms
Request Payload.Flags Request Omits Authorization Header1006ms
Request Payload.Token In Flags Body Matches Init1007ms
Request Payload.Groups Round Trip1006ms
Request Payload.Groups Default To Empty Object1006ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False1007ms
Request Payload.Disable Geoip Omitted Defaults To False1006ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key1007ms
Request Lifecycle.No Flags Request On Init Alone503ms
Request Lifecycle.No Flags Request On Normal Capture1506ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests1011ms
Request Lifecycle.Mock Response Value Is Returned To Caller1002ms
Retry Behavior.Retries Flags On 5021007ms
Retry Behavior.Retries Flags On 5041006ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event1509ms

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
@github-actions

Copy link
Copy Markdown
Contributor

This PR hasn't seen activity in a week! Should it be merged, closed, or further worked on? If you want to keep it open, post a comment or remove the stale label – otherwise this will be closed in another week.

@github-actions

Copy link
Copy Markdown
Contributor

This PR was closed due to lack of activity. Feel free to reopen if it's still relevant.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@gesh