Skip to content

feat(mcp): capture model identifiers - #927

Merged
lucasheriques merged 4 commits into
mainfrom
codex/mcp-model-client-metadata
Sep 9, 2026
Merged

feat(mcp): capture model identifiers#927
lucasheriques merged 4 commits into
mainfrom
codex/mcp-model-client-metadata

Conversation

@lucasheriques

@lucasheriques lucasheriques commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Python MCP server owners can compare tool behavior by calling model, matching posthog-js#4829.

  • Model capture is opt-in and prefers recognized Codex metadata over an injected self-report field.
  • $mcp_llm_model_source distinguishes client_metadata from self_reported values.
  • Application-owned fields and complex schemas remain untouched by model injection.
  • Custom dispatchers preserve model-field ownership across repeated listings by copying object tools before injection.
  • Analytics schema injection preserves existing restrictions on undeclared arguments.
  • Raw low-level and standalone FastMCP adapters keep the model field optional for validation compatibility.
  • Both model sources remain unverified and suit product analytics, not billing or access control.

Public API snapshot updates and the shared injection predicate are mechanical.

💚 How did you test it?

  • Regression coverage checks default-off and explicit opt-out behavior through prepared calls and captured events.
  • Object-tool cases cover repeated listings with and without an explicit original tool across both MCP SDK majors.
  • Schema coverage checks accepted analytics fields and rejected undeclared arguments, including after a low-level tool-cache rebuild.
  • Existing wire coverage checks metadata precedence, argument stripping, capture properties and tool execution.
  • The full non-MCP suite was not rerun locally for the review fixes; CI covers the broader matrix.

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

Codex authored the change and review fixes with terminal and GitHub CLI tools. Skills: debugging MCP analytics, writing tests, writing dataclasses, and writing PR descriptions.

Model resolution respects opt-in on custom dispatchers. Optional fields remain optional where stripping them before validation would otherwise reject calls.

Capture model identifiers from recognized client metadata, with an SDK-owned self-report fallback for other clients. Preserve source provenance and fail closed when the application owns the field.\n\nVerify both MCP Python SDK 1.x and 2.x, including a 2026-07-28 wire-level call.
@lucasheriques
lucasheriques requested a review from a team as a code owner September 7, 2026 17:23
@lucasheriques lucasheriques self-assigned this Sep 7, 2026
@lucasheriques
lucasheriques requested a review from a team September 7, 2026 17:24
@github-actions

github-actions Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-09-09 14:23:17 UTC
Duration: 256418ms

✅ 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 518ms
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 510ms
Required Headers.Has Posthog Attempt Header 511ms
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 511ms
Event Format.Event Has Required Root Fields 510ms
Event Format.Event Uuid Is Valid 511ms
Event Format.Event Timestamp Is Rfc3339 511ms
Event Format.Distinct Id Is String 510ms
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 511ms
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 513ms
Event Format.Event Timestamp Is Rfc3339 Batch 514ms
Event Format.Distinct Id Is String Batch 514ms
Event Format.Distinct Id At Root Not Properties Batch 513ms
Event Format.Custom Properties Preserved Batch 514ms
Event Format.Set Properties Preserved Batch 514ms
Event Format.Set Once Properties Preserved Batch 514ms
Event Format.Groups Properties Preserved Batch 513ms
Event Format.Sdk Generates Uuid If Not Provided Batch 514ms
Batch Behavior.Multiple Events In Single Batch 518ms
Batch Behavior.Batch Envelope Smoke 515ms
Batch Behavior.Flush With No Events Sends Nothing 506ms
Batch Behavior.Flush At Triggers Batch 1012ms
Batch Behavior.Created At Reflects Batch Creation Time 510ms
Deduplication.Generates Unique Uuids 518ms
Deduplication.Different Events Same Content Different Uuids 513ms
Deduplication.Preserves Uuid On Retry 6515ms
Deduplication.Preserves Timestamp On Retry 6521ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 6523ms
Deduplication.No Duplicate Events In Batch 519ms
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 6516ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3020ms
Header Behavior On Retry.Request Timestamp Changes On Retry 6521ms
Response Format Validation.Success Response Has Uuid Keyed Results 510ms
Response Format Validation.Success Response Has Ok For Each Event 515ms
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 6520ms
Retry Behavior.Retryable Errors Have Retry After 3517ms
Retry Behavior.Respects Retry After On Retryable Error 11521ms
Retry Behavior.Does Not Retry On 400 2512ms
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 2514ms
Retry Behavior.Non Retryable Errors Have No Retry After 2514ms
Retry Behavior.Implements Backoff 22534ms
Retry Behavior.Max Retries Respected 22534ms
Partial Batch Handling.Handles 200 Full Success 2513ms
Partial Batch Handling.Handles 200 With All Ok 3515ms
Partial Batch Handling.Does Not Retry Dropped Events 3515ms
Partial Batch Handling.Does Not Retry Limited Events 3517ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 6519ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 6521ms
Partial Batch Handling.Retries Only Retry Events From Partial 6525ms
Partial Batch Handling.Partial Retry Preserves Uuids 6522ms
Partial Batch Handling.Partial Retry Attempt Header Increments 6522ms
Partial Batch Handling.Partial Retry Request Id Preserved 6518ms
Partial Batch Handling.Respects Retry After On Partial 8522ms
Partial Batch Handling.Unknown Result Treated As Terminal 3515ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry 3521ms
Compression.Sends Gzip Content Encoding 511ms
Compression.No Content Encoding When Disabled 510ms
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 511ms
Event Options.Process Person Profile Override 511ms
Event Options.Product Tour Id Override 510ms
Event Options.Unset Options Omitted 510ms
Event Options.Options Override In Batch 514ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties 511ms
Geoip And Historical Migration.Historical Migration Set In Body 512ms
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 13ms
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 9ms
Request Payload.Groups Round Trip 10ms
Request Payload.Groups Default To Empty Object 10ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 9ms
Request Payload.Disable Geoip Omitted Defaults To False 10ms
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 510ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests 15ms
Request Lifecycle.Mock Response Value Is Returned To Caller 10ms
Retry Behavior.Retries Flags On 502 313ms
Retry Behavior.Retries Flags On 504 315ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 513ms

@greptile-apps

greptile-apps Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor
Prompt To Fix All With AI
### Issue 1
posthog/mcp/_model_parameters.py:68-69
**Strict schemas become permissive**

When model capture is enabled, this removes `additionalProperties: false` from otherwise strict input schemas even though `llm_model` has already been added to `properties`. Raw low-level servers use the advertised schema for validation and do not strip other keys, so clients can submit undeclared arguments that were previously rejected. Preserve the strictness constraint while adding the declared analytics property.

### Issue 2
posthog/mcp/posthog_mcp.py:319-322
**Injected field loses ownership**

For object-based tools, `prepare_tool_list()` mutates the original object by adding `llm_model`. If that same object is then passed as `original_tool`, as the README recommends, this check mistakes the SDK-injected field for an application-owned field. As a result, `prepare_tool_call()` neither captures nor strips the self-reported model, and dispatch can receive an unexpected `llm_model` argument. Record ownership before mutating object schemas or avoid inferring it from an already-mutated object.

### Issue 3
posthog/mcp/_instrumentation.py:690-694
**Low-level model field optional**

Model requiredness is tied to the adapter-specific `context_required` flag. Both low-level adapters pass this flag as false, so compatible tool schemas advertise `llm_model` as optional even though the documented feature contract says the self-report field is required. Schema-driven clients may therefore omit it, causing model capture to silently produce no value. Give model injection its own requiredness decision or explicitly exclude these adapters from the documented contract.

---

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

Reviews (1): Last reviewed commit: "feat(mcp): capture model identifiers" | Re-trigger Greptile

Comment thread posthog/mcp/_model_parameters.py Outdated
Comment thread posthog/mcp/posthog_mcp.py
Comment thread posthog/mcp/_instrumentation.py

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

Comment thread posthog/mcp/posthog_mcp.py Outdated
Comment thread posthog/mcp/posthog_mcp.py
Comment thread posthog/mcp/_model_parameters.py
Comment thread posthog/mcp/posthog_mcp.py
Gate custom-dispatcher model resolution behind capture_model and copy
object tools before model injection so repeated listings preserve ownership.
Publish the completed ownership map without an intermediate empty state.

Keep additionalProperties constraints in all analytics schema injectors.
Document adapter-specific requiredness rather than requiring fields that
standalone FastMCP strips before input validation. Share the eligibility
predicate and update prepare helper documentation and the changeset.

Verification:
- MCP v1 suite: 267 passed.
- MCP v2 suite: 245 passed, 13 expected skips.
- Ruff check and format check passed repository-wide.
- Repository mypy/baseline check passed (229 source files).
- Public API snapshot and git diff --check passed.
- Regression cases failed before the fix for disabled capture, object
  ownership and strict validation through a low-level tool-cache rebuild.

Full non-MCP test suite not rerun locally; CI covers the broader matrix.

@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 round 2 @ 11c48e9. All four round 1 findings verified fixed. See inline comments.

Comment thread posthog/mcp/_context_parameters.py
Comment thread posthog/test/mcp/test_model_parameters.py

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

Approving to unblock, the robot comments look meaningful

Clarify that preserving strict schemas during context and conversation-ID injection also affects existing users with model capture disabled. Declare jsonschema>=4.0 in the test extra and refresh only its direct dependency entries in uv.lock.

Verification: python -m pytest posthog/test/mcp --timeout=30 -q passed (267 tests, MCP SDK 1.29.0); uv lock --check and git diff --check passed. Configured pre-commit checks skipped these non-Python files. CodeScene reported no applicable changes. MCP v2 was not rerun locally for this documentation and dependency-only update.
Append model capture fields after the existing public dataclass fields. Existing positional MCPAnalyticsOptions calls keep their identity and callback bindings, and PreparedToolCall retains the fourth positional missing-capability flag.

Add four parameterized regression cases and regenerate the public API snapshot. The cases failed before the field reorder and pass afterward.

Verification: 271 MCP tests passed; public_api_snapshot and public_api_check passed; configured Ruff pre-commit checks passed; mypy baseline check found no issues in 230 source files; strict import and git diff checks passed. CodeScene checked both Python files with no issues. MCP v2 validation remains covered by CI.
@lucasheriques
lucasheriques merged commit b8f8253 into main Sep 9, 2026
42 checks passed
@lucasheriques
lucasheriques deleted the codex/mcp-model-client-metadata branch September 9, 2026 15:22
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