Skip to main content

PostHog

PostHog is an analytics platform with AI observability features for monitoring LLM applications. Use it with Mastra in two ways:

  • Agent tools let an agent work with PostHog data, such as events, insights, and feature flags, through Mastra Connect.
  • Tracing exports your Mastra traces to PostHog as structured events.

Connect
Direct link to Connect

Before you start, complete the Connect setup to install @mastra/connect and configure your platform project.

Agent tools
Direct link to Agent tools

Give agents tools to capture events, run queries, and manage feature flags, experiments, insights, dashboards, cohorts, and surveys in PostHog.

Connect an account with the posthog provider ID. Run this command from the directory that contains your .env file:

mastra connect add posthog

Then pass tools() to the agent and select the provider:

src/mastra/agents/posthog-agent.ts
import { Agent } from '@mastra/core/agent'
import { tools } from '@mastra/connect'

export const posthogAgent = new Agent({
id: 'posthog-agent',
name: 'PostHog agent',
instructions:
'You help people capture events, run queries, and manage feature flags, experiments, insights, dashboards, cohorts, and surveys in PostHog.',
model: '__GATEWAY_OPENAI_MODEL_LUNA__',
tools: tools({ providers: ['posthog'] }),
})

The agent gets 67 PostHog tools, with keys such as posthog_capture_event. See PostHog tools for the full list, and the tools() parameters to restrict tools or require approval before a call runs.

Tracing
Direct link to Tracing

The PostHog exporter sends your traces to PostHog as structured events, providing insights into token usage, costs, latency, and conversation flows.

Installation
Direct link to Installation

npm install @mastra/posthog@latest

Configuration
Direct link to Configuration

Prerequisites
Direct link to Prerequisites

  1. PostHog Account: Sign up at posthog.com
  2. Project API Key: Get your project API key from PostHog Settings → Project API Key
  3. Environment Variables: Set your credentials
.env
# Required
POSTHOG_API_KEY=phc_xxxxxxxxxxxxxxxx

# Optional
POSTHOG_HOST=https://us.i.posthog.com # or eu.i.posthog.com for EU region

Zero-config setup
Direct link to Zero-config setup

With environment variables set, use the exporter with no configuration:

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { Observability } from '@mastra/observability'
import { PosthogExporter } from '@mastra/posthog'

export const mastra = new Mastra({
observability: new Observability({
configs: {
posthog: {
serviceName: 'my-service',
exporters: [new PosthogExporter()],
},
},
}),
})

Explicit configuration
Direct link to Explicit configuration

You can also pass credentials directly (takes precedence over environment variables):

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { Observability } from '@mastra/observability'
import { PosthogExporter } from '@mastra/posthog'

export const mastra = new Mastra({
observability: new Observability({
configs: {
posthog: {
serviceName: 'my-service',
exporters: [
new PosthogExporter({
apiKey: process.env.POSTHOG_API_KEY,
}),
],
},
},
}),
})

Configuration options
Direct link to Configuration options

Complete configuration
Direct link to Complete configuration

new PosthogExporter({
// Required credentials
apiKey: process.env.POSTHOG_API_KEY!,

// Optional settings
host: 'https://us.i.posthog.com', // Default: US region
// or "https://eu.i.posthog.com" for EU region
// or your self-hosted URL

// Batching configuration
flushAt: 20, // Batch size (default: 20)
flushInterval: 10000, // Flush interval in ms (default: 10000)
serverless: false, // Serverless mode: flushAt=10, flushInterval=2000

// User identification
defaultDistinctId: 'anonymous', // Fallback if no userId in metadata

// Privacy settings
enablePrivacyMode: false, // Excludes input/output from generation events

// Diagnostic logging
logLevel: 'info', // debug | info | warn | error
})

Serverless mode
Direct link to Serverless mode

Optimized batching for serverless environments:

new PosthogExporter({
apiKey: process.env.POSTHOG_API_KEY!,
serverless: true, // Configures smaller batches for faster flushing
})

Privacy mode
Direct link to Privacy mode

Exclude input/output data from generation events while preserving token metrics:

new PosthogExporter({
apiKey: process.env.POSTHOG_API_KEY!,
enablePrivacyMode: true, // Removes $ai_input and $ai_output_choices
})

Group analytics
Direct link to Group analytics

To attach events to a PostHog group, add a $groups object to tracingOptions.metadata. The exporter sends those values as the top-level groups field on the PostHog capture call, so you can slice analytics such as LLM cost by group.

await agent.generate(input, {
tracingOptions: {
metadata: {
$groups: {
publication: 'publication-1',
},
},
},
})