Go MCP Analytics installation

Beta SDK

The Go SDK is in beta. It has the same defaults as the other SDKs, but captures fewer events and has fewer optional features. See Limits.

posthogmcpsdk instruments servers built on the official Go MCP SDK (github.com/modelcontextprotocol/go-sdk) v1.6.1 or later. Use go-sdk v1.8.0 or later in your own go.mod to serve protocol 2026-07-28 and input_required rounds. It ships in the posthog-go repository as its own module, so your app only depends on the MCP SDK if it uses this package.

You need Go 1.25+, posthogmcpsdk v2.0.0 or later, and a PostHog project token. Using a server that isn't built on go-sdk? See Custom dispatchers.

Learn more

The wizard installs the package and adds posthogmcpsdk.Instrument for you. To install by hand, follow the steps below.

  1. Install the package

    Required
    Terminal
    go get github.com/posthog/posthog-go/posthogmcpsdk/v2

    Earlier releases lack some options and events on this page.

  2. Wrap your server

    Required

    Call posthogmcpsdk.Instrument once, before the server accepts requests:

    Go
    package main
    import (
    "log"
    "os"
    "github.com/modelcontextprotocol/go-sdk/mcp"
    "github.com/posthog/posthog-go/posthogmcpsdk/v2"
    posthog "github.com/posthog/posthog-go/v2"
    "github.com/posthog/posthog-go/v2/posthogmcp"
    )
    func main() {
    client, err := posthog.NewWithConfig(os.Getenv("POSTHOG_PROJECT_TOKEN"), posthog.Config{
    Endpoint: "https://us.i.posthog.com", // or https://eu.i.posthog.com
    })
    if err != nil {
    log.Fatal(err)
    }
    defer client.Close()
    server := mcp.NewServer(&mcp.Implementation{Name: "weather-server", Version: "1.0.0"}, nil)
    posthogmcpsdk.Instrument(server, posthogmcp.New(client),
    posthogmcpsdk.WithServerInfo("weather-server", "1.0.0"),
    )
    // register your tools with mcp.AddTool as usual, then run the server
    }

    WithServerInfo adds your server's name and version to each event.

  3. Close the client on shutdown

    Required

    posthog-go sends events in batches. client.Close() sends queued events, so make sure it runs before the process exits. The defer above does this when main returns. If you stop the process from a signal handler, call client.Close() there.

  4. Check your first events

    Required

    Connect an agent to your server and call a tool. Then open the activity feed and filter for event = $mcp_tool_call. See the event reference for every property.

Identify the caller

Use WithIdentity to attach a person and groups to each call. go-sdk gives you the HTTP headers and any verified OAuth token in req.Extra:

Go
posthogmcpsdk.Instrument(server, posthogmcp.New(client),
posthogmcpsdk.WithIdentity(func(ctx context.Context, req *mcp.CallToolRequest) (posthogmcpsdk.Identity, error) {
if req.Extra == nil || req.Extra.TokenInfo == nil {
return posthogmcpsdk.Identity{}, nil // anonymous
}
user, err := lookupUser(ctx, req.Extra.TokenInfo.UserID)
if err != nil {
return posthogmcpsdk.Identity{}, err
}
return posthogmcpsdk.Identity{
DistinctID: user.ID,
Groups: posthog.NewGroups().Set("organization", user.OrgID),
SetProperties: posthog.NewProperties().Set("plan", user.Plan),
}, nil
}),
)

An error from the resolver doesn't change the MCP response. The SDK sends the event without identity and reports the error to your WithErrorHandler.

Sessions

Every event has a $session_id. See session resolution. Stateless HTTP has no transport session, so the SDK uses conversation IDs. A client that ignores the handle gets a new session per request, so use WithIdentity to group those calls by user.

Configuration

OptionDefaultWhat it does
WithServerInfo(name, version)–Adds the server name and version to each event.
WithContextParameter(bool)trueAdds a required context argument to capture agent intent. The SDK removes it before your handler and go-sdk's input validation run.
WithCaptureModel(bool)trueCaptures the calling model from client metadata, or from a required llm_model argument the SDK adds.
WithConversationID(bool)trueAdds an optional conversation_id argument to group calls across requests. When it mints a handle, it appends a last {"conversation_id": ...} text block to the result.
WithIntentFallback(fallback)–func(ctx, req) (string, error). Supplies intent, with $mcp_intent_source "inferred", when the agent sends no context. The agent's own context always wins.
WithIdentity(resolver)–Maps a call to a person and groups. See Identify the caller.
WithProperties(resolver)–Adds properties to each $mcp_tool_call and its $exception. The resolver also receives the result and the handler's error.
WithEventOptions(resolver)–Sets event options on each $mcp_tool_call and its $exception.
WithMissingCapabilityTool(name)offAdds the get_more_tools virtual tool. Agents call it to report a capability your server lacks. The call sends $mcp_missing_capability, not $mcp_tool_call. An empty name uses get_more_tools.
WithCaptureParameters(bool)trueCaptures the tool arguments as $mcp_parameters.
WithCaptureResponses(bool)trueCaptures the tool result as $mcp_response. A failed call's error text is captured either way.
WithErrorHandler(handler)no-opReceives instrumentation errors. Its errors and panics never change the MCP response.

To stop the $exception event for failed calls, pass posthogmcp.WithExceptionAutocapture(false) to posthogmcp.New. To change or drop events before they're sent, use BeforeSend in your posthog.Config. See Privacy.

The adapter's WithErrorHandler default is a no-op, but the posthog-go client logs to stderr by default. Set Config.Logger to change that.

A tool that declares its own context, llm_model, or conversation_id argument keeps it. Schemas built from $ref, allOf, anyOf, or oneOf, and schemas with a non-object type or non-object properties, get no added arguments.

Event options

Set event options, such as cookieless_mode or process_person_profile, with WithEventOptions. Its resolver returns posthog.Options for each $mcp_tool_call and its $exception:

Go
posthogmcpsdk.Instrument(server, posthogmcp.New(client),
posthogmcpsdk.WithEventOptions(func(
ctx context.Context, req *mcp.CallToolRequest, result *mcp.CallToolResult, err error,
) (posthog.Options, error) {
return posthog.NewOptions().Set("cookieless_mode", true), nil
}),
)

Report missing capabilities

Add WithMissingCapabilityTool to give agents a get_more_tools tool to report what your server lacks. The option is off by default.

Go
posthogmcpsdk.Instrument(server, posthogmcp.New(client),
posthogmcpsdk.WithServerInfo("weather-server", "1.0.0"),
posthogmcpsdk.WithMissingCapabilityTool("get_more_tools"),
)

A server that registers no tools must still declare the tools capability. Without it, clients never list tools and never see get_more_tools:

Go
server := mcp.NewServer(&mcp.Implementation{Name: "weather-server", Version: "1.0.0"},
&mcp.ServerOptions{HasTools: true},
)

Middleware order

Receiving middleware you add before Instrument runs inside the measured duration, and middleware you add after it runs outside. To place it yourself, install both halves of NewMiddleware:

Go
middleware := posthogmcpsdk.NewMiddleware(posthogmcp.New(client))
server.AddReceivingMiddleware(middleware.Receiving)
server.AddSendingMiddleware(middleware.Sending)

Custom dispatchers

For a server that isn't built on go-sdk, use the posthogmcp package directly. CaptureToolCall builds the same $mcp_tool_call event, with the same redaction and size limits:

Go
analytics := posthogmcp.New(client)
err := analytics.CaptureToolCall(ctx, posthogmcp.ToolCall{
ToolName: "search_docs",
Intent: intent, // the agent's "context" argument, if you add one
IntentSource: posthogmcp.IntentSourceContextParameter,
Parameters: arguments,
Response: result,
Duration: time.Since(started),
Error: toolErr, // sets $mcp_is_error and emits $exception
DistinctID: user.ID,
SessionID: sessionID,
ClientName: clientName,
ClientVersion: clientVersion,
ProtocolVersion: protocolVersion,
})
if err != nil {
log.Printf("capture MCP analytics: %v", err)
}

A call with neither SessionID nor ConversationID gets a new ses_ plus UUIDv7 session, and distinct_id falls back to it. Pass a stable SessionID or ConversationID to group calls. ToolCall also takes ConversationID, LLMModel with LLMModelSource, ClientUserAgent, VendorClient, ErrorType, and EventOptions for event options. EventContext takes EventOptions for the other events.

This path has no prepare steps. You strip any injected arguments and manage sessions and conversation handles yourself. If Intent comes from an argument, remove it from Parameters.

Three more methods capture calls that are not tool calls:

Go
err = analytics.CaptureUnknownTool(ctx, posthogmcp.UnknownTool{
EventContext: posthogmcp.EventContext{SessionID: sessionID},
ToolName: requestedName,
})
err = analytics.CaptureInputRequired(ctx, posthogmcp.InputRequired{
EventContext: posthogmcp.EventContext{SessionID: sessionID},
ToolName: "search_docs",
Duration: time.Since(started),
Methods: []string{"elicitation/create"}, // the method of each request, never its content
})
err = analytics.CaptureMissingCapability(ctx, posthogmcp.MissingCapability{
EventContext: posthogmcp.EventContext{SessionID: sessionID},
ToolName: "get_more_tools",
Intent: report, // the agent's description of what it needed
})

Limits

The Go SDK doesn't yet have:

  • $mcp_tools_list, $mcp_initialize, resource, and prompt events
  • Task handling

Still have questions?

Was this page useful?