Skip to content
Open
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 .changeset/mcp-virtual-tool-handle.md
Original file line number Diff line number Diff line change
@@ -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`.
4 changes: 2 additions & 2 deletions lib/posthog/mcp/conversation_id.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
75 changes: 47 additions & 28 deletions lib/posthog/mcp/instrumentation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -156,62 +155,51 @@ 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?)
Comment thread
lucasheriques marked this conversation as resolved.
Resolved
end
anchored = minted ? nil : conversation_id

if virtual_tool?(name)
# Run the gem's own handler so validation, in-flight tracking and
# 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, anchored) }
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

if unregistered_tool?(name)
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

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,
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 = []
Expand Down Expand Up @@ -777,6 +787,15 @@ def mutate_tool(tool, advertise_handle)
mutated
end

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)
Expand Down
6 changes: 3 additions & 3 deletions lib/posthog/mcp/tools.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
15 changes: 7 additions & 8 deletions spec/posthog/mcp/conversation_id_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
5 changes: 2 additions & 3 deletions spec/posthog/mcp/instrument_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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',
Expand Down
64 changes: 64 additions & 0 deletions spec/posthog/mcp/virtual_tool_session_spec.rb
Original file line number Diff line number Diff line change
@@ -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