-
Notifications
You must be signed in to change notification settings - Fork 81
fix(mcp): restore analytics capture for standalone FastMCP 4 #936
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
base: main
Are you sure you want to change the base?
Changes from all commits
62bb16f
8865969
7027977
2b91f14
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -31,7 +31,8 @@ | |
| 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 | ||
|
|
||
|
|
@@ -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) | ||
|
|
@@ -394,6 +396,49 @@ 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( | ||
| server: Any, data: MCPAnalyticsData, name: str, version: Optional[str] | ||
| ) -> Optional[FrozenSet[str]]: | ||
| """Which analytics parameters to strip, derived from the tool's own schema, for | ||
| a tool this process never listed or a client-pinned version. ``None`` when the | ||
| tool cannot be resolved. Without a schema, stripping could delete application | ||
| arguments. Middleware tools normally use the recorded tools/list ownership | ||
| instead, since they can dispatch without resolving through get_tool().""" | ||
| try: | ||
| from fastmcp.utilities.versions import VersionSpec | ||
|
|
||
| tool = await server.get_tool( | ||
| name, version=VersionSpec(eq=version) if version else None | ||
| ) | ||
| 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 = {"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): | ||
|
|
@@ -403,6 +448,26 @@ 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: | ||
| # The listing this process served is the source of truth for what was | ||
| # advertised. A client-pinned version may differ from the listed one, | ||
| # so only then is the tool's own schema consulted. | ||
| version = _requested_tool_version(ctx) | ||
| injected = data.tool_injected_parameters.get(name) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Low: Tool ownership cache is shared across sessions
|
||
| if injected is None or version is not None: | ||
| injected = await _standalone_injected_parameters( | ||
| standalone, data, name, version | ||
| ) | ||
| if injected is not None: | ||
| analytics_owns_model = "llm_model" in injected | ||
| 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) | ||
| ) | ||
|
|
@@ -411,9 +476,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, | ||
|
|
||
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.
Note
🤖 Automated comment by QA Swarm — not written by a human
[router] 🟡 MEDIUM
When
server.get_tool()fails, or returns an object whose.parametersis not a dict, this function returnsNone._wrap_v2_call_toolthen 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_toolwith one unexpected keyword raises a pydanticValidationError(verified in a fastmcp 4.0.3 environment). So this fail-open path can break dispatch — the opposite of the invariant the otherexceptblocks in this PR protect.The common case looks safe: FastMCP's own
call_tool()resolves the tool throughself.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 whoseon_call_toolhook 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.pybuild 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.