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
16 changes: 12 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -156,14 +156,22 @@ jobs:
# 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 standalone FastMCP 4, which uses
# the v2 registry. posthog/test/mcp/conftest.py splits collection by major.
# the v2 registry. The v2-bare leg runs mcp>=2 without FastMCP: importing
# FastMCP 4 patches camelCase properties onto mcp_types models for the
# whole process, which hides reads that plain mcp 2.x rejects.
# 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']
mcp-major: ['v1', 'v2']
mcp-major: ['v1', 'v2', 'v2-bare']
include:
- mcp-major: 'v2'
mcp-packages: "'mcp>=2,<3' 'fastmcp>=4,<5'"
- mcp-major: 'v2-bare'
mcp-packages: "'mcp>=2,<3'"

steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
Expand All @@ -187,11 +195,11 @@ jobs:
UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --extra test

- name: Swap in MCP SDK v2
if: matrix.mcp-major == 'v2'
if: matrix.mcp-major != 'v1'
shell: bash
run: |
uv pip uninstall --python "$pythonLocation" fastmcp
uv pip install --python "$pythonLocation" 'mcp>=2,<3' 'fastmcp>=4,<5'
uv pip install --python "$pythonLocation" ${{ matrix.mcp-packages }}

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

`PostHogMCP.prepare_tool_list` now adds the `context` argument to MCP SDK 2.x `Tool` objects. It only added it to dicts and 1.x `Tool` objects before, so `$mcp_intent` was never captured for 2.x tool objects.
4 changes: 2 additions & 2 deletions posthog/mcp/posthog_mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -773,10 +773,10 @@ def _inject_context(self, tool: Any, description: Optional[str]) -> Any:
if self._is_sdk_virtual_tool(tool):
return tool
new_schema = add_context_parameter_to_schema(
getattr(tool, "inputSchema", None), name, description
_tool_schema(tool), name, description
)
try:
tool.inputSchema = new_schema
_set_tool_schema(tool, new_schema)
except Exception: # noqa: BLE001
pass
return tool
Expand Down
11 changes: 11 additions & 0 deletions posthog/test/mcp/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,17 @@ def events_named(source, name):
return [e for e in events if e["event"] == name]


def structured_content(result):
"""A ``CallToolResult``'s structured half: ``structuredContent`` on MCP SDK
1.x models, ``structured_content`` on 2.x (same wire field). Read the field
itself rather than the camelCase spelling, which 2.x only resolves once
standalone FastMCP 4's compatibility shim has been imported."""
for attr in ("structured_content", "structuredContent"):
if hasattr(result, attr):
return getattr(result, attr)
raise AssertionError("no structured content attribute")


def listed_uris(response):
"""The uris a captured ``$mcp_resources_list`` response advertises, whether it
listed static resources or templates."""
Expand Down
5 changes: 3 additions & 2 deletions posthog/test/mcp/conftest.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
"""Split the MCP test suite by installed MCP SDK major.

The suite runs against both majors in CI — the ``tests-mcp`` matrix has a
``mcp>=1.26,<2`` leg and a ``mcp>=2,<3`` leg (the main ``tests`` matrix also
exercises the v1 side incidentally). Files coupled to one
``mcp>=1.26,<2`` leg and two ``mcp>=2,<3`` legs, with and without standalone
FastMCP 4 (the main ``tests`` matrix also exercises the v1 side incidentally).
Files coupled to one
major's seams import symbols the other major doesn't ship, so they are excluded
from *collection* (a skip marker can't help — the failure is at import time).
Version-agnostic files (units, truncation, session tokens, PostHogMCP, ids)
Expand Down
18 changes: 8 additions & 10 deletions posthog/test/mcp/test_output_instructions.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
can_declare_output_instructions,
mirror_instructions_into_structured_content,
)
from posthog.test.mcp._helpers import structured_content


def _tool(output_schema, name="demo"):
Expand Down Expand Up @@ -204,13 +205,6 @@ def test_mirror_does_not_mutate_a_shared_model_result():
— and, through the handle, collapse unrelated clients into one session."""
import mcp.types as mcp_types

# `structuredContent` on SDK 1.x, `structured_content` on 2.x (same wire field).
def structured(result):
for attr in ("structured_content", "structuredContent"):
if hasattr(result, attr):
return getattr(result, attr)
raise AssertionError("no structured content attribute")

shared = mcp_types.CallToolResult(
content=[mcp_types.TextContent(type="text", text="{}")],
structuredContent={"total": 7},
Expand All @@ -220,9 +214,13 @@ def structured(result):

assert delivered is True
assert first is not shared # a copy, not the caller's object
assert structured(first)[MCP_INSTRUCTIONS_KEY] == {"conversation_id": "conv-A"}
assert structured_content(first)[MCP_INSTRUCTIONS_KEY] == {
"conversation_id": "conv-A"
}
# the shared object the customer owns is untouched, so the next caller is clean
assert MCP_INSTRUCTIONS_KEY not in structured(shared)
assert MCP_INSTRUCTIONS_KEY not in structured_content(shared)

second, _ = mirror_instructions_into_structured_content(shared, "conv-B")
assert structured(second)[MCP_INSTRUCTIONS_KEY] == {"conversation_id": "conv-B"}
assert structured_content(second)[MCP_INSTRUCTIONS_KEY] == {
"conversation_id": "conv-B"
}
26 changes: 25 additions & 1 deletion posthog/test/mcp/test_posthog_mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from posthog.test.mcp._helpers import (
events_named as _events,
flush_background as _flush,
structured_content,
)
from posthog.version import VERSION

Expand Down Expand Up @@ -262,6 +263,29 @@ def test_prepare_tool_list_injects_context_into_dicts():
assert "context" not in tools[0]["inputSchema"]["properties"]


@pytest.mark.parametrize("sdk_tool", [False, True])
def test_prepare_tool_list_injects_context_into_tool_objects(sdk_tool: bool) -> None:
client, _ = make_client()
schema = {"type": "object", "properties": {"q": {"type": "string"}}}
tool = (
Tool(name="search", inputSchema=schema)
if sdk_tool
else SimpleNamespace(name="search", input_schema=schema)
)
schema_attribute = (
"input_schema" if hasattr(tool, "input_schema") else "inputSchema"
)

prepared = client.prepare_tool_list([tool])

advertised = getattr(prepared[0], schema_attribute)
assert "context" in advertised["properties"]
assert "context" in advertised["required"]
assert "q" in advertised["properties"]
# the caller's schema dict is untouched
assert "context" not in schema["properties"]


def test_prepare_tool_list_can_be_disabled():
client, _ = make_client()
tools = [{"name": "search", "inputSchema": {"type": "object", "properties": {}}}]
Expand Down Expand Up @@ -602,7 +626,7 @@ def test_prepare_tool_result_delivers_into_call_tool_result_models(wrapped):
delivered = prepared.result.root if wrapped else prepared.result
assert len(call_result.content) == 1
assert delivered.content[-1].text == _handle_block(prepared.conversation_id)["text"]
assert delivered.structuredContent[MCP_INSTRUCTIONS_KEY] == {
assert structured_content(delivered)[MCP_INSTRUCTIONS_KEY] == {
"conversation_id": prepared.conversation_id
}
assert _UUID7.match(prepared.conversation_id)
Expand Down
Loading