Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -155,10 +155,11 @@ jobs:
# The MCP suite as a named gate per MCP Python SDK major. The v1 leg uses
# the lockfile's mcp 1.x (also exercised incidentally by the `tests`
# matrix — this leg exists as an explicit, named signal); the v2 leg
# (spec 2026-07-28) swaps in mcp>=2 and drops jlowin fastmcp, which pins
# mcp<2. posthog/test/mcp/conftest.py splits collection by major.
# (spec 2026-07-28) swaps in mcp>=2 and standalone FastMCP 4, which uses
# the v2 registry. posthog/test/mcp/conftest.py splits collection by major.
name: MCP SDK ${{ matrix.mcp-major }} (Python ${{ matrix.python-version }})
runs-on: ubuntu-latest
timeout-minutes: 20
strategy:
matrix:
python-version: ['3.10', '3.14']
Expand Down Expand Up @@ -189,8 +190,8 @@ jobs:
if: matrix.mcp-major == 'v2'
shell: bash
run: |
uv pip uninstall --python $pythonLocation fastmcp
uv pip install --python $pythonLocation 'mcp>=2,<3'
uv pip uninstall --python "$pythonLocation" fastmcp
uv pip install --python "$pythonLocation" 'mcp>=2,<3' 'fastmcp>=4,<5'

- name: Run MCP tests against SDK ${{ matrix.mcp-major }}
run: |
Expand Down
5 changes: 5 additions & 0 deletions .sampo/changesets/chivalrous-witch-goulven.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
pypi/posthog: patch
---

Fix missing MCP analytics events with standalone FastMCP 4 while preserving tool arguments and compatibility with MCP SDK v1.
10 changes: 10 additions & 0 deletions posthog/mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,16 @@ Neither fires for stdio, for a correctly-wired server, or for a conversation-anc
session. The instrument-time check can't see whether you added the middleware yourself
(the app is already built by then), so ignore it if you did.

Standalone `fastmcp` 4 uses the MCP SDK v2 handler registry. `instrument()` detects
that registry automatically and captures tool calls over stdio and streamable HTTP,
including the stateless protocol. Mounted tools retain their own arguments; analytics
parameters are removed before dispatch only when the tool does not declare them.
Instrumenting both the wrapper and its underlying server works in either order.
For versioned tools, argument ownership follows the version requested by the client.
Each tool call resolves the schema through FastMCP's tool listing in the current request context, including middleware and session transforms.
This adds a schema lookup per call so clients with different tool schemas cannot change how another client's arguments are handled.
The same installation code continues to support standalone FastMCP 2.x/3.x on MCP SDK v1.

Two gaps worth knowing: jlowin's `fastmcp` 2.x/3.x doesn't expose the attribute the
instrument-time check reads, so those servers get the runtime warning only. And the
deprecated SSE transport is excluded — it keys sessions off a query parameter, and the
Expand Down
42 changes: 26 additions & 16 deletions posthog/mcp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@

from __future__ import annotations

import weakref
from datetime import datetime, timezone
from typing import Any, Optional

Expand Down Expand Up @@ -257,48 +258,57 @@ def instrument(
key = _canonical_server(server)

try:
# Imported inside the try: the adapters touch major-specific modules, and
# an import error must degrade to the no-op handle, not crash the host.
# MCP is an optional peer: load adapters only when instrumentation is
# requested, inside the no-crash boundary. Class probes stay major-specific.
from ._compatibility import (
is_fastmcp,
is_fastmcp_v2,
is_low_level_server,
is_mcpserver,
uses_v2_handler_registry,
)
from ._instrument_fastmcp import instrument_fastmcp
from ._instrument_lowlevel import instrument_fastmcp_v2, instrument_low_level
from ._instrument_v2 import instrument_lowlevel_v2, instrument_mcpserver_v2

client = _resolve_client(posthog_client)
if client is None:
log("Warning: no PostHog client available; MCP events will not be sent.")

if get_server_tracking_data(key) is not None:
existing_data = get_server_tracking_data(key)
data = existing_data
if data is None:
sink = McpEventSink(client) if client is not None else None
data = MCPAnalyticsData(
options=opts, sink=sink, session_id=new_session_id()
)

if is_fastmcp_v2(server) and uses_v2_handler_registry(key):
data.standalone_fastmcp = weakref.ref(server)

# A standalone FastMCP wrapper and its low-level server share one tracking
# key, so instrumenting the second of the pair must still attach what only
# that object provides: the wrapper's schema lookup and ASGI app factories.
if existing_data is not None:
autowire_stateless_mint(server)
log("instrument() - server already instrumented, skipping initialization")
return McpAnalytics(key)

sink = McpEventSink(client) if client is not None else None
data = MCPAnalyticsData(options=opts, sink=sink, session_id=new_session_id())
set_server_tracking_data(key, data)

if is_fastmcp(server):
from ._instrument_fastmcp import instrument_fastmcp

instrument_fastmcp(server, data)
elif is_mcpserver(server):
from ._instrument_v2 import instrument_mcpserver_v2

instrument_mcpserver_v2(server, data)
elif is_fastmcp_v2(server):
from ._instrument_lowlevel import instrument_fastmcp_v2

instrument_fastmcp_v2(server, data)
if uses_v2_handler_registry(server._mcp_server):
instrument_lowlevel_v2(server._mcp_server, data)
else:
instrument_fastmcp_v2(server, data)
elif is_low_level_server(server):
if uses_v2_handler_registry(server):
from ._instrument_v2 import instrument_lowlevel_v2

instrument_lowlevel_v2(server, data)
else:
from ._instrument_lowlevel import instrument_low_level

instrument_low_level(server, data)
else:
raise TypeError(
Expand Down
2 changes: 1 addition & 1 deletion posthog/mcp/_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def _is_call_tool_result(value: Any) -> bool:
dict or a pydantic model from the ``mcp`` SDK."""
if isinstance(value, dict):
return "isError" in value and isinstance(value.get("content"), list)
return hasattr(value, "isError") and isinstance(
return (hasattr(value, "is_error") or hasattr(value, "isError")) and isinstance(
getattr(value, "content", None), list
)

Expand Down
80 changes: 74 additions & 6 deletions posthog/mcp/_instrument_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,12 @@
from __future__ import annotations

import time
from typing import Any, Dict, Optional, Tuple
from collections.abc import Mapping
from typing import Any, Dict, FrozenSet, Optional, Tuple

import mcp.types as mcp_types

from ._context_parameters import schema_has_param
from ._context_parameters import is_context_enabled, schema_has_param
from ._conversation_id import build_prompt_back
from ._instrumentation import (
_to_jsonable,
Expand Down Expand Up @@ -93,7 +94,8 @@ def instrument_lowlevel_v2(server: Any, data: MCPAnalyticsData) -> None:
"""Instrument a raw v2 low-level ``Server``. ``context`` is injected as an
*optional* schema property and NOT stripped — the schema doubles as the
call's validation surface, and a typical ``(ctx, params)`` handler ignores
extra argument keys."""
extra argument keys. For standalone FastMCP, the shared tracking state supplies
the tool schemas so injected arguments are removed before validation."""
data.server_name = getattr(server, "name", None)
data.server_version = getattr(server, "version", None)
_wrap_v2_call_tool(server, data)
Expand Down Expand Up @@ -394,6 +396,59 @@ def _deliver_conversation_id(
# --- low-level: tools/call ------------------------------------------------------


def _requested_tool_version(ctx: Any) -> Optional[str]:
"""The FastMCP tool version a client pinned via request ``_meta``, if any."""
try:
# Standalone FastMCP is optional even when the official MCP SDK is installed.
from fastmcp.server.dependencies import extract_version_spec

params = getattr(ctx, "params", None)
meta = params.get("_meta") if isinstance(params, Mapping) else None
return extract_version_spec(meta)
except Exception: # noqa: BLE001 - version parsing must not prevent dispatch
return None


async def _standalone_injected_parameters(

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.

Note

🤖 Automated comment by QA Swarm — not written by a human

[router] 🟡 MEDIUM

When server.get_tool() fails, or returns an object whose .parameters is not a dict, this function returns None. _wrap_v2_call_tool then skips the strip step and sends the raw arguments to the real dispatch. The arguments still contain the injected analytics keys (context, conversation_id, llm_model).

FastMCP binds tool arguments strictly. A direct call to fastmcp.FastMCP.call_tool with one unexpected keyword raises a pydantic ValidationError (verified in a fastmcp 4.0.3 environment). So this fail-open path can break dispatch — the opposite of the invariant the other except blocks in this PR protect.

The common case looks safe: FastMCP's own call_tool() resolves the tool through self.get_tool(name, version=...) at the same point, so a lookup failure usually breaks the underlying dispatch too. The residual risk is narrower: a middleware whose on_call_tool hook short-circuits before the manager stage and dispatches to a bound function directly. Dispatch then succeeds, but the PostHog lookup fails and the unstripped keys go through.

None of the new tests in test_fastmcp_v4.py build that shape, so the path is untested. This is plausible, not confirmed.

Suggested action: either add a test for a tool that dispatches but does not resolve through get_tool(), or confirm that the path is unreachable in the supported FastMCP middleware patterns and record that in the docstring.

server: Any, data: MCPAnalyticsData, name: str, version: Optional[str]
) -> Optional[FrozenSet[str]]:
"""Resolve ownership in the current request, including middleware and versions.

Listings from other requests can have different application-owned parameters.
Without a schema, stripping could delete application arguments.
"""
try:
from fastmcp.utilities.versions import VersionSpec, version_sort_key

version_spec = VersionSpec(eq=version) if version else None
# Middleware can shadow registered tools, so resolve the effective listing.
candidates = [
tool
for tool in await server.list_tools()
if tool.name == name
and (version_spec is None or version_spec.matches(tool.version))
]
tool = max(candidates, key=version_sort_key, default=None)
if tool is None:
tool = await server.get_tool(name, version=version_spec)
schema = getattr(tool, "parameters", None)
except Exception as error: # noqa: BLE001 - schema lookup must not prevent dispatch
log(f"PostHog MCP: could not resolve schema for tool {name!r} - {error}")
return None
if not isinstance(schema, dict):
return None
injected = set()
if is_context_enabled(data.options.context):
injected.add("context")
if data.options.enable_conversation_id:
injected.add("conversation_id")
if is_capture_model_enabled(data.options.capture_model) and (
can_inject_model_parameter(schema)
):
injected.add("llm_model")
return frozenset(key for key in injected if not schema_has_param(schema, key))


def _wrap_v2_call_tool(server: Any, data: MCPAnalyticsData) -> None:
entry = server.get_request_handler(_CALL_METHOD)
if entry is None or getattr(entry.handler, _WRAPPED_FLAG, False):
Expand All @@ -403,6 +458,21 @@ def _wrap_v2_call_tool(server: Any, data: MCPAnalyticsData) -> None:
async def handler(ctx: Any, params: Any) -> Any:
name = params.name
arguments = dict(params.arguments or {})
analytics_owns_model = data.tool_model_parameter_injected.get(name, False)
standalone = data.standalone_fastmcp() if data.standalone_fastmcp else None
if standalone is not None:
version = _requested_tool_version(ctx)
injected = await _standalone_injected_parameters(
standalone, data, name, version
)
analytics_owns_model = injected is not None and "llm_model" in injected
if injected is not None:
call_arguments = {
key: value
for key, value in arguments.items()
if key not in injected
}
params = params.model_copy(update={"arguments": call_arguments})
token, client_name, client_version, protocol_version, mcp_session_id = (
_resolve_ctx(ctx)
)
Expand All @@ -411,9 +481,7 @@ async def handler(ctx: Any, params: Any) -> Any:
name=name,
arguments=arguments,
request_meta=request_meta_from_context(ctx),
allow_self_reported_model=data.tool_model_parameter_injected.get(
name, False
),
allow_self_reported_model=analytics_owns_model,
mcp_session_id=mcp_session_id,
token=token,
client_name=client_name,
Expand Down
8 changes: 4 additions & 4 deletions posthog/mcp/_instrumentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,10 +164,10 @@ def is_tool_result_error(result: Any) -> bool:
(wire JSON unchanged); check both shapes."""
if isinstance(result, dict):
return result.get("isError") is True or result.get("is_error") is True
return (
getattr(result, "isError", None) is True
or getattr(result, "is_error", None) is True
)
is_error = getattr(result, "is_error", None)
if is_error is not None:
return is_error is True
return getattr(result, "isError", None) is True


def build_tool_call_request(
Expand Down
2 changes: 2 additions & 0 deletions posthog/mcp/_internal.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ class MCPAnalyticsData:
initialized_sessions: "OrderedDict[str, None]" = field(default_factory=OrderedDict)
server_name: Optional[str] = None
server_version: Optional[str] = None
# A strong wrapper reference would retain the low-level WeakKeyDictionary key.
standalone_fastmcp: Optional["weakref.ReferenceType[Any]"] = None
session_lock: asyncio.Lock = field(default_factory=asyncio.Lock)

def mark_session_initialized(self, session_id: str) -> None:
Expand Down
4 changes: 2 additions & 2 deletions posthog/mcp/_output_instructions.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@
_CONVERSATION_ID_FIELD_DESCRIPTION = "The server-issued conversation identifier."

# `outputSchema` on MCP SDK 1.x models, `output_schema` on 2.x (same wire field).
_OUTPUT_SCHEMA_ATTRS = ("outputSchema", "output_schema")
_STRUCTURED_CONTENT_ATTRS = ("structuredContent", "structured_content")
_OUTPUT_SCHEMA_ATTRS = ("output_schema", "outputSchema")
_STRUCTURED_CONTENT_ATTRS = ("structured_content", "structuredContent")


def _read_attr(obj: Any, names: Tuple[str, ...]) -> Tuple[Optional[str], Any]:
Expand Down
1 change: 1 addition & 0 deletions posthog/test/mcp/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"test_v2_mcpserver.py",
"test_v2_lowlevel.py",
"test_v2_wire_dual_era.py",
"test_fastmcp_v4.py",
]

collect_ignore = _V2_ONLY if MCP_MAJOR < 2 else _V1_ONLY
Loading