Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/mcp-session-rotation.md
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 2 additions & 1 deletion lib/posthog/mcp/instrumentation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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.start_tool_call(@data) unless http?
name = fetch(@params, :name)
arguments = fetch(@params, :arguments)
arguments = nil unless arguments.is_a?(Hash)
Expand Down Expand Up @@ -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
Expand Down
34 changes: 15 additions & 19 deletions lib/posthog/mcp/session.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,53 +36,49 @@ 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

if present?(mcp_session_id)
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 = 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 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 data.session_source == 'generated' && idle?(data)
data.tool_calls_in_flight += 1
end
end

now = Time.now
data.session_id = new_session_id if stale?(data, now)
data.last_activity = now
def end_tool_call(data)
data.synchronize do
data.tool_calls_in_flight -= 1
data.last_tool_call_end = Time.now
end
end

def stale?(data, now)
(now - data.last_activity) > (INACTIVITY_TIMEOUT_MINUTES * 60)
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)
Expand Down
9 changes: 5 additions & 4 deletions lib/posthog/mcp/tracking_data.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,20 @@ 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, :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)
@options = options
@sink = sink
@server_name = server_name
@server_version = server_version
@mutex = Mutex.new
@session_id = nil
@session_id = Session.new_session_id
@session_source = 'generated'
@last_mcp_session_id = nil
@last_activity = 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.
Expand Down
13 changes: 9 additions & 4 deletions spec/posthog/mcp/identity_and_session_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.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)
data.last_activity = Time.now - (31 * 60)
described_class.start_tool_call(data)
expect(described_class.resolve(data, nil, token: token)[0]).to eq('ses_tok')
end
end
111 changes: 111 additions & 0 deletions spec/posthog/mcp/session_rotation_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
# 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 '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)

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