diff --git a/.changeset/mcp-client-conversation-session.md b/.changeset/mcp-client-conversation-session.md new file mode 100644 index 00000000..60de0c7b --- /dev/null +++ b/.changeset/mcp-client-conversation-session.md @@ -0,0 +1,5 @@ +--- +"posthog-ruby": minor +--- + +`PostHog::MCP` groups ChatGPT, Codex, and VS Code calls by the conversation id each client sends in `_meta`, and every event now carries `$mcp_session_source`. The id is never sent itself, not even in `$mcp_parameters`, so the request your `identify` and `event_properties` callbacks receive no longer has that `_meta` key. ChatGPT is no longer advertised or minted a `conversation_id`, and neither is a call whose session the transport already carries. On HTTP, a request that carries no session, including every 2026-07-28 request, gets a `$session_id` of its own instead of the server's or the per-request session the `mcp` gem assigns, and is no longer named after another client's handshake. A custom event captured during a tool call carries the session and identity that call records, including a conversation handle the call delivers. diff --git a/lib/posthog/mcp.rb b/lib/posthog/mcp.rb index 3fa56d18..e37ac270 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/client_conversation' require 'posthog/mcp/intent' require 'posthog/mcp/schema_mutation' require 'posthog/mcp/event_builder' diff --git a/lib/posthog/mcp/README.md b/lib/posthog/mcp/README.md index 6f8518db..4ceb8857 100644 --- a/lib/posthog/mcp/README.md +++ b/lib/posthog/mcp/README.md @@ -42,6 +42,7 @@ These are the few things that differ from what the docs describe for the other S | `mcp.rb` (parent dir) | `PostHog::MCP.instrument` and the public helpers | | `server_extension.rb` | Prepended onto `MCP::Server` and the Streamable HTTP transport | | `instrumentation.rb` | Per-request dispatch: intent, identity, sessions, recording | +| `session.rb`, `client_conversation.rb` | Session resolution and the clients whose `_meta` conversation ids it reads | | `client.rb` | `PostHog::MCP::Client` for custom dispatchers | | `rack_middleware.rb` | `Mcp-Session-Id` tokens for a custom Rack stack | | `sanitization.rb`, `truncation.rb` | Redaction and payload budgets | diff --git a/lib/posthog/mcp/analytics.rb b/lib/posthog/mcp/analytics.rb index 6b14f09b..c9f2f686 100644 --- a/lib/posthog/mcp/analytics.rb +++ b/lib/posthog/mcp/analytics.rb @@ -7,6 +7,10 @@ module MCP # # @note Experimental. class Analytics + MAX_HELD_EVENTS = 1000 + MAX_HELD_BYTES = 4 * 1024 * 1024 + private_constant :MAX_HELD_EVENTS, :MAX_HELD_BYTES + # @api private def initialize(server) @server = server @@ -37,13 +41,13 @@ def capture(event, properties = {}) scope = RequestScope.current scope = nil unless scope.is_a?(Hash) - Instrumentation.capture_event(data, { - 'session_id' => current_session_id(data, scope), - 'event_type' => EventType::CUSTOM, - 'event_name' => event, - 'timestamp' => Time.now.utc, - 'properties' => properties - }, actor: scoped_actor(scope)) + input = { 'event_type' => EventType::CUSTOM, 'event_name' => event, 'timestamp' => Time.now.utc, + 'properties' => properties } + return if hold(data, scope, input) + + session_id, source = current_session(data, scope) + Instrumentation.capture_event(data, input.merge('session_id' => session_id, 'session_source' => source), + actor: scoped_actor(scope)) nil end @@ -67,13 +71,49 @@ def flush # created before the request. Fail closed with a standalone session # rather than filing the event under another caller's identity; over stdio a # server only ever talks to one client, so the fallback stays. - def current_session_id(data, scope) - scoped = scope ? scope[:session_id] : nil - return scoped if scoped - return data.session_id unless data.http_transport_seen + def current_session(data, scope) + return scope.values_at(:session_id, :session_source) if scope&.[](:session_id) + return [data.session_id, data.session_source] unless data.http_transport_seen warn_unscoped_capture(data) - Session.new_session_id + [Session.new_session_id, 'generated'] + end + + # The sink's own sanitize and truncate steps run at capture, so a held event + # is a snapshot no later change to its properties reaches, and its size is bounded. + def hold(data, scope, input) + return false unless scope&.key?(:held) + + snapshot = Truncation.truncate_event(Sanitization.sanitize_event( + Sanitization.stringify_keys(input.merge('duration' => 0)) + )) + bytes = JSON.generate(snapshot['properties'] || {}).bytesize + data.synchronize do + held = scope[:held] + next false unless held + + held_bytes = scope.fetch(:held_bytes, 0) + bytes + if held.size < MAX_HELD_EVENTS && held_bytes <= MAX_HELD_BYTES + held << snapshot + scope[:held_bytes] = held_bytes + next true + end + + warn_overflow(data, scope) + false + end + rescue StandardError => e + Log.debug(data.options, "analytics.capture could not hold its event, sending it now: #{e.message}") + false + end + + def warn_overflow(data, scope) + return if scope[:overflowed_held] + + scope[:overflowed_held] = true + Log.warn(data.options, "Warning: a tool call captured more than #{MAX_HELD_EVENTS} custom events or " \ + "#{MAX_HELD_BYTES / 1024 / 1024} MiB of them before its conversation handle was " \ + 'delivered; sending the rest with the session the call has so far') end # The identity the in-flight request resolved, which {Instrumentation} pinned diff --git a/lib/posthog/mcp/client_conversation.rb b/lib/posthog/mcp/client_conversation.rb new file mode 100644 index 00000000..f2e25322 --- /dev/null +++ b/lib/posthog/mcp/client_conversation.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +module PostHog + module MCP + # {ROWS} is the table of the MCP analytics spec's "Session identity" + # requirement, row for row, in its order. posthog-js and posthog-python keep + # the same table. + # + # @api private + module ClientConversation + Row = Struct.new(:key, :id, :user_agent, :client_names, :handle_free, keyword_init: true) do + def recognizes?(user_agent, client_name) + return true if user_agent.is_a?(String) && self.user_agent.match?(user_agent) + + client_name.is_a?(String) && client_names.any? { |name| name.casecmp?(client_name) } + end + end + + UUID = /\A\h{8}-\h{4}-\h{4}-\h{4}-\h{12}\z/ + NIL_UUID = '00000000-0000-0000-0000-000000000000' + PRINTABLE_ASCII = /\A[\x20-\x7e]{1,128}\z/ + + uuid = lambda do |value| + lowered = value.downcase + lowered if UUID.match?(lowered) && lowered != NIL_UUID + end + + ROWS = [ + Row.new(key: 'openai/session', id: ->(value) { value if PRINTABLE_ASCII.match?(value) }, handle_free: true, + user_agent: %r{\Aopenai-mcp/[^\s(]*\s*\(\s*chatgpt\s*[;,)]}i, client_names: []), + Row.new(key: 'sessionId', id: uuid, handle_free: false, + user_agent: %r{\Acodex-mcp-client/}i, client_names: ['codex-mcp-client']), + Row.new(key: 'vscode.conversationId', id: uuid, handle_free: false, + user_agent: %r{\AVisual Studio Code(?: - Insiders)?/}i, + client_names: ['Visual Studio Code', 'Visual Studio Code - Insiders']) + ].freeze + + module_function + + def recognize(user_agent, client_name) + ROWS.find { |row| row.recognizes?(user_agent, client_name) } + end + + def read(row, meta) + value = row && SchemaMutation.fetch(meta, row.key) + id = row.id.call(value) if value.is_a?(String) + id && "#{row.key}:#{id}" + end + end + end +end diff --git a/lib/posthog/mcp/constants.rb b/lib/posthog/mcp/constants.rb index eab712e6..e84a80a5 100644 --- a/lib/posthog/mcp/constants.rb +++ b/lib/posthog/mcp/constants.rb @@ -69,6 +69,7 @@ module Property SERVER_NAME = '$mcp_server_name' SERVER_VERSION = '$mcp_server_version' SESSION_ID = '$session_id' + SESSION_SOURCE = '$mcp_session_source' SOURCE = '$mcp_source' TOOL_CATEGORY = '$mcp_tool_category' TOOL_DESCRIPTION = '$mcp_tool_description' diff --git a/lib/posthog/mcp/conversation_id.rb b/lib/posthog/mcp/conversation_id.rb index a550ce8f..ca851962 100644 --- a/lib/posthog/mcp/conversation_id.rb +++ b/lib/posthog/mcp/conversation_id.rb @@ -38,13 +38,13 @@ 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) + def resolve(enabled, supplied, tool_name, missing_capability_tool_name, mint: true) return [nil, false] if !enabled || tool_name == missing_capability_tool_name value = normalize(supplied) return [value.downcase, false] if value && MINTED_CONVERSATION_ID.match?(value) - [Ids.uuid_v7, true] + mint ? [Ids.uuid_v7, true] : [nil, false] end def prompt_back?(result) diff --git a/lib/posthog/mcp/event_builder.rb b/lib/posthog/mcp/event_builder.rb index 2dbf6ec8..57ad659f 100644 --- a/lib/posthog/mcp/event_builder.rb +++ b/lib/posthog/mcp/event_builder.rb @@ -8,6 +8,8 @@ module MCP # # @api private module EventBuilder + WIRE_SESSION_SOURCES = { 'token' => 'transport', 'mcp' => 'transport' }.freeze + module_function # @return [Array] payloads `{'event', 'distinct_id', 'properties', 'timestamp'}` @@ -44,6 +46,8 @@ def build_capture_event(event) def add_session_id(event, properties) session_id = event['session_id'] properties[Property::SESSION_ID] = session_id if session_id.is_a?(String) && !session_id.empty? + source = event['session_source'] + properties[Property::SESSION_SOURCE] = WIRE_SESSION_SOURCES.fetch(source, source) if source end def add_conversation_id(event, properties) diff --git a/lib/posthog/mcp/instrumentation.rb b/lib/posthog/mcp/instrumentation.rb index d180283a..956c6553 100644 --- a/lib/posthog/mcp/instrumentation.rb +++ b/lib/posthog/mcp/instrumentation.rb @@ -105,6 +105,7 @@ def initialize(server, data, method:, request:, params:, session: nil, request_i @token = SessionToken.decode(header_session_id) @data.http_transport_seen = true if http? @identified_in_request = {} + @session_sources = {} end # Runs the wrapped handler and records the request. @@ -131,6 +132,8 @@ def dispatch_kind(&) when :initialize then dispatch_initialize(&) else dispatch_generic(&) end + ensure + safely { release_custom_events(@scope[:session_id]) } end # --- dispatchers ------------------------------------------------------- @@ -146,11 +149,14 @@ def dispatch_tool_call # Resolution reads the stripped values, never `original_arguments`: only an # argument this layer injected is ours to interpret. A `conversation_id` or # `context` the tool declares itself stays application data and is left to it. + handle_free = safely(false) { client_row&.handle_free } + @client_conversation = safely { ClientConversation.read(client_row, envelope_meta) } + request = request_with_arguments(original_arguments) conversation_id, minted = safely([nil, false]) do - ConversationId.resolve(@options.enable_conversation_id, stripped[ConversationId::PARAM_NAME], name, - missing_name) + ConversationId.resolve(@options.enable_conversation_id && !@client_conversation, + stripped[ConversationId::PARAM_NAME], name, missing_name, + mint: !handle_free && !carries_session?) end - request = request_with_arguments(original_arguments) if virtual_tool?(name) # Run the gem's own handler so validation, in-flight tracking and @@ -172,7 +178,7 @@ def dispatch_tool_call return result end - safely { prime_session(request, minted ? nil : conversation_id) } + safely { prime_session(request, minted ? nil : conversation_id, hold_custom_events: minted) } begin result = yield rescue StandardError => e @@ -191,7 +197,7 @@ def dispatch_tool_call error_source = result unless no_response?(result) || conversation_id.nil? safely do - if @data.tool_output_instructions[name] + if @data.tool_output_instructions[name] && !handle_free result, delivered = ConversationId.mirror_instructions(result, conversation_id) end if minted @@ -205,6 +211,7 @@ def dispatch_tool_call 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, stripped: stripped, error_source: error_source) end @@ -228,7 +235,8 @@ def dispatch_tools_list if tools.is_a?(Array) names = tools.map { |tool| fetch(tool, :name) }.compact empty = tools.empty? - mutated = tools.map { |tool| mutate_tool(tool) } + advertise_handle = !client_row&.handle_free + mutated = tools.map { |tool| mutate_tool(tool, advertise_handle) } result = result.merge(SchemaMutation.key_for(result, :tools) => mutated) end end @@ -405,6 +413,7 @@ def base_event(event_type, session_id, request) event = { 'event_type' => event_type, 'session_id' => session_id, + 'session_source' => @session_sources[session_id], 'duration' => duration_ms, 'client_name' => nil, 'client_version' => nil, @@ -454,17 +463,44 @@ def resolve_event_properties(request) # recorded under. A minted handle is not known to have reached the agent # until the call returns, so it stays out of here. {#prepare_request} runs # again after the call; the second run is idempotent. - def prime_session(request, conversation_id) + def prime_session(request, conversation_id, hold_custom_events: false) session_id = prepare_request(request, conversation_id: conversation_id) - @scope[:session_id] = session_id if @scope.is_a?(Hash) + @data.synchronize do + @scope[:session_id] = session_id + @scope[:session_source] = @session_sources[session_id] + @scope[:held] = [] if hold_custom_events + end + end + + def release_custom_events(session_id) + return unless @scope.key?(:held) + + held = @data.synchronize do + next nil unless @scope.key?(:held) + + @scope[:session_id] = session_id + @scope[:session_source] = @session_sources[session_id] + @scope[:actor] = actor_for(session_id) + @scope.delete(:held) + end + actor = actor_for(session_id) + held&.each do |input| + self.class.capture_event(@data, input.merge('session_id' => session_id, + 'session_source' => @session_sources[session_id]), + actor: actor) + end end # Resolve the session id and run identify. def prepare_request(request, conversation_id: nil, token: nil) token ||= @token session_id, source = Session.resolve(@data, mcp_session_id(token), token: token, - conversation_id: conversation_id) + conversation_id: conversation_id, + client_conversation: @client_conversation, + request_session_id: request_session_id) + @session_sources[session_id] = source warn_stateless_session_not_wired if source == 'generated' && http? + Session.touch_connection(@data) if (@client_conversation || conversation_id) && !http? # A tool call prepares twice: once before the body to pin the session, and # once after it, when the conversation anchor is known. A customer's @@ -478,7 +514,10 @@ def prepare_request(request, conversation_id: nil, token: nil) # overwritten while the handler ran. @identified_in_request[session_id] = actor @scope[:actor] = actor if @scope.is_a?(Hash) - self.class.capture_event(@data, identify_event, actor: actor) if identify_event + if identify_event + self.class.capture_event(@data, identify_event.merge('session_source' => source), + actor: actor) + end end session_id end @@ -501,14 +540,28 @@ def mint_session_token(client_name, client_version, protocol_version, requested_ payload end + def carries_session? + !@token.nil? || !mcp_session_id(@token).nil? + end + + def request_session_id + @request_session_id ||= (Session.new_session_id if http?) + end + + def client_row + return @client_row if defined?(@client_row) + + @client_row = ClientConversation.recognize(@headers['user-agent'], client_identity(@request)[0]) + end + def warn_stateless_session_not_wired return if @data.warned_no_stateless_session @data.warned_no_stateless_session = true Log.warn( @options, - 'Warning: an MCP request arrived over streamable HTTP with no session id, so PostHog generated a ' \ - 'per-process $session_id that will fragment across requests and pods. In stateless mode the ' \ + 'Warning: an MCP request arrived over streamable HTTP with no session id, so PostHog gave it a ' \ + '$session_id of its own, shared with no other request. In stateless mode the ' \ 'client must replay the Mcp-Session-Id header PostHog::MCP mints at initialize; for a custom Rack ' \ 'stack add PostHog::MCP::RackMiddleware. Conversation ids, which are enabled by default, also anchor ' \ 'the session without any middleware. See https://posthog.com/docs/mcp-analytics/installation#ruby.' @@ -521,9 +574,12 @@ def header_session_id SessionToken.read_header(@headers) end - # The transport's own session id (never our token). + # The transport's own session id (never our token). A 2026-07-28 request + # carries none: the session the gem gives it is assigned afresh to each request. def mcp_session_id(token) - transport_id = @session.respond_to?(:session_id) ? @session.session_id : nil + if @session.respond_to?(:session_id) && self.class.legacy_era?(protocol_version) + transport_id = @session.session_id + end return transport_id if transport_id.is_a?(String) && !transport_id.empty? token ? nil : header_session_id @@ -539,7 +595,8 @@ def envelope_meta end def client_identity(request) - info = envelope_client_info || session_client || server_client + # One instance serves every stateless HTTP client, so its handshake may be another client's. + info = envelope_client_info || session_client || (server_client unless http?) info = fetch(request_params(request), :clientInfo) if info.nil? && @kind == :initialize name = info.is_a?(Hash) ? fetch(info, :name) : nil version = info.is_a?(Hash) ? fetch(info, :version) : nil @@ -596,8 +653,14 @@ def request_params(request) params.is_a?(Hash) ? params : {} end + # A recognized client's conversation id only groups the call; its value is never sent. def request_with_arguments(arguments) params = @params.merge(SchemaMutation.key_for(@params, :arguments) => arguments) + meta = envelope_meta + if client_row && meta + params = params.merge(SchemaMutation.key_for(@params, :_meta) => meta.except(client_row.key, + client_row.key.to_sym)) + end @request.merge(SchemaMutation.key_for(@request, :params) => params) end @@ -673,7 +736,7 @@ def strip_injected_arguments(arguments, owned) stripped end - def mutate_tool(tool) + def mutate_tool(tool, advertise_handle) return tool unless tool.is_a?(Hash) name = fetch(tool, :name) @@ -691,7 +754,7 @@ def mutate_tool(tool) if @options.enable_conversation_id updated = SchemaMutation.add_conversation_id_parameter(schema, tool_name: name, options: @options) owned << ConversationId::PARAM_NAME unless updated.equal?(schema) - schema = updated + schema = updated if advertise_handle end if @options.capture_model_enabled? updated = SchemaMutation.add_model_parameter( @@ -703,7 +766,7 @@ def mutate_tool(tool) mutated = tool.merge(SchemaMutation.key_for(tool, :inputSchema) => schema) declared = nil - if @options.enable_conversation_id + if @options.enable_conversation_id && advertise_handle output_schema = fetch(tool, :outputSchema) new_output, declared = SchemaMutation.add_output_instructions(output_schema, tool_name: name, options: @options) diff --git a/lib/posthog/mcp/session.rb b/lib/posthog/mcp/session.rb index 937b3276..d3c4771b 100644 --- a/lib/posthog/mcp/session.rb +++ b/lib/posthog/mcp/session.rb @@ -2,10 +2,12 @@ module PostHog module MCP - # Session id resolution, in priority order: the - # agent's echoed `conversation_id` handle first, then our self-encoded - # session token, then the transport's MCP session id, then this server's own - # memory (which rolls over after {INACTIVITY_TIMEOUT_MINUTES} of inactivity). + # Session id resolution, in priority order: the client's own conversation id, + # the agent's echoed `conversation_id` handle, our self-encoded session token, + # the transport's MCP session id, a session of its own for a request that + # carries none over a transport shared by every client (stateless HTTP), and + # last this server's own memory (which rolls over after + # {INACTIVITY_TIMEOUT_MINUTES} of inactivity). # # @api private module Session @@ -25,8 +27,12 @@ def derive_session_id_from_conversation(conversation_id) end # @return [Array(String, String)] `[session_id, source]` where source is one of - # `conversation`, `token`, `mcp`, `generated` - def resolve(data, mcp_session_id, token: nil, conversation_id: nil) + # `client_metadata`, `conversation`, `token`, `mcp`, `generated` + def resolve(data, mcp_session_id, token: nil, conversation_id: nil, client_conversation: nil, + request_session_id: nil) + if present?(client_conversation) + return [derive_session_id_from_conversation(client_conversation), 'client_metadata'] + end return [derive_session_id_from_conversation(conversation_id), 'conversation'] if present?(conversation_id) data.synchronize do @@ -47,13 +53,14 @@ def resolve(data, mcp_session_id, token: nil, conversation_id: nil) return [data.session_id, 'mcp'] end + return [request_session_id, 'generated'] if present?(request_session_id) + if data.session_source == 'mcp' && data.last_mcp_session_id data.last_activity = now return [data.session_id, 'mcp'] end - stale = (now - data.last_activity) > (INACTIVITY_TIMEOUT_MINUTES * 60) - if data.session_source != 'generated' || stale || data.session_id.nil? + if data.session_source != 'generated' || stale?(data, now) || data.session_id.nil? data.session_id = new_session_id data.session_source = 'generated' end @@ -62,6 +69,22 @@ def resolve(data, mcp_session_id, token: nil, conversation_id: nil) end end + # A call grouped by its client or agent is still activity on a one-client + # connection, so the connection's own session does not roll over under it. + def touch_connection(data) + data.synchronize do + next unless data.session_source == 'generated' + + now = Time.now + data.session_id = new_session_id if stale?(data, now) + data.last_activity = now + end + end + + def stale?(data, now) + (now - data.last_activity) > (INACTIVITY_TIMEOUT_MINUTES * 60) + end + def present?(value) value.is_a?(String) && !value.empty? end diff --git a/public_api_snapshot.txt b/public_api_snapshot.txt index 69779a00..7b508778 100644 --- a/public_api_snapshot.txt +++ b/public_api_snapshot.txt @@ -289,6 +289,7 @@ constant PostHog::MCP::Property::RESPONSE: String constant PostHog::MCP::Property::SERVER_NAME: String constant PostHog::MCP::Property::SERVER_VERSION: String constant PostHog::MCP::Property::SESSION_ID: String +constant PostHog::MCP::Property::SESSION_SOURCE: String constant PostHog::MCP::Property::SOURCE: String constant PostHog::MCP::Property::TOOL_CATEGORY: String constant PostHog::MCP::Property::TOOL_DESCRIPTION: String diff --git a/spec/posthog/mcp/client_session_spec.rb b/spec/posthog/mcp/client_session_spec.rb new file mode 100644 index 00000000..306823d9 --- /dev/null +++ b/spec/posthog/mcp/client_session_spec.rb @@ -0,0 +1,346 @@ +# frozen_string_literal: true + +# rubocop:disable Layout/LineLength + +require_relative 'spec_helper' +require 'rack' +require 'stringio' + +class PostHogMcpSearchDocsTool < MCP::Tool + tool_name 'search_docs' + input_schema(properties: { query: { type: 'string' } }) + class << self + attr_accessor :analytics, :received, :before_capture + + def call(**arguments) + self.received = arguments.except(:server_context) + before_capture&.call + analytics&.capture('docs_searched') + MCP::Tool::Response.new([{ type: 'text', text: 'found' }]) + end + end +end + +module PostHogMcpClientSessionVectors + CHATGPT = 'openai-mcp/1.0.0 (ChatGPT)' + CODEX = 'codex-mcp-client/0.50.0' + CHATGPT_SESSION = 'ses_2f5d35b7108d17c807766f2f769a1e8c' + CODEX_SESSION = 'ses_0fdf126b8e2c1f9689ca12f3dd3383e6' + HANDLE_BLOCK = /\A\{"conversation_id":"[0-9a-f-]{36}"\}\z/ + + RSpec.describe 'PostHog::MCP session identity' do + let(:client) { new_test_client } + let(:server) { MCP::Server.new(name: 'docs-server', version: '1.0.0', tools: [PostHogMcpSearchDocsTool]) } + let(:transport) { MCP::Server::Transports::StreamableHTTPTransport.new(server, stateless: true, enable_json_response: true) } + + before do + allow(Kernel).to receive(:warn) + PostHogMcpSearchDocsTool.analytics = nil + PostHogMcpSearchDocsTool.before_capture = nil + end + + def instrument(**options) + PostHogMcpSearchDocsTool.analytics = PostHog::MCP.instrument(server, client, **options) + end + + def call_search(user_agent: nil, meta: nil, arguments: { query: 'flags' }, headers: {}, id: 2) + params = { name: 'search_docs', arguments: arguments } + params[:_meta] = meta if meta + headers = headers.merge('user-agent' => user_agent) if user_agent + response = transport.call(env_for(rpc(id, 'tools/call', params), headers)) + body = parse(response) + raise body.inspect unless body['result'] + + body['result']['content'].map { |block| block['text'] } + end + + def list_tools(user_agent) + response = transport.call(env_for(rpc(9, 'tools/list'), 'user-agent' => user_agent)) + parse(response)['result']['tools'].to_h { |tool| [tool['name'], tool['inputSchema']['properties'].keys] } + end + + def tool_calls + events_named(drain_events(client), '$mcp_tool_call').map { |event| event[:properties] } + end + + it 'derives the session from a client conversation id and adds no conversation_id block' do + instrument + texts = call_search(user_agent: CHATGPT, meta: { 'openai/session' => 'v1/conv-example-0001' }) + + expect(texts).to eq(['found']) + call = tool_calls.first + expect(call['$session_id']).to eq(CHATGPT_SESSION) + expect(call).not_to have_key('$mcp_conversation_id') + expect(call['$mcp_session_source']).to eq('client_metadata') + end + + it 'prefers a client conversation id to an echoed handle and strips the handle' do + instrument + call_search(user_agent: CHATGPT, meta: { 'openai/session' => 'v1/conv-example-0001' }, + arguments: { query: 'flags', conversation_id: '0190f0e8-7a6b-7c3d-9e4f-5a6b7c8d9e0f' }) + + expect(PostHogMcpSearchDocsTool.received).to eq(query: 'flags') + call = tool_calls.first + expect(call['$session_id']).to eq(CHATGPT_SESSION) + expect(call).not_to have_key('$mcp_conversation_id') + end + + it 'reads a client conversation id with conversation anchoring disabled' do + instrument(enable_conversation_id: false) + call_search(user_agent: CHATGPT, meta: { 'openai/session' => 'v1/conv-example-0001' }) + + expect(tool_calls.first['$session_id']).to eq(CHATGPT_SESSION) + end + + it 'falls back to a minted handle when the id is not its row\'s shape' do + instrument + texts = call_search(user_agent: CODEX, meta: { 'sessionId' => 'not-a-uuid' }) + + expect(texts.last).to match(HANDLE_BLOCK) + end + + it 'mints a handle-free client no handle, and its sessionless calls stand alone' do + instrument + first = call_search(user_agent: CHATGPT, meta: { 'openai/session' => '' }) + second = call_search(user_agent: CHATGPT, id: 3) + + expect([first, second]).to eq([['found'], ['found']]) + sessions = tool_calls.map { |call| call['$session_id'] } + expect(sessions.uniq.size).to eq(2) + end + + it 'derives Codex and VS Code sessions from their ids' do + instrument + codex = call_search(user_agent: CODEX, meta: { 'sessionId' => '019A4F2E-1C3D-7B8A-9E0F-1A2B3C4D5E6F' }) + vscode = call_search(meta: { + 'io.modelcontextprotocol/protocolVersion' => '2026-07-28', + 'io.modelcontextprotocol/clientInfo' => { 'name' => 'Visual Studio Code', 'version' => '1.100.0' }, + 'io.modelcontextprotocol/clientCapabilities' => {}, + 'vscode.conversationId' => '3f1c2b7e-8d4a-4c6b-9a1e-5f2d7c8b9a0e' + }, headers: { 'mcp-protocol-version' => '2026-07-28', 'mcp-method' => 'tools/call', + 'mcp-name' => 'search_docs' }, id: 3) + + expect([codex, vscode]).to eq([['found'], ['found']]) + expect(tool_calls.map { |call| call['$session_id'] }).to eq([CODEX_SESSION, 'ses_0571acb894e6753d33e37e5c2b327c59']) + end + + it 'reads a key only from the client that defines it' do + instrument + texts = call_search(user_agent: 'example-client/1.0', + meta: { 'sessionId' => '019a4f2e-1c3d-7b8a-9e0f-1a2b3c4d5e6f', 'openai/session' => 'v1/conv-example-0001' }) + + expect(texts.last).to match(HANDLE_BLOCK) + call = tool_calls.first + expect([CODEX_SESSION, CHATGPT_SESSION]).not_to include(call['$session_id']) + expect(call['$mcp_session_source']).to eq('conversation') + end + + it 'advertises no conversation_id to a handle-free client and keeps stripping it for others' do + instrument + expect(list_tools(CHATGPT)['search_docs']).not_to include('conversation_id') + expect(list_tools(CODEX)['search_docs']).to include('conversation_id') + + list_tools(CHATGPT) + call_search(user_agent: CODEX, arguments: { query: 'flags', conversation_id: '0190f0e8-7a6b-7c3d-9e4f-5a6b7c8d9e0f' }) + expect(PostHogMcpSearchDocsTool.received).to eq(query: 'flags') + end + + it 'recognizes a client by the name its replayed token carries, not by another client\'s handshake' do + instrument + init = lambda do |name| + body = rpc(1, 'initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: name, version: '1' } }) + transport.call(env_for(body))[1]['mcp-session-id'] + end + example_token = init.call('example-client') + codex_token = init.call('codex-mcp-client') + meta = { 'sessionId' => '019a4f2e-1c3d-7b8a-9e0f-1a2b3c4d5e6f' } + call_search(meta: meta, headers: { 'mcp-session-id' => codex_token }) + call_search(meta: meta, headers: { 'mcp-session-id' => example_token }, id: 3) + call_search(meta: meta, id: 4) + + sessions = tool_calls.map { |call| call['$session_id'] } + expect(sessions.map { |session| session == CODEX_SESSION }).to eq([true, false, false]) + end + + { + 'legacy' => [{}, {}], + '2026-07-28' => [ + { 'io.modelcontextprotocol/protocolVersion' => '2026-07-28', 'io.modelcontextprotocol/clientCapabilities' => {}, + 'io.modelcontextprotocol/clientInfo' => { 'name' => 'example-client', 'version' => '1' } }, + { 'mcp-protocol-version' => '2026-07-28', 'mcp-method' => 'tools/call', 'mcp-name' => 'search_docs' } + ] + }.each do |era, (meta, headers)| + it "gives every sessionless #{era} stateless HTTP request a fresh generated session" do + instrument(enable_conversation_id: false) + call_search(meta: meta, headers: headers) + call_search(meta: meta, headers: headers, id: 3) + + calls = tool_calls + expect(calls.map { |call| call['$mcp_session_source'] }).to eq(%w[generated generated]) + expect(calls.map { |call| call['$session_id'] }.uniq.size).to eq(2) + expect(calls.map { |call| call['$session_id'] }).to all(match(/\Ases_\h{8}-\h{4}-7/)) + end + + next if meta.empty? + + it "mints a handle for a sessionless #{era} request on a stateful transport" do + stateful = MCP::Server::Transports::StreamableHTTPTransport.new(server, stateless: false, enable_json_response: true) + instrument + params = { name: 'search_docs', arguments: { query: 'flags' }, _meta: meta } + texts = parse(stateful.call(env_for(rpc(2, 'tools/call', params), headers)))['result']['content'].map { |block| block['text'] } + + expect(texts.last).to match(HANDLE_BLOCK) + expect(tool_calls.first['$mcp_session_source']).to eq('conversation') + end + end + + it 'labels a replayed token as transport and mints no handle beside it' do + instrument + token = PostHog::MCP.encode_session_id(PostHog::MCP::SessionTokenPayload.new(session_id: 'ses_first')) + texts = call_search(headers: { 'mcp-session-id' => token }) + + expect(texts).to eq(['found']) + call = tool_calls.first + expect(call.values_at('$session_id', '$mcp_session_source')).to eq(%w[ses_first transport]) + end + + { + 'ChatGPT' => [CHATGPT, { 'openai/session' => 'v1/conv-canary-0001' }], + 'Codex' => [CODEX, { 'sessionId' => '019a4f2e-1c3d-7b8a-9e0f-cafecafecafe' }], + 'invalid Codex' => [CODEX, { 'sessionId' => 'not-a-uuid-canary' }] + }.each do |name, (user_agent, meta)| + it "sends no #{name} conversation id in any property" do + instrument(identify: ->(_request, _extra) { { distinct_id: 'user-1' } }) + call_search(user_agent: user_agent, meta: meta) + + events = drain_events(client) + expect(events_named(events, '$mcp_tool_call').size).to eq(1) + expect(events.map { |event| JSON.generate(event) }.grep(/#{Regexp.escape(meta.values.first)}/)).to eq([]) + end + end + + it 'labels the $identify event with the session source' do + instrument(identify: ->(_request, _extra) { { distinct_id: 'user-1' } }) + call_search(user_agent: CHATGPT, meta: { 'openai/session' => 'v1/conv-example-0001' }) + + identify = events_named(drain_events(client), '$identify').first + expect(identify[:properties]['$mcp_session_source']).to eq('client_metadata') + end + + { + 'keeps a connection session a client-id call kept active' => [[0, 20, 40, 45], true], + 'rolls a connection session over after 30 idle minutes, even under a client-id call' => [[0, 40, 41], false] + }.each do |behavior, (minutes, same)| + it behavior do + instrument(enable_conversation_id: false) + start = Time.now + server.handle(rpc(1, 'initialize', { protocolVersion: '2025-06-18', capabilities: {}, + clientInfo: { name: 'Visual Studio Code', version: '1' } })) + minutes.each_with_index do |minute, index| + allow(Time).to receive(:now).and_return(start + (minute * 60)) + params = { name: 'search_docs', arguments: { query: 'flags' } } + params[:_meta] = { 'vscode.conversationId' => '3f1c2b7e-8d4a-4c6b-9a1e-5f2d7c8b9a0e' } unless [0, minutes.size - 1].include?(index) + server.handle(rpc(index + 2, 'tools/call', params)) + end + + sessions = tool_calls.map { |call| call['$session_id'] } + expect(sessions.first == sessions.last).to eq(same) + end + end + + context 'custom events captured during a call' do + def custom_events(events) + events_named(events, 'docs_searched').map { |event| [event[:properties]['$session_id'], event[:properties]['$mcp_session_source']] } + end + + def call_sessions(events) + events_named(events, '$mcp_tool_call').map { |event| [event[:properties]['$session_id'], event[:properties]['$mcp_session_source']] } + end + + it 'keeps that call\'s session while another call runs' do + instrument(enable_conversation_id: false) + token = PostHog::MCP.encode_session_id(PostHog::MCP::SessionTokenPayload.new(session_id: 'ses_first')) + other = nil + PostHogMcpSearchDocsTool.before_capture = lambda do + PostHogMcpSearchDocsTool.before_capture = nil + other = Thread.new { call_search(id: 3) } + expect(other.join(5)).to eq(other) + end + call_search(headers: { 'mcp-session-id' => token }) + + events = drain_events(client) + expect(custom_events(events)).to match_array(call_sessions(events)) + expect(custom_events(events)).to include(%w[ses_first transport]) + ensure + other&.join(2) + end + + it 'carries the client conversation session' do + instrument + call_search(user_agent: CHATGPT, meta: { 'openai/session' => 'v1/conv-example-0001' }) + + expect(custom_events(drain_events(client))).to eq([[CHATGPT_SESSION, 'client_metadata']]) + end + + it 'carries the session and identity of the handle its call delivered' do + instrument(identify: ->(_request, _extra) { { distinct_id: 'user-1' } }) + texts = call_search + + handle = JSON.parse(texts.last)['conversation_id'] + events = drain_events(client) + expect(custom_events(events)).to eq([[PostHog::MCP.derive_session_id_from_conversation(handle), 'conversation']]) + expect(custom_events(events)).to eq(call_sessions(events)) + expect(events_named(events, 'docs_searched').map { |event| event[:distinct_id] }).to eq(['user-1']) + end + + it 'sends custom events past the hold bound at once, and warns once' do + logs = [] + instrument(logger: ->(message) { logs << message }) + PostHogMcpSearchDocsTool.before_capture = -> { 1001.times { PostHogMcpSearchDocsTool.analytics.capture('docs_searched') } } + call_search + + expect(events_named(drain_events(client), 'docs_searched').size).to eq(1002) + expect(logs.grep(/custom events/).size).to eq(1) + end + + it 'keeps a held event\'s nested properties as they were when captured' do + instrument + filters = ['flags'] + PostHogMcpSearchDocsTool.before_capture = lambda do + PostHogMcpSearchDocsTool.analytics.capture('filtered', { filters: filters }) + filters << 'changed after capture' + end + call_search + + filtered = events_named(drain_events(client), 'filtered').first + expect(filtered[:properties]['filters']).to eq(['flags']) + end + + it 'sends custom events past the held byte budget at once' do + instrument + PostHogMcpSearchDocsTool.before_capture = lambda do + 300.times { PostHogMcpSearchDocsTool.analytics.capture('bulky', { blob: 'x' * 65_536 }) } + end + call_search + + sources = events_named(drain_events(client), 'bulky').map { |event| event[:properties]['$mcp_session_source'] } + expect(sources.size).to eq(300) + expect(sources.tally.keys).to contain_exactly('conversation', 'generated') + end + + it 'carries the session the call recorded when the tool raises before delivering its handle' do + instrument + PostHogMcpSearchDocsTool.before_capture = lambda do + PostHogMcpSearchDocsTool.analytics.capture('docs_searched') + raise 'search backend down' + end + transport.call(env_for(rpc(2, 'tools/call', { name: 'search_docs', arguments: { query: 'flags' } }))) + + events = drain_events(client) + expect(custom_events(events)).to eq(call_sessions(events)) + expect(custom_events(events).map(&:last)).to eq(['generated']) + end + end + end +end +# rubocop:enable Layout/LineLength diff --git a/spec/posthog/mcp/http_transport_spec.rb b/spec/posthog/mcp/http_transport_spec.rb index 2aa6d719..9c1197b1 100644 --- a/spec/posthog/mcp/http_transport_spec.rb +++ b/spec/posthog/mcp/http_transport_spec.rb @@ -36,25 +36,10 @@ def call(**) before { allow(Kernel).to receive(:warn) } - def env_for(body, headers = {}) - env = { - 'REQUEST_METHOD' => 'POST', 'PATH_INFO' => '/', 'SCRIPT_NAME' => '', 'QUERY_STRING' => '', - 'SERVER_NAME' => 'localhost', 'SERVER_PORT' => '80', 'HTTP_HOST' => 'localhost', 'rack.url_scheme' => 'http', - 'HTTP_ACCEPT' => 'application/json, text/event-stream', 'CONTENT_TYPE' => 'application/json', - 'rack.input' => StringIO.new(JSON.generate(body)), 'rack.errors' => StringIO.new - } - headers.each { |name, value| env["HTTP_#{name.upcase.tr('-', '_')}"] = value } - env - end - def initialize_body(id = 1, version = '2025-06-18') rpc(id, 'initialize', { protocolVersion: version, capabilities: {}, clientInfo: { name: 'claude-code', version: '1.2.3' } }) end - def parse(response) - JSON.parse(response[2].respond_to?(:join) ? response[2].join : response[2].to_s) - end - context 'stateless mode' do let(:transport) { MCP::Server::Transports::StreamableHTTPTransport.new(server, stateless: true, enable_json_response: true) } @@ -92,7 +77,7 @@ def parse(response) response = transport.call(env_for(initialize_body(1, 'draft'))) expect(response[1]['mcp-session-id']).to be_nil 2.times { |i| transport.call(env_for(rpc(i + 2, 'tools/call', { name: 'ping_tool', arguments: {} }))) } - expect(logs.count { |m| m.include?('fragment across requests') }).to eq(1) + expect(logs.count { |m| m.include?('a $session_id of its own') }).to eq(1) end { diff --git a/spec/posthog/mcp/spec_helper.rb b/spec/posthog/mcp/spec_helper.rb index eee41f51..f433fe2a 100644 --- a/spec/posthog/mcp/spec_helper.rb +++ b/spec/posthog/mcp/spec_helper.rb @@ -2,6 +2,7 @@ require 'spec_helper' require 'posthog/mcp' +require 'stringio' module MCPSpecHelpers def drain_events(client) @@ -20,6 +21,21 @@ def rpc(id, method, params = nil) request end + def env_for(body, headers = {}) + env = { + 'REQUEST_METHOD' => 'POST', 'PATH_INFO' => '/', 'SCRIPT_NAME' => '', 'QUERY_STRING' => '', + 'SERVER_NAME' => 'localhost', 'SERVER_PORT' => '80', 'HTTP_HOST' => 'localhost', 'rack.url_scheme' => 'http', + 'HTTP_ACCEPT' => 'application/json, text/event-stream', 'CONTENT_TYPE' => 'application/json', + 'rack.input' => StringIO.new(JSON.generate(body)), 'rack.errors' => StringIO.new + } + headers.each { |name, value| env["HTTP_#{name.upcase.tr('-', '_')}"] = value } + env + end + + def parse(response) + JSON.parse(response[2].respond_to?(:join) ? response[2].join : response[2].to_s) + end + def new_test_client PostHog::Client.new(api_key: 'phc_test', test_mode: true) end