From 4916cc125de6738e3a43704f850447c3741b9de0 Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 11:00:16 -0300 Subject: [PATCH 1/9] feat(mcp): group sessions by ChatGPT, Codex and VS Code conversation ids Implements the sdk-specs MCP analytics "Session identity" requirement in PostHog::MCP, ported from posthog-js #5577/#5740 and posthog-python #1193. - Reads a client conversation id from tools/call `_meta`, only from the client whose row recognizes the request (User-Agent or client name): ChatGPT `openai/session`, Codex `sessionId`, VS Code `vscode.conversationId`. It outranks a conversation handle. - ChatGPT is handle-free: its listing omits `conversation_id` (still owned and stripped for other clients) and it is minted no handle. - Every event carries `$mcp_session_source` (client_metadata, conversation, transport, generated). - Rule 4: a stateless HTTP request with no session gets a fresh per-request session instead of the server's shared one. - The handshake names the client only off HTTP, so a stateless request is never recognized as another client. - Custom events captured during a call that mints a handle are held and sent with the session and identity the call records. Tested: bundle exec rspec (2612 examples, 0 failures; new client_session_spec failed 13 of 14 before the change), rubocop clean, rake public_api:check passes (adds Property::SESSION_SOURCE). --- .changeset/mcp-client-conversation-session.md | 5 + lib/posthog/mcp.rb | 1 + lib/posthog/mcp/README.md | 1 + lib/posthog/mcp/analytics.rb | 44 ++- lib/posthog/mcp/client_conversation.rb | 71 +++++ lib/posthog/mcp/constants.rb | 1 + lib/posthog/mcp/event_builder.rb | 1 + lib/posthog/mcp/instrumentation.rb | 89 +++++- lib/posthog/mcp/session.rb | 43 ++- public_api_snapshot.txt | 1 + spec/posthog/mcp/client_session_spec.rb | 255 ++++++++++++++++++ spec/posthog/mcp/http_transport_spec.rb | 2 +- spec/posthog/mcp/identity_and_session_spec.rb | 7 +- 13 files changed, 482 insertions(+), 39 deletions(-) create mode 100644 .changeset/mcp-client-conversation-session.md create mode 100644 lib/posthog/mcp/client_conversation.rb create mode 100644 spec/posthog/mcp/client_session_spec.rb diff --git a/.changeset/mcp-client-conversation-session.md b/.changeset/mcp-client-conversation-session.md new file mode 100644 index 00000000..e33f7ec5 --- /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`. ChatGPT is no longer advertised or minted a `conversation_id`. On stateless HTTP, a request that carries no session gets a `$session_id` of its own instead of the server's, 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..893ed32b 100644 --- a/lib/posthog/mcp/analytics.rb +++ b/lib/posthog/mcp/analytics.rb @@ -7,6 +7,9 @@ module MCP # # @note Experimental. class Analytics + MAX_HELD_EVENTS = 1000 + private_constant :MAX_HELD_EVENTS + # @api private def initialize(server) @server = server @@ -37,13 +40,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 +70,30 @@ 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, Session.server_source(data)] unless data.http_transport_seen warn_unscoped_capture(data) - Session.new_session_id + [Session.new_session_id, 'generated'] + end + + # A call whose session waits on delivering a minted handle holds its custom + # events until it records (see {Instrumentation#prime_session}). Each is fixed + # when captured, its properties copied and its duration zero. + def hold(data, scope, input) + data.synchronize do + held = scope&.[](:held) + next false unless held + + if held.size < MAX_HELD_EVENTS + held << input.merge('properties' => input['properties'].dup, 'duration' => 0) + else + Log.debug(data.options, "analytics.capture(#{input['event_name']}) dropped: the call holds " \ + "#{MAX_HELD_EVENTS} events already") + end + true + end 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..3230ac2f --- /dev/null +++ b/lib/posthog/mcp/client_conversation.rb @@ -0,0 +1,71 @@ +# frozen_string_literal: true + +module PostHog + module MCP + # Client conversation ids: the value an MCP client puts in a `tools/call` + # request's `_meta` to name the conversation the call belongs to. + # + # {ROWS} is the table of the MCP analytics spec's "Session identity" + # requirement, row for row, in its order. A row's key is read only from a + # request its recognition rule matches, so a generic key such as Codex's + # `sessionId` is never read from a client that means something else by it. + # posthog-js and posthog-python keep the same table. + # + # @api private + module ClientConversation + # `handle_free`: the client sends its id on every call, so it is advertised + # no `conversation_id` and minted no handle. + Row = Struct.new(:key, :value, :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 + + # @return [String, nil] the id in `meta` when it is this row's shape + def read(meta) + id = meta[key] || meta[key.to_sym] + ClientConversation.public_send(value, id) if id.is_a?(String) + 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/ + VSCODE_NAMES = ['Visual Studio Code', 'Visual Studio Code - Insiders'].freeze + + ROWS = [ + Row.new(key: 'openai/session', value: :printable_ascii, handle_free: true, client_names: [], + user_agent: %r{\Aopenai-mcp/[^\s(]*\s*\(\s*chatgpt\s*[;,)]}i), + Row.new(key: 'sessionId', value: :uuid, handle_free: false, client_names: ['codex-mcp-client'], + user_agent: %r{\Acodex-mcp-client/}i), + Row.new(key: 'vscode.conversationId', value: :uuid, handle_free: false, client_names: VSCODE_NAMES, + user_agent: /\A(?:#{VSCODE_NAMES.map { |name| Regexp.escape("#{name}/") }.join('|')})/i) + ].freeze + + module_function + + # @return [Row, nil] the first row that recognizes the request + def recognize(user_agent, client_name) + ROWS.find { |row| row.recognizes?(user_agent, client_name) } + end + + # @return [String, nil] `":"`, what the session is derived from + def read(row, meta) + return nil unless row && meta.is_a?(Hash) + + id = row.read(meta) + id && "#{row.key}:#{id}" + end + + def uuid(value) + lowered = value.downcase + lowered if UUID.match?(lowered) && lowered != NIL_UUID + end + + def printable_ascii(value) + value if PRINTABLE_ASCII.match?(value) + 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/event_builder.rb b/lib/posthog/mcp/event_builder.rb index 2dbf6ec8..bbb81737 100644 --- a/lib/posthog/mcp/event_builder.rb +++ b/lib/posthog/mcp/event_builder.rb @@ -44,6 +44,7 @@ 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? + properties[Property::SESSION_SOURCE] = event['session_source'] if event['session_source'] end def add_conversation_id(event, properties) diff --git a/lib/posthog/mcp/instrumentation.rb b/lib/posthog/mcp/instrumentation.rb index d180283a..5fbd0d65 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,9 @@ def dispatch_kind(&) when :initialize then dispatch_initialize(&) else dispatch_generic(&) end + ensure + # A call that recorded nothing still sends what it held, with the session it arrived with. + safely { release_custom_events(@scope[:session_id]) } end # --- dispatchers ------------------------------------------------------- @@ -146,11 +150,19 @@ 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. + request = request_with_arguments(original_arguments) + handle_free = safely(false) { client_row(request)&.handle_free } + @client_conversation = safely { ClientConversation.read(client_row(request), envelope_meta) } conversation_id, minted = safely([nil, false]) do ConversationId.resolve(@options.enable_conversation_id, stripped[ConversationId::PARAM_NAME], name, missing_name) end - request = request_with_arguments(original_arguments) + # The client's own id outranks a handle, and a handle-free client names its + # conversation itself, so neither is minted one. + if @client_conversation || (minted && handle_free) + conversation_id = nil + minted = false + end if virtual_tool?(name) # Run the gem's own handler so validation, in-flight tracking and @@ -172,7 +184,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 +203,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 +217,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 +241,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(@request)&.handle_free + mutated = tools.map { |tool| mutate_tool(tool, advertise_handle) } result = result.merge(SchemaMutation.key_for(result, :tools) => mutated) end end @@ -405,6 +419,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,16 +469,46 @@ 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) + # + # A minted handle groups the call only once its result delivers it, so with + # `hold_custom_events` the body's custom events wait for + # {#release_custom_events} and go out with the session the call settles on. + 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 + + # Send the custom events {#prime_session} held, with the session the call + # recorded, and let later ones (from threads the tool left running) go out + # with it directly. Runs once per call; later runs find nothing held. + def release_custom_events(session_id) + 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 + held&.each do |input| + self.class.capture_event(@data, input.merge('session_id' => session_id, + 'session_source' => @session_sources[session_id]), + actor: actor_for(session_id)) + 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? # A tool call prepares twice: once before the body to pin the session, and @@ -501,14 +546,28 @@ def mint_session_token(client_name, client_version, protocol_version, requested_ payload end + # The session a request that carries none gets on stateless HTTP, where the + # server's own session would group every client it serves. Fixed per request, + # so each event of the request agrees. + def request_session_id + @request_session_id ||= (Session.new_session_id if http?) + end + + # The row of the client this request comes from, see {ClientConversation}. + def client_row(request) + 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.' @@ -539,8 +598,10 @@ def envelope_meta end def client_identity(request) - info = envelope_client_info || session_client || server_client + info = envelope_client_info || session_client info = fetch(request_params(request), :clientInfo) if info.nil? && @kind == :initialize + # One instance serves every stateless HTTP client, so its handshake may be another client's. + info = server_client if info.nil? && !http? name = info.is_a?(Hash) ? fetch(info, :name) : nil version = info.is_a?(Hash) ? fetch(info, :version) : nil name ||= @token&.client_name @@ -673,7 +734,9 @@ def strip_injected_arguments(arguments, owned) stripped end - def mutate_tool(tool) + # A handle-free client's listing advertises no `conversation_id`, but the + # argument stays owned: other clients' listings still advertise it. + 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..f59881ec 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 @@ -24,9 +26,28 @@ def derive_session_id_from_conversation(conversation_id) Ids.deterministic_prefixed_id('ses', 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) + # `data.session_source` names what the server's own session came from; + # `$mcp_session_source` files a token and a transport id alike. + WIRE_SOURCES = { 'token' => 'transport', 'mcp' => 'transport' }.freeze + + # @return [String] the `$mcp_session_source` of the server's own session + def server_source(data) + WIRE_SOURCES.fetch(data.session_source, data.session_source) + end + + # A client conversation id and a handle name one chat, so they never touch + # the server's shared state: a concurrent request would read them. + # + # @param client_conversation [String, nil] `"<_meta key>:"`, see {ClientConversation.read} + # @param request_session_id [String, nil] the session a request that carries + # none gets on a transport every client shares; never stored either + # @return [Array(String, String)] `[session_id, source]`, the source as + # `$mcp_session_source` names it + 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 @@ -36,7 +57,7 @@ def resolve(data, mcp_session_id, token: nil, conversation_id: nil) data.session_id = token.session_id data.session_source = 'token' data.last_activity = now - return [data.session_id, 'token'] + return [data.session_id, 'transport'] end if present?(mcp_session_id) @@ -44,12 +65,14 @@ def resolve(data, mcp_session_id, token: nil, conversation_id: nil) data.last_mcp_session_id = mcp_session_id data.session_source = 'mcp' data.last_activity = now - return [data.session_id, 'mcp'] + return [data.session_id, 'transport'] 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'] + return [data.session_id, 'transport'] end stale = (now - data.last_activity) > (INACTIVITY_TIMEOUT_MINUTES * 60) 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..dc5a0323 --- /dev/null +++ b/spec/posthog/mcp/client_session_spec.rb @@ -0,0 +1,255 @@ +# 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 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 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 = JSON.parse(response[2].join) + 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)) + JSON.parse(response[2].join)['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 + + it 'gives every sessionless stateless HTTP request a fresh generated session' do + instrument(enable_conversation_id: false) + call_search + call_search(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) + end + + it 'labels a replayed token and a transport session id as transport' do + instrument(enable_conversation_id: false) + token = PostHog::MCP.encode_session_id(PostHog::MCP::SessionTokenPayload.new(session_id: 'ses_first')) + call_search(headers: { 'mcp-session-id' => token }) + + call = tool_calls.first + expect(call.values_at('$session_id', '$mcp_session_source')).to eq(%w[ses_first transport]) + 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 '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..d57f42b4 100644 --- a/spec/posthog/mcp/http_transport_spec.rb +++ b/spec/posthog/mcp/http_transport_spec.rb @@ -92,7 +92,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/identity_and_session_spec.rb b/spec/posthog/mcp/identity_and_session_spec.rb index 77a43232..5cf28e30 100644 --- a/spec/posthog/mcp/identity_and_session_spec.rb +++ b/spec/posthog/mcp/identity_and_session_spec.rb @@ -118,16 +118,17 @@ it 'uses a token session verbatim, hashes transport sessions stickily, and generates otherwise' do token = PostHog::MCP::SessionTokenPayload.new(session_id: 'ses_tok') - expect(described_class.resolve(data, 'ignored-raw', token: token)).to eq(%w[ses_tok token]) + expect(described_class.resolve(data, 'ignored-raw', token: token)).to eq(%w[ses_tok transport]) generated, source = described_class.resolve(data, nil) expect(source).to eq('generated') expect(generated).not_to eq('ses_tok') expect(described_class.resolve(data, 'mcp-123')).to eq([PostHog::MCP.derive_session_id_from_mcp_session('mcp-123'), - 'mcp']) + 'transport']) expect(described_class.resolve(data, - nil)).to eq([PostHog::MCP.derive_session_id_from_mcp_session('mcp-123'), 'mcp']) + nil)).to eq([PostHog::MCP.derive_session_id_from_mcp_session('mcp-123'), + 'transport']) end it 'rolls generated sessions over after 30 minutes of inactivity' do From 7ac02e091aeb9e10f89a54476efef701a12629ca Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 11:03:52 -0300 Subject: [PATCH 2/9] refactor(mcp): simplify session identity per /simplify review - Session.resolve keeps its internal sources; EventBuilder maps token and mcp to the wire's transport in one place. - ConversationId.resolve takes mint:, so a handle-free or client-id call never mints a handle it then discards. - Client recognition runs once per request; the client table uses validator lambdas, literal regexes and SchemaMutation.fetch. - Release and hold skip the server mutex when nothing is held. - env_for and parse move to the MCP spec helpers. Tested: bundle exec rspec (2612 examples, 0 failures), rubocop clean, rake public_api:check passes. --- lib/posthog/mcp/analytics.rb | 6 ++- lib/posthog/mcp/client_conversation.rb | 46 ++++++++----------- lib/posthog/mcp/conversation_id.rb | 6 ++- lib/posthog/mcp/event_builder.rb | 6 ++- lib/posthog/mcp/instrumentation.rb | 31 ++++++------- lib/posthog/mcp/session.rb | 19 ++------ spec/posthog/mcp/client_session_spec.rb | 15 +----- spec/posthog/mcp/http_transport_spec.rb | 15 ------ spec/posthog/mcp/identity_and_session_spec.rb | 7 ++- spec/posthog/mcp/spec_helper.rb | 17 +++++++ 10 files changed, 72 insertions(+), 96 deletions(-) diff --git a/lib/posthog/mcp/analytics.rb b/lib/posthog/mcp/analytics.rb index 893ed32b..87c6cf58 100644 --- a/lib/posthog/mcp/analytics.rb +++ b/lib/posthog/mcp/analytics.rb @@ -72,7 +72,7 @@ def flush # server only ever talks to one client, so the fallback stays. def current_session(data, scope) return scope.values_at(:session_id, :session_source) if scope&.[](:session_id) - return [data.session_id, Session.server_source(data)] unless data.http_transport_seen + return [data.session_id, data.session_source] unless data.http_transport_seen warn_unscoped_capture(data) [Session.new_session_id, 'generated'] @@ -82,8 +82,10 @@ def current_session(data, scope) # events until it records (see {Instrumentation#prime_session}). Each is fixed # when captured, its properties copied and its duration zero. def hold(data, scope, input) + return false unless scope&.key?(:held) + data.synchronize do - held = scope&.[](:held) + held = scope[:held] next false unless held if held.size < MAX_HELD_EVENTS diff --git a/lib/posthog/mcp/client_conversation.rb b/lib/posthog/mcp/client_conversation.rb index 3230ac2f..95bc0e89 100644 --- a/lib/posthog/mcp/client_conversation.rb +++ b/lib/posthog/mcp/client_conversation.rb @@ -13,34 +13,34 @@ module MCP # # @api private module ClientConversation - # `handle_free`: the client sends its id on every call, so it is advertised - # no `conversation_id` and minted no handle. - Row = Struct.new(:key, :value, :user_agent, :client_names, :handle_free, keyword_init: true) do + # `id` returns the id when a value is the row's shape. `handle_free`: the + # client sends its id on every call, so it is advertised no + # `conversation_id` and minted no handle. + 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 - - # @return [String, nil] the id in `meta` when it is this row's shape - def read(meta) - id = meta[key] || meta[key.to_sym] - ClientConversation.public_send(value, id) if id.is_a?(String) - 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/ - VSCODE_NAMES = ['Visual Studio Code', 'Visual Studio Code - Insiders'].freeze + + uuid = lambda do |value| + lowered = value.downcase + lowered if UUID.match?(lowered) && lowered != NIL_UUID + end ROWS = [ - Row.new(key: 'openai/session', value: :printable_ascii, handle_free: true, client_names: [], - user_agent: %r{\Aopenai-mcp/[^\s(]*\s*\(\s*chatgpt\s*[;,)]}i), - Row.new(key: 'sessionId', value: :uuid, handle_free: false, client_names: ['codex-mcp-client'], - user_agent: %r{\Acodex-mcp-client/}i), - Row.new(key: 'vscode.conversationId', value: :uuid, handle_free: false, client_names: VSCODE_NAMES, - user_agent: /\A(?:#{VSCODE_NAMES.map { |name| Regexp.escape("#{name}/") }.join('|')})/i) + 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 @@ -52,20 +52,10 @@ def recognize(user_agent, client_name) # @return [String, nil] `":"`, what the session is derived from def read(row, meta) - return nil unless row && meta.is_a?(Hash) - - id = row.read(meta) + value = row && SchemaMutation.fetch(meta, row.key) + id = row.id.call(value) if value.is_a?(String) id && "#{row.key}:#{id}" end - - def uuid(value) - lowered = value.downcase - lowered if UUID.match?(lowered) && lowered != NIL_UUID - end - - def printable_ascii(value) - value if PRINTABLE_ASCII.match?(value) - end end end end diff --git a/lib/posthog/mcp/conversation_id.rb b/lib/posthog/mcp/conversation_id.rb index a550ce8f..c2375493 100644 --- a/lib/posthog/mcp/conversation_id.rb +++ b/lib/posthog/mcp/conversation_id.rb @@ -37,14 +37,16 @@ def extract(args) # when this layer owns it. A tool that declares `conversation_id` in its # own schema is passed application data, which must not anchor analytics: # two users sharing such a value would be stitched into one conversation. + # @param mint [Boolean] false for a call that gets no handle of ours: a + # handle-free client's, or one already grouped by its client's own id # @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 bbb81737..7e784a56 100644 --- a/lib/posthog/mcp/event_builder.rb +++ b/lib/posthog/mcp/event_builder.rb @@ -8,6 +8,9 @@ module MCP # # @api private module EventBuilder + # A replayed token and a transport session id are both carried by the transport. + WIRE_SESSION_SOURCES = { 'token' => 'transport', 'mcp' => 'transport' }.freeze + module_function # @return [Array] payloads `{'event', 'distinct_id', 'properties', 'timestamp'}` @@ -44,7 +47,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? - properties[Property::SESSION_SOURCE] = event['session_source'] if event['session_source'] + 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 5fbd0d65..818c7c2d 100644 --- a/lib/posthog/mcp/instrumentation.rb +++ b/lib/posthog/mcp/instrumentation.rb @@ -151,17 +151,12 @@ def dispatch_tool_call # 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. request = request_with_arguments(original_arguments) - handle_free = safely(false) { client_row(request)&.handle_free } - @client_conversation = safely { ClientConversation.read(client_row(request), envelope_meta) } + handle_free = safely(false) { client_row&.handle_free } + @client_conversation = safely { ClientConversation.read(client_row, envelope_meta) } + # The client's own id outranks a handle the agent echoes. conversation_id, minted = safely([nil, false]) do - ConversationId.resolve(@options.enable_conversation_id, stripped[ConversationId::PARAM_NAME], name, - missing_name) - end - # The client's own id outranks a handle, and a handle-free client names its - # conversation itself, so neither is minted one. - if @client_conversation || (minted && handle_free) - conversation_id = nil - minted = false + ConversationId.resolve(@options.enable_conversation_id && !@client_conversation, + stripped[ConversationId::PARAM_NAME], name, missing_name, mint: !handle_free) end if virtual_tool?(name) @@ -241,7 +236,7 @@ def dispatch_tools_list if tools.is_a?(Array) names = tools.map { |tool| fetch(tool, :name) }.compact empty = tools.empty? - advertise_handle = !client_row(@request)&.handle_free + 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 @@ -486,6 +481,8 @@ def prime_session(request, conversation_id, hold_custom_events: false) # recorded, and let later ones (from threads the tool left running) go out # with it directly. Runs once per call; later runs find nothing held. def release_custom_events(session_id) + return unless @scope.key?(:held) + held = @data.synchronize do next nil unless @scope.key?(:held) @@ -494,10 +491,11 @@ def release_custom_events(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_for(session_id)) + actor: actor) end end @@ -554,10 +552,10 @@ def request_session_id end # The row of the client this request comes from, see {ClientConversation}. - def client_row(request) + def client_row return @client_row if defined?(@client_row) - @client_row = ClientConversation.recognize(@headers['user-agent'], client_identity(request)[0]) + @client_row = ClientConversation.recognize(@headers['user-agent'], client_identity(@request)[0]) end def warn_stateless_session_not_wired @@ -598,10 +596,9 @@ def envelope_meta end def client_identity(request) - info = envelope_client_info || session_client - info = fetch(request_params(request), :clientInfo) if info.nil? && @kind == :initialize # One instance serves every stateless HTTP client, so its handshake may be another client's. - info = server_client if info.nil? && !http? + 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 name ||= @token&.client_name diff --git a/lib/posthog/mcp/session.rb b/lib/posthog/mcp/session.rb index f59881ec..83f63f08 100644 --- a/lib/posthog/mcp/session.rb +++ b/lib/posthog/mcp/session.rb @@ -26,23 +26,14 @@ def derive_session_id_from_conversation(conversation_id) Ids.deterministic_prefixed_id('ses', conversation_id) end - # `data.session_source` names what the server's own session came from; - # `$mcp_session_source` files a token and a transport id alike. - WIRE_SOURCES = { 'token' => 'transport', 'mcp' => 'transport' }.freeze - - # @return [String] the `$mcp_session_source` of the server's own session - def server_source(data) - WIRE_SOURCES.fetch(data.session_source, data.session_source) - end - # A client conversation id and a handle name one chat, so they never touch # the server's shared state: a concurrent request would read them. # # @param client_conversation [String, nil] `"<_meta key>:"`, see {ClientConversation.read} # @param request_session_id [String, nil] the session a request that carries # none gets on a transport every client shares; never stored either - # @return [Array(String, String)] `[session_id, source]`, the source as - # `$mcp_session_source` names it + # @return [Array(String, String)] `[session_id, source]` where source is one of + # `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) @@ -57,7 +48,7 @@ def resolve(data, mcp_session_id, token: nil, conversation_id: nil, client_conve data.session_id = token.session_id data.session_source = 'token' data.last_activity = now - return [data.session_id, 'transport'] + return [data.session_id, 'token'] end if present?(mcp_session_id) @@ -65,14 +56,14 @@ def resolve(data, mcp_session_id, token: nil, conversation_id: nil, client_conve data.last_mcp_session_id = mcp_session_id data.session_source = 'mcp' data.last_activity = now - return [data.session_id, 'transport'] + 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, 'transport'] + return [data.session_id, 'mcp'] end stale = (now - data.last_activity) > (INACTIVITY_TIMEOUT_MINUTES * 60) diff --git a/spec/posthog/mcp/client_session_spec.rb b/spec/posthog/mcp/client_session_spec.rb index dc5a0323..ec5702a6 100644 --- a/spec/posthog/mcp/client_session_spec.rb +++ b/spec/posthog/mcp/client_session_spec.rb @@ -43,23 +43,12 @@ def instrument(**options) PostHogMcpSearchDocsTool.analytics = PostHog::MCP.instrument(server, client, **options) 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 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 = JSON.parse(response[2].join) + body = parse(response) raise body.inspect unless body['result'] body['result']['content'].map { |block| block['text'] } @@ -67,7 +56,7 @@ def call_search(user_agent: nil, meta: nil, arguments: { query: 'flags' }, heade def list_tools(user_agent) response = transport.call(env_for(rpc(9, 'tools/list'), 'user-agent' => user_agent)) - JSON.parse(response[2].join)['result']['tools'].to_h { |tool| [tool['name'], tool['inputSchema']['properties'].keys] } + parse(response)['result']['tools'].to_h { |tool| [tool['name'], tool['inputSchema']['properties'].keys] } end def tool_calls diff --git a/spec/posthog/mcp/http_transport_spec.rb b/spec/posthog/mcp/http_transport_spec.rb index d57f42b4..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) } diff --git a/spec/posthog/mcp/identity_and_session_spec.rb b/spec/posthog/mcp/identity_and_session_spec.rb index 5cf28e30..77a43232 100644 --- a/spec/posthog/mcp/identity_and_session_spec.rb +++ b/spec/posthog/mcp/identity_and_session_spec.rb @@ -118,17 +118,16 @@ it 'uses a token session verbatim, hashes transport sessions stickily, and generates otherwise' do token = PostHog::MCP::SessionTokenPayload.new(session_id: 'ses_tok') - expect(described_class.resolve(data, 'ignored-raw', token: token)).to eq(%w[ses_tok transport]) + expect(described_class.resolve(data, 'ignored-raw', token: token)).to eq(%w[ses_tok token]) generated, source = described_class.resolve(data, nil) expect(source).to eq('generated') expect(generated).not_to eq('ses_tok') expect(described_class.resolve(data, 'mcp-123')).to eq([PostHog::MCP.derive_session_id_from_mcp_session('mcp-123'), - 'transport']) + 'mcp']) expect(described_class.resolve(data, - nil)).to eq([PostHog::MCP.derive_session_id_from_mcp_session('mcp-123'), - 'transport']) + nil)).to eq([PostHog::MCP.derive_session_id_from_mcp_session('mcp-123'), 'mcp']) end it 'rolls generated sessions over after 30 minutes of inactivity' do diff --git a/spec/posthog/mcp/spec_helper.rb b/spec/posthog/mcp/spec_helper.rb index eee41f51..979d846f 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,22 @@ def rpc(id, method, params = nil) request end + # A Rack env for a POST to the Streamable HTTP transport. + 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 From 62080f3f68d90e380291b7064196e6b4ec8c531b Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 11:05:08 -0300 Subject: [PATCH 3/9] chore(mcp): drop comments the session identity code and specs already say Tested: bundle exec rspec spec/posthog/mcp (240 examples, 0 failures). --- lib/posthog/mcp/analytics.rb | 3 --- lib/posthog/mcp/client_conversation.rb | 14 ++------------ lib/posthog/mcp/conversation_id.rb | 2 -- lib/posthog/mcp/event_builder.rb | 1 - lib/posthog/mcp/instrumentation.rb | 15 --------------- lib/posthog/mcp/session.rb | 6 ------ spec/posthog/mcp/spec_helper.rb | 1 - 7 files changed, 2 insertions(+), 40 deletions(-) diff --git a/lib/posthog/mcp/analytics.rb b/lib/posthog/mcp/analytics.rb index 87c6cf58..d984433f 100644 --- a/lib/posthog/mcp/analytics.rb +++ b/lib/posthog/mcp/analytics.rb @@ -78,9 +78,6 @@ def current_session(data, scope) [Session.new_session_id, 'generated'] end - # A call whose session waits on delivering a minted handle holds its custom - # events until it records (see {Instrumentation#prime_session}). Each is fixed - # when captured, its properties copied and its duration zero. def hold(data, scope, input) return false unless scope&.key?(:held) diff --git a/lib/posthog/mcp/client_conversation.rb b/lib/posthog/mcp/client_conversation.rb index 95bc0e89..f2e25322 100644 --- a/lib/posthog/mcp/client_conversation.rb +++ b/lib/posthog/mcp/client_conversation.rb @@ -2,20 +2,12 @@ module PostHog module MCP - # Client conversation ids: the value an MCP client puts in a `tools/call` - # request's `_meta` to name the conversation the call belongs to. - # # {ROWS} is the table of the MCP analytics spec's "Session identity" - # requirement, row for row, in its order. A row's key is read only from a - # request its recognition rule matches, so a generic key such as Codex's - # `sessionId` is never read from a client that means something else by it. - # posthog-js and posthog-python keep the same table. + # requirement, row for row, in its order. posthog-js and posthog-python keep + # the same table. # # @api private module ClientConversation - # `id` returns the id when a value is the row's shape. `handle_free`: the - # client sends its id on every call, so it is advertised no - # `conversation_id` and minted no handle. 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) @@ -45,12 +37,10 @@ def recognizes?(user_agent, client_name) module_function - # @return [Row, nil] the first row that recognizes the request def recognize(user_agent, client_name) ROWS.find { |row| row.recognizes?(user_agent, client_name) } end - # @return [String, nil] `":"`, what the session is derived from def read(row, meta) value = row && SchemaMutation.fetch(meta, row.key) id = row.id.call(value) if value.is_a?(String) diff --git a/lib/posthog/mcp/conversation_id.rb b/lib/posthog/mcp/conversation_id.rb index c2375493..ca851962 100644 --- a/lib/posthog/mcp/conversation_id.rb +++ b/lib/posthog/mcp/conversation_id.rb @@ -37,8 +37,6 @@ def extract(args) # when this layer owns it. A tool that declares `conversation_id` in its # own schema is passed application data, which must not anchor analytics: # two users sharing such a value would be stitched into one conversation. - # @param mint [Boolean] false for a call that gets no handle of ours: a - # handle-free client's, or one already grouped by its client's own id # @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 diff --git a/lib/posthog/mcp/event_builder.rb b/lib/posthog/mcp/event_builder.rb index 7e784a56..57ad659f 100644 --- a/lib/posthog/mcp/event_builder.rb +++ b/lib/posthog/mcp/event_builder.rb @@ -8,7 +8,6 @@ module MCP # # @api private module EventBuilder - # A replayed token and a transport session id are both carried by the transport. WIRE_SESSION_SOURCES = { 'token' => 'transport', 'mcp' => 'transport' }.freeze module_function diff --git a/lib/posthog/mcp/instrumentation.rb b/lib/posthog/mcp/instrumentation.rb index 818c7c2d..5834dcd0 100644 --- a/lib/posthog/mcp/instrumentation.rb +++ b/lib/posthog/mcp/instrumentation.rb @@ -133,7 +133,6 @@ def dispatch_kind(&) else dispatch_generic(&) end ensure - # A call that recorded nothing still sends what it held, with the session it arrived with. safely { release_custom_events(@scope[:session_id]) } end @@ -153,7 +152,6 @@ def dispatch_tool_call request = request_with_arguments(original_arguments) handle_free = safely(false) { client_row&.handle_free } @client_conversation = safely { ClientConversation.read(client_row, envelope_meta) } - # The client's own id outranks a handle the agent echoes. 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) @@ -464,10 +462,6 @@ 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. - # - # A minted handle groups the call only once its result delivers it, so with - # `hold_custom_events` the body's custom events wait for - # {#release_custom_events} and go out with the session the call settles on. def prime_session(request, conversation_id, hold_custom_events: false) session_id = prepare_request(request, conversation_id: conversation_id) @data.synchronize do @@ -477,9 +471,6 @@ def prime_session(request, conversation_id, hold_custom_events: false) end end - # Send the custom events {#prime_session} held, with the session the call - # recorded, and let later ones (from threads the tool left running) go out - # with it directly. Runs once per call; later runs find nothing held. def release_custom_events(session_id) return unless @scope.key?(:held) @@ -544,14 +535,10 @@ def mint_session_token(client_name, client_version, protocol_version, requested_ payload end - # The session a request that carries none gets on stateless HTTP, where the - # server's own session would group every client it serves. Fixed per request, - # so each event of the request agrees. def request_session_id @request_session_id ||= (Session.new_session_id if http?) end - # The row of the client this request comes from, see {ClientConversation}. def client_row return @client_row if defined?(@client_row) @@ -731,8 +718,6 @@ def strip_injected_arguments(arguments, owned) stripped end - # A handle-free client's listing advertises no `conversation_id`, but the - # argument stays owned: other clients' listings still advertise it. def mutate_tool(tool, advertise_handle) return tool unless tool.is_a?(Hash) diff --git a/lib/posthog/mcp/session.rb b/lib/posthog/mcp/session.rb index 83f63f08..6d43e14e 100644 --- a/lib/posthog/mcp/session.rb +++ b/lib/posthog/mcp/session.rb @@ -26,12 +26,6 @@ def derive_session_id_from_conversation(conversation_id) Ids.deterministic_prefixed_id('ses', conversation_id) end - # A client conversation id and a handle name one chat, so they never touch - # the server's shared state: a concurrent request would read them. - # - # @param client_conversation [String, nil] `"<_meta key>:"`, see {ClientConversation.read} - # @param request_session_id [String, nil] the session a request that carries - # none gets on a transport every client shares; never stored either # @return [Array(String, String)] `[session_id, source]` where source is one of # `client_metadata`, `conversation`, `token`, `mcp`, `generated` def resolve(data, mcp_session_id, token: nil, conversation_id: nil, client_conversation: nil, diff --git a/spec/posthog/mcp/spec_helper.rb b/spec/posthog/mcp/spec_helper.rb index 979d846f..f433fe2a 100644 --- a/spec/posthog/mcp/spec_helper.rb +++ b/spec/posthog/mcp/spec_helper.rb @@ -21,7 +21,6 @@ def rpc(id, method, params = nil) request end - # A Rack env for a POST to the Streamable HTTP transport. def env_for(body, headers = {}) env = { 'REQUEST_METHOD' => 'POST', 'PATH_INFO' => '/', 'SCRIPT_NAME' => '', 'QUERY_STRING' => '', From e17ca52d742012e36f00f5c552b9de0365e89b65 Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 11:14:17 -0300 Subject: [PATCH 4/9] fix(mcp): close session identity gaps the pre-PR gate found - The client conversation id no longer reaches $mcp_parameters or $identify: the captured request drops the `_meta` key it was read from. - A 2026-07-28 stateless request's per-request gem session is not a transport session; it falls to rule 4 and is labelled generated. - A call with a carried session (token or transport id) is minted no handle, as in posthog-python. - A client id or echoed handle on stdio counts as connection activity, so the 30-minute rollover does not split a live connection. - $identify carries $mcp_session_source; dropping held custom events past the cap warns once instead of logging at debug. Tested: bundle exec rspec (2618 examples, 0 failures; 7 new examples failed first), rubocop clean, rake public_api:check passes. --- lib/posthog/mcp/analytics.rb | 7 ++- lib/posthog/mcp/instrumentation.rb | 26 ++++++-- lib/posthog/mcp/request_scope.rb | 5 +- lib/posthog/mcp/server_extension.rb | 3 +- lib/posthog/mcp/session.rb | 6 ++ spec/posthog/mcp/client_session_spec.rb | 84 ++++++++++++++++++++++--- 6 files changed, 110 insertions(+), 21 deletions(-) diff --git a/lib/posthog/mcp/analytics.rb b/lib/posthog/mcp/analytics.rb index d984433f..bd619a7e 100644 --- a/lib/posthog/mcp/analytics.rb +++ b/lib/posthog/mcp/analytics.rb @@ -87,9 +87,10 @@ def hold(data, scope, input) if held.size < MAX_HELD_EVENTS held << input.merge('properties' => input['properties'].dup, 'duration' => 0) - else - Log.debug(data.options, "analytics.capture(#{input['event_name']}) dropped: the call holds " \ - "#{MAX_HELD_EVENTS} events already") + elsif !scope[:dropped_held] + scope[:dropped_held] = true + Log.warn(data.options, "Warning: a tool call captured more than #{MAX_HELD_EVENTS} custom events " \ + 'before its conversation handle was delivered; dropping the rest') end true end diff --git a/lib/posthog/mcp/instrumentation.rb b/lib/posthog/mcp/instrumentation.rb index 5834dcd0..fcdd41ad 100644 --- a/lib/posthog/mcp/instrumentation.rb +++ b/lib/posthog/mcp/instrumentation.rb @@ -149,12 +149,13 @@ 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. - request = request_with_arguments(original_arguments) 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 && !@client_conversation, - stripped[ConversationId::PARAM_NAME], name, missing_name, mint: !handle_free) + stripped[ConversationId::PARAM_NAME], name, missing_name, + mint: !handle_free && !carries_session?) end if virtual_tool?(name) @@ -499,6 +500,7 @@ def prepare_request(request, conversation_id: nil, token: nil) 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 @@ -512,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 @@ -535,6 +540,10 @@ 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 @@ -565,9 +574,10 @@ 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 stateless transport's + # session is assigned afresh to every request, so it groups nothing. def mcp_session_id(token) - transport_id = @session.respond_to?(:session_id) ? @session.session_id : nil + transport_id = @session.session_id if @session.respond_to?(:session_id) && !@scope[:stateless] return transport_id if transport_id.is_a?(String) && !transport_id.empty? token ? nil : header_session_id @@ -641,8 +651,14 @@ def request_params(request) params.is_a?(Hash) ? params : {} end + # A client 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_conversation && 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 diff --git a/lib/posthog/mcp/request_scope.rb b/lib/posthog/mcp/request_scope.rb index 8abf7c28..6e483d3e 100644 --- a/lib/posthog/mcp/request_scope.rb +++ b/lib/posthog/mcp/request_scope.rb @@ -65,9 +65,10 @@ def header_name(env_key) # @param headers [Hash{String => String}] lowercase header names # @param transport [Symbol] `:http` for the Streamable HTTP transport, `:other` # for a transport that publishes no headers (stdio, a custom dispatcher) - def with(headers:, transport: :http) + # @param stateless [Boolean] the transport assigns each request a session of its own + def with(headers:, transport: :http, stateless: false) previous = current - self.current = { headers: headers, transport: transport, mint: nil, session_id: nil } + self.current = { headers: headers, transport: transport, stateless: stateless, mint: nil, session_id: nil } yield current ensure self.current = previous diff --git a/lib/posthog/mcp/server_extension.rb b/lib/posthog/mcp/server_extension.rb index 0975be8b..5b9866b7 100644 --- a/lib/posthog/mcp/server_extension.rb +++ b/lib/posthog/mcp/server_extension.rb @@ -39,7 +39,8 @@ def handle_request(request) env = request.respond_to?(:env) ? request.env : {} - RequestScope.with(headers: RequestScope.headers_from_env(env)) do |scope| + stateless = instance_variable_defined?(:@stateless) && @stateless + RequestScope.with(headers: RequestScope.headers_from_env(env), stateless: stateless) do |scope| response = super mint = scope[:mint] if mint && response.is_a?(Array) && response[1].is_a?(Hash) && diff --git a/lib/posthog/mcp/session.rb b/lib/posthog/mcp/session.rb index 6d43e14e..90ae4c3b 100644 --- a/lib/posthog/mcp/session.rb +++ b/lib/posthog/mcp/session.rb @@ -70,6 +70,12 @@ def resolve(data, mcp_session_id, token: nil, conversation_id: nil, client_conve 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 { data.last_activity = Time.now if data.session_source == 'generated' } + end + def present?(value) value.is_a?(String) && !value.empty? end diff --git a/spec/posthog/mcp/client_session_spec.rb b/spec/posthog/mcp/client_session_spec.rb index ec5702a6..4dfbe46a 100644 --- a/spec/posthog/mcp/client_session_spec.rb +++ b/spec/posthog/mcp/client_session_spec.rb @@ -162,25 +162,79 @@ def tool_calls expect(sessions.map { |session| session == CODEX_SESSION }).to eq([true, false, false]) end - it 'gives every sessionless stateless HTTP request a fresh generated session' do - instrument(enable_conversation_id: false) - call_search - call_search(id: 3) + { + '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) + 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 end - it 'labels a replayed token and a transport session id as transport' do - instrument(enable_conversation_id: false) + 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')) - call_search(headers: { 'mcp-session-id' => token }) + 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' }] + }.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 + + it 'counts a call with a client id as activity on a one-client connection' do + instrument(enable_conversation_id: false) + start = Time.now + stdio_call = lambda do |minutes, meta = nil| + allow(Time).to receive(:now).and_return(start + (minutes * 60)) + params = { name: 'search_docs', arguments: { query: 'flags' } } + params[:_meta] = meta if meta + server.handle(rpc(minutes, 'tools/call', params)) + end + server.handle(rpc(1, 'initialize', { protocolVersion: '2025-06-18', capabilities: {}, + clientInfo: { name: 'Visual Studio Code', version: '1' } })) + stdio_call.call(0) + vscode = { 'vscode.conversationId' => '3f1c2b7e-8d4a-4c6b-9a1e-5f2d7c8b9a0e' } + stdio_call.call(20, vscode) + stdio_call.call(40, vscode) + stdio_call.call(45) + + sessions = tool_calls.map { |call| call['$session_id'] } + expect(sessions.first).to eq(sessions.last) + 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']] } @@ -226,6 +280,16 @@ def call_sessions(events) expect(events_named(events, 'docs_searched').map { |event| event[:distinct_id] }).to eq(['user-1']) end + it 'warns once when a call holds more custom events than it keeps' 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(1000) + expect(logs.grep(/custom events/).size).to eq(1) + end + it 'carries the session the call recorded when the tool raises before delivering its handle' do instrument PostHogMcpSearchDocsTool.before_capture = lambda do From f0ddc0dd44ba177deb1d6d8b201dd9e147f58255 Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 11:14:25 -0300 Subject: [PATCH 5/9] docs(mcp): name the minting and stateless changes in the changeset --- .changeset/mcp-client-conversation-session.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/mcp-client-conversation-session.md b/.changeset/mcp-client-conversation-session.md index e33f7ec5..7f185cf9 100644 --- a/.changeset/mcp-client-conversation-session.md +++ b/.changeset/mcp-client-conversation-session.md @@ -2,4 +2,4 @@ "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`. ChatGPT is no longer advertised or minted a `conversation_id`. On stateless HTTP, a request that carries no session gets a `$session_id` of its own instead of the server's, 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. +`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`. ChatGPT is no longer advertised or minted a `conversation_id`, and neither is a call whose session the transport already carries. On stateless HTTP, a request that carries no session 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. From 8af6bc043dd3c58d719a851a8669edaf9d4dad31 Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 11:50:38 -0300 Subject: [PATCH 6/9] fix(mcp): treat every 2026-07-28 request as sessionless and roll stale stdio sessions From the second pre-PR gate round: - The gem gives each 2026-07-28 request a throwaway session on stateful transports too, so the era, not the transport's stateless flag, decides that its id is not a transport session. A sessionless modern call is minted a handle again; the stateless flag on RequestScope is gone. - A recognized client's `_meta` key is dropped from the captured request whatever its value, so an invalid id is not sent either. - A client-id or handle call on stdio after 30 idle minutes rolls the connection session instead of extending it. - The changeset names that callbacks lose the stripped `_meta` key. Tested: bundle exec rspec (2621 examples, 0 failures; the new stateful 2026-07-28 and stale-stdio examples failed first), rubocop clean, rake public_api:check passes. --- .changeset/mcp-client-conversation-session.md | 2 +- lib/posthog/mcp/instrumentation.rb | 12 +++-- lib/posthog/mcp/request_scope.rb | 5 +- lib/posthog/mcp/server_extension.rb | 3 +- lib/posthog/mcp/session.rb | 15 ++++-- spec/posthog/mcp/client_session_spec.rb | 51 ++++++++++++------- 6 files changed, 55 insertions(+), 33 deletions(-) diff --git a/.changeset/mcp-client-conversation-session.md b/.changeset/mcp-client-conversation-session.md index 7f185cf9..60de0c7b 100644 --- a/.changeset/mcp-client-conversation-session.md +++ b/.changeset/mcp-client-conversation-session.md @@ -2,4 +2,4 @@ "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`. ChatGPT is no longer advertised or minted a `conversation_id`, and neither is a call whose session the transport already carries. On stateless HTTP, a request that carries no session 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. +`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/instrumentation.rb b/lib/posthog/mcp/instrumentation.rb index fcdd41ad..956c6553 100644 --- a/lib/posthog/mcp/instrumentation.rb +++ b/lib/posthog/mcp/instrumentation.rb @@ -574,10 +574,12 @@ def header_session_id SessionToken.read_header(@headers) end - # The transport's own session id (never our token). A stateless transport's - # session is assigned afresh to every request, so it groups nothing. + # 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.session_id if @session.respond_to?(:session_id) && !@scope[:stateless] + 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 @@ -651,11 +653,11 @@ def request_params(request) params.is_a?(Hash) ? params : {} end - # A client conversation id only groups the call; its value is never sent. + # 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_conversation && meta + if client_row && meta params = params.merge(SchemaMutation.key_for(@params, :_meta) => meta.except(client_row.key, client_row.key.to_sym)) end diff --git a/lib/posthog/mcp/request_scope.rb b/lib/posthog/mcp/request_scope.rb index 6e483d3e..8abf7c28 100644 --- a/lib/posthog/mcp/request_scope.rb +++ b/lib/posthog/mcp/request_scope.rb @@ -65,10 +65,9 @@ def header_name(env_key) # @param headers [Hash{String => String}] lowercase header names # @param transport [Symbol] `:http` for the Streamable HTTP transport, `:other` # for a transport that publishes no headers (stdio, a custom dispatcher) - # @param stateless [Boolean] the transport assigns each request a session of its own - def with(headers:, transport: :http, stateless: false) + def with(headers:, transport: :http) previous = current - self.current = { headers: headers, transport: transport, stateless: stateless, mint: nil, session_id: nil } + self.current = { headers: headers, transport: transport, mint: nil, session_id: nil } yield current ensure self.current = previous diff --git a/lib/posthog/mcp/server_extension.rb b/lib/posthog/mcp/server_extension.rb index 5b9866b7..0975be8b 100644 --- a/lib/posthog/mcp/server_extension.rb +++ b/lib/posthog/mcp/server_extension.rb @@ -39,8 +39,7 @@ def handle_request(request) env = request.respond_to?(:env) ? request.env : {} - stateless = instance_variable_defined?(:@stateless) && @stateless - RequestScope.with(headers: RequestScope.headers_from_env(env), stateless: stateless) do |scope| + RequestScope.with(headers: RequestScope.headers_from_env(env)) do |scope| response = super mint = scope[:mint] if mint && response.is_a?(Array) && response[1].is_a?(Hash) && diff --git a/lib/posthog/mcp/session.rb b/lib/posthog/mcp/session.rb index 90ae4c3b..d3c4771b 100644 --- a/lib/posthog/mcp/session.rb +++ b/lib/posthog/mcp/session.rb @@ -60,8 +60,7 @@ def resolve(data, mcp_session_id, token: nil, conversation_id: nil, client_conve 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 @@ -73,7 +72,17 @@ def resolve(data, mcp_session_id, token: nil, conversation_id: nil, client_conve # 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 { data.last_activity = Time.now if data.session_source == 'generated' } + 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) diff --git a/spec/posthog/mcp/client_session_spec.rb b/spec/posthog/mcp/client_session_spec.rb index 4dfbe46a..ecb19989 100644 --- a/spec/posthog/mcp/client_session_spec.rb +++ b/spec/posthog/mcp/client_session_spec.rb @@ -180,6 +180,18 @@ def tool_calls 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 @@ -194,7 +206,8 @@ def tool_calls { 'ChatGPT' => [CHATGPT, { 'openai/session' => 'v1/conv-canary-0001' }], - 'Codex' => [CODEX, { 'sessionId' => '019a4f2e-1c3d-7b8a-9e0f-cafecafecafe' }] + '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' } }) @@ -214,25 +227,25 @@ def tool_calls expect(identify[:properties]['$mcp_session_source']).to eq('client_metadata') end - it 'counts a call with a client id as activity on a one-client connection' do - instrument(enable_conversation_id: false) - start = Time.now - stdio_call = lambda do |minutes, meta = nil| - allow(Time).to receive(:now).and_return(start + (minutes * 60)) - params = { name: 'search_docs', arguments: { query: 'flags' } } - params[:_meta] = meta if meta - server.handle(rpc(minutes, 'tools/call', params)) - end - server.handle(rpc(1, 'initialize', { protocolVersion: '2025-06-18', capabilities: {}, - clientInfo: { name: 'Visual Studio Code', version: '1' } })) - stdio_call.call(0) - vscode = { 'vscode.conversationId' => '3f1c2b7e-8d4a-4c6b-9a1e-5f2d7c8b9a0e' } - stdio_call.call(20, vscode) - stdio_call.call(40, vscode) - stdio_call.call(45) + { + '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).to eq(sessions.last) + 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 From 94b92c90d4a7eb4011b145a11ecdd09d7629b132 Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 11:52:07 -0300 Subject: [PATCH 7/9] fix(mcp): send custom events past the hold bound at once, as posthog-python does posthog-python #1193 (5308a74) stopped dropping held custom events past 1,000: the rest go out at once with the session the call has so far. Ruby now does the same and warns once. Tested: bundle exec rspec (2621 examples, 0 failures; the bound example failed first), rubocop clean. --- lib/posthog/mcp/analytics.rb | 12 ++++++++---- spec/posthog/mcp/client_session_spec.rb | 4 ++-- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/lib/posthog/mcp/analytics.rb b/lib/posthog/mcp/analytics.rb index bd619a7e..13483d6b 100644 --- a/lib/posthog/mcp/analytics.rb +++ b/lib/posthog/mcp/analytics.rb @@ -87,12 +87,16 @@ def hold(data, scope, input) if held.size < MAX_HELD_EVENTS held << input.merge('properties' => input['properties'].dup, 'duration' => 0) - elsif !scope[:dropped_held] - scope[:dropped_held] = true + next true + end + + unless scope[:overflowed_held] + scope[:overflowed_held] = true Log.warn(data.options, "Warning: a tool call captured more than #{MAX_HELD_EVENTS} custom events " \ - 'before its conversation handle was delivered; dropping the rest') + 'before its conversation handle was delivered; sending the rest with the ' \ + 'session the call has so far') end - true + false end end diff --git a/spec/posthog/mcp/client_session_spec.rb b/spec/posthog/mcp/client_session_spec.rb index ecb19989..eb6575b9 100644 --- a/spec/posthog/mcp/client_session_spec.rb +++ b/spec/posthog/mcp/client_session_spec.rb @@ -293,13 +293,13 @@ def call_sessions(events) expect(events_named(events, 'docs_searched').map { |event| event[:distinct_id] }).to eq(['user-1']) end - it 'warns once when a call holds more custom events than it keeps' do + 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(1000) + expect(events_named(drain_events(client), 'docs_searched').size).to eq(1001) expect(logs.grep(/custom events/).size).to eq(1) end From bb31d73d1447a5bae0d3043b1a001b5a36c04a0e Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 11:53:14 -0300 Subject: [PATCH 8/9] test(mcp): count the tool's own custom event past the hold bound Tested: bundle exec rspec (2621 examples, 0 failures). --- spec/posthog/mcp/client_session_spec.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/posthog/mcp/client_session_spec.rb b/spec/posthog/mcp/client_session_spec.rb index eb6575b9..120b3a39 100644 --- a/spec/posthog/mcp/client_session_spec.rb +++ b/spec/posthog/mcp/client_session_spec.rb @@ -299,7 +299,7 @@ def call_sessions(events) PostHogMcpSearchDocsTool.before_capture = -> { 1001.times { PostHogMcpSearchDocsTool.analytics.capture('docs_searched') } } call_search - expect(events_named(drain_events(client), 'docs_searched').size).to eq(1001) + expect(events_named(drain_events(client), 'docs_searched').size).to eq(1002) expect(logs.grep(/custom events/).size).to eq(1) end From 16df26ba1b15d9b517e18173eb4e2d868c174974 Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 14:37:34 -0300 Subject: [PATCH 9/9] fix(mcp): snapshot held custom events and bound their bytes PostHog Review on bb31d73: a held event copied only its top-level properties, so later changes to nested values reached it, and it kept the full object graph until the call ended. hold now runs the sink's stringify, sanitize and truncate steps at capture, so a held event is a deep snapshot of at most one event's size, and a call holds at most 4 MiB of them besides the 1,000-event cap. Past either bound the rest go out at once with the session the call has so far. Tested: bundle exec rspec (2623 examples, 0 failures; both new examples failed first), rubocop clean, rake public_api:check passes. --- lib/posthog/mcp/analytics.rb | 34 ++++++++++++++++++------- spec/posthog/mcp/client_session_spec.rb | 25 ++++++++++++++++++ 2 files changed, 50 insertions(+), 9 deletions(-) diff --git a/lib/posthog/mcp/analytics.rb b/lib/posthog/mcp/analytics.rb index 13483d6b..c9f2f686 100644 --- a/lib/posthog/mcp/analytics.rb +++ b/lib/posthog/mcp/analytics.rb @@ -8,7 +8,8 @@ module MCP # @note Experimental. class Analytics MAX_HELD_EVENTS = 1000 - private_constant :MAX_HELD_EVENTS + MAX_HELD_BYTES = 4 * 1024 * 1024 + private_constant :MAX_HELD_EVENTS, :MAX_HELD_BYTES # @api private def initialize(server) @@ -78,26 +79,41 @@ def current_session(data, scope) [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 - if held.size < MAX_HELD_EVENTS - held << input.merge('properties' => input['properties'].dup, 'duration' => 0) + 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 - unless scope[:overflowed_held] - scope[:overflowed_held] = true - Log.warn(data.options, "Warning: a tool call captured more than #{MAX_HELD_EVENTS} custom events " \ - 'before its conversation handle was delivered; sending the rest with the ' \ - 'session the call has so far') - 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/spec/posthog/mcp/client_session_spec.rb b/spec/posthog/mcp/client_session_spec.rb index 120b3a39..306823d9 100644 --- a/spec/posthog/mcp/client_session_spec.rb +++ b/spec/posthog/mcp/client_session_spec.rb @@ -303,6 +303,31 @@ def call_sessions(events) 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