From 682e25af32feac3198a2aeb435693e02d38bdfe8 Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 16:07:38 -0300 Subject: [PATCH 1/3] fix(mcp): get_more_tools follows the conversation handle like any tool sdk-specs "Optional events": a virtual tool gets every enabled injected argument except `context` and follows "Session identity" like any tool call; neither report event carries $mcp_parameters. - get_more_tools listings advertise `conversation_id` (left out for a handle-free client). A report files under an echoed handle, or mints and appends one when nothing else groups the call, through the same deliver_handle step as other tools. - $mcp_missing_capability carries $mcp_conversation_id and no longer sends $mcp_parameters. - ConversationId.resolve drops its virtual-tool exclusion. Tested: bundle exec rspec (2640 examples, 0 failures; the new virtual_tool_session_spec failed 4 of 5 first), rubocop clean, rake public_api:check passes. --- .changeset/mcp-virtual-tool-handle.md | 5 ++ lib/posthog/mcp/conversation_id.rb | 4 +- lib/posthog/mcp/instrumentation.rb | 67 ++++++++++++------- lib/posthog/mcp/tools.rb | 6 +- spec/posthog/mcp/conversation_id_spec.rb | 15 ++--- spec/posthog/mcp/instrument_spec.rb | 5 +- spec/posthog/mcp/virtual_tool_session_spec.rb | 64 ++++++++++++++++++ 7 files changed, 127 insertions(+), 39 deletions(-) create mode 100644 .changeset/mcp-virtual-tool-handle.md create mode 100644 spec/posthog/mcp/virtual_tool_session_spec.rb diff --git a/.changeset/mcp-virtual-tool-handle.md b/.changeset/mcp-virtual-tool-handle.md new file mode 100644 index 00000000..a4ea7ec2 --- /dev/null +++ b/.changeset/mcp-virtual-tool-handle.md @@ -0,0 +1,5 @@ +--- +"posthog-ruby": minor +--- + +`PostHog::MCP`'s `get_more_tools` virtual tool now follows the conversation handle like any tool: it advertises `conversation_id`, files a report under a handle the agent echoes, and mints and returns one when nothing else groups the call. `$mcp_missing_capability` no longer carries `$mcp_parameters`; the report is already its `$mcp_intent`. diff --git a/lib/posthog/mcp/conversation_id.rb b/lib/posthog/mcp/conversation_id.rb index ca851962..deb2174c 100644 --- a/lib/posthog/mcp/conversation_id.rb +++ b/lib/posthog/mcp/conversation_id.rb @@ -38,8 +38,8 @@ def extract(args) # own schema is passed application data, which must not anchor analytics: # two users sharing such a value would be stitched into one conversation. # @return [Array(String, Boolean), Array(nil, false)] `[conversation_id, minted]` - def resolve(enabled, supplied, tool_name, missing_capability_tool_name, mint: true) - return [nil, false] if !enabled || tool_name == missing_capability_tool_name + def resolve(enabled, supplied, mint: true) + return [nil, false] unless enabled value = normalize(supplied) return [value.downcase, false] if value && MINTED_CONVERSATION_ID.match?(value) diff --git a/lib/posthog/mcp/instrumentation.rb b/lib/posthog/mcp/instrumentation.rb index 11bf1b64..dc776517 100644 --- a/lib/posthog/mcp/instrumentation.rb +++ b/lib/posthog/mcp/instrumentation.rb @@ -145,7 +145,6 @@ def dispatch_tool_call arguments = fetch(@params, :arguments) arguments = nil unless arguments.is_a?(Hash) original_arguments = arguments&.dup - missing_name = Tools.missing_capability_tool_name(@options) owned = safely([]) { owned_params_for(name) } stripped = safely({}) { strip_injected_arguments(arguments, owned) } # Resolution reads the stripped values, never `original_arguments`: only an @@ -156,8 +155,7 @@ def dispatch_tool_call request = request_with_arguments(original_arguments) conversation_id, minted = safely([nil, false]) do ConversationId.resolve(@options.enable_conversation_id && !@client_conversation, - stripped[ConversationId::PARAM_NAME], name, missing_name, - mint: !handle_free && !carries_session?) + stripped[ConversationId::PARAM_NAME], mint: !handle_free && !carries_session?) end if virtual_tool?(name) @@ -165,9 +163,12 @@ def dispatch_tool_call # cancellation behave exactly as for any other tool; only the event differs. begin result = yield - ensure - safely { record_missing_capability(name, original_arguments, request) } + rescue StandardError + safely { record_missing_capability(name, original_arguments, request, minted ? nil : conversation_id) } + raise end + result, cid = deliver_handle(result, name, conversation_id, minted, handle_free) + safely { record_missing_capability(name, original_arguments, request, cid) } return result end @@ -192,26 +193,13 @@ def dispatch_tool_call raise 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 # `$mcp_error_message`. Grouping reads the result the tool returned. error_source = result - unless no_response?(result) || conversation_id.nil? - safely do - if @data.tool_output_instructions[name] && !handle_free - result, delivered = ConversationId.mirror_instructions(result, conversation_id) - end - if minted - with_prompt_back = ConversationId.inject_prompt_back(result, conversation_id) - delivered ||= !with_prompt_back.equal?(result) - result = with_prompt_back - end - end - end + result, cid = deliver_handle(result, name, conversation_id, minted, handle_free) safely do - cid = minted && !delivered ? nil : conversation_id session_id = prepare_request(request, conversation_id: cid) release_custom_events(session_id) record_tool_call(session_id, name, request, result: result, conversation_id: cid, @@ -220,6 +208,28 @@ def dispatch_tool_call result end + # Mirror the handle into `structuredContent` where the listing declared it, and + # append a minted one to the result. A minted handle anchors the call only + # once a result carries it. + # + # @return [Array(Object, String), Array(Object, nil)] `[result, conversation_id the call records]` + def deliver_handle(result, name, conversation_id, minted, handle_free) + return [result, minted ? nil : conversation_id] if no_response?(result) || conversation_id.nil? + + delivered = false + safely do + if @data.tool_output_instructions[name] && !handle_free + result, delivered = ConversationId.mirror_instructions(result, conversation_id) + end + if minted + with_prompt_back = ConversationId.inject_prompt_back(result, conversation_id) + delivered ||= !with_prompt_back.equal?(result) + result = with_prompt_back + end + end + [result, minted && !delivered ? nil : conversation_id] + end + def dispatch_tools_list result = begin yield @@ -334,12 +344,12 @@ def record_tool_call(session_id, name, request, result: nil, error: nil, convers finish_event(event, request) end - def record_missing_capability(name, arguments, request) - session_id = prepare_request(request) + def record_missing_capability(name, arguments, request, conversation_id) + session_id = prepare_request(request, conversation_id: conversation_id) event = base_event(EventType::MCP_MISSING_CAPABILITY, session_id, request) event.delete('duration') event['resource_name'] = name - event['parameters'] = Sanitization.build_captured_mcp_parameters(request) + event['conversation_id'] = conversation_id context = arguments.is_a?(Hash) ? (arguments[:context] || arguments['context']) : nil if context.is_a?(String) && !context.strip.empty? event['user_intent'] = context.strip @@ -737,7 +747,7 @@ def mutate_tool(tool, advertise_handle) return tool unless tool.is_a?(Hash) name = fetch(tool, :name) - return tool if virtual_tool?(name) + return mutate_virtual_tool(tool, advertise_handle) if virtual_tool?(name) schema = fetch(tool, :inputSchema) owned = [] @@ -777,6 +787,17 @@ def mutate_tool(tool, advertise_handle) mutated end + # A virtual tool registers its own report arguments and `llm_model`, and + # takes `conversation_id` like any tool. + def mutate_virtual_tool(tool, advertise_handle) + return tool unless @options.enable_conversation_id && advertise_handle + + name = fetch(tool, :name) + schema = SchemaMutation.add_conversation_id_parameter(fetch(tool, :inputSchema), tool_name: name, + options: @options) + tool.merge(SchemaMutation.key_for(tool, :inputSchema) => schema) + end + # --- helpers ----------------------------------------------------------- def fetch(hash, key) diff --git a/lib/posthog/mcp/tools.rb b/lib/posthog/mcp/tools.rb index 388d5b16..aee34fd0 100644 --- a/lib/posthog/mcp/tools.rb +++ b/lib/posthog/mcp/tools.rb @@ -24,9 +24,9 @@ def missing_capability_tool_name(options = nil) # The advertised descriptor (a `tools/list` entry, symbol keys like `MCP::Tool#to_h`). # With `capture_model` on, the `llm_model` argument is advertised here too, so - # a missing-capability report carries the model that asked for it. The virtual - # tool is deliberately left out of the `conversation_id` loop-back: it reports - # a gap in the tool list rather than taking part in a tool conversation. + # a missing-capability report carries the model that asked for it. + # `conversation_id` is added per listing, as for any tool, so a handle-free + # client's listing can leave it out. def descriptor(name = GET_MORE_TOOLS_NAME, options = nil) spec = { name: name, diff --git a/spec/posthog/mcp/conversation_id_spec.rb b/spec/posthog/mcp/conversation_id_spec.rb index 24b92b3b..7197508e 100644 --- a/spec/posthog/mcp/conversation_id_spec.rb +++ b/spec/posthog/mcp/conversation_id_spec.rb @@ -7,31 +7,30 @@ describe '.resolve' do it 'echoes a minted-shaped handle (lowercased) and mints over anything else' do - expect(described_class.resolve(true, handle, 'a_tool', 'get_more_tools')).to eq([handle, false]) - expect(described_class.resolve(true, " #{handle.upcase} ", 'a_tool', 'get_more_tools')).to eq([handle, false]) + expect(described_class.resolve(true, handle)).to eq([handle, false]) + expect(described_class.resolve(true, " #{handle.upcase} ")).to eq([handle, false]) %w[conv-1 1 session chat_abc not-a-uuid 019fd2b0-1111-4111-8111-111111111111].each do |value| - id, minted = described_class.resolve(true, value, 'a_tool', 'get_more_tools') + id, minted = described_class.resolve(true, value) expect(minted).to be(true) expect(id).not_to eq(value) expect(id).to match(described_class::MINTED_CONVERSATION_ID) end - minted_id, = described_class.resolve(true, nil, 'a_tool', 'get_more_tools') - expect(described_class.resolve(true, minted_id, 'a_tool', 'get_more_tools')).to eq([minted_id, false]) + minted_id, = described_class.resolve(true, nil) + expect(described_class.resolve(true, minted_id)).to eq([minted_id, false]) end it 'mints when handed no value it owns' do # A tool that declares `conversation_id` itself is never stripped, so nothing # reaches `.resolve` and its value cannot anchor an analytics conversation. [nil, 123, ' '].each do |supplied| - id, minted = described_class.resolve(true, supplied, 'a_tool', 'get_more_tools') + id, minted = described_class.resolve(true, supplied) expect(minted).to be(true) expect(id).to match(described_class::MINTED_CONVERSATION_ID) end end it 'is inert when disabled or for the missing-capability tool' do - expect(described_class.resolve(false, handle, 'a_tool', 'get_more_tools')).to eq([nil, false]) - expect(described_class.resolve(true, nil, 'get_more_tools', 'get_more_tools')).to eq([nil, false]) + expect(described_class.resolve(false, handle)).to eq([nil, false]) end end diff --git a/spec/posthog/mcp/instrument_spec.rb b/spec/posthog/mcp/instrument_spec.rb index 933c9edc..83373a24 100644 --- a/spec/posthog/mcp/instrument_spec.rb +++ b/spec/posthog/mcp/instrument_spec.rb @@ -703,7 +703,7 @@ def stringify_result_keys(target) list = server.handle(rpc(1, 'tools/list')) virtual = list[:result][:tools].last expect(virtual[:name]).to eq('get_more_tools') - expect(virtual[:inputSchema][:properties].keys).to eq([:context]) + expect(virtual[:inputSchema][:properties].keys).to eq(%i[context conversation_id]) result = server.handle(rpc(2, 'tools/call', { name: 'get_more_tools', arguments: { context: 'need csv export' } })) expect(result[:result][:content][0][:text]).to include('Unfortunately') @@ -755,8 +755,7 @@ def stringify_result_keys(target) described_class.instrument(server, client, report_missing: true, capture_model: true) list = server.handle(rpc(1, 'tools/list')) virtual = list[:result][:tools].find { |t| t[:name] == 'get_more_tools' } - expect(virtual[:inputSchema][:properties].keys).to contain_exactly(:context, :llm_model) - expect(virtual[:inputSchema][:properties].keys).not_to include(:conversation_id) + expect(virtual[:inputSchema][:properties].keys).to contain_exactly(:context, :llm_model, :conversation_id) expect(virtual[:inputSchema][:required]).to contain_exactly('context') result = server.handle(rpc(2, 'tools/call', { name: 'get_more_tools', arguments: { context: 'need csv export', diff --git a/spec/posthog/mcp/virtual_tool_session_spec.rb b/spec/posthog/mcp/virtual_tool_session_spec.rb new file mode 100644 index 00000000..4ea53735 --- /dev/null +++ b/spec/posthog/mcp/virtual_tool_session_spec.rb @@ -0,0 +1,64 @@ +# frozen_string_literal: true + +require_relative 'spec_helper' + +RSpec.describe 'PostHog::MCP get_more_tools sessions' do + let(:client) { new_test_client } + let(:server) { MCP::Server.new(name: 'docs-server', version: '1.0.0', tools: []) } + let(:handle) { '0190f0e8-7a6b-7c3d-9e4f-5a6b7c8d9e0f' } + + before { allow(Kernel).to receive(:warn) } + + def report(arguments) + server.handle(rpc(2, 'tools/call', + { name: 'get_more_tools', arguments: { context: 'need csv export' }.merge(arguments) })) + end + + def listed_arguments + server.handle(rpc(1, 'tools/list'))[:result][:tools].find do |tool| + tool[:name] == 'get_more_tools' + end[:inputSchema][:properties].keys + end + + def missing_capability + events_named(drain_events(client), '$mcp_missing_capability').first[:properties] + end + + { + 'on' => [true, true], + 'off' => [false, false] + }.each do |anchoring, (enabled, advertised)| + it "advertises conversation_id on get_more_tools with anchoring #{anchoring}" do + PostHog::MCP.instrument(server, client, report_missing: true, capture_model: false, + enable_conversation_id: enabled) + + expect(listed_arguments.include?(:conversation_id)).to eq(advertised) + end + end + + it 'mints a handle for a report that carries none, and files the report under it' do + PostHog::MCP.instrument(server, client, report_missing: true) + texts = report({})[:result][:content].map { |block| block[:text] } + + minted = JSON.parse(texts.last)['conversation_id'] + expect(minted).to match(/\A\h{8}-\h{4}-7\h{3}-/) + expect(missing_capability.values_at('$mcp_conversation_id', '$session_id', '$mcp_session_source')) + .to eq([minted, PostHog::MCP.derive_session_id_from_conversation(minted), 'conversation']) + end + + it 'sends the report without $mcp_parameters' do + PostHog::MCP.instrument(server, client, report_missing: true) + report({ conversation_id: handle }) + + expect(missing_capability).not_to have_key('$mcp_parameters') + end + + it 'files a report under the handle the agent echoes, and mints none' do + PostHog::MCP.instrument(server, client, report_missing: true) + texts = report({ conversation_id: handle })[:result][:content].map { |block| block[:text] } + + expect(texts.size).to eq(1) + expect(missing_capability.values_at('$mcp_conversation_id', '$session_id')) + .to eq([handle, PostHog::MCP.derive_session_id_from_conversation(handle)]) + end +end From 5eb080cd00df01f09104ab8605068fc8730d30b3 Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 16:13:17 -0300 Subject: [PATCH 2/3] refactor(mcp): name the anchored handle once in dispatch_tool_call /simplify on the stack: `minted ? nil : conversation_id` was repeated in four branches. Tested: bundle exec rspec spec/posthog/mcp (268 examples, 0 failures). --- lib/posthog/mcp/instrumentation.rb | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/lib/posthog/mcp/instrumentation.rb b/lib/posthog/mcp/instrumentation.rb index dc776517..d1ced89f 100644 --- a/lib/posthog/mcp/instrumentation.rb +++ b/lib/posthog/mcp/instrumentation.rb @@ -157,6 +157,8 @@ def dispatch_tool_call ConversationId.resolve(@options.enable_conversation_id && !@client_conversation, stripped[ConversationId::PARAM_NAME], mint: !handle_free && !carries_session?) end + # A minted handle anchors the call only once a result delivers it. + anchored = minted ? nil : conversation_id if virtual_tool?(name) # Run the gem's own handler so validation, in-flight tracking and @@ -164,7 +166,7 @@ def dispatch_tool_call begin result = yield rescue StandardError - safely { record_missing_capability(name, original_arguments, request, minted ? nil : conversation_id) } + safely { record_missing_capability(name, original_arguments, request, anchored) } raise end result, cid = deliver_handle(result, name, conversation_id, minted, handle_free) @@ -176,19 +178,18 @@ def dispatch_tool_call begin result = yield ensure - safely { record_unknown_tool(name, request, minted ? nil : conversation_id) } + safely { record_unknown_tool(name, request, anchored) } end return result end - safely { prime_session(request, minted ? nil : conversation_id, hold_custom_events: minted) } + safely { prime_session(request, anchored, hold_custom_events: minted) } begin result = yield rescue StandardError => e safely do - cid = minted ? nil : conversation_id - session_id = prepare_request(request, conversation_id: cid) - record_tool_call(session_id, name, request, error: e, conversation_id: cid, stripped: stripped) + session_id = prepare_request(request, conversation_id: anchored) + record_tool_call(session_id, name, request, error: e, conversation_id: anchored, stripped: stripped) end raise end From ed113a175a7e27027bd5c9b10695e7fc4b8476fa Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 16:35:16 -0300 Subject: [PATCH 3/3] chore(mcp): drop comments the handle code already says Tested: bundle exec rspec spec/posthog/mcp (no failures). --- lib/posthog/mcp/instrumentation.rb | 3 --- 1 file changed, 3 deletions(-) diff --git a/lib/posthog/mcp/instrumentation.rb b/lib/posthog/mcp/instrumentation.rb index d1ced89f..c8f28879 100644 --- a/lib/posthog/mcp/instrumentation.rb +++ b/lib/posthog/mcp/instrumentation.rb @@ -157,7 +157,6 @@ def dispatch_tool_call ConversationId.resolve(@options.enable_conversation_id && !@client_conversation, stripped[ConversationId::PARAM_NAME], mint: !handle_free && !carries_session?) end - # A minted handle anchors the call only once a result delivers it. anchored = minted ? nil : conversation_id if virtual_tool?(name) @@ -788,8 +787,6 @@ def mutate_tool(tool, advertise_handle) mutated end - # A virtual tool registers its own report arguments and `llm_model`, and - # takes `conversation_id` like any tool. def mutate_virtual_tool(tool, advertise_handle) return tool unless @options.enable_conversation_id && advertise_handle