Skip to content

chore(mcp): enable model capture and conversation correlation by default - #944

Merged
lucasheriques merged 10 commits into
mainfrom
codex/mcp-analytics-defaults
Sep 17, 2026
Merged

lucasheriques merged 10 commits into
mainfrom
codex/mcp-analytics-defaults

Conversation

@lucasheriques

@lucasheriques lucasheriques commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Motivation and changes

Model capture and conversation correlation currently require separate opt-ins. Enable both by default, preserve explicit opt-outs, and leave missing-capability reporting and feedback collection disabled for Gesh's work. Both SDKs follow ADR-0013, which records the decision and compatibility tradeoffs.

Compatible schemas gain llm_model (required on the official high-level adapters, optional elsewhere, never enforced by analytics dispatch) and optional conversation_id. An echoed handle takes precedence, but a newly minted handle no longer replaces an existing transport session or PostHog session token. Sessionless calls can still receive a handle to echo. MCPAnalyticsOptions(capture_model=False, enable_conversation_id=False) restores the previous defaults. Model capture is also on by default on PostHogMCP; the public API snapshot records the new defaults.

Fresh raw low-level instances read analytics arguments when ownership is unknown and strip only with evidence of SDK ownership, following ADR-0011. No host catalog is replayed during calls. Standalone FastMCP reads ownership from its registered schema, accounts for references/composition and middleware, and preserves application-declared keys. Transient registry lookup failures now preserve potentially host-owned arguments; actual not-found results retain middleware fallback behavior.

On MCP SDK v1, standalone FastMCP middleware that overrides listing or dispatch disables model argument injection and invalidates stale ownership. This prevents a fresh replica from rejecting an advertised analytics argument and preserves a replacement tool's own llm_model argument. Model capture from client metadata remains enabled; self-report injection is unavailable on these middleware installations, including pass-through logging/auth middleware. No new public option or catalog replay is introduced.

Validation

  • Regression coverage includes fresh instances with pass-through middleware, client metadata capture, replacement tools, listing order, and middleware added after cached discovery.
  • MCP v1 suite: 553 passed, 1 version-specific skip.
  • MCP v2 suite: 444 passed, 21 version-specific skips.
  • Ruff lint/format, mypy baseline (239 files), and public API snapshot check pass.
  • CodeScene pre-commit safeguard passes for the middleware fixes, improving both runtime files. Existing large-module and regression-test complexity warnings remain.
  • Merged current main and verified its virtual-tool collision regressions alongside the new defaults, resolving conflicts without rewriting branch history.

Release

.sampo/changesets/mcp-analytics-defaults.md requests a minor release. Human review and the normal release workflow are still required; no package has been published from this branch.

Agent context

Autonomy: Human-driven (agent-assisted), directed by Lucas Faria.

Initial implementation and latest review fixes with Codex. Ownership rework and earlier review response with Claude Code. Human review required, particularly for _standalone_ownership and its helpers in posthog/mcp/_instrument_lowlevel.py.

https://claude.ai/code/session_012YBJXRzzCizpHFGn2mZaEg

Enable both existing instrumentation features and model capture on PostHogMCP,
with explicit opt-outs. Missing-capability reporting and feedback stay disabled.

Resolve model argument ownership from bounded raw catalog lookups on fresh
low-level instances. Do not emit synthetic tools/list events, alter application
model arguments, or block dispatch when catalog resolution fails.

Validation: 486 MCP v1 tests passed (1 skipped), 433 MCP v2 tests passed
(21 skipped); Ruff lint/format, mypy baseline for 237 files, public API snapshot,
warning-as-error import and wheel build passed. CodeScene gate passed.
One feedback cursor deprecation warning remains outside the requested scope.
Include a Sampo minor changeset and document changed defaults and opt-outs.
@lucasheriques
lucasheriques requested a review from a team as a code owner September 11, 2026 18:49
@lucasheriques lucasheriques self-assigned this Sep 11, 2026
@greptile-apps

greptile-apps Bot commented Sep 11, 2026

Copy link
Copy Markdown
Contributor
Prompt To Fix All With AI
### Issue 1
posthog/mcp/_tool_schema.py:23-25
**Ownership lookup is not cached**

The fallback returns the resolved ownership without storing it. On a cold low-level server, each direct tool call therefore invokes the original `tools/list` handler again, potentially traversing 16 pages, repeating handler side effects, and adding up to 250 ms of latency. Cache the result in `data.tool_model_parameter_injected` before returning it.

```suggestion
        owns_model = await asyncio.wait_for(
            _find_model_ownership(name, list_page), timeout=0.25
        )
        data.tool_model_parameter_injected[name] = owns_model
        return owns_model
```

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Reviews (1): Last reviewed commit: "chore(mcp): enable model capture and con..." | Re-trigger Greptile

Comment thread posthog/mcp/_tool_schema.py Outdated
@github-actions

github-actions Bot commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-09-17 19:30:36 UTC
Duration: 256362ms

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

Feature_Flags Tests

17/17 tests passed

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

Remove the duplicate custom-dispatcher default and opt-out test. The
existing parameterized prepare-and-capture test already covers both.
Keep the fresh-instance regressions and bounded catalog lookup coverage.

Validation: MCP v1: 485 passed, 1 skipped. MCP v2: 432 passed, 21 skipped.
Ruff lint/format and CodeScene pre-commit checks passed. The existing
feedback nextCursor deprecation warning remains outside this change.
Runtime behavior is unchanged.
Store both confirmed ownership outcomes in the existing model cache.
Return None internally for unresolved catalogs so missing tools, page
limits, errors and timeouts do not become permanent negative entries.

Extended existing pagination/failure tests and added late-tool recovery.
Caching regressions failed before the fix. Validation: MCP v1 486 passed,
1 skipped; MCP v2 433 passed, 21 skipped. Ruff, mypy baseline (237 files),
and CodeScene pre-commit checks passed. The feedback nextCursor warning
remains outside this change.

Addresses review discussion_r3992430558 on #944.

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

Note

🤖 Automated comment by QA Swarm — not written by a human

QA Swarm review complete — see inline comments. Summary posted separately.

Comment thread .sampo/changesets/mcp-analytics-defaults.md
Comment thread .sampo/changesets/mcp-analytics-defaults.md Outdated
Comment thread posthog/mcp/types.py
Comment thread posthog/mcp/types.py
Comment thread posthog/mcp/posthog_mcp.py
Comment thread posthog/mcp/_instrument_lowlevel.py Outdated
Comment thread posthog/mcp/_tool_schema.py Outdated
Comment thread posthog/mcp/_instrument_lowlevel.py Outdated
Comment thread posthog/mcp/_instrument_v2.py Outdated
Comment thread posthog/test/mcp/test_defaults.py Outdated

gesh commented Sep 15, 2026

Copy link
Copy Markdown
Member

Note

🤖 Automated comment by QA Swarm — not written by a human

Multi-perspective review: router (cheap-first pass) + delegated reviewers (qa-team, paul-reviewer, xp-reviewer, security-audit as warranted)

Verdict: ⚠️ REQUEST CHANGES (round 1 @ 80a8dd2)

No correctness, security, or data-loss bug was found. The code works. Both reviewers instead stopped at the same place: this change alters the wire-visible tool contract of every existing deployment on a routine pip install --upgrade posthog, and the release note does not say so.

Key findings

🟠 HIGH

  • Is minor the right semver tier? (.sampo/changesets/…) — With capture_model=True by default, the advertised inputSchema of every tool on the official high-level FastMCP / MCPServer adapters now lists llm_model in required. enable_conversation_id=True adds a handle to eligible tool responses. Both happen with zero code change by the user. Dispatch does not enforce required, so servers keep working — the risk is client-side (strict-schema clients, cached call templates). references/public_api_snapshot.txt also changes on four lines, which CONTRIBUTING.md says means the shape should be agreed on an issue first.
  • capture_model is one boolean doing two unrelated jobs (posthog/mcp/types.py:201) — (a) read the model from recognised client _meta, which is invisible and changes no wire contract; (b) inject llm_model into the advertised schema as required, which very much does. Because it is one flag, the safe half cannot ship first. An inject_argument field on the already-existing MCPAnalyticsModelOptions would allow default-on observation now, and the schema flip after the data is in.

🟡 MEDIUM

  • Changeset body names what was turned on, but not what the upgrader will see, nor the opt-out one-liner.
  • README "Defaults and opt-outs" covers conversation correlation well, but never says llm_model joins required — the words a surprised operator would grep for.
  • Discovery walk runs on the standalone FastMCP path even though a live tool registry is available there, unlike the equivalent v2 path (_instrument_v2.py:253).
  • Negative lookups are never cached, so a permanently missing or slow-listing tool re-pays the full walk on every call, not just the first.
  • Discovery calls the application's real tools/list handler out-of-band during tools/call, and a 250 ms timeout cancels it mid-flight. Arbitrary handlers may not be safely cancellable.

🟢 LOW / ⚪ NIT_meta not forwarded on the v2 discovery path (v1 forwards it); no test asserts that llm_model is stripped before the real handler runs; no env-var escape hatch; two README copy nits.

Convergence

One finding was raised independently by both reviewers: the semver tier and the silent default flip (.sampo/changesets/mcp-analytics-defaults.md:2). The router reached it from the empirical side (it installed mcp 1.30.0 and 2.2.0, instrumented live servers, and confirmed the required schema change and the response-payload change). Paul reached it from the rollout side. Convergent findings carry the highest confidence — treat this one as the review's main ask.

Reviewer summaries

Reviewer Assessment
🧭 router Danger MEDIUM, confidence HIGH. Read every touched file with full context, installed both MCP SDK majors in real virtualenvs, and confirmed the pagination duck-typing, the argument stripping on cold low-level servers, and that the full suite plus the new tests pass under both majors. Found no correctness bug. Delegated one item: the rollout/semver judgment call.
👤 paul-reviewer Approves with caveats. Likes the direction — "you get the data without reading the docs" is usually right for an analytics SDK — and can live with minor, since capture_model is about a week old and context set the precedent. One real ask: split the capture_model boolean so the observing half can ship before the contract-changing half.

Warning

qa-team was unavailable in this environment (skill not on disk). Its correctness, concurrency, and database lenses were not applied. xp-reviewer and security-audit were available but the router did not delegate to them.


Automated by QA Swarm — not a human review

Replaces the raw-catalog replay added earlier on this branch with the
ownership rule posthog-js ADR-0011 applies to `context`: a fresh raw
low-level instance reads the self-reported model and strips nothing, and
the SDK never replays the host's tools/list handler on the call path.
Standalone FastMCP reads ownership of all three injected keys from the
tool signature, so it strips llm_model without a prior listing.

Tested: .venv pytest posthog/test/mcp (478 passed, 1 skipped),
.venv-mcp-v2 (424 passed, 21 skipped), ruff check/format, mypy baseline
(no issues), public API snapshot up to date.

Reviewer notes: raw low-level servers keep main's behaviour of never
stripping llm_model; posthog-js strips on positive ownership. That
pre-existing difference is unchanged here.

Claude-Session: https://claude.ai/code/session_012YBJXRzzCizpHFGn2mZaEg
A jlowin `Tool` subclass declares its arguments in `parameters` and may
have no `fn`, so the signature-based check returned nothing owned and
the strip loop deleted an application-declared `llm_model`. Ownership
now comes from the advertised schema first, matching the v2 standalone
path, with the signature as fallback.

Tested: .venv pytest posthog/test/mcp (480 passed, 1 skipped),
.venv-mcp-v2 (424 passed, 21 skipped), ruff, mypy baseline.
Found by `codex review --base main` on the previous commit.

Claude-Session: https://claude.ai/code/session_012YBJXRzzCizpHFGn2mZaEg
The v1 and v2 standalone adapters resolved injected-argument ownership
two different ways, and the v1 one stripped an application-declared
`llm_model` inside a composed schema (`allOf`, `$ref`). Lift the v2
helper into `_standalone.py`, add the per-key composed-schema guard the
listing-time injection already applies, and use it from both paths.
Lookup failure now strips nothing on v1 too (fail closed), matching v2.

Tested: .venv pytest posthog/test/mcp (482 passed, 1 skipped),
.venv-mcp-v2 (424 passed, 21 skipped), ruff, mypy baseline, public API
snapshot. Found by `codex review --base main` on the previous commit.

Claude-Session: https://claude.ai/code/session_012YBJXRzzCizpHFGn2mZaEg
…from its schema

With model capture on by default, a standalone FastMCP replica that
never served the listing which advertised `llm_model` forwarded it to
FastMCP's validator and the call failed. FastMCP rejects any undeclared
argument, so stripping an analytics key the tool does not declare can
never hurt, while stripping a declared one always does. The v1 standalone
path now strips `llm_model` like `context` and `conversation_id`: unless
the registered schema (or, without one, the function signature) declares
it, with nothing stripped from a composed schema because nothing was
injected into one. The registry is read directly, never through
middleware, so rate limiters are not charged and no listing is needed.
A local root `$ref` is dereferenced first, as FastMCP's built-in
middleware does before the client sees the listing, and a pinned
`_meta.fastmcp.version` is honoured only where FastMCP's own dispatch
honours it, so ownership always follows the version that runs.
Only keys the SDK injects under the current options are ever stripped,
so a disabled feature leaves its key to the application, and sibling
properties beside a root `$ref` count as declared, as does every node
along a reference chain. For `llm_model` the effective listing is the
first witness, because middleware can provide or shadow the tool the
registry knows; the registry is second; with neither the argument stays
and is still read.
The registry is not trusted for `llm_model` while application middleware
can change the listing or reroute dispatch, the server's own dereferencing setting decides
whether a root `$ref` would have been injected into, and a listing that
advertises two tools under one name (FastMCP 2.x with a shadowing
middleware) marks the model argument as the application's.
Application subclasses of FastMCP's built-in middleware count as the
application's, and `$ref` segments decode JSON Pointer escapes.
The model is read exactly when it was stripped; raw low-level servers
keep reading it fail-open on unknown ownership (posthog-js ADR-0011).

This replaces the listing-based resolver tried earlier on this branch,
which five Codex rounds showed diverging from the advertised listing
across FastMCP 2.5-4.0 and middleware combinations.

Tested: .venv pytest posthog/test/mcp (502 passed, 1 skipped),
.venv-mcp-v2 (424 passed, 21 skipped), a throwaway venv with
fastmcp==2.14.5 (standalone and defaults tests: 28 passed, 5 skipped),
and one with fastmcp==2.8.1, which has no middleware module (9 passed,
23 skipped; the one failure is a pre-existing test passing a constructor
kwarg that release lacks),
ruff, mypy baseline, public API snapshot.

Claude-Session: https://claude.ai/code/session_012YBJXRzzCizpHFGn2mZaEg
@lucasheriques
lucasheriques requested a review from gesh September 15, 2026 18:17
Merge main, retaining both standalone schema ownership and virtual-tool
collision protections. Suppress new conversation handles when the request
already carries a token/transport session; echoed handles still win.

Preserve host arguments when standalone FastMCP registry introspection
fails transiently, while retaining the not-found middleware fallback.
Adjust fixtures that deliberately test behavior with model capture off.

Validation: MCP v1 549 passed, 1 skip; MCP v2 444 passed, 21 skips.
Ruff lint/format, mypy baseline (239 files), and public API snapshot pass.
The pre-commit CodeScene merge comparison flagged inherited main changes;
a scoped PR comparison against origin/main follows before push.
Keep the conversation guard readable and remove the new complex-condition finding. Existing transport and token sessions retain the same precedence.

Validation: defaults tests pass (6 passed, 1 skipped); Ruff lint and format pass. CodeScene pre-commit safeguard passes. Full MCP v1/v2 suites passed before this condition extraction.
@DanielVisca
DanielVisca self-requested a review September 17, 2026 17:55
Skip model argument injection on standalone MCP SDK v1 servers when application middleware can alter listing or dispatch. Keep client metadata capture enabled, and invalidate earlier model ownership so a replacement tool retains its own llm_model argument.

Document the middleware limitation in the README and changeset. Extend the existing shadowing test with listed, reordered, and late middleware cases, and verify a fresh replica executes advertised calls while still capturing client metadata.

Validation: MCP v1 553 passed, 1 skipped; MCP v2 444 passed, 21 skipped. Ruff lint/format, mypy (239 files), public API snapshot, and CodeScene safeguard pass. CodeScene improves both runtime files; existing large-module and test-complexity warnings remain.
@lucasheriques
lucasheriques merged commit 8ee7ad1 into main Sep 17, 2026
43 checks passed
@lucasheriques
lucasheriques deleted the codex/mcp-analytics-defaults branch September 17, 2026 20:29
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