Skip to content

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

Open
lucasheriques wants to merge 7 commits into
mainfrom
codex/mcp-analytics-defaults
Open

lucasheriques wants to merge 7 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. This enables both by default, preserves explicit opt-outs, and leaves missing-capability reporting and feedback collection disabled for Gesh's work. The decision and the alternatives considered are recorded in posthog-js ADR-0013, which both SDKs follow.

A fresh raw low-level instance (a new server per request) never serves a tools/list, so it could not say who owns llm_model and stayed silent. It now follows the rule posthog-js ADR-0011 applies to context: reads fail open, strips fail closed. Nothing new runs on the call path. An earlier revision of this branch replayed the host's listing inside tools/call; that is the design ADR-0011 rejects, and it was removed after review.

Standalone fastmcp.FastMCP on MCP SDK 1.x validates arguments, so a cold replica must strip what the listing injected. It now reads ownership from the registered tool schema, never through middleware, and strips only the keys the SDK injects under the current options that the tool does not declare. The registry is trusted for llm_model only when no application middleware can change the listing or reroute dispatch; otherwise the argument stays and is read fail-open. Root $ref chains, JSON Pointer escapes, composed schemas, the server's own dereferencing setting, pinned tool versions, and duplicate names in a listing are each handled the way the listing handles them. The v2 adapter's registry path is unchanged from main.

Wire-visible effects on upgrade: compatible schemas gain llm_model (required on the official high-level adapters, optional elsewhere, never enforced at dispatch) and an optional conversation_id, and eligible results gain a prompt-back handle. MCPAnalyticsOptions(capture_model=False, enable_conversation_id=False) restores the previous shape. capture_model is also on by default on PostHogMCP. No option shape changes; the public API snapshot records the new defaults.

Validation

  • MCP v1 venv: 502 passed, 1 version-specific skip.
  • MCP v2 venv with standalone FastMCP 4: 424 passed, 21 version-specific skips.
  • Throwaway venvs with FastMCP 2.14.5 (28 passed, 5 skipped) and FastMCP 2.8.1, which predates middleware (9 passed, 23 skipped, 1 pre-existing failure from a test passing a constructor kwarg that release lacks).
  • Ruff lint and format, mypy baseline (no issues), public API snapshot up to date.
  • codex review --base main: fourteen rounds on the standalone path, each finding fixed with a regression test; the final round on 5f20b75 reported no actionable regressions.

Release

.sampo/changesets/mcp-analytics-defaults.md requests a minor release. Review and merge, then approve the normal release workflow; nothing has been published from this branch.

Agent context

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

Initial implementation with Codex. Ownership rework and review response with Claude Code. Human review required, with particular attention to _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-15 18:21:49 UTC
Duration: 256411ms

✅ 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 510ms
Required Headers.Has Content Type Json 511ms
Required Headers.Has Posthog Sdk Info Format 511ms
Required Headers.Has Posthog Attempt Header 510ms
Required Headers.Has Posthog Request Id 510ms
Required Headers.Has Posthog Request Timestamp 511ms
Required Headers.Has User Agent 510ms
Body Format.Body Has Created At And Batch 510ms
Body Format.No Api Key In Body 512ms
Body Format.No Sent At In Body 510ms
Event Format.Event Has Required Root Fields 510ms
Event Format.Event Uuid Is Valid 510ms
Event Format.Event Timestamp Is Rfc3339 510ms
Event Format.Distinct Id Is String 511ms
Event Format.Distinct Id At Root Not Properties 510ms
Event Format.Custom Properties Preserved 510ms
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 515ms
Event Format.Event Uuid Is Valid Batch 514ms
Event Format.Event Timestamp Is Rfc3339 Batch 514ms
Event Format.Distinct Id Is String Batch 515ms
Event Format.Distinct Id At Root Not Properties Batch 516ms
Event Format.Custom Properties Preserved Batch 514ms
Event Format.Set Properties Preserved Batch 514ms
Event Format.Set Once Properties Preserved Batch 515ms
Event Format.Groups Properties Preserved Batch 514ms
Event Format.Sdk Generates Uuid If Not Provided Batch 516ms
Batch Behavior.Multiple Events In Single Batch 519ms
Batch Behavior.Batch Envelope Smoke 516ms
Batch Behavior.Flush With No Events Sends Nothing 506ms
Batch Behavior.Flush At Triggers Batch 1011ms
Batch Behavior.Created At Reflects Batch Creation Time 511ms
Deduplication.Generates Unique Uuids 518ms
Deduplication.Different Events Same Content Different Uuids 512ms
Deduplication.Preserves Uuid On Retry 6516ms
Deduplication.Preserves Timestamp On Retry 6516ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 6524ms
Deduplication.No Duplicate Events In Batch 520ms
Header Behavior On Retry.Attempt Header Starts At One 511ms
Header Behavior On Retry.Attempt Header Increments On Retry 13524ms
Header Behavior On Retry.Request Id Preserved On Retry 6516ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3021ms
Header Behavior On Retry.Request Timestamp Changes On Retry 6515ms
Response Format Validation.Success Response Has Uuid Keyed Results 511ms
Response Format Validation.Success Response Has Ok For Each Event 514ms
Response Format Validation.Success No Retry After When All Ok 513ms
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 511ms
Retry Behavior.Retries On 408 6518ms
Retry Behavior.Retries On 500 6516ms
Retry Behavior.Retries On 503 8524ms
Retry Behavior.Retries On 504 6520ms
Retry Behavior.Retryable Errors Have Retry After 3515ms
Retry Behavior.Respects Retry After On Retryable Error 11518ms
Retry Behavior.Does Not Retry On 400 2513ms
Retry Behavior.Does Not Retry On 401 2514ms
Retry Behavior.Does Not Retry On 402 2513ms
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 2514ms
Retry Behavior.Implements Backoff 22526ms
Retry Behavior.Max Retries Respected 22525ms
Partial Batch Handling.Handles 200 Full Success 2513ms
Partial Batch Handling.Handles 200 With All Ok 3518ms
Partial Batch Handling.Does Not Retry Dropped Events 3517ms
Partial Batch Handling.Does Not Retry Limited Events 3516ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 6522ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 6521ms
Partial Batch Handling.Retries Only Retry Events From Partial 6524ms
Partial Batch Handling.Partial Retry Preserves Uuids 6516ms
Partial Batch Handling.Partial Retry Attempt Header Increments 6521ms
Partial Batch Handling.Partial Retry Request Id Preserved 6522ms
Partial Batch Handling.Respects Retry After On Partial 8521ms
Partial Batch Handling.Unknown Result Treated As Terminal 3517ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry 3520ms
Compression.Sends Gzip Content Encoding 511ms
Compression.No Content Encoding When Disabled 510ms
Compression.Compressed Body Is Decompressible 510ms
Error Handling.Does Not Retry On Unknown 4Xx 2514ms
Event Options.Cookieless Mode Override 510ms
Event Options.Disable Skew Correction Override 510ms
Event Options.Process Person Profile Override 510ms
Event Options.Product Tour Id Override 510ms
Event Options.Unset Options Omitted 511ms
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 11ms
Request Payload.Flags Request Uses V2 Query Param 9ms
Request Payload.Flags Request Hits Flags Path Not Decide 9ms
Request Payload.Flags Request Omits Authorization Header 10ms
Request Payload.Token In Flags Body Matches Init 10ms
Request Payload.Groups Round Trip 10ms
Request Payload.Groups Default To Empty Object 10ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 8ms
Request Payload.Disable Geoip Omitted Defaults To False 8ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 9ms
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 14ms
Request Lifecycle.Mock Response Value Is Returned To Caller 9ms
Retry Behavior.Retries Flags On 502 313ms
Retry Behavior.Retries Flags On 504 313ms
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.

@@ -0,0 +1,5 @@
---
pypi/posthog: minor

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

[convergent: router + paul] 🟠 HIGH

Two reviewers landed on this line independently: is minor the right tier?

Verified empirically — 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 (next to the already-default context). On a routine pip install --upgrade posthog, every existing deployment's wire-visible tool contract changes with zero code change by the user. enable_conversation_id=True adds a handle to eligible tool responses on top of that.

The dispatch path does not enforce the required flag — a call omitting context and llm_model still dispatches fine — so there is no server-side breakage. The risk is client-side: strict-schema MCP clients that validate before sending, and tooling that generates call templates from a cached schema.

Paul's read: "i can talk myself into minor (capture_model only landed in #927 six days ago, so the blast radius is genuinely small, and context already set the precedent of injecting a required arg), and i'm not going to block on the tier. but the thing i'd actually want confirmed: references/public_api_snapshot.txt changes on four lines here, and CONTRIBUTING.md now says that means 'this touches public API, agree the shape on the issue first'. i'm lazily asking rather than digging — was this one agreed somewhere?"

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Keeping minor: context shipped the same required-argument precedent as a minor, and dispatch never enforces required. On the CONTRIBUTING.md point: this repo has no "agree the shape on an issue first" rule; AGENTS.md only asks that the snapshot be regenerated (make public_api_snapshot), which it is. posthog-js does have that rule for new or changed option shapes, and this change alters no shape: same options, same types, different defaults. The decision and the rejected alternatives are now recorded in posthog-js ADR-0013, which both SDKs cite.

Comment thread .sampo/changesets/mcp-analytics-defaults.md Outdated
Comment thread posthog/mcp/types.py
# SDK-injected llm_model argument. Off by default.
capture_model: Union[bool, MCPAnalyticsModelOptions] = False
# SDK-injected llm_model argument. On by default; False disables capture.
capture_model: Union[bool, MCPAnalyticsModelOptions] = True

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

[paul] 🟠 HIGH

this is the one i keep coming back to. capture_model is a single boolean doing two completely unrelated things: (a) read the model out of recognised client _meta — invisible, read-only, no wire change at all; and (b) inject llm_model into the advertised schema and stick it in required — very much a wire change. i'm allergic to flags like that generally, but here it also blocks the rollout i'd want: default-on the half that only observes, keep the half that changes the contract opt-in, and use a release or two of $mcp_llm_model_source: client_metadata data to find out how much self-reporting is even buying us. log before you limit.

MCPAnalyticsModelOptions already exists as the object form and currently only carries description, so there's a ready-made home for something like inject_argument: bool = False. that'd let this ship default-on today with no consumer-visible change, and the schema half flip once we've seen numbers. feel free to disagree — but "the schema we advertise to the world changes on a patch-ish upgrade" is exactly the class of thing i'd want a staged path for.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Considered and rejected in posthog-js ADR-0013. Only Codex exposes model metadata today, so a default-on observe-only half yields near-zero data for every other harness and only delays what the flip exists to collect. The object form (MCPAnalyticsModelOptions) leaves room for an inject=False knob later without a breaking change, if the data says self-report is not earning its field.

Comment thread posthog/mcp/types.py
missing_capability_tool_name: Optional[str] = None,
mcp_exception_autocapture: bool = True,
capture_model: Union[bool, MCPAnalyticsModelOptions] = False,
capture_model: Union[bool, MCPAnalyticsModelOptions] = True,

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

[paul] 🟢 LOW

not blocking at all, just planting a seed. the only way off this default is an argument in source, which means a code change and a redeploy — and the person upgrading is often not the person who wrote the instrument() call. an env-var override (POSTHOG_MCP_CAPTURE_MODEL=0 or similar) reading through to this default would let someone turn it off at 3am without shipping code. knight capital is my usual sermon here (https://specbranch.com/posts/knight-capital/) and it's admittedly a bit heavy for an analytics field — but "make it configurable and measurable" is cheap now and expensive later. ship as you see fit.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Not taking this one: nothing in the package reads the environment, and the opt-out is a one-line option. Recorded as rejected in posthog-js ADR-0013.

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