Skip to content
Open
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
5 changes: 5 additions & 0 deletions .sampo/changesets/mcp-clear-removed-tool-metadata.md
Original file line number Diff line number Diff line change
@@ -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.
9 changes: 8 additions & 1 deletion posthog/mcp/_instrumentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
54 changes: 54 additions & 0 deletions posthog/test/mcp/test_fastmcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
27 changes: 27 additions & 0 deletions posthog/test/mcp/test_fastmcp_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
101 changes: 100 additions & 1 deletion posthog/test/mcp/test_units.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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."}