Skip to content

fix(mcp): report the raised exception on mcp 1.x low-level isError results - #1231

Open
lucasheriques wants to merge 3 commits into
lucas/mcp-error-statusfrom
lucas/mcp-lowlevel-raised-error
Open

lucasheriques wants to merge 3 commits into
lucas/mcp-error-statusfrom
lucas/mcp-lowlevel-raised-error

Conversation

@lucasheriques

@lucasheriques lucasheriques commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Part of #1223. On mcp 1.x, a tool registered with the low-level Server's @server.call_tool() that raises now reports the exception it raised. $mcp_tool_call gets the raised class, the cause chain with frames, and $mcp_error_status. Before, the event said $mcp_error_type: "Error", with no frames and no status. #1229 listed this as an open gap.

Stacked on #1229. Review only the top three commits (68ff269, e18d71f, 2dc2abd).

The decorator catches the raise and builds CallToolResult(isError=True) before our handler sees it. It builds that result through server._make_error_result(str(e)), inside its except Exception block. A wrapper on the server instance reads the live exception there with sys.exc_info(). It settles the exception into the same raised_tool_error slot that #1226 added for standalone FastMCP.

  • Input and output validation also call _make_error_result inside an except, but with a prefixed message. The wrapper only takes an exception whose str() equals the message, so validation failures stay Error.
  • The hook is looked up on the instance at call time. It works whether instrument() runs before or after the tool is registered.
  • _make_error_result first ships in mcp 1.10. On older 1.x the hook does nothing and the event is the same as today.
  • mcp 2.x low-level needs no change. Raw v2 handlers raise straight through to our wrapper. A scratch run on mcp 2.3 showed RuntimeError, frames on both chain links, and status 503.
Raw low-level tool on mcp 1.x Before After
raises httpx.HTTPStatusError(503) Error, no frames, no status HTTPStatusError, frames, 503
raises RuntimeError from a 503 Error, no frames, no status RuntimeError, chain with frames, 503
client sends arguments that fail input validation Error Error (unchanged)
result sent to the client isError with message unchanged

💚 How did you test it?

  • test_lowlevel.py now has a parameterized test: plain ValueError, plain 503, wrapped 503, and an input-validation row. The three raising rows failed before the change. Without the message guard, the validation row reports ValidationError.
  • pytest posthog/test/mcp: 728 passed, 11 skipped on mcp 1.30 + fastmcp 3.2. 551 passed, 55 skipped on mcp 2.3 without FastMCP.
  • ruff check, ruff format --check, and mypy --no-site-packages --config-file mypy.ini . are clean.
  • Pre-PR adversarial review (Opus and Sonnet) checked concurrency, nested calls, idempotent instrument(), unchanged client results, and frame redaction. All of it held. Findings:
    • A background task started by a failing tool kept the exception alive. fix(mcp): report the exception behind a FastMCP isError tool result #1226's slot fix (52fc421) closes this on this path too. The repro prints False after the rebase.
    • The fix does nothing before mcp 1.10. The changeset now says so.
    • Dismissed: other exceptions the decorator's catch-all sees are also reported, such as a list_tools raise during its cache refresh, an invalid tool schema, or a malformed return value. These are real server-side exceptions behind the isError result, so naming their class is the intent.
    • Dismissed: an outer exception whose text exactly equals an SDK error message could be picked up. It needs a contrived match.

Not in this PR: on mcp 1.x, calling instrument() before @server.call_tool() registers the handler drops every $mcp_tool_call. That gap already exists on the base branch.

📝 Checklist

  • All commits are signed (see Commit signing)
  • 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)

  • Written by Claude Code (Opus 5.5, claude-opus-5-5), as a side session started from the feat(mcp): set $mcp_error_status from the raised exception's cause chain #1229 work.
  • Chose the _make_error_result seam over wrapping the user's tool function or Server.call_tool. Both of those need to run before registration, and instrument() usually runs after it.
  • /simplify (four Sonnet reviewers) suggested a shared wrap helper and shared test fixtures. I kept the duplication, because it is a few lines at two call sites.

@lucasheriques
lucasheriques requested a review from a team as a code owner November 11, 2026 16:30
@lucasheriques lucasheriques self-assigned this Nov 11, 2026
@veria-ai

veria-ai Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

PR overview

No security issues were found in this pull request.

Reviews

@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-11-11T20:01:21.746299+00:00
Duration: 254382ms

✅ All Tests Passed!

270/270 tests passed


Capture_V1 Tests

✅ 95/95 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint ✅ 517ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 510ms
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 ✅ 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 ✅ 510ms
Body Format.No Api Key In Body ✅ 510ms
Body Format.No Sent At In Body ✅ 510ms
Event Format.Event Has Required Root Fields ✅ 510ms
Event Format.Event Uuid Is Valid ✅ 511ms
Event Format.Event Timestamp Is Rfc3339 ✅ 510ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 527ms
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 ✅ 511ms
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 ✅ 513ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 514ms
Event Format.Distinct Id Is String Batch ✅ 513ms
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 ✅ 513ms
Event Format.Groups Properties Preserved Batch ✅ 514ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 514ms
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 ✅ 1013ms
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 ✅ 6518ms
Deduplication.Preserves Timestamp On Retry ✅ 6516ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6524ms
Deduplication.No Duplicate Events In Batch ✅ 518ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 510ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 13527ms
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 ✅ 6519ms
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 ✅ 512ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 1516ms
Response Format Validation.Success No Retry After When Drop Only ✅ 512ms
Response Format Validation.Response Echoes Request Id ✅ 511ms
Retry Behavior.Retries On 408 ✅ 6514ms
Retry Behavior.Retries On 500 ✅ 6516ms
Retry Behavior.Retries On 503 ✅ 8521ms
Retry Behavior.Retries On 504 ✅ 6516ms
Retry Behavior.Retries On 404 ✅ 6519ms
Retry Behavior.Retries On 429 ✅ 6517ms
Retry Behavior.Retries On 502 ✅ 6516ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3516ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11523ms
Retry Behavior.Does Not Retry On 400 ✅ 2513ms
Retry Behavior.Does Not Retry On 401 ✅ 2513ms
Retry Behavior.Does Not Retry On 402 ✅ 2513ms
Retry Behavior.Does Not Retry On 413 ✅ 2512ms
Retry Behavior.Does Not Retry On 415 ✅ 2512ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2512ms
Retry Behavior.Implements Backoff ✅ 19529ms
Partial Batch Handling.Handles 200 Full Success ✅ 2512ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3518ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3516ms
Partial Batch Handling.Does Not Retry Warning Events ✅ 3515ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6522ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6517ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6523ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6521ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6519ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6522ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8518ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3515ms
Partial Batch Handling.Mixed Ok Drop Warning No Retry ✅ 3518ms
Compression.Sends Gzip Content Encoding ✅ 512ms
Compression.No Content Encoding When Disabled ✅ 511ms
Compression.Compressed Body Is Decompressible ✅ 510ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2512ms
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 ✅ 510ms
Event Options.Options Override In Batch ✅ 514ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 510ms

Capture_Ai Tests

✅ 5/5 tests passed

View Details
Test Status Duration
Routing.Capture Ai Posts To Ai Endpoint ✅ 512ms
Routing.Capture Does Not Reroute Ai Named Events ✅ 510ms
Identity.Capture Ai Event Has Uuid ✅ 510ms
Identity.Capture Ai Keeps Supplied Uuid ✅ 510ms
Timestamp Format.Non Utc Event Timestamp Is Converted To Utc ✅ 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 V4 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 ✅ 9ms
Request Payload.Groups Round Trip ✅ 9ms
Request Payload.Groups Default To Empty Object ✅ 9ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 9ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 9ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 9ms
Request Lifecycle.No Flags Request On Init Alone ✅ 3ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 510ms
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 ✅ 312ms
Retry Behavior.Retries Flags On 504 ✅ 313ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 512ms

Feature_Flags_V4 Tests

✅ 149/149 tests passed

View Details
Test Status Duration
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Complete Split] ✅ 11ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Partial Split Missing Config Version] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Partial Split Missing Rule Type] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Partial Split Missing Rule Id] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Partial Split Missing Variant Key] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Split Wrong Type Config Version] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Split Wrong Type Rule Type] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Split Wrong Type Rule Id] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Split Wrong Type Experiment Id] ✅ 10ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Split Extra Experiment Id] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Split Wrong Type Variant Key] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Wrong Rule Type Literal] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Unknown Fields] ✅ 10ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Old Server Variant] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Old Server Boolean] ✅ 10ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Old Server Null Variant] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Old Server False] ✅ 10ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.V4 Value Takes Precedence] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Missing Flag] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Targeting Match Targeted Release] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Targeting Match Percentage Rollout] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Rollout Miss Percentage Rollout] ✅ 10ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Rollout Miss Experiment] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Experiment Paused] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Holdout] ✅ 10ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Holdout Variant Key] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.No Rule Match] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Missing Group Key] ✅ 10ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Dependency Error] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Error] ✅ 10ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Error With Value] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Malformed Sibling Isolation] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Partial Split String Value] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.V1 At V4] ✅ 10ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.V1 Failed] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Integral Json Number Context] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Flag Key Seed] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.Target] ✅ 10ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.Rollout Hit] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.Miss Return Default] ✅ 10ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.Miss Return Default Null] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.Miss Continue] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.No Match Default] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.No Match Null] ✅ 10ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.Order First Match] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.Order Targeting Miss] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Target] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Rollout Hit] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Miss Return Default] ✅ 11ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Miss Return Default Null] ✅ 10ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Miss Continue] ✅ 10ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.No Match Default] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.No Match Null] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Order First Match] ✅ 11ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Order Targeting Miss] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.Target] ✅ 21ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.Rollout Hit] ✅ 10ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.Miss Return Default] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.Miss Return Default Null] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.Miss Continue] ✅ 10ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.No Match Default] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.No Match Null] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.Order First Match] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.Order Targeting Miss] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.Unicode] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.Looks Boolean] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Zero] ✅ 10ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Negative Decimal] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Short Decimal] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Exponent] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Max Safe Integer] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Min Safe Integer] ✅ 10ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.Empty] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.Nested] ✅ 9ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.Max Depth] ✅ 10ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Complete Split] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Partial Split Missing Config Version] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Partial Split Missing Rule Type] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Partial Split Missing Rule Id] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Partial Split Missing Variant Key] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Split Wrong Type Config Version] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Split Wrong Type Rule Type] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Split Wrong Type Rule Id] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Split Wrong Type Experiment Id] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Split Extra Experiment Id] ✅ 8ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Split Wrong Type Variant Key] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Wrong Rule Type Literal] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Unknown Fields] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Old Server Variant] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Old Server Boolean] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Old Server Null Variant] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Old Server False] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.V4 Value Takes Precedence] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Missing Flag] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Targeting Match Targeted Release] ✅ 8ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Targeting Match Percentage Rollout] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Rollout Miss Percentage Rollout] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Rollout Miss Experiment] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Experiment Paused] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Holdout] ✅ 8ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Holdout Variant Key] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.No Rule Match] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Missing Group Key] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Dependency Error] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Error] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Error With Value] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Malformed Sibling Isolation] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Partial Split String Value] ✅ 8ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.V1 At V4] ✅ 6ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Integral Json Number Context] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Flag Key Seed] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.Target] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.Rollout Hit] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.Miss Return Default] ✅ 6ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.Miss Return Default Null] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.Miss Continue] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.No Match Default] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.No Match Null] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.Order First Match] ✅ 6ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.Order Targeting Miss] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Target] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Rollout Hit] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Miss Return Default] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Miss Return Default Null] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Miss Continue] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.No Match Default] ✅ 8ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.No Match Null] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Order First Match] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Order Targeting Miss] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.Target] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.Rollout Hit] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.Miss Return Default] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.Miss Return Default Null] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.Miss Continue] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.No Match Default] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.No Match Null] ✅ 8ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.Order First Match] ✅ 6ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.Order Targeting Miss] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.Unicode] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.Looks Boolean] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Zero] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Negative Decimal] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Short Decimal] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Exponent] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Max Safe Integer] ✅ 6ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Min Safe Integer] ✅ 7ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.Empty] ✅ 8ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.Nested] ✅ 6ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.Max Depth] ✅ 7ms

Feature_Flags_Local_Evaluation Tests

✅ 4/4 tests passed

View Details
Test Status Duration
Versioned Boolean Matching.Matching Version Missing ✅ 67ms
Versioned Boolean Matching.Matching Version 1 ✅ 69ms
Versioned Boolean Matching.Matching Version 2 ✅ 67ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 34ms

@posthog posthog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

PostHog Review · Standard · reviewed 565038f: 1 Should fix.

See this review and its findings in PostHog Review. Comment @posthog review --deep for a Deep review. A Deep review takes longer and looks deeper than a Standard review.

Comment thread posthog/mcp/_raised_tool_error.py Outdated
# except block, but with a prefixed message. Only the catch-all around
# the tool call passes an exception's bare text.
error = sys.exc_info()[1]
if isinstance(error, Exception) and error_message == str(error):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 · Exclude validation results before formatting the exception

When validation rejects a large payload, str(error) pretty-prints the entire instance and schema even though the prefixed message excludes it from capture. This blocks the event loop (about 140 ms for 100,000 items); deeply nested inputs raise RecursionError, replacing the original validation response. Exclude validation results before rendering the exception.

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.

Fixed in afd7389. The wrapper now recognizes the decorator's validation results before rendering anything: the message has to equal one of the Input validation error: / Output validation error: prefixes plus the exception's own short .message. Only then does it compare against str(error), so a jsonschema ValidationError is never rendered. If inspecting the exception raises, the original result goes back untouched. A tool's own raise worded like a validation error is still recovered.

The parameterized test in test_lowlevel.py has two new rows. One sends a 400-deep payload that fails input validation. Before the fix, the response text was maximum recursion depth exceeded; now it keeps Input validation error: ... and the event stays Error. The other has the tool raise ValueError("Input validation error: quota exceeded"), which is still reported as ValueError. pytest posthog/test/mcp: 730 passed on mcp 1.30, 551 passed on mcp 2.3.

@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

SDK performance: posthog-python

Benchmarks completed. No changes flagged for review.

Flags require at least a 5% change in the median and all six pairs agreeing on direction. This is a noise filter, not proof of a performance change or a CI gate.

View all results
Test Measurement Before PR With PR Change Assessment
Capture and deliver events (32-byte payload, burst)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (32-byte payload, steady)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Queue an event (32-byte payload)
Shard: capture
Allocated memory per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Queue an event (32-byte payload)
Shard: capture
Allocations per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Queue an event (4,096-byte payload)
Shard: capture
Allocated memory per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Queue an event (4,096-byte payload)
Shard: capture
Allocations per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Refresh 1,000 flag definitions
Shard: flags-memory
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (32-byte payload, burst)
Shard: capture
Allocated memory per operation 113.54 KiB/op 113.54 KiB/op <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Allocations per operation 1,096.59 count/op 1,096.59 count/op <0.1% more Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Time per operation 108.67 µs/op 108.53 µs/op 0.1% less time Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Idle process memory (RSS) 35.8 MiB 35.91 MiB 0.3% more memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Observed peak process memory (RSS) 37.55 MiB 37.66 MiB 0.3% more memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Process memory after settling (RSS) 37.55 MiB 37.66 MiB 0.3% more memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Process CPU time per operation 109.14 µs/op 109.17 µs/op <0.1% more time Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Lifetime peak process memory (RSS) 40.44 MiB 40.44 MiB No observed change Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Allocated memory per operation 166.11 KiB/op 166.1 KiB/op <0.1% less memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Allocations per operation 1,089.64 count/op 1,089.63 count/op <0.1% fewer Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Time per operation 142.91 µs/op 146.78 µs/op 2.7% more time Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Idle process memory (RSS) 40.83 MiB 40.85 MiB <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Observed peak process memory (RSS) 45.92 MiB 45.95 MiB <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Process memory after settling (RSS) 45.92 MiB 45.95 MiB <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Process CPU time per operation 135.79 µs/op 138.72 µs/op 2.2% more time Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Lifetime peak process memory (RSS) 50.78 MiB 50.64 MiB 0.3% less memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Allocated memory per operation 117.68 KiB/op 117.68 KiB/op <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Allocations per operation 1,136.6 count/op 1,136.6 count/op <0.1% more Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Time per operation 121.22 µs/op 127.44 µs/op 5.1% more time Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Idle process memory (RSS) 35.79 MiB 35.87 MiB 0.2% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Observed peak process memory (RSS) 35.89 MiB 35.97 MiB 0.2% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Process memory after settling (RSS) 35.89 MiB 35.97 MiB 0.2% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Process CPU time per operation 119.66 µs/op 127.54 µs/op 6.6% more time Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Lifetime peak process memory (RSS) 40.44 MiB 40.44 MiB No observed change Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Allocated memory per operation 170.57 KiB/op 170.57 KiB/op <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Allocations per operation 1,129.48 count/op 1,129.49 count/op <0.1% more Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Time per operation 152.28 µs/op 154.82 µs/op 1.7% more time Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Idle process memory (RSS) 40.69 MiB 40.63 MiB 0.1% less memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Observed peak process memory (RSS) 40.69 MiB 40.63 MiB 0.1% less memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Process memory after settling (RSS) 40.69 MiB 40.63 MiB 0.1% less memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Process CPU time per operation 146.03 µs/op 149.64 µs/op 2.5% more time Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Lifetime peak process memory (RSS) 40.96 MiB 40.92 MiB <0.1% less memory Not flagged
Queue an event (32-byte payload)
Shard: capture
Caller-thread CPU time per operation 80.26 µs/op 86.58 µs/op 7.9% more time Not flagged
Queue an event (32-byte payload)
Shard: capture
Time per operation 86.13 µs/op 89.1 µs/op 3.5% more time Not flagged
Queue an event (4,096-byte payload)
Shard: capture
Caller-thread CPU time per operation 82.31 µs/op 84.43 µs/op 2.6% more time Not flagged
Queue an event (4,096-byte payload)
Shard: capture
Time per operation 84.36 µs/op 90.29 µs/op 7% more time Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Allocated memory per operation 200.98 KiB/op 200.98 KiB/op No observed change Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Allocations per operation 2,339.33 count/op 2,339.33 count/op No observed change Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Time per operation 131.06 µs/op 131.95 µs/op 0.7% more time Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Process CPU time per operation 131.06 µs/op 131.95 µs/op 0.7% more time Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Allocated memory per operation 1.93 MiB/op 1.93 MiB/op No observed change Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Allocations per operation 23,013.56 count/op 23,013.56 count/op No observed change Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Time per operation 1.23 ms/op 1.23 ms/op 0.4% less time Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Process CPU time per operation 1.23 ms/op 1.23 ms/op 0.4% less time Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Allocated memory per operation 19.24 MiB/op 19.24 MiB/op No observed change Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Allocations per operation 229,654.94 count/op 229,654.94 count/op No observed change Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Time per operation 12.1 ms/op 12.12 ms/op 0.2% more time Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Process CPU time per operation 12.1 ms/op 12.12 ms/op 0.2% more time Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Idle process memory (RSS) 42.32 MiB 42.35 MiB <0.1% more memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Observed peak process memory (RSS) 42.65 MiB 42.69 MiB <0.1% more memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Process memory after settling (RSS) 42.65 MiB 42.69 MiB <0.1% more memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Lifetime peak process memory (RSS) 42.48 MiB 42.52 MiB <0.1% more memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Idle process memory (RSS) 42.09 MiB 41.77 MiB 0.8% less memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Observed peak process memory (RSS) 42.13 MiB 42.2 MiB 0.2% more memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Process memory after settling (RSS) 41.47 MiB 41.89 MiB 1% more memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Lifetime peak process memory (RSS) 42.49 MiB 42.54 MiB 0.1% more memory Not flagged
Evaluate one boolean flag
Shard: flags-single
Allocated memory per operation 15.05 KiB/op 15.05 KiB/op No observed change Not flagged
Evaluate one boolean flag
Shard: flags-single
Allocations per operation 173.76 count/op 173.76 count/op No observed change Not flagged
Evaluate one boolean flag
Shard: flags-single
Time per operation 6.49 µs/op 6.51 µs/op 0.3% more time Not flagged
Evaluate one boolean flag
Shard: flags-single
Process CPU time per operation 6.49 µs/op 6.51 µs/op 0.3% more time Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Allocated memory per operation 23.12 KiB/op 23.12 KiB/op No observed change Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Allocations per operation 270.27 count/op 270.27 count/op No observed change Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Time per operation 8.6 µs/op 8.51 µs/op 1% less time Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Process CPU time per operation 8.6 µs/op 8.51 µs/op 1% less time Not flagged
Evaluate a flag (early match)
Shard: flags-single
Allocated memory per operation 35.71 KiB/op 35.71 KiB/op No observed change Not flagged
Evaluate a flag (early match)
Shard: flags-single
Allocations per operation 387.27 count/op 387.27 count/op No observed change Not flagged
Evaluate a flag (early match)
Shard: flags-single
Time per operation 12.41 µs/op 12.39 µs/op 0.2% less time Not flagged
Evaluate a flag (early match)
Shard: flags-single
Process CPU time per operation 12.41 µs/op 12.39 µs/op 0.2% less time Not flagged
Evaluate a flag (late match)
Shard: flags-single
Allocated memory per operation 53.59 KiB/op 53.59 KiB/op No observed change Not flagged
Evaluate a flag (late match)
Shard: flags-single
Allocations per operation 576.27 count/op 576.27 count/op No observed change Not flagged
Evaluate a flag (late match)
Shard: flags-single
Time per operation 17.75 µs/op 17.83 µs/op 0.5% more time Not flagged
Evaluate a flag (late match)
Shard: flags-single
Process CPU time per operation 17.75 µs/op 17.83 µs/op 0.5% more time Not flagged
Evaluate a flag (no match)
Shard: flags-single
Allocated memory per operation 52.14 KiB/op 52.14 KiB/op No observed change Not flagged
Evaluate a flag (no match)
Shard: flags-single
Allocations per operation 556.77 count/op 556.77 count/op No observed change Not flagged
Evaluate a flag (no match)
Shard: flags-single
Time per operation 16.93 µs/op 16.88 µs/op 0.3% less time Not flagged
Evaluate a flag (no match)
Shard: flags-single
Process CPU time per operation 16.92 µs/op 16.88 µs/op 0.2% less time Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Allocated memory per operation 17.84 KiB/op 17.84 KiB/op No observed change Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Allocations per operation 198.27 count/op 198.27 count/op No observed change Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Time per operation 7.08 µs/op 7.17 µs/op 1.3% more time Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Process CPU time per operation 7.08 µs/op 7.15 µs/op 1% more time Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Allocated memory per operation 19.23 KiB/op 19.23 KiB/op No observed change Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Allocations per operation 210.77 count/op 210.77 count/op No observed change Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Time per operation 7.62 µs/op 7.62 µs/op <0.1% less time Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Process CPU time per operation 7.62 µs/op 7.62 µs/op <0.1% less time Not flagged
Evaluate a rollout flag
Shard: flags-single
Allocated memory per operation 14.04 KiB/op 14.04 KiB/op No observed change Not flagged
Evaluate a rollout flag
Shard: flags-single
Allocations per operation 160.76 count/op 160.76 count/op No observed change Not flagged
Evaluate a rollout flag
Shard: flags-single
Time per operation 6.07 µs/op 6.18 µs/op 1.7% more time Not flagged
Evaluate a rollout flag
Shard: flags-single
Process CPU time per operation 6.07 µs/op 6.18 µs/op 1.7% more time Not flagged
Evaluate a multivariate flag
Shard: flags-single
Allocated memory per operation 15.21 KiB/op 15.21 KiB/op No observed change Not flagged
Evaluate a multivariate flag
Shard: flags-single
Allocations per operation 177.77 count/op 177.77 count/op No observed change Not flagged
Evaluate a multivariate flag
Shard: flags-single
Time per operation 6.76 µs/op 6.71 µs/op 0.8% less time Not flagged
Evaluate a multivariate flag
Shard: flags-single
Process CPU time per operation 6.76 µs/op 6.71 µs/op 0.8% less time Not flagged

Values are medians of paired measurements. Not flagged does not mean unchanged. Unavailable means a measurement could not be provided, not zero. Estimated allocation measurements retain their instrumentation uncertainty. RSS measures the whole process, not just SDK allocations; observed peaks are sampled checkpoints. Paired ranges in the diagnostics describe variability, not confidence intervals.

Each shard uses its own runner; compare Before PR against With PR within a row, not across shards.

Compared 9f60b4a04a0b3b3dfd7209440f7296dddd99ed02 → 9e6d7cb902d2cfd924c8fff2631d9990005b2d47.

Full report and diagnostics

102 metric rows; 102 rows shown in all results. Omitted or shortened data remain in comparison.json, including per-runner environments, resource limits, measurement methods, samples and checkpoints.

@dustinbyrne dustinbyrne left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The raised-exception recovery works in the exercised low-level MCP 1.x paths. Optional validation-path robustness feedback is inline.

AI-assisted review.

Comment thread posthog/mcp/_raised_tool_error.py Outdated
# except block, but with a prefixed message. Only the catch-all around
# the tool call passes an exception's bare text.
error = sys.exc_info()[1]
if isinstance(error, Exception) and error_message == str(error):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

F1 — [P2] Skip validation results before formatting their exceptions

MINOR · OPTIONAL · introduced — posthog/mcp/_raised_tool_error.py:75 (RIGHT).

A low-level tool with an output schema requiring msg can return invalid, deeply nested output. Base returns the useful Output validation error: 'msg' is a required property; head instead returns maximum recursion depth exceeded while getting the repr of an object. Instrumentation should preserve the framework's validation response. This does not turn a successful call into a failure or crash the process: both results remain HTTP 200 with isError: true.

MCP 1.28.1 deliberately passes prefixed e.message for input/output validation (src/mcp/server/lowlevel/server.py:537–538,573–575, official revision 777b8d06710c140e3606b0d4598e2aa48546c266). The new comparison calls str(error) anyway; jsonschema 4.26.0 renders the entire failing instance and schema before the comparison rejects it. Besides the output-response regression, a transport-reachable invalid request containing 100,000 array items (~300 KB) now performs that unnecessary synchronous traversal. A like-for-like handler probe measured approximately 6 ms base / 120 ms head (illustrative single measurements, not a statistical benchmark); an actual HTTP test independently records zero full ValidationError renders on base versus one on head.

The governing MCP observer-only contract prohibits instrumentation from changing server responses or adding avoidable response latency.

Consider identifying framework validation-result paths before rendering the exception, and letting exception-inspection failures fall back to the original result. Preserve recovery for actual tool exceptions whose text happens to resemble a validation prefix.

Executed regression: Python 3.11.13, MCP 1.28.1, jsonschema 4.26.0, Pydantic 2.12.5, httpx 0.28.1. The following test uses public instrument(Server) and the real MCP Streamable HTTP ASGI transport; capture is a test sink. Normal empty arguments reach the tool, so incoming payload-depth limits do not explain the result: the deep value is server-produced.

import pytest
import httpx
import mcp.types as t
from mcp.server.lowlevel import Server
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
from posthog.mcp import instrument, MCPAnalyticsOptions
from posthog.test.mcp._helpers import FakeClient, flush_background

@pytest.mark.parametrize('depth', [0, 400])
async def test_instrumentation_preserves_invalid_output_response(depth):
    server = Server('validation-regression')
    @server.list_tools()
    async def list_tools():
        return [t.Tool(name='lookup', inputSchema={'type': 'object'}, outputSchema={
            'type': 'object', 'required': ['msg'],
            'properties': {'msg': {'type': 'string'}, 'payload': {}},
        })]
    @server.call_tool()
    async def lookup(name, arguments):
        payload = 0
        for _ in range(depth):
            payload = [payload]
        return {'payload': payload}
    instrument(server, FakeClient(), MCPAnalyticsOptions(
        context=False, capture_model=False, enable_conversation_id=False,
    ))
    manager = StreamableHTTPSessionManager(server, stateless=True, json_response=True)
    async with manager.run():
        async with httpx.AsyncClient(transport=httpx.ASGITransport(app=manager.handle_request),
                base_url='http://localhost', headers={
                    'Accept': 'application/json, text/event-stream',
                    'MCP-Protocol-Version': '2025-06-18',
                }) as client:
            response = await client.post('/mcp', json={
                'jsonrpc': '2.0', 'id': 1, 'method': 'tools/call',
                'params': {'name': 'lookup', 'arguments': {}},
            })
    await flush_background()
    assert response.status_code == 200
    result = response.json()['result']
    assert result['isError'] is True
    assert result['content'][0]['text'] == "Output validation error: 'msg' is a required property"

Save the test as test_output_validation_regression.py and run pytest -q test_output_validation_regression.py with the versions above. Equivalent isolated base/head executions produced: base ddeb000b6730befcfd5c3ca26fd0cba21193b5be: 2 passed. Head 565038fe9f50668b922f14dd0dcfc6e84e4e78f5: 1 passed, 1 failed, at the response-text assertion. The shallow-invalid-output control passes both. No fix was applied or tested.

The unusual output-depth trigger and already-failing call limit the severity; this is optional robustness/performance feedback, not a merge-blocking crash claim.

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.

Fixed in afd7389. The wrapper now recognizes the decorator's validation results before rendering anything: the message has to equal one of the Input validation error: / Output validation error: prefixes plus the exception's own short .message. Only then does it compare against str(error), so a jsonschema ValidationError is never rendered. If inspecting the exception raises, the original result goes back untouched. A tool's own raise worded like a validation error is still recovered.

The parameterized test in test_lowlevel.py has two new rows. One sends a 400-deep payload that fails input validation. Before the fix, the response text was maximum recursion depth exceeded; now it keeps Input validation error: ... and the event stays Error. The other has the tool raise ValueError("Input validation error: quota exceeded"), which is still reported as ValueError. pytest posthog/test/mcp: 730 passed on mcp 1.30, 551 passed on mcp 2.3.

lucasheriques added a commit that referenced this pull request Nov 11, 2026
Review on #1231 (PostHog Review, dustinbyrne): the message guard called str(error)
on jsonschema ValidationErrors, which renders the whole instance and schema. On a
deeply nested payload that raised RecursionError and replaced the SDK's validation
response; on a large one it blocked the loop. A validation result is now matched by
the prefix plus the error's own short .message first, and any failure while
inspecting the exception leaves the original result untouched. A tool's own raise
worded like a validation error is still recovered.

Tested: parameterized test gains a 400-deep payload row (red before: response text
'maximum recursion depth exceeded') and a prefix-worded ValueError row.
pytest posthog/test/mcp: mcp 1.30 730 passed / 11 skipped; mcp 2.3 bare 551 passed
/ 55 skipped. CI-exact mypy clean.
lucasheriques added a commit that referenced this pull request Nov 11, 2026
Review on #1231 (PostHog Review, dustinbyrne): the message guard called str(error)
on jsonschema ValidationErrors, which renders the whole instance and schema. On a
deeply nested payload that raised RecursionError and replaced the SDK's validation
response; on a large one it blocked the loop. A validation result is now matched by
the prefix plus the error's own short .message first, and any failure while
inspecting the exception leaves the original result untouched. A tool's own raise
worded like a validation error is still recovered.

Tested: parameterized test gains a 400-deep payload row (red before: response text
'maximum recursion depth exceeded') and a prefix-worded ValueError row.
pytest posthog/test/mcp: mcp 1.30 730 passed / 11 skipped; mcp 2.3 bare 551 passed
/ 55 skipped. CI-exact mypy clean.
@lucasheriques
lucasheriques force-pushed the lucas/mcp-lowlevel-raised-error branch from afd7389 to 9e6d7cb Compare November 11, 2026 19:16
…sults

On mcp 1.x the low-level @server.call_tool() decorator catches a tool's raise
and returns CallToolResult(isError=True) before our handler sees it, so
$mcp_tool_call had $mcp_error_type "Error", no frames and no $mcp_error_status
(#1223). The decorator builds that result through server._make_error_result
inside its except block, so an instance wrapper reads the live exception there
and settles it into the same raised_tool_error slot standalone FastMCP uses.
Validation failures also pass through that method inside an except block; only
a message equal to str(exception) is the tool's own raise.

mcp 2.x low-level needs no change: raw handlers raise through to our wrapper,
and a scratch check showed RuntimeError, both frames and status 503.

Tested: parameterized test in test_lowlevel.py (plain and wrapped 503, plain
ValueError, input-validation guard). Red before on the three raising rows.
Removing the message guard turns the validation row into ValidationError.
pytest posthog/test/mcp: mcp 1.30 727 passed / 11 skipped; mcp 2.3 bare 551
passed / 55 skipped. CI-exact mypy: only the base branch's _exceptions.py:65.
…what it covers

Pre-PR review: the message guard admits any exception the decorator's catch-all
sees (tool body, list_tools cache refresh, result construction), not only the
tool's own raise, and _make_error_result first ships in mcp 1.10. Comment and
changeset now say so. Tested: pytest posthog/test/mcp on mcp 1.30, 727 passed.
Review on #1231 (PostHog Review, dustinbyrne): the message guard called str(error)
on jsonschema ValidationErrors, which renders the whole instance and schema. On a
deeply nested payload that raised RecursionError and replaced the SDK's validation
response; on a large one it blocked the loop. A validation result is now matched by
the prefix plus the error's own short .message first, and any failure while
inspecting the exception leaves the original result untouched. A tool's own raise
worded like a validation error is still recovered.

Tested: parameterized test gains a 400-deep payload row (red before: response text
'maximum recursion depth exceeded') and a prefix-worded ValueError row.
pytest posthog/test/mcp: mcp 1.30 730 passed / 11 skipped; mcp 2.3 bare 551 passed
/ 55 skipped. CI-exact mypy clean.
@lucasheriques
lucasheriques force-pushed the lucas/mcp-lowlevel-raised-error branch from 9e6d7cb to 2dc2abd Compare November 11, 2026 19:56

This branch has not been deployed

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