posthogmcp

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 10, 2026 License: MIT Imports: 22 Imported by: 0

README

posthog-mcp-go

Community-maintained PostHog MCP analytics for the official modelcontextprotocol/go-sdk.

This project is maintained by AnyAPI. It is not an official PostHog package. Its behavior is specified in SPEC.md and tested against pinned versions of PostHog's official TypeScript and Python MCP analytics implementations.

Install

go get github.com/getanyapi-com/posthog-mcp-go@v0.1.0

Go 1.25 or newer is required. MCP Go SDK v1.6.1 and v1.7.0 are tested in CI.

Use

package main

import (
	"context"
	"log"

	posthogmcp "github.com/getanyapi-com/posthog-mcp-go"
	"github.com/modelcontextprotocol/go-sdk/mcp"
	"github.com/posthog/posthog-go"
)

func instrument(server *mcp.Server, projectKey string) posthog.Client {
	client, err := posthog.NewWithConfig(projectKey, posthog.Config{
		Endpoint: posthog.DefaultEndpoint,
	})
	if err != nil {
		log.Printf("PostHog analytics disabled: %v", err)
		return nil
	}

	analytics := posthogmcp.New(client, &posthogmcp.Options{
		Identify: func(context.Context, mcp.Request) (*posthogmcp.Identity, error) {
			return &posthogmcp.Identity{DistinctID: "customer_123"}, nil
		},
	})
	server.AddReceivingMiddleware(analytics.Middleware())
	return client
}

The application owns the PostHog client. Call Close or CloseWithContext during shutdown so queued events can flush.

Context schema injection and exception autocapture are enabled by default. Conversation IDs and missing-capability reporting are opt-in. See Options in the package API.

Custom events use the same privacy and delivery pipeline:

_ = analytics.Capture(ctx, "feedback_submitted", map[string]any{"rating": 5})

Failure model

Instrumentation is pass-through when the client is nil. Callback, logger, data conversion, queue-full, closed-client, and enqueue failures drop only analytics. The middleware calls ordinary downstream handlers exactly once and preserves their result, error, or panic. It adds no request goroutine, delivery queue, or network call; posthog-go owns asynchronous delivery.

Compatibility and parity

The package emits PostHog's canonical MCP events, sanitizes sensitive and binary payloads, enforces upstream size limits, and supports legacy initialize plus the MCP 2026-07-28 server/discover handshake. Intent context is injected only when the tool schema can be cloned safely, and wrapper-owned arguments are removed before typed tool validation.

Documented parity decisions and test provenance are in SPEC.md and TEST-PORT-MATRIX.md. The TypeScript legacy self-encoded session header is intentionally absent because the Go SDK owns that transport state. $lib remains posthog-go; $mcp_source identifies this integration.

Documentation

Overview

Package posthogmcp instruments servers built with the official MCP Go SDK and emits PostHog's canonical MCP analytics events.

Portions of this file are derived from agentcathq/agentcat-typescript-sdk (formerly MCPCat/mcpcat-typescript-sdk), licensed under the MIT License.

Index

Constants

View Source
const (
	EventCustom            = "$mcp_custom"
	EventException         = "$exception"
	EventIdentify          = "$identify"
	EventInitialize        = "$mcp_initialize"
	EventMissingCapability = "$mcp_missing_capability"
	EventPromptGet         = "$mcp_prompt_get"
	EventPromptsList       = "$mcp_prompts_list"
	EventResourceRead      = "$mcp_resource_read"
	EventResourcesList     = "$mcp_resources_list"
	EventToolCall          = "$mcp_tool_call"
	EventToolsList         = "$mcp_tools_list"
)
View Source
const (
	PropertyClientName      = "$mcp_client_name"
	PropertyAnonDistinctID  = "$anon_distinct_id"
	PropertyClientUserAgent = "$mcp_client_user_agent"
	PropertyClientVersion   = "$mcp_client_version"
	PropertyConversationID  = "$mcp_conversation_id"
	PropertyDurationMS      = "$mcp_duration_ms"
	PropertyErrorMessage    = "$mcp_error_message"
	PropertyErrorType       = "$mcp_error_type"
	PropertyIsError         = "$mcp_is_error"
	PropertyIntent          = "$mcp_intent"
	PropertyIntentSource    = "$mcp_intent_source"
	PropertyListedToolNames = "$mcp_listed_tool_names"
	PropertyParameters      = "$mcp_parameters"
	PropertyProtocolVersion = "$mcp_protocol_version"
	PropertyResourceName    = "$mcp_resource_name"
	PropertyResponse        = "$mcp_response"
	PropertyServerName      = "$mcp_server_name"
	PropertyServerVersion   = "$mcp_server_version"
	PropertySessionID       = "$session_id"
	PropertySource          = "$mcp_source"
	PropertyToolCategory    = "$mcp_tool_category"
	PropertyToolDescription = "$mcp_tool_description"
	PropertyToolName        = "$mcp_tool_name"
	PropertyVendorClient    = "$mcp_vendor_client"
)
View Source
const (
	Source                           = "posthog_mcp_analytics"
	SDKLanguage                      = "go"
	Version                          = "0.1.0"
	DefaultMissingCapabilityToolName = "get_more_tools"
)
View Source
const DefaultContextDescription = `` /* 532-byte string literal not displayed */
View Source
const DefaultConversationIDDescription = "" /* 180-byte string literal not displayed */

Variables

This section is empty.

Functions

This section is empty.

Types

type Analytics

type Analytics struct {
	// contains filtered or unexported fields
}

Analytics is a concurrency-safe MCP analytics middleware and custom capture handle.

func New

func New(client posthog.EnqueueClient, options *Options) *Analytics

New constructs analytics. A nil client produces disabled pass-through instrumentation.

func (*Analytics) Capture

func (a *Analytics) Capture(ctx context.Context, name string, properties map[string]any) (err error)

Capture records a custom event. Disabled analytics treats capture as a no-op.

func (*Analytics) Enabled

func (a *Analytics) Enabled() bool

Enabled reports whether this object has a PostHog enqueue client.

func (*Analytics) Middleware

func (a *Analytics) Middleware() mcp.Middleware

Middleware returns receiving middleware for mcp.Server.AddReceivingMiddleware.

type BeforeSendFunc

type BeforeSendFunc func(context.Context, Event) (*Event, error)

BeforeSendFunc can modify or drop an event immediately before enqueue.

type Event

type Event struct {
	UUID       string
	Event      string
	DistinctID string
	Timestamp  time.Time
	Properties posthog.Properties
	Groups     posthog.Groups
}

Event is the mutable event shape supplied to BeforeSend.

type EventPropertiesFunc

type EventPropertiesFunc func(context.Context, mcp.Request) (posthog.Properties, error)

EventPropertiesFunc supplies properties attached to every automatic event.

type IdentifyFunc

type IdentifyFunc func(context.Context, mcp.Request) (*Identity, error)

IdentifyFunc resolves the identity associated with an MCP request.

type Identity

type Identity struct {
	DistinctID string
	Properties posthog.Properties
	Groups     posthog.Groups
}

Identity is the resolved PostHog identity for one MCP caller.

type IntentFallbackFunc

type IntentFallbackFunc func(context.Context, mcp.Request) (string, error)

IntentFallbackFunc infers user intent when no analytics-owned context is supplied.

type Options

type Options struct {
	Logger                      *slog.Logger
	Identify                    IdentifyFunc
	IntentFallback              IntentFallbackFunc
	EventProperties             EventPropertiesFunc
	BeforeSend                  BeforeSendFunc
	DisableContextInjection     bool
	ContextDescription          string
	ReportMissing               bool
	MissingCapabilityToolName   string
	EnableConversationID        bool
	DisableExceptionAutocapture bool
}

Options configures MCP analytics behavior.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL