Skip to content
Draft
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-input-required.md
Original file line number Diff line number Diff line change
@@ -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()`.
39 changes: 39 additions & 0 deletions posthog/mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
1 change: 1 addition & 0 deletions posthog/mcp/_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
1 change: 1 addition & 0 deletions posthog/mcp/_event_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
65 changes: 65 additions & 0 deletions posthog/mcp/_input_required.py
Original file line number Diff line number Diff line change
@@ -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)
71 changes: 70 additions & 1 deletion posthog/mcp/_instrumentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand Down
13 changes: 10 additions & 3 deletions posthog/mcp/_posthog_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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"]
Expand Down
2 changes: 2 additions & 0 deletions posthog/mcp/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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"
Expand Down
Loading