@openpets/posthog
v1.0.4
Published
PostHog plugin for OpenCode - comprehensive analytics, feature flags, and event tracking
Downloads
12
Maintainers
Readme
PostHog Plugin for OpenCode
A comprehensive PostHog integration plugin for OpenCode that provides full access to PostHog's analytics, feature flags, event tracking, and insights capabilities through a factory-based architecture.
Features
- Event Tracking: Capture single and batch events with custom properties
- Feature Flags: Create, manage, evaluate, and update feature flags
- Analytics & Insights: Get trends, insights, and analytics data
- Person Management: Track and update user/person properties
- Session Recordings: Access and query session recordings
- Cohorts & Annotations: Manage cohorts and create annotations
- Project Management: Get project information and configuration
Prerequisites
- PostHog account (cloud or self-hosted)
- Personal API Key from PostHog
- Project API Key (for event capture)
Setup
1. Get PostHog API Keys
Personal API Key:
- Log into your PostHog instance
- Go to Settings → Personal API Keys
- Create a new Personal API Key
- Copy the key
Project API Key:
- Go to Project Settings
- Find your Project API Key
- Copy the key
2. Configure Environment
Create a .env file in the posthog plugin directory:
cp .env.example .envEdit .env with your credentials:
POSTHOG_HOST=https://app.posthog.com
POSTHOG_API_KEY=phx_your_personal_api_key_here
POSTHOG_PROJECT_API_KEY=phc_your_project_api_key_hereFor self-hosted PostHog, use your instance URL:
POSTHOG_HOST=https://posthog.yourdomain.com3. Install Dependencies
npm install4. Test Connection
opencode run "check posthog status"Using from Other Projects
Add to your project's opencode.json:
{
"$schema": "https://opencode.ai/config.json",
"plugin": [
"/absolute/path/to/openpets/pets/posthog/index.ts"
]
}Available Tools
Event Tracking
posthog-capture-event
Capture a single event with optional properties.
Parameters:
event(required): Event name (e.g., "button_clicked", "page_viewed")distinct_id(required): Unique user/entity identifierproperties(optional): Key-value pairs of event propertiestimestamp(optional): ISO timestamp (defaults to now)
Examples:
opencode run "capture event 'page_view' for user 'user_123'"
opencode run "capture event 'button_clicked' for user 'user_123' with properties {button_name: 'signup', page: '/home'}"posthog-batch-capture-events
Capture multiple events in a single batch request for better performance.
Parameters:
events(required): Array of event objects
Example:
opencode run "batch capture events: [{event: 'login', distinct_id: 'user_1'}, {event: 'view_dashboard', distinct_id: 'user_1'}]"posthog-get-events
Retrieve events with optional filtering.
Parameters:
distinct_id(optional): Filter by user IDevent(optional): Filter by event namelimit(optional): Max results (default: 100)offset(optional): Skip results (default: 0)
Examples:
opencode run "get events for user 'user_123'"
opencode run "get events with name 'page_view' limit 50"Person Management
posthog-get-person
Get information about a person by their distinct ID.
Parameters:
distinct_id(required): The person's unique identifier
Example:
opencode run "get person 'user_123'"posthog-update-person
Update or set properties for a person (identify operation).
Parameters:
distinct_id(required): The person's unique identifierproperties(required): Properties to set (e.g., {email: "[email protected]", name: "John"})
Example:
opencode run "update person 'user_123' with properties {email: '[email protected]', name: 'John Doe', plan: 'premium'}"Feature Flags
posthog-list-feature-flags
List all feature flags in the project.
Example:
opencode run "list feature flags"posthog-get-feature-flag
Get details of a specific feature flag by ID.
Parameters:
flag_id(required): The feature flag ID
Example:
opencode run "get feature flag 123"posthog-create-feature-flag
Create a new feature flag.
Parameters:
key(required): Unique key for the flagname(required): Display namefilters(required): Filter configurationactive(optional): Whether flag is active (default: true)rollout_percentage(optional): Percentage rollout (0-100)
Example:
opencode run "create feature flag with key 'new-dashboard' and name 'New Dashboard UI'"posthog-update-feature-flag
Update an existing feature flag.
Parameters:
flag_id(required): The feature flag IDkey,name,filters,active,rollout_percentage(optional): Fields to update
Example:
opencode run "update feature flag 123 set active to false"posthog-delete-feature-flag
Delete a feature flag.
Parameters:
flag_id(required): The feature flag ID to delete
Example:
opencode run "delete feature flag 123"posthog-evaluate-feature-flag
Evaluate a feature flag for a specific user.
Parameters:
flag_key(required): The feature flag keydistinct_id(required): The user ID to evaluate forperson_properties(optional): Person properties for evaluation
Example:
opencode run "evaluate feature flag 'new-dashboard' for user 'user_123'"Analytics & Insights
posthog-get-insights
Get insights/analytics data from PostHog.
Parameters:
events(required): Array of events to analyzedate_from(optional): Start date (default: "-7d")date_to(optional): End date (default: "now")interval(optional): Data interval (hour/day/week/month, default: day)
Example:
opencode run "get insights for events 'page_view' and 'button_click' from last 30 days"posthog-get-trend
Get trend data for a specific event.
Parameters:
event_name(required): Event name to get trends fordate_from(optional): Start date (default: "-7d")date_to(optional): End date (default: "now")
Example:
opencode run "get trend for event 'signup' from last 30 days"posthog-get-project-info
Get information about the current PostHog project.
Example:
opencode run "get project info"Session Recordings
posthog-get-session-recordings
Get session recordings from PostHog.
Parameters:
limit(optional): Max recordings (default: 50)offset(optional): Skip recordings (default: 0)date_from(optional): Start date filterdate_to(optional): End date filter
Example:
opencode run "get session recordings from last 7 days limit 10"Cohorts & Annotations
posthog-get-cohorts
Get all cohorts from PostHog.
Example:
opencode run "get cohorts"posthog-get-annotations
Get all annotations from PostHog.
Example:
opencode run "get annotations"posthog-create-annotation
Create a new annotation in PostHog.
Parameters:
content(required): Annotation content/messagedate_marker(required): ISO date string for the annotationscope(optional): "organization" or "project" (default: "project")
Example:
opencode run "create annotation 'Deployed v2.0' for today"Status & Configuration
posthog-status
Check PostHog connection and configuration status.
Example:
opencode run "check posthog status"Common Use Cases
Track User Journey
# 1. Identify user
opencode run "update person 'user_123' with properties {email: '[email protected]', signup_date: '2024-01-15'}"
# 2. Track events
opencode run "capture event 'signed_up' for user 'user_123'"
opencode run "capture event 'completed_onboarding' for user 'user_123'"
opencode run "capture event 'first_purchase' for user 'user_123' with properties {amount: 49.99, product: 'premium_plan'}"
# 3. Check user data
opencode run "get person 'user_123'"
opencode run "get events for user 'user_123'"Feature Flag Workflow
# 1. Create feature flag
opencode run "create feature flag with key 'beta-ui' and name 'New Beta UI' with rollout 10"
# 2. Evaluate for user
opencode run "evaluate feature flag 'beta-ui' for user 'user_123'"
# 3. Gradually increase rollout
opencode run "update feature flag 456 set rollout_percentage to 50"
# 4. Monitor usage
opencode run "get trend for event 'beta_ui_viewed' from last 7 days"Analytics Dashboard
# 1. Get project overview
opencode run "get project info"
# 2. Get event trends
opencode run "get trend for event 'page_view' from last 30 days"
opencode run "get trend for event 'conversion' from last 30 days"
# 3. Get detailed insights
opencode run "get insights for events ['signup', 'purchase'] from last 30 days with interval week"
# 4. Add annotation for context
opencode run "create annotation 'Marketing campaign launched' for '2024-01-15'"Configuration
Environment Variables
| Variable | Description | Required |
|----------|-------------|----------|
| POSTHOG_HOST | PostHog instance URL | Yes |
| POSTHOG_API_KEY | Personal API Key | Yes |
| POSTHOG_PROJECT_API_KEY | Project API Key | No* |
* Required for event capture operations
PostHog Cloud vs Self-Hosted
Cloud (app.posthog.com):
POSTHOG_HOST=https://app.posthog.comSelf-Hosted:
POSTHOG_HOST=https://posthog.yourdomain.comPostHog EU Cloud:
POSTHOG_HOST=https://eu.posthog.comError Handling
All tools return structured JSON responses with error information:
{
"success": false,
"error": "Error message here",
"metadata": {
"timestamp": "2024-01-15T10:30:00Z"
}
}Common errors:
- Authentication Failed: Check your API keys
- Project Not Found: Verify POSTHOG_HOST and project access
- Rate Limit: PostHog has rate limits on API calls
- Invalid Event: Check event name and properties format
API Reference
This plugin uses the PostHog REST API. For detailed API documentation, visit:
Development
Testing
# Test basic connectivity
npm run quickstart
# Run all test queries
npm run test:queries
# Run scenario tests
npm run test:scenarios
# Run all tests
npm run test:allAdding New Features
- Update the PostHog provider in
src/utils/posthog/index.ts - Add new tool definitions in
pets/posthog/index.ts - Update this README with documentation
- Add test queries to
package.json
Architecture
This plugin follows the OpenCode factory-based architecture:
- Provider Layer:
src/utils/posthog/- PostHog API client - Plugin Layer:
pets/posthog/index.ts- Tool definitions and orchestration - Factory Pattern: Uses
createPlugin()for consistent tool creation - Type Safety: Zod schemas for parameter validation
Troubleshooting
Connection Issues
# Check status
opencode run "check posthog status"
# Verify environment variables
echo $POSTHOG_HOST
echo $POSTHOG_API_KEYEvent Not Appearing
- Ensure
POSTHOG_PROJECT_API_KEYis set - Check event name doesn't contain special characters
- Verify the project has ingestion enabled
Feature Flag Not Working
- Check flag is active in PostHog dashboard
- Verify user properties match flag filters
- Try evaluating flag through PostHog UI first
Rate Limiting
- PostHog has rate limits (typically 1000 req/sec)
- Use batch operations when capturing multiple events
- Add delays between large operations
Resources
License
MIT
Support
For issues specific to this plugin:
- File an issue in the OpenPets repository
For PostHog-related questions:
- Visit PostHog Community
- Check PostHog Docs
