← Catalog

@posthog/pi

PostHog MCP + LLM analytics extension package for pi coding agent

Package

Install

Install with PiG

pig install npm:@posthog/pi

Install with Pi

pi install npm:@posthog/pi
Review before installing

Packages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.

Pi manifest JSON

The pi field of package.json.

{
  "extensions": [
    "./src/index.ts"
  ]
}

README

Written by the package's publisher, shown as published in version 0.6.0 (README.md). PiG does not review it.

@posthog/pi

PostHog extension package for pi coding agent.

It currently provides two capabilities:

  1. LLM Analytics for pi — captures generations, tool executions, and traces as structured $ai_* events in PostHog.
  2. PostHog MCP bridge for pi — connects pi to the PostHog MCP server and dynamically exposes PostHog MCP tools inside pi.

Install

pi install npm:@posthog/pi

Or for project-local install:

pi install -l npm:@posthog/pi

Quick start

Use PostHog MCP inside pi

Set a PostHog personal API key and start pi:

export POSTHOG_PERSONAL_API_KEY="phx_your_personal_api_key"
pi

You can also pass the full auth header instead:

export POSTHOG_AUTH_HEADER="Bearer phx_your_personal_api_key"
pi

By default, the extension connects to:

  • https://mcp.posthog.com/mcp
  • MCP version header: x-posthog-mcp-version: 2

When connected, PostHog MCP tools are registered dynamically in pi and are callable like any other pi tool.

Useful commands:

  • /posthog-mcp-status — show connection and config status
  • /posthog-mcp-reload — reconnect and refresh MCP tools

Send pi traces to PostHog LLM Analytics

Set your project API key:

export POSTHOG_API_KEY="phc_your_project_key"
pi

Configuration

MCP bridge

VariableDefaultDescription
POSTHOG_MCP_ENABLEDtrueSet to false to disable the MCP bridge
POSTHOG_PERSONAL_API_KEY(none)Personal API key used for PostHog MCP auth
POSTHOG_AUTH_HEADER(none)Full Authorization header, e.g. Bearer phx_...
POSTHOG_MCP_URLhttps://mcp.posthog.com/mcpPostHog MCP endpoint
POSTHOG_MCP_VERSION2Value sent as x-posthog-mcp-version
POSTHOG_MCP_FEATURES(all tools)Optional comma-separated PostHog MCP feature filter
POSTHOG_MCP_TOOLS(none)Optional comma-separated tool allowlist
POSTHOG_MCP_SPILL_TO_FILEtrueSave large MCP responses to a temp file instead of inlining them
POSTHOG_MCP_MAX_INLINE_CHARS12000Max serialized response size before spilling to a file
POSTHOG_MCP_TEMP_DIR/tmp/posthog-mcpDirectory for large saved MCP responses

Examples:

# expose all default PostHog MCP v2 tools
export POSTHOG_PERSONAL_API_KEY="phx_..."

# narrow the tool surface
export POSTHOG_MCP_FEATURES="sql,llm_analytics,error_tracking,flags,experiments"

# or allowlist exact tools
export POSTHOG_MCP_TOOLS="execute-sql,dashboard-get,feature-flag-get-all"

# keep large results out of context
export POSTHOG_MCP_SPILL_TO_FILE="true"
export POSTHOG_MCP_MAX_INLINE_CHARS="12000"

LLM analytics / tracing

VariableDefaultDescription
POSTHOG_API_KEY(required for tracing)Your PostHog project API key
POSTHOG_HOSThttps://us.i.posthog.comPostHog instance URL
POSTHOG_PRIVACY_MODEfalseWhen true, LLM input/output content is not sent to PostHog
POSTHOG_ENABLEDtrueSet to false to disable analytics capture
POSTHOG_TRACE_GROUPINGmessagemessage: one trace per user prompt. session: group all generations in a session into one trace
POSTHOG_SESSION_WINDOW_MINUTES60Minutes of inactivity before starting a new session window
POSTHOG_PROJECT_NAMEcwd basenameProject name included in all events
POSTHOG_AGENT_NAMEproject nameAgent name (auto-detects subagent names from pi-subagents)
POSTHOG_DISTINCT_IDauto-discovered from PostHog personal API key (fallback: session id pi:...)Override distinct_id used for all $ai_* events (for example user@example.com). When set, the extension also calls identify() on session start.
POSTHOG_TAGS(none)Custom tags added to all events (format: key1:val1,key2:val2)
POSTHOG_GROUPS(none)JSON object mapping group types to string or numeric group keys, e.g. {"workspace":"foobar"}
POSTHOG_MAX_ATTRIBUTE_LENGTH12000Max length for serialized tool input/output attributes

If POSTHOG_DISTINCT_ID is set, @posthog/pi calls identify() once on session start for that distinct ID. If the value looks like an email address, it is also sent as the email person property.

If POSTHOG_DISTINCT_ID is not set, @posthog/pi will try to discover your identity from POSTHOG_PERSONAL_API_KEY (or personalApiKey in ~/.pi/agent/posthog.json) and use that as distinct_id. If discovery fails, it falls back to session IDs (pi:...).

Group analytics

To attribute every $ai_generation, $ai_span, and $ai_trace event to a PostHog group, configure group types and keys:

export POSTHOG_GROUPS='{"workspace":"foobar","organization":123}'

Or add groups to ~/.pi/agent/posthog.json:

{
    "apiKey": "phc_your_project_key",
    "groups": {
        "workspace": "foobar",
        "organization": 123
    }
}

POSTHOG_GROUPS replaces the entire file mapping; use {} to clear file-configured groups. Group types and string keys must be non-empty, and numeric keys must be finite (including 0). Invalid configuration logs a warning and is ignored without falling back to file groups or interrupting capture.

Groups are sent as $groups event attribution, including in privacy mode. They do not change distinct_id or create/update group profile properties ($groupidentify).

What gets captured

$ai_generation

Captured on every LLM call, as soon as the response ends and before its tool calls run.

PropertyDescription
$ai_modelModel name (e.g. claude-sonnet-4-20250514)
$ai_providerProvider name (e.g. anthropic, openai)
$ai_latencyLLM request duration in seconds, excluding tool execution
$ai_input_tokensInput token count
$ai_output_tokensOutput token count
$ai_total_tokensTotal token count
$ai_total_cost_usdTotal cost in USD
$ai_input_cost_usdInput cost in USD
$ai_output_cost_usdOutput cost in USD
$ai_stop_reasonWhy generation stopped (stop, length, tool_calls, error)
$ai_is_errorWhether the generation errored
$ai_errorError message (if any)
$ai_inputSystem prompt and messages, with tool calls (redacted in privacy mode)
$ai_output_choicesResponse text and tool calls (redacted in privacy mode)
$ai_user_promptRaw user prompt text (redacted in privacy mode)
$ai_trace_idTrace ID for hierarchical grouping
$ai_span_idSpan ID for this generation
$ai_session_idSession identifier
$ai_project_nameProject name
$ai_agent_nameAgent name (includes subagent name if applicable)
$ai_cache_read_input_tokensCache read token count
$ai_cache_creation_input_tokensCache creation token count
$ai_cache_reporting_exclusiveAlways true: $ai_input_tokens excludes cached tokens

$ai_span

Captured for each tool execution (read, write, edit, bash, etc.).

PropertyDescription
$ai_span_nameTool name
$ai_span_typeAlways tool
$ai_latencyTool execution duration in seconds
$ai_is_errorWhether the tool call errored
$ai_errorError message (if any)
$ai_input_stateTool input parameters (sensitive keys redacted, privacy mode aware)
$ai_output_stateTool output result (sensitive keys redacted, privacy mode aware)
$ai_trace_idTrace ID
$ai_span_idSpan ID for this tool call
$ai_parent_idSpan ID of the generation that made the call (or of the calling tool)
$ai_project_nameProject name
$ai_agent_nameAgent name

$ai_trace

Captured when an agent run completes (one per user prompt).

PropertyDescription
$ai_trace_idTrace ID
$ai_session_idSession identifier
$ai_latencyTotal agent run duration in seconds
$ai_total_input_tokensAccumulated input tokens across all turns
$ai_total_output_tokensAccumulated output tokens across all turns
$ai_is_errorWhether the agent run ended in error
$ai_errorError message (if any)
$ai_project_nameProject name
$ai_agent_nameAgent name

Trace Grouping

  • message (default): Each user prompt creates a new trace. Multiple LLM turns within one prompt (e.g., tool use loops) are grouped under the same trace.
  • session: All generations within a session window are grouped under one trace. A new trace starts after sessionWindowMinutes of inactivity.

Privacy Mode

When POSTHOG_PRIVACY_MODE=true, all LLM input/output content, user prompts, tool inputs, and tool outputs are redacted (sent as null). Token counts, costs, latency, and model metadata are still captured.

Even when privacy mode is off, sensitive keys in tool inputs/outputs (e.g. api_key, token, secret, password, authorization) are automatically redacted.

Subagent Detection

When used with pi-subagents, the extension automatically detects subagent names from --append-system-prompt CLI args and includes them in $ai_agent_name as projectName/subagentName.

Requirements

  • Node.js >= 22

Development

Local development with pi

Run the extension directly from source:

cd /path/to/posthog-pi
pnpm install

# Use a PostHog personal API key for MCP
export POSTHOG_PERSONAL_API_KEY="phx_..."

# Start pi with the local extension source
pi -e ./src/index.ts

Useful commands inside pi:

/posthog-mcp-status
/posthog-mcp-reload

If you prefer to install the package into pi locally instead of using -e:

cd /path/to/posthog-pi
pi install -l .

# then launch pi normally
pi

If large MCP results are causing compaction or context pressure during development, keep spill-to-file enabled (the default) or set it explicitly:

export POSTHOG_MCP_SPILL_TO_FILE="true"
export POSTHOG_MCP_MAX_INLINE_CHARS="12000"
export POSTHOG_MCP_TEMP_DIR="/tmp/posthog-mcp"

Development commands

# Install dependencies
pnpm install

# Test with pi (without installing)
pi -e ./src/index.ts

# Type check
pnpm typecheck

# Lint (oxfmt)
pnpm lint

# Format
pnpm lint:fix

# Run tests (vitest)
pnpm test

License

MIT