From c679049c86a205f66b807d1ad0de982d6be2036d Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 15:58:33 -0300 Subject: [PATCH 1/3] fix(mcp): roll a stdio session over from the previous tool call's end The sdk-specs "Session identity" rule 3: a one-client connection's session is generated when it opens, and a new one goes to the first tool call that arrives 30 minutes or more after the previous tool call ended. Every event of a call uses the id resolved when the call arrived. - TrackingData generates the connection session at startup, so a custom event captured before any request has a $session_id. - Session.resolve never rotates. Session.rotate_if_idle runs when a tool call arrives (>= 30 minutes), and Session.end_tool_call stamps the end. Listings no longer refresh the clock, and the record step of a long call reuses the arrival session. Tested: bundle exec rspec (2629 examples, 0 failures; the new session_rotation_spec failed 4 of 6 first), rubocop clean. --- .changeset/mcp-session-rotation.md | 5 ++ lib/posthog/mcp/instrumentation.rb | 3 +- lib/posthog/mcp/session.rb | 32 +++---- lib/posthog/mcp/tracking_data.rb | 9 +- spec/posthog/mcp/identity_and_session_spec.rb | 13 ++- spec/posthog/mcp/session_rotation_spec.rb | 88 +++++++++++++++++++ 6 files changed, 121 insertions(+), 29 deletions(-) create mode 100644 .changeset/mcp-session-rotation.md create mode 100644 spec/posthog/mcp/session_rotation_spec.rb diff --git a/.changeset/mcp-session-rotation.md b/.changeset/mcp-session-rotation.md new file mode 100644 index 00000000..7b1453df --- /dev/null +++ b/.changeset/mcp-session-rotation.md @@ -0,0 +1,5 @@ +--- +"posthog-ruby": patch +--- + +On stdio, `PostHog::MCP` rolls the connection's `$session_id` over for the first tool call that arrives 30 minutes or more after the previous tool call ended. Listings no longer keep the session alive, and every event of a call keeps the session the call arrived with, however long it runs. A custom event captured before the first request now carries the connection's session. diff --git a/lib/posthog/mcp/instrumentation.rb b/lib/posthog/mcp/instrumentation.rb index 956c6553..2d096280 100644 --- a/lib/posthog/mcp/instrumentation.rb +++ b/lib/posthog/mcp/instrumentation.rb @@ -134,11 +134,13 @@ def dispatch_kind(&) end ensure safely { release_custom_events(@scope[:session_id]) } + Session.end_tool_call(@data) if @kind == :tools_call && !http? end # --- dispatchers ------------------------------------------------------- def dispatch_tool_call + Session.rotate_if_idle(@data) unless http? name = fetch(@params, :name) arguments = fetch(@params, :arguments) arguments = nil unless arguments.is_a?(Hash) @@ -500,7 +502,6 @@ 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 diff --git a/lib/posthog/mcp/session.rb b/lib/posthog/mcp/session.rb index d3c4771b..55aec898 100644 --- a/lib/posthog/mcp/session.rb +++ b/lib/posthog/mcp/session.rb @@ -36,12 +36,9 @@ def resolve(data, mcp_session_id, token: nil, conversation_id: nil, client_conve return [derive_session_id_from_conversation(conversation_id), 'conversation'] if present?(conversation_id) data.synchronize do - now = Time.now - if token data.session_id = token.session_id data.session_source = 'token' - data.last_activity = now return [data.session_id, 'token'] end @@ -49,40 +46,35 @@ def resolve(data, mcp_session_id, token: nil, conversation_id: nil, client_conve data.session_id = derive_session_id_from_mcp_session(mcp_session_id) data.last_mcp_session_id = mcp_session_id data.session_source = 'mcp' - data.last_activity = now return [data.session_id, 'mcp'] end return [request_session_id, 'generated'] if present?(request_session_id) - if data.session_source == 'mcp' && data.last_mcp_session_id - data.last_activity = now - return [data.session_id, 'mcp'] - end + return [data.session_id, 'mcp'] if data.session_source == 'mcp' && data.last_mcp_session_id - if data.session_source != 'generated' || stale?(data, now) || data.session_id.nil? + if data.session_source != 'generated' || data.session_id.nil? data.session_id = new_session_id data.session_source = 'generated' end - data.last_activity = now [data.session_id, 'generated'] 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) + # A one-client connection's session rolls over for the first tool call that + # arrives {INACTIVITY_TIMEOUT_MINUTES} or more after the previous one ended: + # a desktop app can keep one stdio process alive across many chats. + def rotate_if_idle(data) data.synchronize do - next unless data.session_source == 'generated' - - now = Time.now - data.session_id = new_session_id if stale?(data, now) - data.last_activity = now + idle = Time.now - data.last_tool_call_end + if data.session_source == 'generated' && idle >= INACTIVITY_TIMEOUT_MINUTES * 60 + data.session_id = new_session_id + end end end - def stale?(data, now) - (now - data.last_activity) > (INACTIVITY_TIMEOUT_MINUTES * 60) + def end_tool_call(data) + data.synchronize { data.last_tool_call_end = Time.now } end def present?(value) diff --git a/lib/posthog/mcp/tracking_data.rb b/lib/posthog/mcp/tracking_data.rb index 5196dadc..d01230bf 100644 --- a/lib/posthog/mcp/tracking_data.rb +++ b/lib/posthog/mcp/tracking_data.rb @@ -9,8 +9,8 @@ module MCP class TrackingData attr_reader :options, :sink, :server_name, :server_version, :identified_sessions, :tool_descriptions, :tool_categories, :tool_output_instructions, :tool_owned_params - attr_accessor :session_id, :session_source, :last_mcp_session_id, :last_activity, :warned_no_stateless_session, - :virtual_tool, :http_transport_seen, :warned_unscoped_capture + attr_accessor :session_id, :session_source, :last_mcp_session_id, :last_tool_call_end, + :warned_no_stateless_session, :virtual_tool, :http_transport_seen, :warned_unscoped_capture def initialize(options:, sink:, server_name: nil, server_version: nil) @options = options @@ -18,10 +18,11 @@ def initialize(options:, sink:, server_name: nil, server_version: nil) @server_name = server_name @server_version = server_version @mutex = Mutex.new - @session_id = nil + # A one-client connection's session, generated when the server starts. + @session_id = Session.new_session_id @session_source = 'generated' @last_mcp_session_id = nil - @last_activity = Time.now + @last_tool_call_end = Time.now @warned_no_stateless_session = false # Set once a request arrives over HTTP: from then on the server-wide session # is never a safe fallback for a capture that lost its request scope. diff --git a/spec/posthog/mcp/identity_and_session_spec.rb b/spec/posthog/mcp/identity_and_session_spec.rb index 77a43232..d1c82663 100644 --- a/spec/posthog/mcp/identity_and_session_spec.rb +++ b/spec/posthog/mcp/identity_and_session_spec.rb @@ -111,9 +111,12 @@ let(:data) { PostHog::MCP::TrackingData.new(options: PostHog::MCP::Options.new, sink: nil) } it 'anchors on an echoed conversation id without touching shared state' do + expect do + described_class.resolve(data, 'transport-session', conversation_id: '0198d3a7-1111-7222-8333-444455556666') + end + .not_to(change { data.session_id }) expect(described_class.resolve(data, 'transport-session', conversation_id: '0198d3a7-1111-7222-8333-444455556666')) .to eq(%w[ses_57a5f3768678e803a4af9566ca8a661b conversation]) - expect(data.session_id).to be_nil end it 'uses a token session verbatim, hashes transport sessions stickily, and generates otherwise' do @@ -130,14 +133,16 @@ 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 + it 'rolls only a generated session over, and only when asked after 30 idle minutes' do first, = described_class.resolve(data, nil) + data.last_tool_call_end = Time.now - (31 * 60) expect(described_class.resolve(data, nil)[0]).to eq(first) - data.last_activity = Time.now - (31 * 60) + described_class.rotate_if_idle(data) expect(described_class.resolve(data, nil)[0]).not_to eq(first) + token = PostHog::MCP::SessionTokenPayload.new(session_id: 'ses_tok') described_class.resolve(data, nil, token: token) - data.last_activity = Time.now - (31 * 60) + described_class.rotate_if_idle(data) expect(described_class.resolve(data, nil, token: token)[0]).to eq('ses_tok') end end diff --git a/spec/posthog/mcp/session_rotation_spec.rb b/spec/posthog/mcp/session_rotation_spec.rb new file mode 100644 index 00000000..df18056f --- /dev/null +++ b/spec/posthog/mcp/session_rotation_spec.rb @@ -0,0 +1,88 @@ +# frozen_string_literal: true + +require_relative 'spec_helper' + +class PostHogMcpRotationTool < MCP::Tool + tool_name 'search_docs' + input_schema(properties: { query: { type: 'string' } }) + class << self + attr_accessor :analytics, :during_call + + def call(**) + during_call&.call + analytics&.capture('docs_searched') + MCP::Tool::Response.new([{ type: 'text', text: 'found' }]) + end + end +end + +RSpec.describe 'PostHog::MCP one-client connection sessions' do + let(:client) { new_test_client } + let(:server) { MCP::Server.new(name: 'stdio-server', version: '1.0.0', tools: [PostHogMcpRotationTool]) } + let(:start) { Time.now } + + before do + PostHogMcpRotationTool.analytics = PostHog::MCP.instrument(server, client, enable_conversation_id: false) + PostHogMcpRotationTool.during_call = nil + end + + after { PostHogMcpRotationTool.during_call = nil } + + def at(minute) + allow(Time).to receive(:now).and_return(start + (minute * 60)) + end + + def call_tool(id, meta: nil) + params = { name: 'search_docs', arguments: { query: 'flags' } } + params[:_meta] = meta if meta + server.handle(rpc(id, 'tools/call', params)) + end + + def sessions_of(name) + events_named(drain_events(client), name).map { |event| event[:properties]['$session_id'] } + end + + # Each step is [minute, request]; the expectation says which tool calls share a session. + { + 'keeps the session while calls come less than 30 minutes apart' => [[[0, :call], [29, :call]], [0, 0]], + 'rolls the session over at exactly 30 idle minutes' => [[[0, :call], [30, :call]], [0, 1]], + 'counts idle time from tool calls only, not listings' => [[[0, :call], [20, :list], [35, :call]], [0, 1]], + 'counts idle time from when the previous call ended' => [[[0, :long_call], [41, :call]], [0, 0]] + }.each do |behavior, (steps, groups)| + it behavior do + steps.each_with_index do |(minute, request), index| + at(minute) + case request + when :call then call_tool(index + 1) + when :list then server.handle(rpc(index + 1, 'tools/list')) + when :long_call + PostHogMcpRotationTool.during_call = -> { at(minute + 40) } + call_tool(index + 1) + PostHogMcpRotationTool.during_call = nil + end + end + + sessions = sessions_of('$mcp_tool_call') + expect(sessions.map { |session| sessions.uniq.index(session) }).to eq(groups) + end + end + + it 'keeps the session a call arrived with for every event of a call that outlasts the idle limit' do + at(0) + PostHogMcpRotationTool.during_call = -> { at(40) } + call_tool(1) + + events = drain_events(client) + expect(events.map { |event| event[:properties]['$session_id'] }.uniq.size).to eq(1) + end + + it 'gives a custom event captured before any request the connection\'s session' do + PostHogMcpRotationTool.analytics.capture('server_started') + call_tool(1) + + events = drain_events(client) + started = events_named(events, 'server_started').first[:properties] + expect(started.values_at('$session_id', '$mcp_session_source')) + .to eq([events_named(events, '$mcp_tool_call').first[:properties]['$session_id'], 'generated']) + end +end From b9d192e72693b5d760836eb12bfe6bcee6b3c0c0 Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 16:12:39 -0300 Subject: [PATCH 2/3] refactor(mcp): drop the unreachable nil session guard and flatten rotate_if_idle /simplify on the stack: TrackingData now always starts with a session, so resolve's nil check never fires. Tested: bundle exec rspec spec/posthog/mcp (257 examples, 0 failures). --- lib/posthog/mcp/session.rb | 9 ++++----- lib/posthog/mcp/tracking_data.rb | 1 - 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/lib/posthog/mcp/session.rb b/lib/posthog/mcp/session.rb index 55aec898..6a1157a1 100644 --- a/lib/posthog/mcp/session.rb +++ b/lib/posthog/mcp/session.rb @@ -53,7 +53,7 @@ def resolve(data, mcp_session_id, token: nil, conversation_id: nil, client_conve return [data.session_id, 'mcp'] if data.session_source == 'mcp' && data.last_mcp_session_id - if data.session_source != 'generated' || data.session_id.nil? + if data.session_source != 'generated' data.session_id = new_session_id data.session_source = 'generated' end @@ -66,10 +66,9 @@ def resolve(data, mcp_session_id, token: nil, conversation_id: nil, client_conve # a desktop app can keep one stdio process alive across many chats. def rotate_if_idle(data) data.synchronize do - idle = Time.now - data.last_tool_call_end - if data.session_source == 'generated' && idle >= INACTIVITY_TIMEOUT_MINUTES * 60 - data.session_id = new_session_id - end + next unless data.session_source == 'generated' + + data.session_id = new_session_id if Time.now - data.last_tool_call_end >= INACTIVITY_TIMEOUT_MINUTES * 60 end end diff --git a/lib/posthog/mcp/tracking_data.rb b/lib/posthog/mcp/tracking_data.rb index d01230bf..c762044c 100644 --- a/lib/posthog/mcp/tracking_data.rb +++ b/lib/posthog/mcp/tracking_data.rb @@ -18,7 +18,6 @@ def initialize(options:, sink:, server_name: nil, server_version: nil) @server_name = server_name @server_version = server_version @mutex = Mutex.new - # A one-client connection's session, generated when the server starts. @session_id = Session.new_session_id @session_source = 'generated' @last_mcp_session_id = nil From 8e85a7205eb780562fce7b382f3e38f3fe725ee4 Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 16:31:41 -0300 Subject: [PATCH 3/3] fix(mcp): keep a stdio session through the first call and under a running call Pre-PR gate (both adversaries): the startup clock counted as a previous call's end, so a first tool call 30 minutes after startup rotated; and a call arriving while another ran could rotate and re-file the running call's events. Rotation now needs an ended previous call and no call in flight (Session.start_tool_call / end_tool_call keep the count). Tested: bundle exec rspec spec/posthog/mcp (259 examples, 0 failures; both new session_rotation_spec examples failed first). --- lib/posthog/mcp/instrumentation.rb | 2 +- lib/posthog/mcp/session.rb | 21 ++++++++++------- lib/posthog/mcp/tracking_data.rb | 5 ++-- spec/posthog/mcp/identity_and_session_spec.rb | 4 ++-- spec/posthog/mcp/session_rotation_spec.rb | 23 +++++++++++++++++++ 5 files changed, 42 insertions(+), 13 deletions(-) diff --git a/lib/posthog/mcp/instrumentation.rb b/lib/posthog/mcp/instrumentation.rb index 2d096280..175ae342 100644 --- a/lib/posthog/mcp/instrumentation.rb +++ b/lib/posthog/mcp/instrumentation.rb @@ -140,7 +140,7 @@ def dispatch_kind(&) # --- dispatchers ------------------------------------------------------- def dispatch_tool_call - Session.rotate_if_idle(@data) unless http? + Session.start_tool_call(@data) unless http? name = fetch(@params, :name) arguments = fetch(@params, :arguments) arguments = nil unless arguments.is_a?(Hash) diff --git a/lib/posthog/mcp/session.rb b/lib/posthog/mcp/session.rb index 6a1157a1..edf060c6 100644 --- a/lib/posthog/mcp/session.rb +++ b/lib/posthog/mcp/session.rb @@ -61,19 +61,24 @@ def resolve(data, mcp_session_id, token: nil, conversation_id: nil, client_conve end end - # A one-client connection's session rolls over for the first tool call that - # arrives {INACTIVITY_TIMEOUT_MINUTES} or more after the previous one ended: - # a desktop app can keep one stdio process alive across many chats. - def rotate_if_idle(data) + # A desktop app can keep one stdio process alive across many chats. + def start_tool_call(data) data.synchronize do - next unless data.session_source == 'generated' - - data.session_id = new_session_id if Time.now - data.last_tool_call_end >= INACTIVITY_TIMEOUT_MINUTES * 60 + data.session_id = new_session_id if data.session_source == 'generated' && idle?(data) + data.tool_calls_in_flight += 1 end end def end_tool_call(data) - data.synchronize { data.last_tool_call_end = Time.now } + data.synchronize do + data.tool_calls_in_flight -= 1 + data.last_tool_call_end = Time.now + end + end + + def idle?(data) + data.tool_calls_in_flight.zero? && !data.last_tool_call_end.nil? && + Time.now - data.last_tool_call_end >= INACTIVITY_TIMEOUT_MINUTES * 60 end def present?(value) diff --git a/lib/posthog/mcp/tracking_data.rb b/lib/posthog/mcp/tracking_data.rb index c762044c..9993da90 100644 --- a/lib/posthog/mcp/tracking_data.rb +++ b/lib/posthog/mcp/tracking_data.rb @@ -9,7 +9,7 @@ module MCP class TrackingData attr_reader :options, :sink, :server_name, :server_version, :identified_sessions, :tool_descriptions, :tool_categories, :tool_output_instructions, :tool_owned_params - attr_accessor :session_id, :session_source, :last_mcp_session_id, :last_tool_call_end, + attr_accessor :session_id, :session_source, :last_mcp_session_id, :last_tool_call_end, :tool_calls_in_flight, :warned_no_stateless_session, :virtual_tool, :http_transport_seen, :warned_unscoped_capture def initialize(options:, sink:, server_name: nil, server_version: nil) @@ -21,7 +21,8 @@ def initialize(options:, sink:, server_name: nil, server_version: nil) @session_id = Session.new_session_id @session_source = 'generated' @last_mcp_session_id = nil - @last_tool_call_end = Time.now + @last_tool_call_end = nil + @tool_calls_in_flight = 0 @warned_no_stateless_session = false # Set once a request arrives over HTTP: from then on the server-wide session # is never a safe fallback for a capture that lost its request scope. diff --git a/spec/posthog/mcp/identity_and_session_spec.rb b/spec/posthog/mcp/identity_and_session_spec.rb index d1c82663..03ac1574 100644 --- a/spec/posthog/mcp/identity_and_session_spec.rb +++ b/spec/posthog/mcp/identity_and_session_spec.rb @@ -137,12 +137,12 @@ first, = described_class.resolve(data, nil) data.last_tool_call_end = Time.now - (31 * 60) expect(described_class.resolve(data, nil)[0]).to eq(first) - described_class.rotate_if_idle(data) + described_class.start_tool_call(data) expect(described_class.resolve(data, nil)[0]).not_to eq(first) token = PostHog::MCP::SessionTokenPayload.new(session_id: 'ses_tok') described_class.resolve(data, nil, token: token) - described_class.rotate_if_idle(data) + described_class.start_tool_call(data) expect(described_class.resolve(data, nil, token: token)[0]).to eq('ses_tok') end end diff --git a/spec/posthog/mcp/session_rotation_spec.rb b/spec/posthog/mcp/session_rotation_spec.rb index df18056f..13e66ac8 100644 --- a/spec/posthog/mcp/session_rotation_spec.rb +++ b/spec/posthog/mcp/session_rotation_spec.rb @@ -76,6 +76,29 @@ def sessions_of(name) expect(events.map { |event| event[:properties]['$session_id'] }.uniq.size).to eq(1) end + it 'keeps the startup session for the first tool call, however late it arrives' do + at(0) + server.handle(rpc(1, 'tools/list')) + at(31) + call_tool(2) + + expect(drain_events(client).map { |event| event[:properties]['$session_id'] }.uniq.size).to eq(1) + end + + it 'never rolls the session over under a call still running' do + at(0) + call_tool(1) + at(1) + PostHogMcpRotationTool.during_call = lambda do + PostHogMcpRotationTool.during_call = nil + at(31) + call_tool(3) + end + call_tool(2) + + expect(drain_events(client).map { |event| event[:properties]['$session_id'] }.uniq.size).to eq(1) + end + it 'gives a custom event captured before any request the connection\'s session' do PostHogMcpRotationTool.analytics.capture('server_started') call_tool(1)