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

`PostHog::MCP` groups ChatGPT, Codex, and VS Code calls by the conversation id each client sends in `_meta`, and every event now carries `$mcp_session_source`. The id is never sent itself, not even in `$mcp_parameters`, so the request your `identify` and `event_properties` callbacks receive no longer has that `_meta` key. ChatGPT is no longer advertised or minted a `conversation_id`, and neither is a call whose session the transport already carries. On HTTP, a request that carries no session, including every 2026-07-28 request, gets a `$session_id` of its own instead of the server's or the per-request session the `mcp` gem assigns, and is no longer named after another client's handshake. A custom event captured during a tool call carries the session and identity that call records, including a conversation handle the call delivers.
1 change: 1 addition & 0 deletions lib/posthog/mcp.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
1 change: 1 addition & 0 deletions lib/posthog/mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
64 changes: 52 additions & 12 deletions lib/posthog/mcp/analytics.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ module MCP
#
# @note Experimental.
class Analytics
MAX_HELD_EVENTS = 1000
MAX_HELD_BYTES = 4 * 1024 * 1024
private_constant :MAX_HELD_EVENTS, :MAX_HELD_BYTES

# @api private
def initialize(server)
@server = server
Expand Down Expand Up @@ -37,13 +41,13 @@ def capture(event, properties = {})

scope = RequestScope.current
scope = nil unless scope.is_a?(Hash)
Instrumentation.capture_event(data, {
'session_id' => current_session_id(data, scope),
'event_type' => EventType::CUSTOM,
'event_name' => event,
'timestamp' => Time.now.utc,
'properties' => properties
}, actor: scoped_actor(scope))
input = { 'event_type' => EventType::CUSTOM, 'event_name' => event, 'timestamp' => Time.now.utc,
'properties' => properties }
return if hold(data, scope, input)

session_id, source = current_session(data, scope)
Instrumentation.capture_event(data, input.merge('session_id' => session_id, 'session_source' => source),
actor: scoped_actor(scope))
nil
end

Expand All @@ -67,13 +71,49 @@ def flush
# created before the request. Fail closed with a standalone session
# rather than filing the event under another caller's identity; over stdio a
# server only ever talks to one client, so the fallback stays.
def current_session_id(data, scope)
scoped = scope ? scope[:session_id] : nil
return scoped if scoped
return data.session_id unless data.http_transport_seen
def current_session(data, scope)
return scope.values_at(:session_id, :session_source) if scope&.[](:session_id)
return [data.session_id, data.session_source] unless data.http_transport_seen

warn_unscoped_capture(data)
Session.new_session_id
[Session.new_session_id, 'generated']
end

# The sink's own sanitize and truncate steps run at capture, so a held event
# is a snapshot no later change to its properties reaches, and its size is bounded.
def hold(data, scope, input)
return false unless scope&.key?(:held)

snapshot = Truncation.truncate_event(Sanitization.sanitize_event(
Sanitization.stringify_keys(input.merge('duration' => 0))
))
bytes = JSON.generate(snapshot['properties'] || {}).bytesize
data.synchronize do
held = scope[:held]
next false unless held

held_bytes = scope.fetch(:held_bytes, 0) + bytes
if held.size < MAX_HELD_EVENTS && held_bytes <= MAX_HELD_BYTES
held << snapshot
scope[:held_bytes] = held_bytes
next true
end

warn_overflow(data, scope)
false
end
rescue StandardError => e
Log.debug(data.options, "analytics.capture could not hold its event, sending it now: #{e.message}")
false
end

def warn_overflow(data, scope)
return if scope[:overflowed_held]

scope[:overflowed_held] = true
Log.warn(data.options, "Warning: a tool call captured more than #{MAX_HELD_EVENTS} custom events or " \
"#{MAX_HELD_BYTES / 1024 / 1024} MiB of them before its conversation handle was " \
'delivered; sending the rest with the session the call has so far')
end

# The identity the in-flight request resolved, which {Instrumentation} pinned
Expand Down
51 changes: 51 additions & 0 deletions lib/posthog/mcp/client_conversation.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# frozen_string_literal: true

module PostHog
module MCP
# {ROWS} is the table of the MCP analytics spec's "Session identity"
# requirement, row for row, in its order. posthog-js and posthog-python keep
# the same table.
#
# @api private
module ClientConversation
Row = Struct.new(:key, :id, :user_agent, :client_names, :handle_free, keyword_init: true) do
def recognizes?(user_agent, client_name)
return true if user_agent.is_a?(String) && self.user_agent.match?(user_agent)

client_name.is_a?(String) && client_names.any? { |name| name.casecmp?(client_name) }
end
end

UUID = /\A\h{8}-\h{4}-\h{4}-\h{4}-\h{12}\z/
NIL_UUID = '00000000-0000-0000-0000-000000000000'
PRINTABLE_ASCII = /\A[\x20-\x7e]{1,128}\z/

uuid = lambda do |value|
lowered = value.downcase
lowered if UUID.match?(lowered) && lowered != NIL_UUID
end

ROWS = [
Row.new(key: 'openai/session', id: ->(value) { value if PRINTABLE_ASCII.match?(value) }, handle_free: true,
user_agent: %r{\Aopenai-mcp/[^\s(]*\s*\(\s*chatgpt\s*[;,)]}i, client_names: []),
Row.new(key: 'sessionId', id: uuid, handle_free: false,
user_agent: %r{\Acodex-mcp-client/}i, client_names: ['codex-mcp-client']),
Row.new(key: 'vscode.conversationId', id: uuid, handle_free: false,
user_agent: %r{\AVisual Studio Code(?: - Insiders)?/}i,
client_names: ['Visual Studio Code', 'Visual Studio Code - Insiders'])
].freeze

module_function

def recognize(user_agent, client_name)
ROWS.find { |row| row.recognizes?(user_agent, client_name) }
end

def read(row, meta)
value = row && SchemaMutation.fetch(meta, row.key)
id = row.id.call(value) if value.is_a?(String)
id && "#{row.key}:#{id}"
end
end
end
end
1 change: 1 addition & 0 deletions lib/posthog/mcp/constants.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
4 changes: 2 additions & 2 deletions lib/posthog/mcp/conversation_id.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,13 @@ def extract(args)
# own schema is passed application data, which must not anchor analytics:
# two users sharing such a value would be stitched into one conversation.
# @return [Array(String, Boolean), Array(nil, false)] `[conversation_id, minted]`
def resolve(enabled, supplied, tool_name, missing_capability_tool_name)
def resolve(enabled, supplied, tool_name, missing_capability_tool_name, mint: true)
return [nil, false] if !enabled || tool_name == missing_capability_tool_name

value = normalize(supplied)
return [value.downcase, false] if value && MINTED_CONVERSATION_ID.match?(value)

[Ids.uuid_v7, true]
mint ? [Ids.uuid_v7, true] : [nil, false]
end

def prompt_back?(result)
Expand Down
4 changes: 4 additions & 0 deletions lib/posthog/mcp/event_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ module MCP
#
# @api private
module EventBuilder
WIRE_SESSION_SOURCES = { 'token' => 'transport', 'mcp' => 'transport' }.freeze

module_function

# @return [Array<Hash>] payloads `{'event', 'distinct_id', 'properties', 'timestamp'}`
Expand Down Expand Up @@ -44,6 +46,8 @@ def build_capture_event(event)
def add_session_id(event, properties)
session_id = event['session_id']
properties[Property::SESSION_ID] = session_id if session_id.is_a?(String) && !session_id.empty?
source = event['session_source']
properties[Property::SESSION_SOURCE] = WIRE_SESSION_SOURCES.fetch(source, source) if source
end

def add_conversation_id(event, properties)
Expand Down
Loading