Skip to content

fix(mcp): report the exception a tool raised when the SDK masks it - #907

Merged
bernatixer merged 2 commits into
mainfrom
posthog/mcp-unwrap-masked-tool-errors
Sep 1, 2026
Merged

fix(mcp): report the exception a tool raised when the SDK masks it#907
bernatixer merged 2 commits into
mainfrom
posthog/mcp-unwrap-masked-tool-errors

Conversation

@bernatixer

@bernatixer bernatixer commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

The MCP SDK CI matrix went red on Aug 31 with no repo change. The cause is the repo's rolling exclude-newer = "7 days" quarantine: mcp 2.1.0 (published Aug 24, 19:04 UTC) aged into eligibility at 19:04 UTC, between two runs of the same commit, so the unpinned mcp>=2,<3 leg resolved 2.0.0 in the morning and 2.1.0 in the evening. Three of the four red jobs are fail-fast cancellations of the one real failure.

mcp 2.1 masks unexpected tool exceptions: the dispatch wrapper's message becomes Error executing tool <name> with the original kept only on __cause__ (documented in the SDK at tools/base.py). $mcp_error_message and $mcp_error_type read $exception_list[0], so every unexpected tool failure reported the same masked string and the failures view lost the reason a call failed, which is the one thing these properties exist to carry.

The scalars now read the entry behind the SDK's dispatch wrapper. exceptions_from_error_tuple already records the __cause__ chain, so the original exception is sitting right behind the wrapper; the match requires the type name (ToolError / UnexpectedToolError), the Error executing tool message prefix, and a module from an SDK namespace (mcp., fastmcp.), and it walks every consecutive wrapper because a tool invoking a failing tool is wrapped once per dispatch. A wrapper without a chained cause is kept as is, an application's own exception that merely shares the wrapper's name is kept, and the $exception sibling still carries the full chain, so error-tracking grouping is unchanged.

On mcp 1.x the wrapper includes the original text, so the scalars there change from Error executing tool boom: explode / ToolError to explode / ValueError. The tool name is already its own property on the event.

💚 How did you test it?

  • The previously failing gate test (test_instrumented_server_failure_carries_them) passes untouched under every mcp version CI can resolve: 2.0.0 (yesterday's resolution), 2.1.0 (today's), and 2.1.1 (ages in Sep 1, verified with an --exclude-newer override).
  • Four tests pin the unwrap through the public paths: a real SDK wrapper with a chained cause yields the cause's message and type while the $exception sibling keeps the wrapper; a wrapper without a cause is kept; an application exception sharing the wrapper's name is kept; and a nested-server test asserts both the inner and outer events report the root cause. The unit tests import the real per-major ToolError classes.
  • Revert-proven at each round: against main, the gate test and the unwrap test fail; against the first revision of this PR, both review findings reproduce as failing tests (nested wrappers and the same-named application exception); with the final change, all pass.
  • Full posthog/test/mcp suite: 235 passed on the lockfile env (mcp 1.28.1 + fastmcp 3.2.0), 215 passed + 13 skipped on each of mcp 2.0.0, 2.1.0, and 2.1.1.
  • ruff format, ruff check, and the CI mypy command (through mypy-baseline filter) pass.
  • Redaction covers the unwrapped entry: _sanitize_exception_values maps over every chain entry, not just the first.

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Added a changeset under .sampo/changesets/ (hand-written in the sampo add format)

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

Written by Claude Code in a PostHog Desktop session directed by @bernatixer, after tracing why the MCP SDK matrix went red on #906 with a snapshot-only diff. Rejected alternatives: pinning the v2 leg below 2.1 (defeats the gate's purpose and ships masked messages to customers anyway), version-gating the test assertion (accepts the masked string as the product), and raising ToolError in the test (stops exercising the unexpected-exception path customers actually hit). The SDK documents __cause__ as the channel for the original error, so the instrumentation reads it.

The advisory review's two blocking findings (nested double-wrapping, and type-name matching catching application exceptions) were both reproduced first and are fixed in the second commit: the match is gated on the entry's recorded SDK module and traverses consecutive wrappers.

Skills invoked: writing-tests, writing-pr-descriptions.


Created with PostHog Desktop

The MCP SDK's tool dispatch re-raises whatever a tool raised as a ToolError whose message starts "Error executing tool <name>", and mcp 2.1 masks the original text out of that message entirely, keeping it only on __cause__. The $mcp_error_message and $mcp_error_type scalars read $exception_list[0], so on mcp 2.1 every unexpected tool failure reported the same masked string and the failures view lost the reason.

The scalars now read the entry behind the dispatch wrapper, which exceptions_from_error_tuple already records from __cause__. The wrapper is matched by type name and message prefix because each SDK major ships its own ToolError class. A wrapper without a chained cause is kept as is, and the $exception sibling still carries the full chain.

This broke CI without a repo change: the rolling exclude-newer = "7 days" quarantine made mcp 2.1.0 (published Aug 24) eligible on Aug 31 at 19:04 UTC, between two runs of the same commit. The unpinned mcp>=2,<3 leg resolved 2.0.0 in the morning and 2.1.0 in the evening. mcp 2.1.1 ages in on Sep 1; the fix is verified against 2.0.0, 2.1.0, and 2.1.1.

Generated-By: PostHog Desktop
Task-Id: ec0cc27f-fc40-4994-b153-2bfe74de1edf
@github-actions

github-actions Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-09-01 10:03:17 UTC
Duration: 256431ms

✅ All Tests Passed!

111/111 tests passed


Capture_V1 Tests

94/94 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint 518ms
Endpoint And Method.Does Not Use Legacy Endpoints 511ms
Required Headers.Has Authorization Bearer Header 510ms
Required Headers.Has Content Type Json 511ms
Required Headers.Has Posthog Sdk Info Format 510ms
Required Headers.Has Posthog Attempt Header 511ms
Required Headers.Has Posthog Request Id 511ms
Required Headers.Has Posthog Request Timestamp 510ms
Required Headers.Has User Agent 511ms
Body Format.Body Has Created At And Batch 511ms
Body Format.No Api Key In Body 511ms
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.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 514ms
Event Format.Event Timestamp Is Rfc3339 Batch 514ms
Event Format.Distinct Id Is String Batch 514ms
Event Format.Distinct Id At Root Not Properties Batch 514ms
Event Format.Custom Properties Preserved Batch 515ms
Event Format.Set Properties Preserved Batch 515ms
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 518ms
Batch Behavior.Batch Envelope Smoke 515ms
Batch Behavior.Flush With No Events Sends Nothing 507ms
Batch Behavior.Flush At Triggers Batch 1011ms
Batch Behavior.Created At Reflects Batch Creation Time 511ms
Deduplication.Generates Unique Uuids 518ms
Deduplication.Different Events Same Content Different Uuids 513ms
Deduplication.Preserves Uuid On Retry 6519ms
Deduplication.Preserves Timestamp On Retry 6520ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 6523ms
Deduplication.No Duplicate Events In Batch 519ms
Header Behavior On Retry.Attempt Header Starts At One 510ms
Header Behavior On Retry.Attempt Header Increments On Retry 13527ms
Header Behavior On Retry.Request Id Preserved On Retry 6520ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3019ms
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 513ms
Response Format Validation.Success No Retry After When All Ok 512ms
Response Format Validation.Success Retry After Present When Retry Events 1515ms
Response Format Validation.Success No Retry After When Drop Only 513ms
Response Format Validation.Response Echoes Request Id 510ms
Retry Behavior.Retries On 408 6519ms
Retry Behavior.Retries On 500 6520ms
Retry Behavior.Retries On 503 8519ms
Retry Behavior.Retries On 504 6520ms
Retry Behavior.Retryable Errors Have Retry After 3517ms
Retry Behavior.Respects Retry After On Retryable Error 11521ms
Retry Behavior.Does Not Retry On 400 2514ms
Retry Behavior.Does Not Retry On 401 2513ms
Retry Behavior.Does Not Retry On 402 2513ms
Retry Behavior.Does Not Retry On 413 2514ms
Retry Behavior.Does Not Retry On 415 2513ms
Retry Behavior.Non Retryable Errors Have No Retry After 2513ms
Retry Behavior.Implements Backoff 22537ms
Retry Behavior.Max Retries Respected 22536ms
Partial Batch Handling.Handles 200 Full Success 2511ms
Partial Batch Handling.Handles 200 With All Ok 3515ms
Partial Batch Handling.Does Not Retry Dropped Events 3514ms
Partial Batch Handling.Does Not Retry Limited Events 3516ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 6522ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 6516ms
Partial Batch Handling.Retries Only Retry Events From Partial 6523ms
Partial Batch Handling.Partial Retry Preserves Uuids 6518ms
Partial Batch Handling.Partial Retry Attempt Header Increments 6521ms
Partial Batch Handling.Partial Retry Request Id Preserved 6521ms
Partial Batch Handling.Respects Retry After On Partial 8519ms
Partial Batch Handling.Unknown Result Treated As Terminal 3517ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry 3520ms
Compression.Sends Gzip Content Encoding 511ms
Compression.No Content Encoding When Disabled 510ms
Compression.Compressed Body Is Decompressible 510ms
Error Handling.Does Not Retry On Unknown 4Xx 2512ms
Event Options.Cookieless Mode Override 510ms
Event Options.Disable Skew Correction Override 510ms
Event Options.Process Person Profile Override 511ms
Event Options.Product Tour Id Override 510ms
Event Options.Unset Options Omitted 510ms
Event Options.Options Override In Batch 513ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties 511ms
Geoip And Historical Migration.Historical Migration Set In Body 510ms
Geoip And Historical Migration.Historical Migration Absent By Default 510ms

Feature_Flags Tests

17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id 11ms
Request Payload.Flags Request Uses V2 Query Param 9ms
Request Payload.Flags Request Hits Flags Path Not Decide 9ms
Request Payload.Flags Request Omits Authorization Header 9ms
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 10ms
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 314ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 512ms

@bernatixer
bernatixer marked this pull request as ready for review September 1, 2026 09:26
@bernatixer
bernatixer requested a review from a team as a code owner September 1, 2026 09:26
@marandaneto
marandaneto requested a review from a team September 1, 2026 09:35

@marandaneto marandaneto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Automated advisory code review.

Comment thread posthog/mcp/_posthog_events.py Outdated
Comment thread posthog/mcp/_posthog_events.py Outdated
@marandaneto
marandaneto requested a review from a team September 1, 2026 09:36
Two review findings on the dispatch-wrapper unwrap, both reproduced before fixing.

A tool that invokes a failing tool is wrapped once per dispatch, so stepping past a single entry landed on the still-masked inner wrapper. The unwrap now walks every consecutive wrapper to the first real exception; a nested-server test asserts both the inner and the outer event report the root cause.

Matching by type name and message prefix alone also unwrapped an application's own exception that happened to be named ToolError with a matching prefix, replacing the message the application chose to surface. The match now additionally requires the entry's recorded module to come from an SDK namespace (mcp., fastmcp.), verified against mcp 1.28.1, mcp 2.0.0/2.1.0/2.1.1, and standalone fastmcp. The unit tests use the real per-major ToolError classes, and a new test pins that a same-named application exception is kept.

Generated-By: PostHog Desktop
Task-Id: ec0cc27f-fc40-4994-b153-2bfe74de1edf
@bernatixer
bernatixer merged commit caf9030 into main Sep 1, 2026
44 checks passed
@bernatixer
bernatixer deleted the posthog/mcp-unwrap-masked-tool-errors branch September 1, 2026 10:27
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