Class: PostHog::MCP::Analytics

Inherits:
Object
  • Object
show all
Defined in:
lib/posthog/mcp/analytics.rb

Overview

Note:

Experimental.

Handle returned by instrument. Emits custom events onto the same pipeline as the auto-captured $mcp_* events.

Direct Known Subclasses

NoopAnalytics

Instance Method Summary collapse

Constructor Details

#initialize(server) ⇒ Analytics

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of Analytics.



11
12
13
# File 'lib/posthog/mcp/analytics.rb', line 11

def initialize(server)
  @server = server
end

Instance Method Details

#capture(event, properties = {}) ⇒ void

This method returns an undefined value.

Capture a custom event scoped to the current MCP session. The event name is sent verbatim (a customer event, not $-prefixed).

Inside a tool body the session and the identity are the ones pinned to the in-flight request by Instrumentation, so a concurrent request on the same session cannot reattribute this event. Over stdio, where a server only ever talks to one client, the session is the server's current one. On an HTTP server a call that has lost the request scope gets a standalone session rather than the server's, which may belong to another caller's request.

Parameters:

  • event (String) —

    event name

  • properties (Hash) (defaults to: {}) —

    event properties

Raises:

  • (ArgumentError) —

    when the event name is blank



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/posthog/mcp/analytics.rb', line 30

def capture(event, properties = {})
  unless event.is_a?(String) && !event.strip.empty?
    raise ArgumentError, 'capture() requires an event name, e.g. analytics.capture("feedback_submitted")'
  end

  data = PostHog::MCP.tracking_data(@server)
  return if data.nil?

  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))
  nil
end

#flush ⇒ void

This method returns an undefined value.

Flush the underlying PostHog client.



53
54
55
56
57
58
# File 'lib/posthog/mcp/analytics.rb', line 53

def flush
  data = PostHog::MCP.tracking_data(@server)
  client = data&.sink&.client
  client.flush if client.respond_to?(:flush)
  nil
end