diff --git a/.changeset/mcp-input-required.md b/.changeset/mcp-input-required.md new file mode 100644 index 00000000..36f1f10e --- /dev/null +++ b/.changeset/mcp-input-required.md @@ -0,0 +1,5 @@ +--- +"posthog-ruby": minor +--- + +`PostHog::MCP` records an `input_required` round as `$mcp_input_required` instead of a `$mcp_tool_call`, and adds `PostHog::MCP::Client#capture_input_required` with `PostHog::MCP.input_request_methods` for custom dispatchers. diff --git a/lib/posthog/mcp.rb b/lib/posthog/mcp.rb index 3fa56d18..74a90534 100644 --- a/lib/posthog/mcp.rb +++ b/lib/posthog/mcp.rb @@ -14,6 +14,7 @@ require 'posthog/mcp/sanitization' require 'posthog/mcp/truncation' require 'posthog/mcp/conversation_id' +require 'posthog/mcp/input_required' require 'posthog/mcp/intent' require 'posthog/mcp/schema_mutation' require 'posthog/mcp/event_builder' @@ -134,6 +135,16 @@ def derive_session_id_from_conversation(conversation_id) Session.derive_session_id_from_conversation(conversation_id) end + # The method of each request in an `input_required` round, ordered by + # request key, for {PostHog::MCP::Client#capture_input_required}; nil when + # the result is not a round. + # + # @param result [Hash, MCP::Server::InputRequiredResult] a tool's result + # @return [Array, nil] + def input_request_methods(result) + InputRequired.request_methods(result) + end + # The canned `get_more_tools` result for custom dispatchers. # # @return [Hash] diff --git a/lib/posthog/mcp/client.rb b/lib/posthog/mcp/client.rb index efaed139..91f07e25 100644 --- a/lib/posthog/mcp/client.rb +++ b/lib/posthog/mcp/client.rb @@ -98,6 +98,25 @@ def capture_tools_list(tool_names: nil, parameters: nil, response: nil, duration emit(event) end + # Capture an `input_required` round: the tool asked the client for more + # input instead of returning its result. Emits `$mcp_input_required`. Use + # it instead of {#capture_tool_call} when + # {PostHog::MCP.input_request_methods} returns the round's methods; the + # retry that completes the call is the tool call. + # + # @return [void] + def capture_input_required(tool_name, input_request_methods: [], duration_ms: nil, protocol_version: nil, + distinct_id: nil, session_id: nil, client_user_agent: nil, vendor_client: nil, + set_properties: nil, groups: nil, properties: nil, timestamp: nil) + event = base_event(EventType::MCP_INPUT_REQUIRED, distinct_id, session_id, set_properties, groups, + properties, timestamp, client_user_agent, vendor_client) + event['resource_name'] = tool_name + event['protocol_version'] = protocol_version + event['duration'] = duration_ms + event['input_request_methods'] = InputRequired.bound(input_request_methods) + emit(event) + end + # Capture a `get_more_tools` call as a missing-capability report. Emits # `$mcp_missing_capability` with the agent's description as `$mcp_intent`. # diff --git a/lib/posthog/mcp/constants.rb b/lib/posthog/mcp/constants.rb index eab712e6..024317a6 100644 --- a/lib/posthog/mcp/constants.rb +++ b/lib/posthog/mcp/constants.rb @@ -37,6 +37,7 @@ module Event EXCEPTION = '$exception' 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' @@ -57,6 +58,7 @@ module Property DURATION_MS = '$mcp_duration_ms' ERROR_MESSAGE = '$mcp_error_message' ERROR_TYPE = '$mcp_error_type' + INPUT_REQUEST_METHODS = '$mcp_input_request_methods' IS_ERROR = '$mcp_is_error' INTENT = '$mcp_intent' INTENT_SOURCE = '$mcp_intent_source' @@ -82,6 +84,7 @@ module EventType CUSTOM = 'posthog:custom' IDENTIFY = 'posthog:identify' MCP_INITIALIZE = 'mcp:initialize' + MCP_INPUT_REQUIRED = 'mcp:input_required' MCP_MISSING_CAPABILITY = 'mcp:missing_capability' MCP_PROMPTS_GET = 'mcp:prompts/get' MCP_PROMPTS_LIST = 'mcp:prompts/list' @@ -95,6 +98,7 @@ module EventType CUSTOM => Event::CUSTOM, IDENTIFY => Event::IDENTIFY, MCP_INITIALIZE => Event::INITIALIZE, + MCP_INPUT_REQUIRED => Event::INPUT_REQUIRED, MCP_MISSING_CAPABILITY => Event::MISSING_CAPABILITY, MCP_PROMPTS_GET => Event::PROMPT_GET, MCP_PROMPTS_LIST => Event::PROMPTS_LIST, diff --git a/lib/posthog/mcp/event_builder.rb b/lib/posthog/mcp/event_builder.rb index 2dbf6ec8..664a37d5 100644 --- a/lib/posthog/mcp/event_builder.rb +++ b/lib/posthog/mcp/event_builder.rb @@ -70,10 +70,18 @@ def unknown_tool?(event) event['event_type'] == EventType::MCP_UNKNOWN_TOOL end + def input_required?(event) + event['event_type'] == EventType::MCP_INPUT_REQUIRED + end + def add_common_properties(event, properties) + properties[Property::INPUT_REQUEST_METHODS] = event['input_request_methods'] || [] if input_required?(event) if present(event['resource_name']) - properties[Property::RESOURCE_NAME] = event['resource_name'] - properties[Property::TOOL_NAME] = event['resource_name'] if tool_call?(event) || unknown_tool?(event) + # A round is not a tool call, so it names the tool without `$mcp_resource_name`. + properties[Property::RESOURCE_NAME] = event['resource_name'] unless input_required?(event) + if tool_call?(event) || unknown_tool?(event) || input_required?(event) + properties[Property::TOOL_NAME] = event['resource_name'] + end end if present(event['tool_description']) && tool_call?(event) properties[Property::TOOL_DESCRIPTION] = diff --git a/lib/posthog/mcp/input_required.rb b/lib/posthog/mcp/input_required.rb new file mode 100644 index 00000000..520b62c8 --- /dev/null +++ b/lib/posthog/mcp/input_required.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +module PostHog + module MCP + # Reads an `input_required` round: the result a tool returns to ask the + # client for more input, such as a confirmation, before it runs. + # + # @api private + module InputRequired + RESULT_TYPE = 'input_required' + # `$mcp_input_request_methods` holds at most this many entries. + MAX_METHODS = 100 + + module_function + + # The method of each request in the round, ordered by request key, or nil + # when `result` is not a round. A round that carries only `requestState` + # has none. + # + # @return [Array, nil] + def request_methods(result) + result = result.to_h if round_object?(result) + return nil unless result.is_a?(Hash) && value(result, :resultType) == RESULT_TYPE + + requests = value(result, :inputRequests) + return [] unless requests.is_a?(Hash) + + ordered = requests.sort_by { |key, _| key.to_s }.map { |_, request| request } + bound(ordered.map { |request| request.is_a?(Hash) ? value(request, :method) : nil }) + end + + # Keeps the string methods, up to the property's entry limit. + # + # @return [Array] + def bound(methods) + (methods.is_a?(Array) ? methods : []).grep(String).first(MAX_METHODS) + end + + def round_object?(result) + defined?(::MCP::Server::InputRequiredResult) && result.is_a?(::MCP::Server::InputRequiredResult) + end + + def value(hash, key) + hash.key?(key) ? hash[key] : hash[key.to_s] + end + end + end +end diff --git a/lib/posthog/mcp/instrumentation.rb b/lib/posthog/mcp/instrumentation.rb index d180283a..177af9e1 100644 --- a/lib/posthog/mcp/instrumentation.rb +++ b/lib/posthog/mcp/instrumentation.rb @@ -184,6 +184,17 @@ def dispatch_tool_call raise end + input_request_methods = safely { InputRequired.request_methods(result) } + unless input_request_methods.nil? + # A round cannot carry a minted handle, and the retry that ends the call is the tool call. + safely do + cid = minted ? nil : conversation_id + session_id = prepare_request(request, conversation_id: cid) + record_input_required(session_id, name, request, input_request_methods, cid) + end + return result + end + delivered = false # The handle appended below is unique per conversation, so an error read # off the delivered result would give every identical failure a different @@ -354,6 +365,14 @@ def record_unknown_tool(name, request, conversation_id) finish_event(event, request) end + def record_input_required(session_id, name, request, methods, conversation_id) + event = base_event(EventType::MCP_INPUT_REQUIRED, session_id, request) + event['resource_name'] = name + event['conversation_id'] = conversation_id + event['input_request_methods'] = methods + finish_event(event, request) + end + # The virtual tool declares `llm_model` itself, so the argument is never # stripped and is read straight off the call. def self_reported_model(arguments) diff --git a/public_api_snapshot.txt b/public_api_snapshot.txt index 69779a00..1fe0d756 100644 --- a/public_api_snapshot.txt +++ b/public_api_snapshot.txt @@ -188,12 +188,14 @@ class_method PostHog::MCP.derive_session_id_from_conversation(conversation_id) class_method PostHog::MCP.derive_session_id_from_mcp_session(mcp_session_id) class_method PostHog::MCP.encode_session_id(payload) class_method PostHog::MCP.get_more_tools_result() +class_method PostHog::MCP.input_request_methods(result) class_method PostHog::MCP.instrument(server, client = ..., options: ..., **kwargs) class PostHog::MCP::Analytics instance_method PostHog::MCP::Analytics#capture(event, properties = ...) instance_method PostHog::MCP::Analytics#flush() class PostHog::MCP::Client < PostHog::Client instance_method PostHog::MCP::Client#capture_initialize(client_name: ..., client_version: ..., protocol_version: ..., parameters: ..., response: ..., duration_ms: ..., distinct_id: ..., session_id: ..., client_user_agent: ..., vendor_client: ..., set_properties: ..., groups: ..., properties: ..., timestamp: ...) +instance_method PostHog::MCP::Client#capture_input_required(tool_name, input_request_methods: ..., duration_ms: ..., protocol_version: ..., distinct_id: ..., session_id: ..., client_user_agent: ..., vendor_client: ..., set_properties: ..., groups: ..., properties: ..., timestamp: ...) instance_method PostHog::MCP::Client#capture_missing_capability(context: ..., parameters: ..., protocol_version: ..., distinct_id: ..., session_id: ..., client_user_agent: ..., vendor_client: ..., set_properties: ..., groups: ..., properties: ..., timestamp: ..., llm_model: ..., llm_model_source: ...) instance_method PostHog::MCP::Client#capture_tool_call(tool_name, intent: ..., intent_source: ..., parameters: ..., response: ..., duration_ms: ..., is_error: ..., error: ..., error_type: ..., category: ..., tool_description: ..., protocol_version: ..., distinct_id: ..., session_id: ..., client_user_agent: ..., vendor_client: ..., set_properties: ..., groups: ..., properties: ..., timestamp: ..., llm_model: ..., llm_model_source: ...) instance_method PostHog::MCP::Client#capture_tools_list(tool_names: ..., parameters: ..., response: ..., duration_ms: ..., is_error: ..., error: ..., error_type: ..., protocol_version: ..., distinct_id: ..., session_id: ..., client_user_agent: ..., vendor_client: ..., set_properties: ..., groups: ..., properties: ..., timestamp: ...) @@ -216,6 +218,7 @@ constant PostHog::MCP::Event::CUSTOM: String constant PostHog::MCP::Event::EXCEPTION: String constant PostHog::MCP::Event::IDENTIFY: String constant PostHog::MCP::Event::INITIALIZE: String +constant PostHog::MCP::Event::INPUT_REQUIRED: String constant PostHog::MCP::Event::MISSING_CAPABILITY: String constant PostHog::MCP::Event::PROMPTS_LIST: String constant PostHog::MCP::Event::PROMPT_GET: String @@ -276,6 +279,7 @@ constant PostHog::MCP::Property::CONVERSATION_ID: String constant PostHog::MCP::Property::DURATION_MS: String constant PostHog::MCP::Property::ERROR_MESSAGE: String constant PostHog::MCP::Property::ERROR_TYPE: String +constant PostHog::MCP::Property::INPUT_REQUEST_METHODS: String constant PostHog::MCP::Property::INTENT: String constant PostHog::MCP::Property::INTENT_SOURCE: String constant PostHog::MCP::Property::IS_ERROR: String diff --git a/spec/posthog/mcp/input_required_spec.rb b/spec/posthog/mcp/input_required_spec.rb new file mode 100644 index 00000000..88e2530f --- /dev/null +++ b/spec/posthog/mcp/input_required_spec.rb @@ -0,0 +1,92 @@ +# frozen_string_literal: true + +require_relative 'spec_helper' + +class PostHogMcpSpecConfirmTool < MCP::Tool + tool_name 'delete_project' + description 'Deletes a project' + class << self + def call(server_context:, **) + return MCP::Tool::Response.new([{ type: 'text', text: 'deleted' }]) if server_context.input_response('z_confirm') + + round + end + + def round + confirm = { message: 'Delete project secret-42?', requestedSchema: { type: 'object', properties: {} } } + MCP::Server::InputRequiredResult.new(input_requests: { + z_confirm: { method: 'elicitation/create', params: confirm }, + a_roots: { method: 'roots/list' } + }) + end + end +end + +class PostHogMcpSpecStateOnlyTool < MCP::Tool + tool_name 'retry_later' + class << self + def call(server_context:, **) # rubocop:disable Lint/UnusedMethodArgument -- the gem passes it to opt in + MCP::Server::InputRequiredResult.new(request_state: 'state-only') + end + end +end + +RSpec.describe 'PostHog::MCP input_required rounds' do + let(:client) { new_test_client } + let(:server) do + MCP::Server.new(name: 'spec-server', version: '9.9.9', + tools: [PostHogMcpSpecConfirmTool, PostHogMcpSpecStateOnlyTool]) + end + let(:modern_meta) do + { 'io.modelcontextprotocol/protocolVersion' => '2026-07-28', + 'io.modelcontextprotocol/clientCapabilities' => { elicitation: {}, roots: {} } } + end + + before { PostHog::MCP.instrument(server, client) } + + def call(id, name, **params) + server.handle(rpc(id, 'tools/call', { name: name, arguments: {}, _meta: modern_meta, **params })) + end + + it 'records a 2026-07-28 round as $mcp_input_required and only the retry as a tool call' do + expect(call(1, 'delete_project')[:result][:resultType]).to eq('input_required') + events = drain_events(client) + expect(events.map { |e| e[:event] }).to eq(['$mcp_input_required']) + expect(events[0][:properties]).to include('$mcp_tool_name' => 'delete_project', + '$mcp_input_request_methods' => ['roots/list', 'elicitation/create'], + '$mcp_protocol_version' => '2026-07-28') + expect(events[0][:properties]['$mcp_duration_ms']).to be >= 0 + expect(events[0][:properties]).not_to include('$mcp_is_error', '$mcp_resource_name', '$mcp_conversation_id') + expect(events.to_s).not_to include('secret-42') + + answers = { z_confirm: { action: 'accept', content: {} }, a_roots: { roots: [] } } + expect(call(2, 'delete_project', inputResponses: answers)[:result][:content][0][:text]).to eq('deleted') + expect(drain_events(client).map { |e| e[:event] }).to eq(['$mcp_tool_call']) + end + + it 'records no methods for a round that carries only requestState' do + call(1, 'retry_later') + round = events_named(drain_events(client), '$mcp_input_required') + expect(round.size).to eq(1) + expect(round[0][:properties]['$mcp_input_request_methods']).to eq([]) + expect(round.to_s).not_to include('state-only') + end + + it 'records a round from a custom dispatcher with the methods read off the result' do + mcp_client = PostHog::MCP::Client.new(api_key: 'phc_test', test_mode: true) + expect(PostHog::MCP.input_request_methods({ content: [] })).to be_nil + methods = PostHog::MCP.input_request_methods(PostHogMcpSpecConfirmTool.round) + expect(methods).to eq(['roots/list', 'elicitation/create']) + + mcp_client.capture_input_required('delete_project', input_request_methods: methods, duration_ms: 3, + session_id: 'ses_123') + event = mcp_client.dequeue_last_message + expect(event[:event]).to eq('$mcp_input_required') + expect(event[:properties]).to include('$mcp_tool_name' => 'delete_project', + '$mcp_input_request_methods' => ['roots/list', 'elicitation/create'], + '$mcp_duration_ms' => 3, '$session_id' => 'ses_123') + expect(mcp_client.queued_messages).to eq(0) + ensure + mcp_client&.shutdown(timeout: 2) + end +end