diff --git a/.sampo/changesets/mcp-clear-removed-tool-metadata.md b/.sampo/changesets/mcp-clear-removed-tool-metadata.md new file mode 100644 index 000000000..0fbe7ba51 --- /dev/null +++ b/.sampo/changesets/mcp-clear-removed-tool-metadata.md @@ -0,0 +1,5 @@ +--- +pypi/posthog: patch +--- + +`posthog.mcp`: stop reporting a stale `$mcp_tool_description` or `$mcp_tool_category` on `$mcp_tool_call` events when a later `tools/list` still lists the tool but with an empty or missing description, or without `_meta.category`. The cache kept the value from the earlier listing, so events carried text the server no longer advertised; the property is now omitted. \ No newline at end of file diff --git a/posthog/mcp/_instrumentation.py b/posthog/mcp/_instrumentation.py index 8c76f0efd..57b87461f 100644 --- a/posthog/mcp/_instrumentation.py +++ b/posthog/mcp/_instrumentation.py @@ -1190,15 +1190,22 @@ def read_tool_category(tool: Any) -> Optional[str]: def collect_listed_tools(data: MCPAnalyticsData, tools: list) -> tuple[List[str], bool]: - """Cache common tool metadata and return the pre-injection listing summary.""" + """Cache common tool metadata and return the pre-injection listing summary. + + A tool listed with no description or category drops the value an earlier + listing cached, so a later tool call doesn't report it.""" names = [] for tool in tools: names.append(tool.name) if getattr(tool, "description", None): data.tool_descriptions[tool.name] = tool.description + else: + data.tool_descriptions.pop(tool.name, None) category = read_tool_category(tool) if category: data.tool_categories[tool.name] = category + else: + data.tool_categories.pop(tool.name, None) return names, not tools diff --git a/posthog/test/mcp/test_fastmcp.py b/posthog/test/mcp/test_fastmcp.py index 632850d60..522cc4a9f 100644 --- a/posthog/test/mcp/test_fastmcp.py +++ b/posthog/test/mcp/test_fastmcp.py @@ -360,3 +360,57 @@ def flaky_get_tool(name, *args, **kwargs): assert "real tool ran" in str(out) assert _events(client, "$mcp_missing_capability") == [] assert any("delegating the call to your server" in m for m in messages) + + +# --- tool metadata from a later listing -------------------------------------- + + +async def test_tool_call_drops_description_and_category_a_later_listing_removed(): + server = FastMCP("test-server") + + @server.tool(meta={"category": "Math"}) + def add(a: int, b: int) -> int: + """Add two numbers.""" + return a + b + + client = FakeClient() + instrument(server, client) + await _list_tools(server) + + # The server stops advertising a description and a category for the tool. + tool = server._tool_manager.get_tool("add") + tool.description = "" + tool.meta = None + await _list_tools(server) + + await server._tool_manager.call_tool( + "add", {"a": 1, "b": 2, "context": "adding numbers for a report"} + ) + await _flush() + + props = _events(client, "$mcp_tool_call")[0]["properties"] + assert "$mcp_tool_description" not in props + assert "$mcp_tool_category" not in props + + +async def test_tool_call_keeps_description_and_category_while_listings_serve_them(): + server = FastMCP("test-server") + + @server.tool(meta={"category": "Math"}) + def add(a: int, b: int) -> int: + """Add two numbers.""" + return a + b + + client = FakeClient() + instrument(server, client) + await _list_tools(server) + await _list_tools(server) + + await server._tool_manager.call_tool( + "add", {"a": 1, "b": 2, "context": "adding numbers for a report"} + ) + await _flush() + + props = _events(client, "$mcp_tool_call")[0]["properties"] + assert props["$mcp_tool_description"] == "Add two numbers." + assert props["$mcp_tool_category"] == "Math" diff --git a/posthog/test/mcp/test_fastmcp_v2.py b/posthog/test/mcp/test_fastmcp_v2.py index cb1a44817..c530c1e60 100644 --- a/posthog/test/mcp/test_fastmcp_v2.py +++ b/posthog/test/mcp/test_fastmcp_v2.py @@ -726,3 +726,30 @@ async def on_list_tools(self, context, call_next): assert schema is None assert listings == [] + + +async def test_jlowin_call_drops_description_and_category_a_later_listing_removed(): + server = FastMCP("jlowin-probe") + + @server.tool(meta={"category": "Math"}) + def add(a: int, b: int) -> int: + """Add two numbers.""" + return a + b + + client = FakeClient() + instrument(server, client) + await _list(server) + + # The server stops advertising a description and a category for the tool. + tool = await server.get_tool("add") + tool.description = None + tool.meta = None + await _list(server) + + out = await _call(server, "add", {"a": 1, "b": 2, "context": "sum"}) + await _flush() + + assert out.root.isError is False + props = _events(client, "$mcp_tool_call")[0]["properties"] + assert "$mcp_tool_description" not in props + assert "$mcp_tool_category" not in props diff --git a/posthog/test/mcp/test_units.py b/posthog/test/mcp/test_units.py index f5a3546c3..9ff9d30bb 100644 --- a/posthog/test/mcp/test_units.py +++ b/posthog/test/mcp/test_units.py @@ -1,5 +1,6 @@ """Unit tests for branch-heavy internal helpers: intent resolution, conversation_id -schema/loop-back, session-id rollover, and the identity cache. These complement the +schema/loop-back, session-id rollover, the identity cache, and the tool metadata +cache that ``tools/list`` fills. These complement the end-to-end adapter tests by exercising edge branches directly.""" from datetime import datetime, timedelta, timezone @@ -18,6 +19,7 @@ from posthog.mcp._instrumentation import ( VIRTUAL_TOOL_FEEDBACK, VIRTUAL_TOOL_MISSING_CAPABILITY, + collect_listed_tools, enabled_virtual_tool_names, is_first_listing_page, mutate_tool_schema, @@ -430,3 +432,100 @@ def test_identity_cache_evicts_least_recently_used(): ) def test_tools_list_envelope(result, expected): assert tools_list_envelope(result) == expected + + +# --- tool metadata cache ----------------------------------------------------- +# What a tools/list caches for $mcp_tool_call. A listing that no longer serves a +# description or a `_meta.category` must clear what an earlier listing cached. +# Duck-typed on `.name`, `.description` and `.meta`, so these run under both MCP +# SDK majors. + + +def _listed_tool(name="search", description="Search docs.", category="Docs"): + meta = {"category": category} if category is not None else None + return SimpleNamespace(name=name, description=description, meta=meta) + + +def test_listing_caches_description_and_category(): + data = _data() + + collect_listed_tools(data, [_listed_tool()]) + + assert data.tool_descriptions == {"search": "Search docs."} + assert data.tool_categories == {"search": "Docs"} + + +def test_a_later_listing_replaces_the_cached_values(): + data = _data() + collect_listed_tools(data, [_listed_tool()]) + + collect_listed_tools( + data, [_listed_tool(description="Find pages.", category="Pages")] + ) + + assert data.tool_descriptions == {"search": "Find pages."} + assert data.tool_categories == {"search": "Pages"} + + +def test_an_empty_description_clears_the_cached_description(): + data = _data() + collect_listed_tools(data, [_listed_tool()]) + + collect_listed_tools(data, [_listed_tool(description="")]) + + assert "search" not in data.tool_descriptions + + +def test_a_missing_description_clears_the_cached_description(): + data = _data() + collect_listed_tools(data, [_listed_tool()]) + + collect_listed_tools(data, [_listed_tool(description=None)]) + + assert "search" not in data.tool_descriptions + + +def test_a_removed_category_clears_the_cached_category(): + data = _data() + collect_listed_tools(data, [_listed_tool()]) + + collect_listed_tools(data, [_listed_tool(category=None)]) + + assert "search" not in data.tool_categories + + +def test_clearing_the_description_keeps_the_category(): + data = _data() + collect_listed_tools(data, [_listed_tool()]) + + collect_listed_tools(data, [_listed_tool(description="")]) + + assert data.tool_descriptions == {} + assert data.tool_categories == {"search": "Docs"} + + +def test_clearing_the_category_keeps_the_description(): + data = _data() + collect_listed_tools(data, [_listed_tool()]) + + collect_listed_tools(data, [_listed_tool(category=None)]) + + assert data.tool_descriptions == {"search": "Search docs."} + assert data.tool_categories == {} + + +def test_clearing_a_tool_leaves_the_other_tools_alone(): + data = _data() + collect_listed_tools( + data, [_listed_tool(), _listed_tool(name="fetch", description="Fetch.")] + ) + + collect_listed_tools( + data, + [ + _listed_tool(description=""), + _listed_tool(name="fetch", description="Fetch."), + ], + ) + + assert data.tool_descriptions == {"fetch": "Fetch."}