diff --git a/.sampo/changesets/mcp-input-required.md b/.sampo/changesets/mcp-input-required.md new file mode 100644 index 000000000..9629193ac --- /dev/null +++ b/.sampo/changesets/mcp-input-required.md @@ -0,0 +1,5 @@ +--- +pypi/posthog: minor +--- + +`posthog.mcp`: record `input_required` rounds as `$mcp_input_required`, not as tool calls. On the 2026-07-28 revision, a tool that asks for more input, such as a confirmation form, sent a `$mcp_tool_call` for the round and another for the retry, so one confirmed call counted twice. `instrument()` now sends `$mcp_input_required` with `$mcp_tool_name`, `$mcp_duration_ms`, and `$mcp_input_request_methods`, and only the retry that completes the call is a `$mcp_tool_call`. A round returned to a client on an earlier revision, which cannot receive it, is a failed `$mcp_tool_call` with `$mcp_error_type: "input_required"`. Custom dispatchers record rounds with the new `PostHogMCP.capture_input_required()`. diff --git a/posthog/mcp/README.md b/posthog/mcp/README.md index 57bbf2785..06c4e62d9 100644 --- a/posthog/mcp/README.md +++ b/posthog/mcp/README.md @@ -407,6 +407,45 @@ tool call whenever the registry can't rule the tool out: - On standalone `fastmcp.FastMCP` 3.0.0 and later, a mounted server, proxy, or other provider hides its disabled tools. +## Tools that ask for more input + +On the 2026-07-28 revision, a tool can answer `tools/call` with an +`InputRequiredResult`, such as a form asking the user to confirm a delete. The +client retries the call with the answers. The round that asks is not a tool +call: `instrument()` sends `$mcp_input_required` with `$mcp_tool_name`, +`$mcp_duration_ms`, and `$mcp_input_request_methods` (the `method` of each +input request, such as `["elicitation/create"]`). The retry that completes the +call sends the one `$mcp_tool_call`. The requests, the user's answers, and +`requestState` are never captured. + +A client on an earlier revision cannot receive the round, so the framework +answers with an error. The SDK records that as a failed `$mcp_tool_call` with +`$mcp_error_type: "input_required"`. + +In a custom dispatcher, `prepare_tool_result()` sets `input_request_methods` +when the result is a round. Record it with `capture_input_required()`: + +```python +call = posthog.prepare_tool_call(name, raw_args, original_tool=tool) +prepared = posthog.prepare_tool_result(dispatch(name, call.args), call) +if prepared.input_request_methods is not None: + posthog.capture_input_required( + name, + input_request_methods=prepared.input_request_methods, + duration_ms=duration_ms, + session_id=prepared.session_id, + conversation_id=prepared.conversation_id, + ) +else: + posthog.capture_tool_call( + name, + duration_ms=duration_ms, + session_id=prepared.session_id, + conversation_id=prepared.conversation_id, + ) +return prepared.result +``` + ## Virtual tools on a paginated `tools/list` `instrument()` advertises up to two tools of its own: `get_more_tools` diff --git a/posthog/mcp/_capture.py b/posthog/mcp/_capture.py index cd5c3c098..4cf321faf 100644 --- a/posthog/mcp/_capture.py +++ b/posthog/mcp/_capture.py @@ -59,6 +59,7 @@ def capture_event( "tool_category": event_input.get("tool_category"), "tool_description": event_input.get("tool_description"), "listed_tool_names": event_input.get("listed_tool_names"), + "input_request_methods": event_input.get("input_request_methods"), "parameters": event_input.get("parameters"), "response": event_input.get("response"), "user_intent": event_input.get("user_intent"), diff --git a/posthog/mcp/_event_types.py b/posthog/mcp/_event_types.py index 005d08457..24bbf5595 100644 --- a/posthog/mcp/_event_types.py +++ b/posthog/mcp/_event_types.py @@ -15,6 +15,7 @@ class MCPAnalyticsEventType: CUSTOM = "posthog:custom" MCP_FEEDBACK = "mcp:feedback" + MCP_INPUT_REQUIRED = "mcp:input_required" MCP_MISSING_CAPABILITY = "mcp:missing_capability" MCP_INITIALIZE = "mcp:initialize" MCP_PROMPTS_GET = "mcp:prompts/get" diff --git a/posthog/mcp/_input_required.py b/posthog/mcp/_input_required.py new file mode 100644 index 000000000..5832881d9 --- /dev/null +++ b/posthog/mcp/_input_required.py @@ -0,0 +1,65 @@ +"""``input_required`` rounds from the 2026-07-28 revision. + +A tool that needs more input, such as a confirmation form, answers +``tools/call`` with an ``InputRequiredResult`` and runs when the client retries +with the answers. The round is not a tool call. The SDK records it as +``$mcp_input_required``, and the retry that completes the call is the one +``$mcp_tool_call``. +""" + +from typing import Any, Iterable, List, Optional + +from ._truncation import truncate_text + +INPUT_REQUIRED_ERROR_TYPE = "input_required" +LEGACY_INPUT_REQUIRED_MESSAGE = ( + "The tool asked for more input, which a client on a protocol revision " + "before 2026-07-28 cannot receive" +) + +_INPUT_REQUIRED_RESULT_TYPE = "input_required" +_FIRST_INPUT_REQUIRED_REVISION = "2026-07-28" +_MAX_METHODS = 100 +_MAX_METHOD_LENGTH = 256 + + +def input_request_methods(result: Any) -> Optional[List[str]]: + """The ``method`` of each request an ``input_required`` result carries, + ordered by key with duplicates kept, or ``None`` when the result is not + one. Never the requests' content.""" + if isinstance(result, dict): + result_type = result.get("resultType") + requests = result.get("inputRequests") + else: + result_type = getattr(result, "result_type", None) + requests = getattr(result, "input_requests", None) + if result_type != _INPUT_REQUIRED_RESULT_TYPE: + return None + if not isinstance(requests, dict): + return [] + return bound_input_request_methods( + _method_of(requests[key]) for key in sorted(requests) + ) + + +def bound_input_request_methods(methods: Iterable[Any]) -> List[str]: + strings = [method for method in methods if isinstance(method, str)] + return [ + truncate_text(method, _MAX_METHOD_LENGTH) for method in strings[:_MAX_METHODS] + ] + + +def is_legacy_revision(protocol_version: Optional[str]) -> bool: + """Whether the request declared a revision whose clients cannot receive an + ``input_required`` result. An unknown revision is not assumed legacy: the + framework only lets the result through on the modern wire.""" + return ( + isinstance(protocol_version, str) + and protocol_version < _FIRST_INPUT_REQUIRED_REVISION + ) + + +def _method_of(request: Any) -> Any: + if isinstance(request, dict): + return request.get("method") + return getattr(request, "method", None) diff --git a/posthog/mcp/_instrumentation.py b/posthog/mcp/_instrumentation.py index 8c76f0efd..f259ca093 100644 --- a/posthog/mcp/_instrumentation.py +++ b/posthog/mcp/_instrumentation.py @@ -40,6 +40,12 @@ resolve_collect_feedback_options, resolve_send_feedback_tool_name, ) +from ._input_required import ( + INPUT_REQUIRED_ERROR_TYPE, + LEGACY_INPUT_REQUIRED_MESSAGE, + input_request_methods, + is_legacy_revision, +) from ._intent import resolve_tool_call_intent, set_event_intent from ._internal import ( MCPAnalyticsData, @@ -693,6 +699,29 @@ async def record_result( ) -> None: conversation_id = self._anchored_conversation_id(conversation_id_delivered) session_id = await self.prepare_session(conversation_id) + failure: Any = error + error_type: Optional[str] = None + methods = input_request_methods(result) + if methods is not None and not is_legacy_revision(self.protocol_version): + await record_input_required( + self.data, + session_id, + conversation_id=conversation_id, + name=self.name, + arguments=self.arguments, + methods=methods, + duration_ms=duration_ms, + client_name=self.client_name, + client_version=self.client_version, + protocol_version=self.protocol_version, + extra=self.extra, + ) + return + if methods is not None: + # A legacy client cannot receive the round, so the framework answers + # with an error and the call ends there. + result, error_type = None, INPUT_REQUIRED_ERROR_TYPE + failure = error or LEGACY_INPUT_REQUIRED_MESSAGE await record_tool_call( self.data, session_id, @@ -702,7 +731,8 @@ async def record_result( allow_self_reported_model=self.allow_self_reported_model, analytics_owned_parameters=self.analytics_owned_parameters, result=result, - error=error, + error=failure, + error_type=error_type, duration_ms=duration_ms, client_name=self.client_name, client_version=self.client_version, @@ -781,6 +811,7 @@ async def record_tool_call( allow_self_reported_model: bool = False, result: Any = None, error: Any = None, + error_type: Optional[str] = None, duration_ms: Optional[float] = None, client_name: Optional[str] = None, client_version: Optional[str] = None, @@ -845,6 +876,7 @@ async def record_tool_call( if error is not None: event["is_error"] = True event["error"] = capture_exception(error) + event["error_type"] = error_type event["error_status"] = http_status(error) props = await resolve_event_properties(data, request, extra) @@ -1460,6 +1492,43 @@ async def record_unknown_tool( log(f"record_unknown_tool failed (event dropped): {err}") +async def record_input_required( + data: MCPAnalyticsData, + session_id: str, + *, + conversation_id: Optional[str], + name: str, + arguments: Optional[Dict[str, Any]], + methods: List[str], + duration_ms: float, + client_name: Optional[str], + client_version: Optional[str], + protocol_version: Optional[str], + extra: Optional[Dict[str, Any]], +) -> None: + """Record an ``input_required`` round as ``$mcp_input_required``. The retry + that completes the call is its ``$mcp_tool_call``.""" + try: + event: Dict[str, Any] = { + "event_type": MCPAnalyticsEventType.MCP_INPUT_REQUIRED, + "session_id": session_id, + "conversation_id": conversation_id, + "resource_name": name, + "duration": duration_ms, + "input_request_methods": methods, + "client_name": client_name, + "client_version": client_version, + "protocol_version": protocol_version, + } + await _apply_event_properties( + data, event, build_tool_call_request(name, arguments), extra + ) + stamp_transport_identity(event, extra) + fire_and_forget(capture_event(data, event), data) + except Exception as err: # noqa: BLE001 - isolate analytics from the tool path + log(f"record_input_required failed (event dropped): {err}") + + async def record_feedback( data: MCPAnalyticsData, session_id: str, diff --git a/posthog/mcp/_posthog_events.py b/posthog/mcp/_posthog_events.py index 45b1d4c02..8bf63033c 100644 --- a/posthog/mcp/_posthog_events.py +++ b/posthog/mcp/_posthog_events.py @@ -26,6 +26,7 @@ _BUILT_IN_EVENT_NAME_BY_TYPE = { MCPAnalyticsEventType.CUSTOM: PostHogMCPAnalyticsEvent.CUSTOM, MCPAnalyticsEventType.MCP_FEEDBACK: PostHogMCPAnalyticsEvent.FEEDBACK, + MCPAnalyticsEventType.MCP_INPUT_REQUIRED: PostHogMCPAnalyticsEvent.INPUT_REQUIRED, MCPAnalyticsEventType.MCP_MISSING_CAPABILITY: PostHogMCPAnalyticsEvent.MISSING_CAPABILITY, MCPAnalyticsEventType.MCP_INITIALIZE: PostHogMCPAnalyticsEvent.INITIALIZE, MCPAnalyticsEventType.MCP_PROMPTS_GET: PostHogMCPAnalyticsEvent.PROMPT_GET, @@ -332,13 +333,19 @@ def _add_truthy_properties( def _add_resource_properties(event: Event, properties: Dict[str, Any]) -> None: + is_input_required = ( + event.get("event_type") == MCPAnalyticsEventType.MCP_INPUT_REQUIRED + ) + if is_input_required: + properties[_P.INPUT_REQUEST_METHODS] = event.get("input_request_methods") or [] if event.get("resource_name"): - is_unknown_tool = ( + # Neither event is a tool call, so neither carries `$mcp_resource_name`. + names_tool_only = is_input_required or ( event.get("event_type") == MCPAnalyticsEventType.MCP_UNKNOWN_TOOL ) - if not is_unknown_tool: + if not names_tool_only: properties[_P.RESOURCE_NAME] = event["resource_name"] - if is_unknown_tool or _is_tool_call(event): + if names_tool_only or _is_tool_call(event): properties[_P.TOOL_NAME] = event["resource_name"] if event.get("tool_description") and _is_tool_call(event): properties[_P.TOOL_DESCRIPTION] = event["tool_description"] diff --git a/posthog/mcp/constants.py b/posthog/mcp/constants.py index 0ad282e36..38e6d52fa 100644 --- a/posthog/mcp/constants.py +++ b/posthog/mcp/constants.py @@ -48,6 +48,7 @@ class PostHogMCPAnalyticsEvent: # Deprecated: the SDK no longer sends `$identify`. IDENTIFY = "$identify" INITIALIZE = "$mcp_initialize" + INPUT_REQUIRED = "$mcp_input_required" MISSING_CAPABILITY = "$mcp_missing_capability" PROMPT_GET = "$mcp_prompt_get" PROMPTS_LIST = "$mcp_prompts_list" @@ -84,6 +85,7 @@ class PostHogMCPAnalyticsProperty: INTENT_SOURCE = "$mcp_intent_source" INPUT_ALIASES_USED = "$mcp_input_aliases_used" INPUT_KEYS = "$mcp_input_keys" + INPUT_REQUEST_METHODS = "$mcp_input_request_methods" LLM_MODEL = "$mcp_llm_model" LLM_MODEL_SOURCE = "$mcp_llm_model_source" LISTED_TOOL_NAMES = "$mcp_listed_tool_names" diff --git a/posthog/mcp/posthog_mcp.py b/posthog/mcp/posthog_mcp.py index 46896fed1..444118fc2 100644 --- a/posthog/mcp/posthog_mcp.py +++ b/posthog/mcp/posthog_mcp.py @@ -14,7 +14,7 @@ import copy from datetime import datetime, timezone from dataclasses import dataclass -from typing import Any, Dict, List, Optional, Set, Tuple, Union +from typing import Any, Dict, List, Optional, Sequence, Set, Tuple, Union from typing_extensions import Unpack @@ -34,6 +34,10 @@ ) from ._event_types import MCPAnalyticsEventType from ._exceptions import capture_exception, http_status +from ._input_required import ( + bound_input_request_methods, + input_request_methods as _round_request_methods, +) from ._instrumentation import ( VIRTUAL_TOOL_FEEDBACK, VIRTUAL_TOOL_MISSING_CAPABILITY, @@ -104,9 +108,9 @@ class _ConversationOwnership: class PostHogMCP(Client): """A drop-in posthog ``Client`` with ``capture_tool_call`` / ``capture_initialize`` / ``capture_tools_list`` / ``capture_missing_capability`` / ``capture_feedback`` - plus ``prepare_tool_list``, ``prepare_tool_call`` and ``prepare_tool_result`` - helpers. ``capture`` adds the configured server build to custom events. - Other inherited methods work unchanged.""" + / ``capture_input_required`` plus ``prepare_tool_list``, ``prepare_tool_call`` + and ``prepare_tool_result`` helpers. ``capture`` adds the configured server + build to custom events. Other inherited methods work unchanged.""" def __init__( self, @@ -252,6 +256,53 @@ def capture_tool_call( event["error_status"] = http_status(error) self._emit(event) + def capture_input_required( + self, + tool_name: str, + *, + input_request_methods: Sequence[str] = (), + duration_ms: Optional[float] = None, + protocol_version: Optional[str] = None, + distinct_id: Optional[str] = None, + session_id: Optional[str] = None, + conversation_id: Optional[str] = None, + client_user_agent: Optional[str] = None, + vendor_client: Optional[str] = None, + set_properties: Optional[JsonRecord] = None, + groups: Optional[Dict[str, str]] = None, + properties: Optional[JsonRecord] = None, + event_options: Optional[Dict[str, Any]] = None, + timestamp: Optional[datetime] = None, + ) -> None: + """Capture a round where the tool answered with an ``input_required`` + result, such as a confirmation form. Emits ``$mcp_input_required``, not + ``$mcp_tool_call``: capture the retry that completes the call with + :meth:`capture_tool_call`. + + ``input_request_methods`` is the ``method`` of each of the result's + ``inputRequests``, ordered by key, such as ``["elicitation/create"]``. + Never pass the requests or the user's answers.""" + event = self._base_event( + MCPAnalyticsEventType.MCP_INPUT_REQUIRED, + distinct_id, + session_id, + conversation_id, + set_properties, + groups, + properties, + event_options, + timestamp, + client_user_agent, + vendor_client, + ) + event["resource_name"] = tool_name + event["protocol_version"] = protocol_version + event["duration"] = duration_ms + event["input_request_methods"] = bound_input_request_methods( + input_request_methods + ) + self._emit(event) + def capture_initialize( self, *, @@ -750,14 +801,17 @@ def prepare_tool_result( Return the prepared ``result`` to the client, and capture with its ``session_id`` and ``conversation_id``. If a new handle could not reach the client, ``conversation_id`` is omitted and the input ``session_id`` - stays unchanged.""" + stays unchanged. When the result is an ``input_required`` round, + ``input_request_methods`` is set: capture it with + :meth:`capture_input_required` instead of :meth:`capture_tool_call`.""" + methods = _round_request_methods(result) conversation_id = prepared_call.conversation_id session_id = prepared_call.session_id state = prepared_call._conversation_state or PreparedConversationState() minted_conversation_id = state.minted_conversation_id handle = conversation_id or minted_conversation_id if not handle: - return PreparedToolResult(result, session_id, None) + return PreparedToolResult(result, session_id, None, methods) prepared: Any = result delivered = False @@ -774,6 +828,7 @@ def prepare_tool_result( prepared, session_id, None if minted_conversation_id and not delivered else conversation_id, + methods, ) # --- internals ----------------------------------------------------------- diff --git a/posthog/mcp/types.py b/posthog/mcp/types.py index e4aee8d83..ff91517a7 100644 --- a/posthog/mcp/types.py +++ b/posthog/mcp/types.py @@ -325,6 +325,9 @@ class PreparedToolResult(Generic[TResult]): session_id: Optional[str] = None # The conversation handle to capture, set only if it reached the client. conversation_id: Optional[str] = None + # Set when the result is an `input_required` round: the method of each of its + # requests, to pass to `capture_input_required`. `None` for every other result. + input_request_methods: Optional[List[str]] = None @dataclass diff --git a/posthog/test/mcp/test_posthog_mcp.py b/posthog/test/mcp/test_posthog_mcp.py index c92559284..ebfea83d8 100644 --- a/posthog/test/mcp/test_posthog_mcp.py +++ b/posthog/test/mcp/test_posthog_mcp.py @@ -216,6 +216,39 @@ async def test_capture_missing_capability(): ) +async def test_capture_input_required_records_the_round_not_a_call(): + client, captured = make_client() + call = client.prepare_tool_call("delete_project", {"project_id": 42}) + round_result = { + "resultType": "input_required", + "inputRequests": { + "z_confirm": {"method": "elicitation/create"}, + "a_roots": {"method": "roots/list"}, + }, + } + prepared = client.prepare_tool_result(round_result, call) + complete = client.prepare_tool_result({"content": []}, call) + client.capture_input_required( + "delete_project", + input_request_methods=prepared.input_request_methods or [], + duration_ms=12, + session_id="ses_abc", + ) + await _flush() + + assert prepared.input_request_methods == ["roots/list", "elicitation/create"] + assert complete.input_request_methods is None + assert not _events(captured, "$mcp_tool_call") + rounds = _events(captured, "$mcp_input_required") + assert len(rounds) == 1 + props = rounds[0]["properties"] + assert props["$mcp_tool_name"] == "delete_project" + assert props["$mcp_input_request_methods"] == ["roots/list", "elicitation/create"] + assert props["$mcp_duration_ms"] == 12 + assert props["$session_id"] == "ses_abc" + assert "$mcp_resource_name" not in props + + def test_prepare_tool_call_extracts_intent_and_strips_context(): client, _ = make_client() prepared = client.prepare_tool_call( diff --git a/posthog/test/mcp/test_v2_lowlevel.py b/posthog/test/mcp/test_v2_lowlevel.py index 319cbc3eb..9095cc361 100644 --- a/posthog/test/mcp/test_v2_lowlevel.py +++ b/posthog/test/mcp/test_v2_lowlevel.py @@ -404,6 +404,36 @@ async def on_call_tool(ctx, params): assert seen["arguments"] == {"x": 1, "context": "raw handlers see everything"} +@pytest.mark.parametrize( + "round_result, methods", + [ + ( + { + "resultType": "input_required", + "inputRequests": {"confirm": {"method": "elicitation/create"}}, + }, + ["elicitation/create"], + ), + (mcp_types.InputRequiredResult(request_state="state-only"), []), + ], +) +async def test_input_required_round_on_a_raw_server(round_result, methods): + async def on_call_tool(ctx, params): + return round_result + + server = Server("raw", on_call_tool=on_call_tool) + client = FakeClient() + instrument(server, client) + + result = await _call_tool(server, "deploy", {}) + await _flush() + + assert result == round_result + assert not _events(client, "$mcp_tool_call") + rounds = _events(client, "$mcp_input_required") + assert [r["properties"]["$mcp_input_request_methods"] for r in rounds] == [methods] + + async def test_raised_error_is_captured_and_reraised(): server = make_server() client = FakeClient() diff --git a/posthog/test/mcp/test_v2_wire_dual_era.py b/posthog/test/mcp/test_v2_wire_dual_era.py index df5f23235..2e268ded0 100644 --- a/posthog/test/mcp/test_v2_wire_dual_era.py +++ b/posthog/test/mcp/test_v2_wire_dual_era.py @@ -19,8 +19,9 @@ from contextlib import asynccontextmanager import httpx +import mcp.types as mcp_types import pytest -from mcp.server.mcpserver import MCPServer +from mcp.server.mcpserver import Context, MCPServer from posthog.mcp import ( decode_session_id, @@ -386,6 +387,112 @@ async def test_legacy_stateless_token_survives_across_instances(): assert props["$session_id"] == token.session_id +# --- input_required rounds ------------------------------------------------------- + + +def make_confirming_server(): + """A destructive tool that asks the user to confirm before it runs.""" + server = MCPServer("confirm-server") + + @server.tool() + def delete_project( + project_id: int, ctx: Context + ) -> mcp_types.CallToolResult | mcp_types.InputRequiredResult: + if not ctx.input_responses: + confirm = mcp_types.ElicitRequestFormParams( + message=f"Delete project {project_id}?", + requested_schema={"type": "object", "properties": {}}, + ) + return mcp_types.InputRequiredResult( + # Keyed out of insertion order: methods are reported by key. + input_requests={ + "z_confirm": mcp_types.ElicitRequest(params=confirm), + "a_roots": mcp_types.ListRootsRequest(), + }, + request_state="server-state", + ) + return mcp_types.CallToolResult( + content=[mcp_types.TextContent(type="text", text="deleted")] + ) + + return server + + +async def test_modern_input_required_round_is_not_a_tool_call(): + server = make_confirming_server() + client = FakeClient() + instrument(server, client) + + async with wire(server) as http: + asked = await modern_call(http, "delete_project", {"project_id": 42}) + await _flush() + assert not _events(client, "$mcp_tool_call") + + retry = rpc( + "tools/call", + { + "name": "delete_project", + "arguments": {"project_id": 42}, + "_meta": modern_meta(), + "inputResponses": { + "z_confirm": {"action": "accept", "content": {}}, + "a_roots": {"roots": []}, + }, + "requestState": asked.json()["result"]["requestState"], + }, + 2, + ) + done = await http.post( + "/mcp", json=retry, headers=modern_headers("tools/call", "delete_project") + ) + await _flush() + + assert done.json()["result"]["content"][0]["text"] == "deleted" + assert len(_events(client, "$mcp_tool_call")) == 1 + rounds = _events(client, "$mcp_input_required") + assert len(rounds) == 1 + props = rounds[0]["properties"] + assert props["$mcp_tool_name"] == "delete_project" + assert props["$mcp_input_request_methods"] == ["roots/list", "elicitation/create"] + assert isinstance(props["$mcp_duration_ms"], (int, float)) + assert "$mcp_is_error" not in props + sent = json.dumps(client.events, default=str) + assert "Delete project 42?" not in sent + assert asked.json()["result"]["requestState"] not in sent + + +async def test_legacy_input_required_is_a_failed_tool_call(): + server = make_confirming_server() + client = FakeClient() + instrument(server, client) + + async with wire(server) as http: + init = rpc( + "initialize", + { + "protocolVersion": LEGACY_PROTOCOL_VERSION, + "capabilities": {"elicitation": {}}, + "clientInfo": {"name": "legacy-probe", "version": "0.1"}, + }, + ) + response = await http.post("/mcp", json=init, headers=legacy_headers()) + headers = legacy_headers() + if response.headers.get("mcp-session-id"): + headers["mcp-session-id"] = response.headers["mcp-session-id"] + call = rpc( + "tools/call", {"name": "delete_project", "arguments": {"project_id": 1}}, 2 + ) + response = await http.post("/mcp", json=call, headers=headers) + await _flush() + + assert "error" in response.json() + assert not _events(client, "$mcp_input_required") + calls = _events(client, "$mcp_tool_call") + assert len(calls) == 1 + assert calls[0]["properties"]["$mcp_is_error"] is True + assert calls[0]["properties"]["$mcp_error_type"] == "input_required" + + async def test_modern_rejects_initialize_but_analytics_stays_out_of_it(): """The SDK itself refuses initialize on a modern-locked flow — analytics must not change that error contract.""" diff --git a/references/public_api_snapshot.txt b/references/public_api_snapshot.txt index 9891e9fa5..a2ed2a010 100644 --- a/references/public_api_snapshot.txt +++ b/references/public_api_snapshot.txt @@ -1062,6 +1062,7 @@ attribute posthog.mcp.constants.PostHogMCPAnalyticsEvent.EXCEPTION = '$exception attribute posthog.mcp.constants.PostHogMCPAnalyticsEvent.FEEDBACK = '$mcp_feedback' attribute posthog.mcp.constants.PostHogMCPAnalyticsEvent.IDENTIFY = '$identify' attribute posthog.mcp.constants.PostHogMCPAnalyticsEvent.INITIALIZE = '$mcp_initialize' +attribute posthog.mcp.constants.PostHogMCPAnalyticsEvent.INPUT_REQUIRED = '$mcp_input_required' attribute posthog.mcp.constants.PostHogMCPAnalyticsEvent.MISSING_CAPABILITY = '$mcp_missing_capability' attribute posthog.mcp.constants.PostHogMCPAnalyticsEvent.PROMPTS_LIST = '$mcp_prompts_list' attribute posthog.mcp.constants.PostHogMCPAnalyticsEvent.PROMPT_GET = '$mcp_prompt_get' @@ -1087,6 +1088,7 @@ attribute posthog.mcp.constants.PostHogMCPAnalyticsProperty.FEEDBACK_TOOL = '$mc attribute posthog.mcp.constants.PostHogMCPAnalyticsProperty.FEEDBACK_TYPE = '$mcp_feedback_type' attribute posthog.mcp.constants.PostHogMCPAnalyticsProperty.INPUT_ALIASES_USED = '$mcp_input_aliases_used' attribute posthog.mcp.constants.PostHogMCPAnalyticsProperty.INPUT_KEYS = '$mcp_input_keys' +attribute posthog.mcp.constants.PostHogMCPAnalyticsProperty.INPUT_REQUEST_METHODS = '$mcp_input_request_methods' attribute posthog.mcp.constants.PostHogMCPAnalyticsProperty.INTENT = '$mcp_intent' attribute posthog.mcp.constants.PostHogMCPAnalyticsProperty.INTENT_SOURCE = '$mcp_intent_source' attribute posthog.mcp.constants.PostHogMCPAnalyticsProperty.INTERFACE = '$mcp_interface' @@ -1979,6 +1981,7 @@ method posthog.mcp.McpAnalytics.flush() -> None method posthog.mcp.posthog_mcp.PostHogMCP.capture(event: str, **kwargs: Unpack[OptionalCaptureArgs]) -> Optional[str] method posthog.mcp.posthog_mcp.PostHogMCP.capture_feedback(*, report: FeedbackReport, llm_model: Optional[str] = None, llm_model_source: Optional[MCPAnalyticsModelSource] = None, protocol_version: Optional[str] = None, distinct_id: Optional[str] = None, session_id: Optional[str] = None, conversation_id: Optional[str] = None, client_user_agent: Optional[str] = None, vendor_client: Optional[str] = None, set_properties: Optional[JsonRecord] = None, groups: Optional[Dict[str, str]] = None, properties: Optional[JsonRecord] = None, event_options: Optional[Dict[str, Any]] = None, timestamp: Optional[datetime] = None) -> None method posthog.mcp.posthog_mcp.PostHogMCP.capture_initialize(*, client_name: Optional[str] = None, client_version: Optional[str] = None, protocol_version: Optional[str] = None, parameters: Any = None, response: Any = None, duration_ms: Optional[float] = None, distinct_id: Optional[str] = None, session_id: Optional[str] = None, client_user_agent: Optional[str] = None, vendor_client: Optional[str] = None, set_properties: Optional[JsonRecord] = None, groups: Optional[Dict[str, str]] = None, properties: Optional[JsonRecord] = None, event_options: Optional[Dict[str, Any]] = None, timestamp: Optional[datetime] = None) -> None +method posthog.mcp.posthog_mcp.PostHogMCP.capture_input_required(tool_name: str, *, input_request_methods: Sequence[str] = (), duration_ms: Optional[float] = None, protocol_version: Optional[str] = None, distinct_id: Optional[str] = None, session_id: Optional[str] = None, conversation_id: Optional[str] = None, client_user_agent: Optional[str] = None, vendor_client: Optional[str] = None, set_properties: Optional[JsonRecord] = None, groups: Optional[Dict[str, str]] = None, properties: Optional[JsonRecord] = None, event_options: Optional[Dict[str, Any]] = None, timestamp: Optional[datetime] = None) -> None method posthog.mcp.posthog_mcp.PostHogMCP.capture_missing_capability(*, context: Optional[str] = None, llm_model: Optional[str] = None, llm_model_source: Optional[MCPAnalyticsModelSource] = None, parameters: Any = None, protocol_version: Optional[str] = None, distinct_id: Optional[str] = None, session_id: Optional[str] = None, conversation_id: Optional[str] = None, client_user_agent: Optional[str] = None, vendor_client: Optional[str] = None, set_properties: Optional[JsonRecord] = None, groups: Optional[Dict[str, str]] = None, properties: Optional[JsonRecord] = None, event_options: Optional[Dict[str, Any]] = None, timestamp: Optional[datetime] = None) -> None method posthog.mcp.posthog_mcp.PostHogMCP.capture_tool_call(tool_name: str, *, intent: Optional[str] = None, intent_source: Optional[str] = None, parameters: Any = None, response: Any = None, duration_ms: Optional[float] = None, is_error: bool = False, error: Any = None, error_type: Optional[str] = None, category: Optional[str] = None, tool_description: Optional[str] = None, llm_model: Optional[str] = None, llm_model_source: Optional[MCPAnalyticsModelSource] = None, protocol_version: Optional[str] = None, distinct_id: Optional[str] = None, session_id: Optional[str] = None, conversation_id: Optional[str] = None, client_user_agent: Optional[str] = None, vendor_client: Optional[str] = None, set_properties: Optional[JsonRecord] = None, groups: Optional[Dict[str, str]] = None, properties: Optional[JsonRecord] = None, event_options: Optional[Dict[str, Any]] = None, timestamp: Optional[datetime] = None) -> None method posthog.mcp.posthog_mcp.PostHogMCP.capture_tools_list(*, tool_names: Optional[List[str]] = None, parameters: Any = None, response: Any = None, duration_ms: Optional[float] = None, is_error: bool = False, error: Any = None, error_type: Optional[str] = None, protocol_version: Optional[str] = None, distinct_id: Optional[str] = None, session_id: Optional[str] = None, client_user_agent: Optional[str] = None, vendor_client: Optional[str] = None, set_properties: Optional[JsonRecord] = None, groups: Optional[Dict[str, str]] = None, properties: Optional[JsonRecord] = None, event_options: Optional[Dict[str, Any]] = None, timestamp: Optional[datetime] = None) -> None