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 (a58db4a, 08c4555, c5481c3).

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-12T13:54:49.633500+00:00
Duration: 253546ms

✅ 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 ✅ 512ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 507ms
Required Headers.Has Authorization Bearer Header ✅ 506ms
Required Headers.Has Content Type Json ✅ 506ms
Required Headers.Has Posthog Sdk Info Format ✅ 506ms
Required Headers.Has Posthog Attempt Header ✅ 507ms
Required Headers.Has Posthog Request Id ✅ 506ms
Required Headers.Has Posthog Request Timestamp ✅ 506ms
Required Headers.Has User Agent ✅ 506ms
Body Format.Body Has Created At And Batch ✅ 506ms
Body Format.No Api Key In Body ✅ 506ms
Body Format.No Sent At In Body ✅ 506ms
Event Format.Event Has Required Root Fields ✅ 506ms
Event Format.Event Uuid Is Valid ✅ 506ms
Event Format.Event Timestamp Is Rfc3339 ✅ 506ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 518ms
Event Format.Distinct Id Is String ✅ 507ms
Event Format.Distinct Id At Root Not Properties ✅ 506ms
Event Format.Custom Properties Preserved ✅ 506ms
Event Format.Set Properties Preserved ✅ 506ms
Event Format.Set Once Properties Preserved ✅ 506ms
Event Format.Groups Properties Preserved ✅ 506ms
Event Format.Sdk Generates Uuid If Not Provided ✅ 506ms
Event Format.Event Has Required Root Fields Batch ✅ 508ms
Event Format.Event Uuid Is Valid Batch ✅ 509ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 508ms
Event Format.Distinct Id Is String Batch ✅ 509ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 508ms
Event Format.Custom Properties Preserved Batch ✅ 508ms
Event Format.Set Properties Preserved Batch ✅ 509ms
Event Format.Set Once Properties Preserved Batch ✅ 508ms
Event Format.Groups Properties Preserved Batch ✅ 508ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 508ms
Batch Behavior.Multiple Events In Single Batch ✅ 511ms
Batch Behavior.Batch Envelope Smoke ✅ 510ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 503ms
Batch Behavior.Flush At Triggers Batch ✅ 1009ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 506ms
Deduplication.Generates Unique Uuids ✅ 511ms
Deduplication.Different Events Same Content Different Uuids ✅ 508ms
Deduplication.Preserves Uuid On Retry ✅ 6514ms
Deduplication.Preserves Timestamp On Retry ✅ 6515ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6517ms
Deduplication.No Duplicate Events In Batch ✅ 514ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 509ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 13524ms
Header Behavior On Retry.Request Id Preserved On Retry ✅ 6517ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 3016ms
Header Behavior On Retry.Request Timestamp Changes On Retry ✅ 6517ms
Response Format Validation.Success Response Has Uuid Keyed Results ✅ 508ms
Response Format Validation.Success Response Has Ok For Each Event ✅ 511ms
Response Format Validation.Success No Retry After When All Ok ✅ 510ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 1512ms
Response Format Validation.Success No Retry After When Drop Only ✅ 510ms
Response Format Validation.Response Echoes Request Id ✅ 509ms
Retry Behavior.Retries On 408 ✅ 6512ms
Retry Behavior.Retries On 500 ✅ 6517ms
Retry Behavior.Retries On 503 ✅ 8516ms
Retry Behavior.Retries On 504 ✅ 6530ms
Retry Behavior.Retries On 404 ✅ 6516ms
Retry Behavior.Retries On 429 ✅ 6517ms
Retry Behavior.Retries On 502 ✅ 6513ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3515ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11514ms
Retry Behavior.Does Not Retry On 400 ✅ 2511ms
Retry Behavior.Does Not Retry On 401 ✅ 2511ms
Retry Behavior.Does Not Retry On 402 ✅ 2510ms
Retry Behavior.Does Not Retry On 413 ✅ 2511ms
Retry Behavior.Does Not Retry On 415 ✅ 2510ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2511ms
Retry Behavior.Implements Backoff ✅ 19529ms
Partial Batch Handling.Handles 200 Full Success ✅ 2510ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3514ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3512ms
Partial Batch Handling.Does Not Retry Warning Events ✅ 3514ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6518ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6515ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6518ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6515ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6518ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6515ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8515ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3511ms
Partial Batch Handling.Mixed Ok Drop Warning No Retry ✅ 3514ms
Compression.Sends Gzip Content Encoding ✅ 508ms
Compression.No Content Encoding When Disabled ✅ 510ms
Compression.Compressed Body Is Decompressible ✅ 508ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2511ms
Event Options.Cookieless Mode Override ✅ 509ms
Event Options.Disable Skew Correction Override ✅ 508ms
Event Options.Process Person Profile Override ✅ 508ms
Event Options.Product Tour Id Override ✅ 509ms
Event Options.Unset Options Omitted ✅ 508ms
Event Options.Options Override In Batch ✅ 510ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 508ms

Capture_Ai Tests

✅ 5/5 tests passed

View Details
Test Status Duration
Routing.Capture Ai Posts To Ai Endpoint ✅ 510ms
Routing.Capture Does Not Reroute Ai Named Events ✅ 511ms
Identity.Capture Ai Event Has Uuid ✅ 519ms
Identity.Capture Ai Keeps Supplied Uuid ✅ 508ms
Timestamp Format.Non Utc Event Timestamp Is Converted To Utc ✅ 511ms

Feature_Flags Tests

✅ 17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 9ms
Request Payload.Flags Request Uses V4 Query Param ✅ 8ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 8ms
Request Payload.Flags Request Omits Authorization Header ✅ 8ms
Request Payload.Token In Flags Body Matches Init ✅ 7ms
Request Payload.Groups Round Trip ✅ 7ms
Request Payload.Groups Default To Empty Object ✅ 8ms
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 ✅ 8ms
Request Lifecycle.No Flags Request On Init Alone ✅ 3ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 508ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 13ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 8ms
Retry Behavior.Retries Flags On 502 ✅ 311ms
Retry Behavior.Retries Flags On 504 ✅ 312ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 510ms

Feature_Flags_V4 Tests

✅ 149/149 tests passed

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

Feature_Flags_Local_Evaluation Tests

✅ 4/4 tests passed

View Details
Test Status Duration
Versioned Boolean Matching.Matching Version Missing ✅ 50ms
Versioned Boolean Matching.Matching Version 1 ✅ 48ms
Versioned Boolean Matching.Matching Version 2 ✅ 47ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 27ms

@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.53 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.57 count/op 1,096.58 count/op <0.1% more Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Time per operation 50.52 µs/op 52.45 µs/op 3.8% more time Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Idle process memory (RSS) 36 MiB 35.77 MiB 0.6% less memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Observed peak process memory (RSS) 37.76 MiB 37.52 MiB 0.6% less memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Process memory after settling (RSS) 37.76 MiB 37.52 MiB 0.6% less memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Process CPU time per operation 51.24 µs/op 53.32 µs/op 4.1% more time Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Lifetime peak process memory (RSS) 40.55 MiB 40.55 MiB No observed change Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Allocated memory per operation 166.1 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.6 count/op 1,089.6 count/op <0.1% fewer Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Time per operation 72.69 µs/op 75.29 µs/op 3.6% more time Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Idle process memory (RSS) 40.89 MiB 40.77 MiB 0.3% less memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Observed peak process memory (RSS) 45.98 MiB 45.86 MiB 0.3% less memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Process memory after settling (RSS) 45.98 MiB 45.86 MiB 0.3% less memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Process CPU time per operation 67.84 µs/op 68.54 µs/op 1% more time Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Lifetime peak process memory (RSS) 50.8 MiB 50.74 MiB 0.1% 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.59 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 60.82 µs/op 61.55 µs/op 1.2% more time Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Idle process memory (RSS) 35.8 MiB 35.74 MiB 0.2% less memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Observed peak process memory (RSS) 35.9 MiB 35.84 MiB 0.2% less memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Process memory after settling (RSS) 35.9 MiB 35.84 MiB 0.2% less memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Process CPU time per operation 59.95 µs/op 60.13 µs/op 0.3% more time Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Lifetime peak process memory (RSS) 40.55 MiB 40.55 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% less memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Allocations per operation 1,129.49 count/op 1,129.48 count/op <0.1% fewer Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Time per operation 80.39 µs/op 78.04 µs/op 2.9% less time Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Idle process memory (RSS) 40.65 MiB 40.74 MiB 0.2% more memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Observed peak process memory (RSS) 40.65 MiB 40.74 MiB 0.2% more memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Process memory after settling (RSS) 40.65 MiB 40.74 MiB 0.2% more memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Process CPU time per operation 77.78 µs/op 73.86 µs/op 5% less time Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Lifetime peak process memory (RSS) 40.97 MiB 40.96 MiB <0.1% less memory Not flagged
Queue an event (32-byte payload)
Shard: capture
Caller-thread CPU time per operation 37.47 µs/op 37.55 µs/op 0.2% more time Not flagged
Queue an event (32-byte payload)
Shard: capture
Time per operation 37.47 µs/op 37.55 µs/op 0.2% more time Not flagged
Queue an event (4,096-byte payload)
Shard: capture
Caller-thread CPU time per operation 35.04 µs/op 34.07 µs/op 2.8% less time Not flagged
Queue an event (4,096-byte payload)
Shard: capture
Time per operation 36.57 µs/op 34.77 µs/op 4.9% less 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 60.7 µs/op 60.55 µs/op 0.2% less time Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Process CPU time per operation 60.7 µs/op 60.56 µs/op 0.2% less 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 607.63 µs/op 607.27 µs/op <0.1% less time Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Process CPU time per operation 607.71 µs/op 607.32 µs/op <0.1% 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 6.01 ms/op 6.06 ms/op 0.8% more time Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Process CPU time per operation 6.01 ms/op 6.06 ms/op 0.8% more time Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Idle process memory (RSS) 41.69 MiB 42.31 MiB 1.5% more memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Observed peak process memory (RSS) 42.07 MiB 42.72 MiB 1.5% more memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Process memory after settling (RSS) 42.07 MiB 42.72 MiB 1.5% more memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Lifetime peak process memory (RSS) 42.47 MiB 42.46 MiB <0.1% less memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Idle process memory (RSS) 41.81 MiB 42.11 MiB 0.7% more memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Observed peak process memory (RSS) 42.37 MiB 42.19 MiB 0.4% less memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Process memory after settling (RSS) 42.21 MiB 41.87 MiB 0.8% less memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Lifetime peak process memory (RSS) 42.66 MiB 42.55 MiB 0.3% less 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 13.89 µs/op 13.89 µs/op <0.1% more time Not flagged
Evaluate one boolean flag
Shard: flags-single
Process CPU time per operation 13.89 µs/op 13.89 µs/op <0.1% 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 21.7 µs/op 21.89 µs/op 0.9% more time Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Process CPU time per operation 21.7 µs/op 21.88 µs/op 0.8% more 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 27.71 µs/op 27.7 µs/op <0.1% less time Not flagged
Evaluate a flag (early match)
Shard: flags-single
Process CPU time per operation 27.71 µs/op 27.7 µs/op <0.1% 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 38.31 µs/op 38.31 µs/op <0.1% more time Not flagged
Evaluate a flag (late match)
Shard: flags-single
Process CPU time per operation 38.3 µs/op 38.31 µs/op <0.1% 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 34.86 µs/op 34.87 µs/op <0.1% more time Not flagged
Evaluate a flag (no match)
Shard: flags-single
Process CPU time per operation 34.86 µs/op 34.87 µs/op <0.1% more 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 16.64 µs/op 16.62 µs/op <0.1% less time Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Process CPU time per operation 16.64 µs/op 16.62 µs/op <0.1% less 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 17.43 µs/op 17.57 µs/op 0.8% more time Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Process CPU time per operation 17.43 µs/op 17.57 µs/op 0.8% more 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 13.09 µs/op 13.17 µs/op 0.7% more time Not flagged
Evaluate a rollout flag
Shard: flags-single
Process CPU time per operation 13.09 µs/op 13.17 µs/op 0.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 14.49 µs/op 14.52 µs/op 0.2% more time Not flagged
Evaluate a multivariate flag
Shard: flags-single
Process CPU time per operation 14.49 µs/op 14.52 µs/op 0.2% more 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 cc1d8d8994ac9611993937f9b54a22635e881667 → c5481c3f207c0a27430225ad3d0cfb040fc4e3e6.

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
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 9e6d7cb to 2dc2abd Compare November 11, 2026 19:56
…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 2dc2abd to c5481c3 Compare November 12, 2026 13:49

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