Skip to content

posthog.mcp: FastMCP tool failures lose the exception (type is always "Error", no frames) and $mcp_error_status is never set #1223

Closed

Description

@kwent

Version

posthog 7.83.1 (checked against main / 7.86.6: same code path), fastmcp 4.1.6, mcp SDK 2.x

Steps to Reproduce

import asyncio, logging
from fastmcp import Client, FastMCP
from posthog import Posthog
from posthog.mcp import MCPAnalyticsOptions, instrument

server = FastMCP("repro")

def fetch():
    raise ConnectionError("upstream down")

@server.tool
def boom() -> str:
    try:
        fetch()
    except ConnectionError as exc:
        raise RuntimeError("lookup failed") from exc

client = Posthog("phc_xxx", send=False)
captured = []
client.capture = lambda event, **kw: captured.append((event, kw["properties"]))
instrument(server, client, MCPAnalyticsOptions())

async def main():
    async with Client(server) as c:
        await c.call_tool("boom", {}, raise_on_error=False)
    await asyncio.sleep(0.2)
    for event, props in captured:
        if event in ("$mcp_tool_call", "$exception"):
            print(event, props.get("$mcp_error_type"), props.get("$exception_list"))

asyncio.run(main())

Expected Result

The failure carries the exception the tool raised, the same way posthog-python's capture_exception reports any other exception:

  • $mcp_error_type is RuntimeError
  • the $exception event's $exception_list has the chain (RuntimeError caused by ConnectionError) with stack frames

And when the cause is an HTTP error (e.g. an OpenAPI-generated tool getting a 404 from its upstream), $mcp_error_status is set. The MCP failure views group by $mcp_error_status.

Actual Result

  • $mcp_error_type is always "Error".
  • $exception_list has a single synthetic entry (type: "Error", mechanism.type: "generic") holding only the message text, with no frames and no cause chain.
  • $mcp_error_status is never set: nothing in posthog/mcp writes it.

In production on a FastMCP server, 2 of 1,254 MCP $exception events over two days had any stack frames.

Cause: FastMCP catches the tool's exception and returns a CallToolResult with isError=True before the instrumented handler sees it. _instrumentation.py then takes the is_tool_result_error(result) branch and calls capture_exception(result). That reaches _from_message(...), so the original exception and its __traceback__ are already gone.

Workaround we run today: a FastMCP middleware registered first in server.middleware catches the exception in on_call_tool, stores it in a ContextVar, and re-raises it unchanged. A before_send hook then reads the ContextVar and:

  • sets $mcp_error_type to the real class (stepping past fastmcp's ToolError("Error calling tool ...") wrapper)
  • sets $mcp_error_status from exc.response.status_code anywhere in the chain
  • rebuilds $exception_list with posthog.exception_utils.exceptions_from_error_tuple

It works because the capture task is created in the request's context. Source: https://github.com/rootlyhq/rootly-mcp-server/blob/main/src/rootly_mcp_server/posthog_analytics.py (ToolExceptionCaptureMiddleware, enrich_posthog_mcp_event).

Suggested fix: when instrument() detects a FastMCP server, have the SDK register a similar outermost middleware itself, and prefer the captured exception over the CallToolResult text when building error. Derive $mcp_error_status from an HTTPStatusError-like response.status_code in the chain.

Activity

  1. posthog commented on Nov 11, 2026

    @posthog
    Contributor

    PostHog self-driving picked up this issue. Status: Research is done.

    Somebody may already be working on it, so ask before you start a fix.

    Report (team access only): https://us.posthog.com/project/2/inbox/reports/01a1c84a-8c50-7140-9525-048036f02f9f?link_source=github_comment

  2. lucasheriques commented on Nov 13, 2026

    @lucasheriques
    Contributor

    Fixed in posthog 7.90.0. FastMCP tool errors now report the real exception type and stack trace, and set $mcp_error_status. Your middleware workaround isn’t needed anymore. Thanks for the detailed report!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions