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-no-standalone-identify.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"posthog-ruby": minor
---

`PostHog::MCP` no longer sends a standalone `$identify` event. Every event already carries the identity your `identify` option resolves, as its `distinct_id`, `$set`, and `$groups`, and `$exception` now carries `$set` too.
2 changes: 0 additions & 2 deletions lib/posthog/mcp/constants.rb
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ module Property
# @api private
module EventType
CUSTOM = 'posthog:custom'
IDENTIFY = 'posthog:identify'
MCP_INITIALIZE = 'mcp:initialize'
MCP_MISSING_CAPABILITY = 'mcp:missing_capability'
MCP_PROMPTS_GET = 'mcp:prompts/get'
Expand All @@ -94,7 +93,6 @@ module EventType

EVENT_NAME_BY_TYPE = {
CUSTOM => Event::CUSTOM,
IDENTIFY => Event::IDENTIFY,
MCP_INITIALIZE => Event::INITIALIZE,
MCP_MISSING_CAPABILITY => Event::MISSING_CAPABILITY,
MCP_PROMPTS_GET => Event::PROMPT_GET,
Expand Down
5 changes: 5 additions & 0 deletions lib/posthog/mcp/event_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,10 @@ def add_common_properties(event, properties)
add_error_details(event, properties) if event['is_error']
properties[Property::PARAMETERS] = event['parameters'] unless event['parameters'].nil?
properties[Property::RESPONSE] = event['response'] unless event['response'].nil?
add_person_properties(event, properties)
end

def add_person_properties(event, properties)
actor_data = event['identify_actor_data']
properties['$set'] = actor_data.dup if actor_data.is_a?(Hash) && !actor_data.empty?
end
Expand All @@ -132,6 +136,7 @@ def build_exception_event(event)
add_session_id(event, properties)
add_conversation_id(event, properties)
add_person_processing(event, properties)
add_person_properties(event, properties)
add_groups(event, properties)

error = event['error']
Expand Down
99 changes: 14 additions & 85 deletions lib/posthog/mcp/identity.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,19 +31,16 @@ def set(session_id, identity)
end
end

# Atomically read the cached identity, merge the new one, store it, and
# report whether it changed. Keeps concurrent requests for one session
# from interleaving their read-merge-write.
# Atomically read the cached identity, merge the new one, and store it.
# Keeps concurrent requests for one session from interleaving their
# read-merge-write.
#
# @return [Array(UserIdentity, Boolean)] `[merged, changed]`
# @return [UserIdentity] the merged identity
def merge!(session_id, identity)
@mutex.synchronize do
previous = @cache.delete(session_id)
merged = Identity.merge_identities(previous, identity)
changed = !(previous && Identity.identities_equal?(previous, merged))
merged = Identity.merge_identities(@cache.delete(session_id), identity)
@cache.shift if @cache.length >= @max_size
@cache[session_id] = merged
[merged, changed]
end
end

Expand All @@ -56,31 +53,13 @@ def size
end
end

# Identity resolution: runs the `identify` option, dedupes against the
# per-server cache, and decides when a standalone `$identify` event fires.
# Identity resolution: runs the `identify` option and merges the result into
# the per-server cache.
#
# @api private
module Identity
module_function

def identities_equal?(first, second)
return false if first.distinct_id != second.distinct_id
return false if sorted_json(first.groups || {}) != sorted_json(second.groups || {})

a_props = first.properties || {}
b_props = second.properties || {}
return false if a_props.keys.map(&:to_s).sort != b_props.keys.map(&:to_s).sort

a_props.all? do |key, value|
other = if b_props.key?(key)
b_props[key]
else
b_props[key.is_a?(Symbol) ? key.to_s : key.to_s.to_sym]
end
sorted_json(value) == sorted_json(other)
end
end

def merge_identities(previous, nxt)
return nxt if previous.nil?

Expand All @@ -92,8 +71,7 @@ def merge_identities(previous, nxt)
end

# Resolve the optional `identify` callback for one request: the identity the
# request's events belong to, plus an `$identify` event to emit only when
# that identity has materially changed.
# request's events belong to.
#
# The actor is handed back rather than left for the caller to read out of
# {IdentityCache} later. The cache is keyed by session, and a request's
Expand All @@ -102,10 +80,10 @@ def merge_identities(previous, nxt)
# When resolution yields nothing the cache is read once, here, so whatever
# a request is attributed to it is attributed to consistently.
#
# @return [Array(Hash, UserIdentity), Array(nil, UserIdentity), Array(nil, nil)] `[event, actor]`
def identify_for_request(data, session_id, request, extra)
# @return [UserIdentity, nil]
def resolve(data, session_id, request, extra)
identify = data.options.identify
return [nil, nil] unless identify
return nil unless identify

result = if identify.is_a?(UserIdentity) || identify.is_a?(Hash)
identify
Expand All @@ -116,62 +94,13 @@ def identify_for_request(data, session_id, request, extra)
identity = UserIdentity.coerce(result)
unless identity
Log.debug(data.options, "Warning: Supplied identify function returned null for session #{session_id}")
return [nil, data.identified_sessions.get(session_id)]
return data.identified_sessions.get(session_id)
end

merged, changed = data.identified_sessions.merge!(session_id, identity)
return [nil, merged] unless changed

Log.debug(data.options, "Identified session #{session_id}")
[{
'session_id' => session_id,
'resource_name' => request_resource_name(request),
'event_type' => EventType::IDENTIFY,
'parameters' => { 'request' => request, 'extra' => captured_extra(extra) },
'timestamp' => Time.now.utc
}, merged]
data.identified_sessions.merge!(session_id, identity)
rescue StandardError => e
Log.debug(data.options, "Error: identify function threw while identifying session #{session_id} - #{e.message}")
[nil, data.identified_sessions.get(session_id)]
end

# @return [Hash, nil] the `$identify` event alone; see {identify_for_request}.
def handle_identify(data, session_id, request, extra)
identify_for_request(data, session_id, request, extra).first
end

def request_resource_name(request)
return 'Unknown' unless request.is_a?(Hash)

params = request[:params] || request['params']
return 'Unknown' unless params.is_a?(Hash)

name = params[:name] || params['name']
name.is_a?(String) ? name : 'Unknown'
end

# Only JSON scalars from `extra` are captured; never opaque transport objects.
def captured_extra(extra)
return nil unless extra.is_a?(Hash)

extra.select do |_, value|
value.nil? || value.is_a?(String) || value.is_a?(Numeric) || value == true || value == false
end
end

def sorted_json(value)
JSON.generate(sort_deep(value))
rescue StandardError
value.to_s
end

def sort_deep(value)
case value
when Hash then value.map { |k, v| [k.to_s, sort_deep(v)] }.sort_by(&:first).to_h
when Array then value.map { |v| sort_deep(v) }
when String, Numeric, true, false, nil then value
else value.to_s
end
data.identified_sessions.get(session_id)
end
end

Expand Down
6 changes: 1 addition & 5 deletions lib/posthog/mcp/instrumentation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -508,17 +508,13 @@ def prepare_request(request, conversation_id: nil, token: nil)
# `identify` callback runs once per session per request, so preparing
# twice never asks it the same question twice.
unless @identified_in_request.key?(session_id)
identify_event, actor = Identity.identify_for_request(@data, session_id, request, extra)
actor = Identity.resolve(@data, session_id, request, extra)
# Pin what this request resolved. Every event it emits afterwards -
# including one a tool body captures through {Analytics} - is attributed
# to this, never to a re-read of the cache another request may have
# overwritten while the handler ran.
@identified_in_request[session_id] = actor
@scope[:actor] = actor if @scope.is_a?(Hash)
if identify_event
self.class.capture_event(@data, identify_event.merge('session_source' => source),
actor: actor)
end
end
session_id
end
Expand Down
8 changes: 0 additions & 8 deletions spec/posthog/mcp/client_session_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -219,14 +219,6 @@ def tool_calls
end
end

it 'labels the $identify event with the session source' do
instrument(identify: ->(_request, _extra) { { distinct_id: 'user-1' } })
call_search(user_agent: CHATGPT, meta: { 'openai/session' => 'v1/conv-example-0001' })

identify = events_named(drain_events(client), '$identify').first
expect(identify[:properties]['$mcp_session_source']).to eq('client_metadata')
end

{
'keeps a connection session a client-id call kept active' => [[0, 20, 40, 45], true],
'rolls a connection session over after 30 idle minutes, even under a client-id call' => [[0, 40, 41], false]
Expand Down
2 changes: 1 addition & 1 deletion spec/posthog/mcp/event_builder_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def error_for(message, type)

it 'maps every event type and sends custom names verbatim' do
{
'posthog:custom' => '$mcp_custom', 'posthog:identify' => '$identify', 'mcp:tools/call' => '$mcp_tool_call',
'posthog:custom' => '$mcp_custom', 'mcp:tools/call' => '$mcp_tool_call',
'mcp:tools/list' => '$mcp_tools_list', 'mcp:initialize' => '$mcp_initialize',
'mcp:resources/read' => '$mcp_resource_read', 'mcp:resources/list' => '$mcp_resources_list',
'mcp:prompts/get' => '$mcp_prompt_get', 'mcp:prompts/list' => '$mcp_prompts_list',
Expand Down
1 change: 0 additions & 1 deletion spec/posthog/mcp/http_transport_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,6 @@ def initialize_body(id = 1, version = '2025-06-18')

events = drain_events(client)
expect(events_named(events, '$mcp_tool_call').map { |e| e[:distinct_id] }).to eq(['user-1'])
expect(events_named(events, '$identify').size).to eq(1)
expect(events.map { |e| JSON.generate(e) }.grep(/#{secret}/)).to eq([])
end
end
Expand Down
75 changes: 25 additions & 50 deletions spec/posthog/mcp/identity_and_session_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,68 +8,43 @@
let(:identify) { ->(_request, _extra) { { distinct_id: 'user-1', properties: { role: 'developer' } } } }
let(:request) { { method: 'tools/call', params: { name: 'add_todo', arguments: {} } } }

it 'fires $identify once per session and again only on material change' do
event = described_class.handle_identify(data, 'ses_1', request, { 'session_id' => 'abc', 'session' => Object.new })
expect(event['event_type']).to eq('posthog:identify')
expect(event['resource_name']).to eq('add_todo')
expect(event['parameters']['extra']).to eq('session_id' => 'abc')
expect(described_class.handle_identify(data, 'ses_1', request, nil)).to be_nil
expect(data.identified_sessions.get('ses_1').to_h).to eq(distinct_id: 'user-1', properties: { role: 'developer' },
groups: nil)
it 'merges a later identity for the session into the cached one' do
expect(described_class.resolve(data, 'ses_1', request, nil).to_h)
.to eq(distinct_id: 'user-1', properties: { role: 'developer' }, groups: nil)

data.options.instance_variable_set(:@identify, ->(_r, _e) { { distinct_id: 'user-2', groups: { org: 'o' } } })
changed = described_class.handle_identify(data, 'ses_1', request, nil)
expect(changed).not_to be_nil
merged = data.identified_sessions.get('ses_1')
expect(merged.distinct_id).to eq('user-2')
expect(merged.properties).to eq(role: 'developer')
expect(merged.groups).to eq(org: 'o')
expect(described_class.resolve(data, 'ses_1', request, nil).to_h)
.to eq(distinct_id: 'user-2', properties: { role: 'developer' }, groups: { org: 'o' })
end

it 'accepts static identities, 1-arity callables, and swallows errors and nils' do
static = PostHog::MCP::TrackingData.new(options: PostHog::MCP::Options.new(identify: { distinct_id: 'static' }),
sink: nil)
expect(described_class.handle_identify(static, 'ses_1', request, nil)['session_id']).to eq('ses_1')
one = PostHog::MCP::TrackingData.new(options: PostHog::MCP::Options.new(identify: lambda { |req|
{ distinct_id: req[:params][:name] }
}), sink: nil)
described_class.handle_identify(one, 'ses_1', request, nil)
expect(one.identified_sessions.get('ses_1').distinct_id).to eq('add_todo')
boom = PostHog::MCP::TrackingData.new(options: PostHog::MCP::Options.new(identify: lambda { |_r, _e|
raise 'nope'
}), sink: nil)
expect(described_class.handle_identify(boom, 'ses_1', request, nil)).to be_nil
nils = PostHog::MCP::TrackingData.new(options: PostHog::MCP::Options.new(identify: ->(_r, _e) {}), sink: nil)
expect(described_class.handle_identify(nils, 'ses_1', request, nil)).to be_nil
{
'a static identity' => [{ distinct_id: 'static' }, 'static'],
'a 1-arity callable' => [->(req) { { distinct_id: req[:params][:name] } }, 'add_todo'],
'a callable that raises' => [->(_r, _e) { raise 'nope' }, nil],
'a callable that returns nil' => [->(_r, _e) {}, nil],
'no identify option' => [nil, nil]
}.each do |kind, (identify_option, distinct_id)|
it "resolves #{kind}" do
one = PostHog::MCP::TrackingData.new(options: PostHog::MCP::Options.new(identify: identify_option), sink: nil)
expect(described_class.resolve(one, 'ses_1', request, nil)&.distinct_id).to eq(distinct_id)
end
end

it 'hands back the identity it resolved, as a snapshot a later request cannot move' do
event, actor = described_class.identify_for_request(data, 'ses_1', request, nil)
expect(event['event_type']).to eq('posthog:identify')
expect(actor.distinct_id).to eq('user-1')
actor = described_class.resolve(data, 'ses_1', request, nil)

data.options.instance_variable_set(:@identify, ->(_r, _e) { { distinct_id: 'user-2' } })
_later, later_actor = described_class.identify_for_request(data, 'ses_1', request, nil)
expect(later_actor.distinct_id).to eq('user-2')
expect(described_class.resolve(data, 'ses_1', request, nil).distinct_id).to eq('user-2')
expect(data.identified_sessions.get('ses_1').distinct_id).to eq('user-2')
# The cache has moved on; the first request's own actor has not, which is what
# keeps its events attributed to it after its handler returns.
expect(actor.distinct_id).to eq('user-1')
end

it 'falls back to the cached identity at resolution time when the callback yields nothing' do
described_class.identify_for_request(data, 'ses_1', request, nil)
data.options.instance_variable_set(:@identify, ->(_r, _e) { raise 'nope' })
event, actor = described_class.identify_for_request(data, 'ses_1', request, nil)
expect(event).to be_nil
expect(actor.distinct_id).to eq('user-1')

data.options.instance_variable_set(:@identify, ->(_r, _e) {})
expect(described_class.identify_for_request(data, 'ses_1', request, nil)[1].distinct_id).to eq('user-1')

# No `identify` option at all: nothing to attribute, and nothing cached either.
none = PostHog::MCP::TrackingData.new(options: PostHog::MCP::Options.new, sink: nil)
expect(described_class.identify_for_request(none, 'ses_1', request, nil)).to eq([nil, nil])
it 'falls back to the cached identity when the callback yields nothing' do
described_class.resolve(data, 'ses_1', request, nil)
[->(_r, _e) { raise 'nope' }, ->(_r, _e) {}].each do |identify_option|
data.options.instance_variable_set(:@identify, identify_option)
expect(described_class.resolve(data, 'ses_1', request, nil).distinct_id).to eq('user-1')
end
end

it 'keeps the identity cache consistent under concurrent identification' do
Expand All @@ -82,7 +57,7 @@
threads = 16.times.map do |i|
Thread.new do
50.times do |j|
described_class.handle_identify(concurrent, "ses_#{j % 4}", { params: { name: "t#{i}" } }, nil)
described_class.resolve(concurrent, "ses_#{j % 4}", { params: { name: "t#{i}" } }, nil)
end
end
end
Expand Down
5 changes: 1 addition & 4 deletions spec/posthog/mcp/instrument_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,7 @@ def stringify_result_keys(target)
describe 'identify, event_properties and before_send' do
before { allow(Kernel).to receive(:warn) }

it 'identifies once per session, sets $set/$groups and turns person processing on' do
it 'sets $set/$groups from identify and turns person processing on' do
calls = 0
identify = lambda do |_request, _extra|
calls += 1
Expand All @@ -480,15 +480,12 @@ def stringify_result_keys(target)
server.handle(initialize_request)
3.times { |i| server.handle(rpc(i + 2, 'tools/call', { name: 'echo', arguments: { message: 'x' } })) }
events = drain_events(client)
expect(events.count { |e| e[:event] == '$identify' }).to eq(1)
expect(calls).to eq(4)
call = events.find { |e| e[:event] == '$mcp_tool_call' }
expect(call[:distinct_id]).to eq('user-1')
expect(call[:properties]).to include('$set' => { 'name' => 'Alice' }, '$groups' => { 'organization' => 'org_123' },
'env' => 'production')
expect(call[:properties]).not_to have_key('$process_person_profile')
identify_event = events.find { |e| e[:event] == '$identify' }
expect(identify_event[:properties]['$mcp_resource_name']).to eq('Unknown')
end

it 'runs before_send per payload, dropping and mutating' do
Expand Down
Loading