Repository navigation
fix(mcp): report the exception behind a FastMCP isError tool result #1226
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
+647
−17
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
a7f8683
test(mcp): failing repro for FastMCP tool failures losing the raised …
lucasheriques 8bbd1fb
fix(mcp): report the exception behind a FastMCP isError tool result
lucasheriques 81b3170
fix(mcp): keep another server's handled tool failure off this call
lucasheriques f5aea70
fix(mcp): keep FastMCP 2.x instrumented, and freeze the slot on exit
lucasheriques 34fbaeb
fix(mcp): redact secrets in captured exception frame source lines
lucasheriques 52fc421
fix(mcp): don't let a lingering background task keep a tool's traceba…
lucasheriques d8a7a55
fix(mcp): redact sensitive JSON members inside captured strings
lucasheriques 9c1cb4f
fix(mcp): keep JSON-member redaction linear on malformed arrays
lucasheriques f9832cc
fix(mcp): scan JSON members once instead of retrying the regex at eve…
lucasheriques File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| pypi/posthog: patch | ||
| --- | ||
|
|
||
| `posthog.mcp`: a failed tool call on a standalone FastMCP server now reports the exception the tool raised, with its cause chain and stack frames, and `$mcp_error_type` names its class. Before, FastMCP converted the exception into an error result first, so the failure was a generic `Error` with no frames. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| """Recover the exception behind a standalone FastMCP ``isError`` tool result. | ||
|
|
||
| FastMCP's ``tools/call`` handler, the one we wrap, turns whatever its tool | ||
| dispatch raised into ``CallToolResult(isError=True)``, keeping only the | ||
| message text. Wrapping that dispatch on the server instance sees the exception | ||
| first, and hands it to the enclosing handler through a context variable. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from contextlib import contextmanager | ||
| from contextvars import ContextVar | ||
| from dataclasses import dataclass | ||
| from typing import Any, Iterator, Optional | ||
|
|
||
| _WRAPPED_FLAG = "__posthog_mcp_wrapped__" | ||
|
|
||
| # fastmcp 3+ dispatches tools/call through the public `call_tool`; 2.x has no | ||
| # `call_tool` and dispatches through `_call_tool_middleware`. | ||
| _DISPATCH_METHODS = ("call_tool", "_call_tool_middleware") | ||
|
|
||
|
|
||
| @dataclass | ||
| class RaisedToolError: | ||
| error: Optional[BaseException] = None | ||
|
|
||
|
|
||
| @dataclass | ||
| class _Slot: | ||
| server: Any | ||
| error: Optional[BaseException] = None | ||
| open: bool = True | ||
|
|
||
|
|
||
| _current: ContextVar[Optional[_Slot]] = ContextVar( | ||
| "posthog_mcp_raised_tool_error", default=None | ||
| ) | ||
|
|
||
|
|
||
| def wrap_tool_dispatch(server: Any) -> None: | ||
| method = next((m for m in _DISPATCH_METHODS if hasattr(server, m)), None) | ||
| if method is None: | ||
| return | ||
| original = getattr(server, method) | ||
| if getattr(original, _WRAPPED_FLAG, False): | ||
| return | ||
|
|
||
| async def dispatch(*args: Any, **kwargs: Any) -> Any: | ||
| # A tool calling another tool nests these calls. The outermost call | ||
| # settles last, so the slot ends holding the outcome the client sees. | ||
| try: | ||
| result = await original(*args, **kwargs) | ||
| except Exception as error: | ||
| _settle(server, error) | ||
| raise | ||
| _settle(server, None) | ||
| return result | ||
|
|
||
| setattr(dispatch, _WRAPPED_FLAG, True) | ||
| setattr(server, method, dispatch) | ||
|
|
||
|
|
||
| def _settle(server: Any, error: Optional[BaseException]) -> None: | ||
| # Another server's dispatch, reached from inside a tool, must not write | ||
| # its outcome onto this call, nor may a background task that outlives it. | ||
| slot = _current.get() | ||
| if slot is not None and slot.open and slot.server is server: | ||
| slot.error = error | ||
|
|
||
|
|
||
| @contextmanager | ||
| def raised_tool_error(server: Any) -> Iterator[RaisedToolError]: | ||
| slot = _Slot(server) | ||
| raised = RaisedToolError() | ||
| token = _current.set(slot) | ||
| try: | ||
| yield raised | ||
| finally: | ||
| _current.reset(token) | ||
| # A background task started by the tool keeps a copy of this context, | ||
| # so the slot outlives the call; it must not keep the traceback alive. | ||
| raised.error, slot.error = slot.error, None | ||
| slot.open = False |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P1 · Sanitize source context before capturing recovered exceptions
On failed standalone FastMCP calls,
record_resultnow forwards exceptions with source snippets in their stack frames._sanitize_exception_valuesscrubs only exceptionvalue, leavingpre_context,context_line, andpost_contextuntouched. URL passwords and PostHog tokens in those lines reach$exceptionverbatim, violating the MCP privacy contract; sanitize frame strings before capture.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
+1, on fastmcp 3.2.0 a
phx_token written in theraiseline is redacted invaluebut shows up as-is in that frame'scontext_line. Base sent no frames here.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 34fbaeb. The sanitizer now runs
pre_context,context_lineandpost_contextof every frame throughsanitize_captured_value, the same passvaluegets. That also covers the official SDK path, which already sent frames.test_secrets_in_frame_source_lines_are_redactedputs a database URL with a password on the line before the raise. It fails without the change and passes with it, on fastmcp 2.14.7, 3.2 and 4.1.8.