@arvoretech/posthog-mcp 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Arvore Education
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,197 @@
1
+ # PostHog MCP Server
2
+
3
+ A Model Context Protocol (MCP) server for PostHog that provides access to analytics, feature flags, experiments, dashboards, and more. Works with both PostHog Cloud and self-hosted instances.
4
+
5
+ ## Features
6
+
7
+ - **Analytics**: Run HogQL queries and structured queries (Trends, Funnels, Retention, Lifecycle, Paths, Stickiness)
8
+ - **Feature Flags**: Create, update, list, and delete feature flags with rollout control
9
+ - **Experiments**: List and inspect A/B test experiments with variants and metrics
10
+ - **Dashboards & Insights**: Create, list, and inspect dashboards and saved insights
11
+ - **Events & Properties**: Explore event definitions and property definitions
12
+ - **Persons & Cohorts**: Search users and manage segments
13
+ - **Surveys & Early Access**: List surveys and early access features
14
+ - **Annotations**: Create and list chart annotations for deployments and events
15
+ - **Search**: Search across all PostHog entities
16
+ - **Self-Hosted**: Direct API connection with static credentials — no OAuth needed
17
+ - **TypeScript**: Fully typed with Zod validation
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ npm install -g @arvoretech/posthog-mcp
23
+ ```
24
+
25
+ ## Configuration
26
+
27
+ The server is configured via environment variables:
28
+
29
+ ```bash
30
+ export POSTHOG_BASE_URL=https://posthog.example.com # or https://app.posthog.com
31
+ export POSTHOG_API_KEY=phx_your_personal_api_key
32
+ export POSTHOG_PROJECT_ID=1 # optional, defaults to 1
33
+ ```
34
+
35
+ ### Getting your API Key
36
+
37
+ 1. Go to PostHog → Settings → Personal API Keys
38
+ 2. Click "Create personal API key"
39
+ 3. Select the scopes you need (or use the "MCP Server" preset if available)
40
+ 4. Copy the generated key (starts with `phx_`)
41
+
42
+ ## Usage
43
+
44
+ ```bash
45
+ # Development
46
+ pnpm dev
47
+
48
+ # Production
49
+ node dist/index.js
50
+ ```
51
+
52
+ ## Available MCP Tools
53
+
54
+ ### Feature Flags
55
+
56
+ | Tool | Description |
57
+ |------|-------------|
58
+ | `list_feature_flags` | List all feature flags with search and pagination |
59
+ | `get_feature_flag` | Get details of a specific flag by ID |
60
+ | `create_feature_flag` | Create a new flag with optional rollout percentage |
61
+ | `update_feature_flag` | Update flag key, name, or active state |
62
+ | `delete_feature_flag` | Delete a feature flag by ID |
63
+
64
+ ### Experiments
65
+
66
+ | Tool | Description |
67
+ |------|-------------|
68
+ | `list_experiments` | List all A/B test experiments |
69
+ | `get_experiment` | Get experiment details including variants and metrics |
70
+
71
+ ### Insights & Analytics
72
+
73
+ | Tool | Description |
74
+ |------|-------------|
75
+ | `list_insights` | List saved insights (trends, funnels, retention, etc.) |
76
+ | `get_insight` | Get a specific insight by ID |
77
+ | `create_insight` | Create a new insight and optionally add to dashboards |
78
+ | `execute_sql` | Execute a HogQL query against PostHog data |
79
+ | `execute_query` | Run structured queries (TrendsQuery, FunnelsQuery, RetentionQuery, etc.) |
80
+
81
+ ### Dashboards
82
+
83
+ | Tool | Description |
84
+ |------|-------------|
85
+ | `list_dashboards` | List all dashboards with optional search |
86
+ | `get_dashboard` | Get dashboard details including its tiles |
87
+
88
+ ### Events & Properties
89
+
90
+ | Tool | Description |
91
+ |------|-------------|
92
+ | `list_event_definitions` | List all tracked event types |
93
+ | `list_property_definitions` | List event or person property definitions |
94
+
95
+ ### Persons & Cohorts
96
+
97
+ | Tool | Description |
98
+ |------|-------------|
99
+ | `list_persons` | Search users by email, name, or distinct ID |
100
+ | `list_cohorts` | List all cohorts (user segments) |
101
+
102
+ ### Annotations
103
+
104
+ | Tool | Description |
105
+ |------|-------------|
106
+ | `list_annotations` | List all chart annotations |
107
+ | `create_annotation` | Create a new annotation marker |
108
+
109
+ ### Surveys & Early Access
110
+
111
+ | Tool | Description |
112
+ |------|-------------|
113
+ | `list_surveys` | List all surveys |
114
+ | `list_early_access_features` | List early access features |
115
+
116
+ ### Organization & Search
117
+
118
+ | Tool | Description |
119
+ |------|-------------|
120
+ | `list_projects` | List all projects for the current API key |
121
+ | `search` | Search across all PostHog entities |
122
+
123
+ ## HogQL Examples
124
+
125
+ Daily event counts for the last 7 days:
126
+
127
+ ```sql
128
+ SELECT toDate(timestamp) as day, count() as events
129
+ FROM events
130
+ WHERE timestamp > now() - INTERVAL 7 DAY
131
+ GROUP BY day ORDER BY day
132
+ ```
133
+
134
+ Unique users by browser:
135
+
136
+ ```sql
137
+ SELECT properties.$browser as browser, uniq(distinct_id) as users
138
+ FROM events
139
+ WHERE event = 'pageview' AND timestamp > now() - INTERVAL 30 DAY
140
+ GROUP BY browser ORDER BY users DESC
141
+ ```
142
+
143
+ Daily active users:
144
+
145
+ ```sql
146
+ SELECT toDate(timestamp) as day, uniq(distinct_id) as dau
147
+ FROM events
148
+ WHERE timestamp > now() - INTERVAL 30 DAY
149
+ GROUP BY day ORDER BY day
150
+ ```
151
+
152
+ ## Programmatic Usage
153
+
154
+ ```typescript
155
+ import { PostHogMCPServer } from "@arvoretech/posthog-mcp";
156
+
157
+ const server = new PostHogMCPServer({
158
+ baseUrl: "https://posthog.example.com",
159
+ apiKey: "phx_your_key",
160
+ projectId: "1",
161
+ });
162
+
163
+ server.setupGracefulShutdown();
164
+ await server.start();
165
+ ```
166
+
167
+ ## Claude Desktop / Kiro Integration
168
+
169
+ ```json
170
+ {
171
+ "mcpServers": {
172
+ "posthog": {
173
+ "command": "npx",
174
+ "args": ["-y", "@arvoretech/posthog-mcp"],
175
+ "env": {
176
+ "POSTHOG_BASE_URL": "https://posthog.example.com",
177
+ "POSTHOG_API_KEY": "phx_your_personal_api_key"
178
+ }
179
+ }
180
+ }
181
+ }
182
+ ```
183
+
184
+ ## Development
185
+
186
+ ```bash
187
+ pnpm install
188
+ pnpm dev
189
+ pnpm build
190
+ pnpm lint
191
+ ```
192
+
193
+ ## Limitations
194
+
195
+ - Stdio transport only (no HTTP/WebSocket)
196
+ - HogQL queries are read-only by design (PostHog API restriction)
197
+ - Requires a Personal API Key (`phx_` prefix), not a project API key
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@arvoretech/posthog-mcp",
3
+ "version": "1.0.0",
4
+ "description": "PostHog MCP Server for analytics, feature flags, experiments, error tracking and more (self-hosted compatible)",
5
+ "main": "dist/index.js",
6
+ "type": "module",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "bin": {
11
+ "posthog-mcp": "./dist/index.js"
12
+ },
13
+ "keywords": [
14
+ "mcp",
15
+ "posthog",
16
+ "analytics",
17
+ "feature-flags",
18
+ "experiments",
19
+ "error-tracking",
20
+ "llm",
21
+ "ai",
22
+ "arvore"
23
+ ],
24
+ "author": "Arvore",
25
+ "license": "MIT",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "https://github.com/arvoreeducacao/arvore-mcp-servers.git",
29
+ "directory": "packages/posthog"
30
+ },
31
+ "dependencies": {
32
+ "@modelcontextprotocol/sdk": "~1.22.0",
33
+ "zod": "^3.22.4"
34
+ },
35
+ "scripts": {
36
+ "build": "tsc",
37
+ "dev": "tsx src/index.ts",
38
+ "start": "node dist/index.js",
39
+ "lint": "eslint src/**/*.ts",
40
+ "lint:fix": "eslint src/**/*.ts --fix"
41
+ }
42
+ }
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import { PostHogMCPServer } from "./server.js";
3
+
4
+ const server = PostHogMCPServer.fromEnvironment();
5
+ server.setupGracefulShutdown();
6
+ server.start();
@@ -0,0 +1,356 @@
1
+ export interface PostHogConfig {
2
+ baseUrl: string;
3
+ apiKey: string;
4
+ projectId?: string;
5
+ }
6
+
7
+ export class PostHogClient {
8
+ private baseUrl: string;
9
+ private apiKey: string;
10
+ private projectId: string;
11
+
12
+ constructor(config: PostHogConfig) {
13
+ this.baseUrl = config.baseUrl.replace(/\/$/, "");
14
+ this.apiKey = config.apiKey;
15
+ this.projectId = config.projectId || "1";
16
+ }
17
+
18
+ private async request<T>(
19
+ method: string,
20
+ path: string,
21
+ body?: unknown
22
+ ): Promise<T> {
23
+ const url = `${this.baseUrl}${path}`;
24
+ const headers: Record<string, string> = {
25
+ Authorization: `Bearer ${this.apiKey}`,
26
+ "Content-Type": "application/json",
27
+ };
28
+
29
+ const response = await fetch(url, {
30
+ method,
31
+ headers,
32
+ ...(body ? { body: JSON.stringify(body) } : {}),
33
+ });
34
+
35
+ if (!response.ok) {
36
+ const errorText = await response.text();
37
+ throw new Error(
38
+ `PostHog API error: ${response.status} ${response.statusText} - ${errorText}`
39
+ );
40
+ }
41
+
42
+ const text = await response.text();
43
+ if (!text) return {} as T;
44
+ return JSON.parse(text) as T;
45
+ }
46
+
47
+ async testConnection(): Promise<boolean> {
48
+ try {
49
+ await this.request("GET", "/api/projects/");
50
+ return true;
51
+ } catch {
52
+ return false;
53
+ }
54
+ }
55
+
56
+ async listProjects(): Promise<unknown> {
57
+ return this.request("GET", "/api/projects/");
58
+ }
59
+
60
+ async getProject(projectId?: string): Promise<unknown> {
61
+ return this.request("GET", `/api/projects/${projectId || this.projectId}/`);
62
+ }
63
+
64
+ async listFeatureFlags(params?: {
65
+ limit?: number;
66
+ offset?: number;
67
+ search?: string;
68
+ }): Promise<unknown> {
69
+ const qs = new URLSearchParams();
70
+ if (params?.limit) qs.set("limit", String(params.limit));
71
+ if (params?.offset) qs.set("offset", String(params.offset));
72
+ if (params?.search) qs.set("search", params.search);
73
+ const query = qs.toString();
74
+ return this.request(
75
+ "GET",
76
+ `/api/projects/${this.projectId}/feature_flags/${query ? `?${query}` : ""}`
77
+ );
78
+ }
79
+
80
+ async getFeatureFlag(id: number): Promise<unknown> {
81
+ return this.request(
82
+ "GET",
83
+ `/api/projects/${this.projectId}/feature_flags/${id}/`
84
+ );
85
+ }
86
+
87
+ async createFeatureFlag(data: {
88
+ key: string;
89
+ name?: string;
90
+ active?: boolean;
91
+ filters?: unknown;
92
+ rollout_percentage?: number;
93
+ }): Promise<unknown> {
94
+ return this.request(
95
+ "POST",
96
+ `/api/projects/${this.projectId}/feature_flags/`,
97
+ data
98
+ );
99
+ }
100
+
101
+ async updateFeatureFlag(
102
+ id: number,
103
+ data: {
104
+ key?: string;
105
+ name?: string;
106
+ active?: boolean;
107
+ filters?: unknown;
108
+ rollout_percentage?: number;
109
+ }
110
+ ): Promise<unknown> {
111
+ return this.request(
112
+ "PATCH",
113
+ `/api/projects/${this.projectId}/feature_flags/${id}/`,
114
+ data
115
+ );
116
+ }
117
+
118
+ async deleteFeatureFlag(id: number): Promise<unknown> {
119
+ return this.request(
120
+ "DELETE",
121
+ `/api/projects/${this.projectId}/feature_flags/${id}/`
122
+ );
123
+ }
124
+
125
+ async listExperiments(params?: {
126
+ limit?: number;
127
+ offset?: number;
128
+ }): Promise<unknown> {
129
+ const qs = new URLSearchParams();
130
+ if (params?.limit) qs.set("limit", String(params.limit));
131
+ if (params?.offset) qs.set("offset", String(params.offset));
132
+ const query = qs.toString();
133
+ return this.request(
134
+ "GET",
135
+ `/api/projects/${this.projectId}/experiments/${query ? `?${query}` : ""}`
136
+ );
137
+ }
138
+
139
+ async getExperiment(id: number): Promise<unknown> {
140
+ return this.request(
141
+ "GET",
142
+ `/api/projects/${this.projectId}/experiments/${id}/`
143
+ );
144
+ }
145
+
146
+ async listInsights(params?: {
147
+ limit?: number;
148
+ offset?: number;
149
+ search?: string;
150
+ }): Promise<unknown> {
151
+ const qs = new URLSearchParams();
152
+ if (params?.limit) qs.set("limit", String(params.limit));
153
+ if (params?.offset) qs.set("offset", String(params.offset));
154
+ if (params?.search) qs.set("search", params.search);
155
+ const query = qs.toString();
156
+ return this.request(
157
+ "GET",
158
+ `/api/projects/${this.projectId}/insights/${query ? `?${query}` : ""}`
159
+ );
160
+ }
161
+
162
+ async getInsight(id: number): Promise<unknown> {
163
+ return this.request(
164
+ "GET",
165
+ `/api/projects/${this.projectId}/insights/${id}/`
166
+ );
167
+ }
168
+
169
+ async listDashboards(params?: {
170
+ limit?: number;
171
+ offset?: number;
172
+ search?: string;
173
+ }): Promise<unknown> {
174
+ const qs = new URLSearchParams();
175
+ if (params?.limit) qs.set("limit", String(params.limit));
176
+ if (params?.offset) qs.set("offset", String(params.offset));
177
+ if (params?.search) qs.set("search", params.search);
178
+ const query = qs.toString();
179
+ return this.request(
180
+ "GET",
181
+ `/api/projects/${this.projectId}/dashboards/${query ? `?${query}` : ""}`
182
+ );
183
+ }
184
+
185
+ async getDashboard(id: number): Promise<unknown> {
186
+ return this.request(
187
+ "GET",
188
+ `/api/projects/${this.projectId}/dashboards/${id}/`
189
+ );
190
+ }
191
+
192
+ async executeQuery(query: unknown): Promise<unknown> {
193
+ return this.request(
194
+ "POST",
195
+ `/api/projects/${this.projectId}/query/`,
196
+ { query }
197
+ );
198
+ }
199
+
200
+ async executeSql(sql: string): Promise<unknown> {
201
+ return this.executeQuery({
202
+ kind: "HogQLQuery",
203
+ query: sql,
204
+ });
205
+ }
206
+
207
+ async listEventDefinitions(params?: {
208
+ limit?: number;
209
+ offset?: number;
210
+ search?: string;
211
+ }): Promise<unknown> {
212
+ const qs = new URLSearchParams();
213
+ if (params?.limit) qs.set("limit", String(params.limit));
214
+ if (params?.offset) qs.set("offset", String(params.offset));
215
+ if (params?.search) qs.set("search", params.search);
216
+ const query = qs.toString();
217
+ return this.request(
218
+ "GET",
219
+ `/api/projects/${this.projectId}/event_definitions/${query ? `?${query}` : ""}`
220
+ );
221
+ }
222
+
223
+ async listPropertyDefinitions(params?: {
224
+ limit?: number;
225
+ offset?: number;
226
+ type?: "event" | "person";
227
+ search?: string;
228
+ }): Promise<unknown> {
229
+ const qs = new URLSearchParams();
230
+ if (params?.limit) qs.set("limit", String(params.limit));
231
+ if (params?.offset) qs.set("offset", String(params.offset));
232
+ if (params?.type) qs.set("type", params.type);
233
+ if (params?.search) qs.set("search", params.search);
234
+ const query = qs.toString();
235
+ return this.request(
236
+ "GET",
237
+ `/api/projects/${this.projectId}/property_definitions/${query ? `?${query}` : ""}`
238
+ );
239
+ }
240
+
241
+ async listCohorts(params?: {
242
+ limit?: number;
243
+ offset?: number;
244
+ }): Promise<unknown> {
245
+ const qs = new URLSearchParams();
246
+ if (params?.limit) qs.set("limit", String(params.limit));
247
+ if (params?.offset) qs.set("offset", String(params.offset));
248
+ const query = qs.toString();
249
+ return this.request(
250
+ "GET",
251
+ `/api/projects/${this.projectId}/cohorts/${query ? `?${query}` : ""}`
252
+ );
253
+ }
254
+
255
+ async listAnnotations(params?: {
256
+ limit?: number;
257
+ offset?: number;
258
+ }): Promise<unknown> {
259
+ const qs = new URLSearchParams();
260
+ if (params?.limit) qs.set("limit", String(params.limit));
261
+ if (params?.offset) qs.set("offset", String(params.offset));
262
+ const query = qs.toString();
263
+ return this.request(
264
+ "GET",
265
+ `/api/projects/${this.projectId}/annotations/${query ? `?${query}` : ""}`
266
+ );
267
+ }
268
+
269
+ async createAnnotation(data: {
270
+ content: string;
271
+ date_marker: string;
272
+ scope?: "project" | "organization";
273
+ }): Promise<unknown> {
274
+ return this.request(
275
+ "POST",
276
+ `/api/projects/${this.projectId}/annotations/`,
277
+ data
278
+ );
279
+ }
280
+
281
+ async listPersons(params?: {
282
+ limit?: number;
283
+ offset?: number;
284
+ search?: string;
285
+ distinct_id?: string;
286
+ }): Promise<unknown> {
287
+ const qs = new URLSearchParams();
288
+ if (params?.limit) qs.set("limit", String(params.limit));
289
+ if (params?.offset) qs.set("offset", String(params.offset));
290
+ if (params?.search) qs.set("search", params.search);
291
+ if (params?.distinct_id) qs.set("distinct_id", params.distinct_id);
292
+ const query = qs.toString();
293
+ return this.request(
294
+ "GET",
295
+ `/api/projects/${this.projectId}/persons/${query ? `?${query}` : ""}`
296
+ );
297
+ }
298
+
299
+ async listSurveys(): Promise<unknown> {
300
+ return this.request(
301
+ "GET",
302
+ `/api/projects/${this.projectId}/surveys/`
303
+ );
304
+ }
305
+
306
+ async listEarlyAccessFeatures(): Promise<unknown> {
307
+ return this.request(
308
+ "GET",
309
+ `/api/projects/${this.projectId}/early_access_feature/`
310
+ );
311
+ }
312
+
313
+ async createInsight(data: {
314
+ name: string;
315
+ description?: string;
316
+ query?: unknown;
317
+ dashboards?: number[];
318
+ saved?: boolean;
319
+ }): Promise<unknown> {
320
+ return this.request(
321
+ "POST",
322
+ `/api/projects/${this.projectId}/insights/`,
323
+ data
324
+ );
325
+ }
326
+
327
+ async updateDashboard(
328
+ id: number,
329
+ data: {
330
+ name?: string;
331
+ description?: string;
332
+ pinned?: boolean;
333
+ tags?: string[];
334
+ }
335
+ ): Promise<unknown> {
336
+ return this.request(
337
+ "PATCH",
338
+ `/api/projects/${this.projectId}/dashboards/${id}/`,
339
+ data
340
+ );
341
+ }
342
+
343
+ async search(query: string, entities?: string[]): Promise<unknown> {
344
+ const qs = new URLSearchParams();
345
+ qs.set("q", query);
346
+ if (entities) {
347
+ for (const entity of entities) {
348
+ qs.append("entities", entity);
349
+ }
350
+ }
351
+ return this.request(
352
+ "GET",
353
+ `/api/projects/${this.projectId}/search/?${qs.toString()}`
354
+ );
355
+ }
356
+ }
package/src/server.ts ADDED
@@ -0,0 +1,608 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { z } from "zod";
4
+ import { PostHogClient, PostHogConfig } from "./posthog-client.js";
5
+
6
+ function result(data: unknown) {
7
+ return {
8
+ content: [
9
+ { type: "text" as const, text: JSON.stringify(data, null, 2) },
10
+ ],
11
+ };
12
+ }
13
+
14
+ function errorResult(error: unknown) {
15
+ const message = error instanceof Error ? error.message : String(error);
16
+ return {
17
+ content: [{ type: "text" as const, text: `Error: ${message}` }],
18
+ isError: true,
19
+ };
20
+ }
21
+
22
+ export class PostHogMCPServer {
23
+ private server: McpServer;
24
+ private client: PostHogClient;
25
+
26
+ constructor(config: PostHogConfig) {
27
+ this.server = new McpServer({
28
+ name: "posthog-mcp-server",
29
+ version: "1.0.0",
30
+ });
31
+
32
+ this.client = new PostHogClient(config);
33
+ this.setupTools();
34
+ }
35
+
36
+ static fromEnvironment(): PostHogMCPServer {
37
+ const baseUrl = process.env.POSTHOG_BASE_URL;
38
+ const apiKey = process.env.POSTHOG_API_KEY;
39
+ const projectId = process.env.POSTHOG_PROJECT_ID;
40
+
41
+ if (!baseUrl || !apiKey) {
42
+ console.error(
43
+ "POSTHOG_BASE_URL and POSTHOG_API_KEY environment variables are required"
44
+ );
45
+ process.exit(1);
46
+ }
47
+
48
+ return new PostHogMCPServer({ baseUrl, apiKey, projectId });
49
+ }
50
+
51
+ private setupTools(): void {
52
+ this.server.registerTool(
53
+ "list_projects",
54
+ {
55
+ title: "List Projects",
56
+ description: "List all PostHog projects accessible with the current API key",
57
+ inputSchema: {},
58
+ },
59
+ async () => {
60
+ try {
61
+ return result(await this.client.listProjects());
62
+ } catch (e) {
63
+ return errorResult(e);
64
+ }
65
+ }
66
+ );
67
+
68
+ this.server.registerTool(
69
+ "list_feature_flags",
70
+ {
71
+ title: "List Feature Flags",
72
+ description:
73
+ "List all feature flags in the project. Supports search and pagination.",
74
+ inputSchema: {
75
+ limit: z.number().optional().describe("Max results to return"),
76
+ offset: z.number().optional().describe("Offset for pagination"),
77
+ search: z.string().optional().describe("Search by flag key or name"),
78
+ },
79
+ },
80
+ async (params) => {
81
+ try {
82
+ return result(await this.client.listFeatureFlags(params));
83
+ } catch (e) {
84
+ return errorResult(e);
85
+ }
86
+ }
87
+ );
88
+
89
+ this.server.registerTool(
90
+ "get_feature_flag",
91
+ {
92
+ title: "Get Feature Flag",
93
+ description: "Get details of a specific feature flag by ID",
94
+ inputSchema: {
95
+ id: z.number().describe("Feature flag ID"),
96
+ },
97
+ },
98
+ async (params) => {
99
+ try {
100
+ return result(await this.client.getFeatureFlag(params.id));
101
+ } catch (e) {
102
+ return errorResult(e);
103
+ }
104
+ }
105
+ );
106
+
107
+ this.server.registerTool(
108
+ "create_feature_flag",
109
+ {
110
+ title: "Create Feature Flag",
111
+ description: "Create a new feature flag",
112
+ inputSchema: {
113
+ key: z.string().describe("Unique key for the feature flag"),
114
+ name: z.string().optional().describe("Human-readable name"),
115
+ active: z.boolean().optional().describe("Whether the flag is active"),
116
+ rollout_percentage: z
117
+ .number()
118
+ .min(0)
119
+ .max(100)
120
+ .optional()
121
+ .describe("Percentage of users to roll out to (0-100)"),
122
+ },
123
+ },
124
+ async (params) => {
125
+ try {
126
+ const data: Record<string, unknown> = { key: params.key };
127
+ if (params.name) data.name = params.name;
128
+ if (params.active !== undefined) data.active = params.active;
129
+ if (params.rollout_percentage !== undefined) {
130
+ data.filters = {
131
+ groups: [
132
+ {
133
+ properties: [],
134
+ rollout_percentage: params.rollout_percentage,
135
+ },
136
+ ],
137
+ };
138
+ }
139
+ return result(await this.client.createFeatureFlag(data as any));
140
+ } catch (e) {
141
+ return errorResult(e);
142
+ }
143
+ }
144
+ );
145
+
146
+ this.server.registerTool(
147
+ "update_feature_flag",
148
+ {
149
+ title: "Update Feature Flag",
150
+ description: "Update an existing feature flag",
151
+ inputSchema: {
152
+ id: z.number().describe("Feature flag ID"),
153
+ key: z.string().optional().describe("New key"),
154
+ name: z.string().optional().describe("New name"),
155
+ active: z.boolean().optional().describe("Enable or disable the flag"),
156
+ },
157
+ },
158
+ async (params) => {
159
+ try {
160
+ const { id, ...data } = params;
161
+ return result(await this.client.updateFeatureFlag(id, data));
162
+ } catch (e) {
163
+ return errorResult(e);
164
+ }
165
+ }
166
+ );
167
+
168
+ this.server.registerTool(
169
+ "delete_feature_flag",
170
+ {
171
+ title: "Delete Feature Flag",
172
+ description: "Delete a feature flag by ID",
173
+ inputSchema: {
174
+ id: z.number().describe("Feature flag ID"),
175
+ },
176
+ },
177
+ async (params) => {
178
+ try {
179
+ return result(await this.client.deleteFeatureFlag(params.id));
180
+ } catch (e) {
181
+ return errorResult(e);
182
+ }
183
+ }
184
+ );
185
+
186
+ this.server.registerTool(
187
+ "list_experiments",
188
+ {
189
+ title: "List Experiments",
190
+ description: "List all A/B test experiments",
191
+ inputSchema: {
192
+ limit: z.number().optional().describe("Max results"),
193
+ offset: z.number().optional().describe("Offset for pagination"),
194
+ },
195
+ },
196
+ async (params) => {
197
+ try {
198
+ return result(await this.client.listExperiments(params));
199
+ } catch (e) {
200
+ return errorResult(e);
201
+ }
202
+ }
203
+ );
204
+
205
+ this.server.registerTool(
206
+ "get_experiment",
207
+ {
208
+ title: "Get Experiment",
209
+ description:
210
+ "Get details of a specific experiment including variants and metrics",
211
+ inputSchema: {
212
+ id: z.number().describe("Experiment ID"),
213
+ },
214
+ },
215
+ async (params) => {
216
+ try {
217
+ return result(await this.client.getExperiment(params.id));
218
+ } catch (e) {
219
+ return errorResult(e);
220
+ }
221
+ }
222
+ );
223
+
224
+ this.server.registerTool(
225
+ "list_insights",
226
+ {
227
+ title: "List Insights",
228
+ description: "List saved insights (trends, funnels, retention, etc.)",
229
+ inputSchema: {
230
+ limit: z.number().optional().describe("Max results"),
231
+ offset: z.number().optional().describe("Offset for pagination"),
232
+ search: z.string().optional().describe("Search by name"),
233
+ },
234
+ },
235
+ async (params) => {
236
+ try {
237
+ return result(await this.client.listInsights(params));
238
+ } catch (e) {
239
+ return errorResult(e);
240
+ }
241
+ }
242
+ );
243
+
244
+ this.server.registerTool(
245
+ "get_insight",
246
+ {
247
+ title: "Get Insight",
248
+ description: "Get details of a specific insight by ID",
249
+ inputSchema: {
250
+ id: z.number().describe("Insight ID"),
251
+ },
252
+ },
253
+ async (params) => {
254
+ try {
255
+ return result(await this.client.getInsight(params.id));
256
+ } catch (e) {
257
+ return errorResult(e);
258
+ }
259
+ }
260
+ );
261
+
262
+ this.server.registerTool(
263
+ "create_insight",
264
+ {
265
+ title: "Create Insight",
266
+ description:
267
+ "Create a new insight and optionally add it to dashboards. Supports TrendsQuery, FunnelsQuery, RetentionQuery, PathsQuery, StickinessQuery, LifecycleQuery via the query field.",
268
+ inputSchema: {
269
+ name: z.string().describe("Name of the insight"),
270
+ description: z.string().optional().describe("Description"),
271
+ query: z
272
+ .record(z.unknown())
273
+ .optional()
274
+ .describe(
275
+ "PostHog query object with 'kind' field (e.g. TrendsQuery, RetentionQuery)"
276
+ ),
277
+ dashboards: z
278
+ .array(z.number())
279
+ .optional()
280
+ .describe("Dashboard IDs to add this insight to"),
281
+ saved: z
282
+ .boolean()
283
+ .optional()
284
+ .describe("Whether to save the insight (default true)"),
285
+ },
286
+ },
287
+ async (params) => {
288
+ try {
289
+ return result(await this.client.createInsight(params));
290
+ } catch (e) {
291
+ return errorResult(e);
292
+ }
293
+ }
294
+ );
295
+
296
+ this.server.registerTool(
297
+ "list_dashboards",
298
+ {
299
+ title: "List Dashboards",
300
+ description: "List all dashboards",
301
+ inputSchema: {
302
+ limit: z.number().optional().describe("Max results"),
303
+ offset: z.number().optional().describe("Offset for pagination"),
304
+ search: z.string().optional().describe("Search by name"),
305
+ },
306
+ },
307
+ async (params) => {
308
+ try {
309
+ return result(await this.client.listDashboards(params));
310
+ } catch (e) {
311
+ return errorResult(e);
312
+ }
313
+ }
314
+ );
315
+
316
+ this.server.registerTool(
317
+ "get_dashboard",
318
+ {
319
+ title: "Get Dashboard",
320
+ description: "Get details of a specific dashboard including its tiles",
321
+ inputSchema: {
322
+ id: z.number().describe("Dashboard ID"),
323
+ },
324
+ },
325
+ async (params) => {
326
+ try {
327
+ return result(await this.client.getDashboard(params.id));
328
+ } catch (e) {
329
+ return errorResult(e);
330
+ }
331
+ }
332
+ );
333
+
334
+ this.server.registerTool(
335
+ "execute_sql",
336
+ {
337
+ title: "Execute SQL (HogQL)",
338
+ description:
339
+ "Execute a HogQL query against PostHog data. HogQL is PostHog's SQL dialect that queries events, persons, groups, and more.",
340
+ inputSchema: {
341
+ query: z.string().describe("HogQL SQL query to execute"),
342
+ },
343
+ },
344
+ async (params) => {
345
+ try {
346
+ return result(await this.client.executeSql(params.query));
347
+ } catch (e) {
348
+ return errorResult(e);
349
+ }
350
+ }
351
+ );
352
+
353
+ this.server.registerTool(
354
+ "execute_query",
355
+ {
356
+ title: "Execute Query",
357
+ description:
358
+ "Execute a PostHog query using the query API. Supports TrendsQuery, FunnelsQuery, RetentionQuery, PathsQuery, StickinessQuery, LifecycleQuery, and HogQLQuery.",
359
+ inputSchema: {
360
+ query: z
361
+ .record(z.unknown())
362
+ .describe(
363
+ "PostHog query object. Must include 'kind' field (e.g. TrendsQuery, FunnelsQuery, HogQLQuery)"
364
+ ),
365
+ },
366
+ },
367
+ async (params) => {
368
+ try {
369
+ return result(await this.client.executeQuery(params.query));
370
+ } catch (e) {
371
+ return errorResult(e);
372
+ }
373
+ }
374
+ );
375
+
376
+ this.server.registerTool(
377
+ "list_event_definitions",
378
+ {
379
+ title: "List Event Definitions",
380
+ description: "List all event definitions (tracked event types)",
381
+ inputSchema: {
382
+ limit: z.number().optional().describe("Max results"),
383
+ offset: z.number().optional().describe("Offset for pagination"),
384
+ search: z.string().optional().describe("Search by event name"),
385
+ },
386
+ },
387
+ async (params) => {
388
+ try {
389
+ return result(await this.client.listEventDefinitions(params));
390
+ } catch (e) {
391
+ return errorResult(e);
392
+ }
393
+ }
394
+ );
395
+
396
+ this.server.registerTool(
397
+ "list_property_definitions",
398
+ {
399
+ title: "List Property Definitions",
400
+ description: "List all property definitions (event or person properties)",
401
+ inputSchema: {
402
+ limit: z.number().optional().describe("Max results"),
403
+ offset: z.number().optional().describe("Offset for pagination"),
404
+ type: z
405
+ .enum(["event", "person"])
406
+ .optional()
407
+ .describe("Filter by property type"),
408
+ search: z.string().optional().describe("Search by property name"),
409
+ },
410
+ },
411
+ async (params) => {
412
+ try {
413
+ return result(await this.client.listPropertyDefinitions(params));
414
+ } catch (e) {
415
+ return errorResult(e);
416
+ }
417
+ }
418
+ );
419
+
420
+ this.server.registerTool(
421
+ "list_cohorts",
422
+ {
423
+ title: "List Cohorts",
424
+ description: "List all cohorts (user segments)",
425
+ inputSchema: {
426
+ limit: z.number().optional().describe("Max results"),
427
+ offset: z.number().optional().describe("Offset for pagination"),
428
+ },
429
+ },
430
+ async (params) => {
431
+ try {
432
+ return result(await this.client.listCohorts(params));
433
+ } catch (e) {
434
+ return errorResult(e);
435
+ }
436
+ }
437
+ );
438
+
439
+ this.server.registerTool(
440
+ "list_persons",
441
+ {
442
+ title: "List Persons",
443
+ description: "List persons (users) with optional search",
444
+ inputSchema: {
445
+ limit: z.number().optional().describe("Max results"),
446
+ offset: z.number().optional().describe("Offset for pagination"),
447
+ search: z
448
+ .string()
449
+ .optional()
450
+ .describe("Search by email, name, or distinct ID"),
451
+ distinct_id: z
452
+ .string()
453
+ .optional()
454
+ .describe("Filter by exact distinct ID"),
455
+ },
456
+ },
457
+ async (params) => {
458
+ try {
459
+ return result(await this.client.listPersons(params));
460
+ } catch (e) {
461
+ return errorResult(e);
462
+ }
463
+ }
464
+ );
465
+
466
+ this.server.registerTool(
467
+ "list_annotations",
468
+ {
469
+ title: "List Annotations",
470
+ description: "List all annotations (markers on charts)",
471
+ inputSchema: {
472
+ limit: z.number().optional().describe("Max results"),
473
+ offset: z.number().optional().describe("Offset for pagination"),
474
+ },
475
+ },
476
+ async (params) => {
477
+ try {
478
+ return result(await this.client.listAnnotations(params));
479
+ } catch (e) {
480
+ return errorResult(e);
481
+ }
482
+ }
483
+ );
484
+
485
+ this.server.registerTool(
486
+ "create_annotation",
487
+ {
488
+ title: "Create Annotation",
489
+ description: "Create a new annotation (marker on charts)",
490
+ inputSchema: {
491
+ content: z.string().describe("Annotation text"),
492
+ date_marker: z
493
+ .string()
494
+ .describe("ISO date string for the annotation marker"),
495
+ scope: z
496
+ .enum(["project", "organization"])
497
+ .optional()
498
+ .describe("Scope of the annotation"),
499
+ },
500
+ },
501
+ async (params) => {
502
+ try {
503
+ return result(await this.client.createAnnotation(params));
504
+ } catch (e) {
505
+ return errorResult(e);
506
+ }
507
+ }
508
+ );
509
+
510
+ this.server.registerTool(
511
+ "list_surveys",
512
+ {
513
+ title: "List Surveys",
514
+ description: "List all surveys",
515
+ inputSchema: {},
516
+ },
517
+ async () => {
518
+ try {
519
+ return result(await this.client.listSurveys());
520
+ } catch (e) {
521
+ return errorResult(e);
522
+ }
523
+ }
524
+ );
525
+
526
+ this.server.registerTool(
527
+ "list_early_access_features",
528
+ {
529
+ title: "List Early Access Features",
530
+ description: "List all early access features",
531
+ inputSchema: {},
532
+ },
533
+ async () => {
534
+ try {
535
+ return result(await this.client.listEarlyAccessFeatures());
536
+ } catch (e) {
537
+ return errorResult(e);
538
+ }
539
+ }
540
+ );
541
+
542
+ this.server.registerTool(
543
+ "search",
544
+ {
545
+ title: "Search PostHog",
546
+ description:
547
+ "Search across PostHog entities (insights, dashboards, feature flags, experiments, cohorts, etc.)",
548
+ inputSchema: {
549
+ query: z.string().describe("Search query"),
550
+ entities: z
551
+ .array(z.string())
552
+ .optional()
553
+ .describe(
554
+ "Entity types to search: insight, dashboard, experiment, feature_flag, cohort, notebook, action"
555
+ ),
556
+ },
557
+ },
558
+ async (params) => {
559
+ try {
560
+ return result(
561
+ await this.client.search(params.query, params.entities)
562
+ );
563
+ } catch (e) {
564
+ return errorResult(e);
565
+ }
566
+ }
567
+ );
568
+ }
569
+
570
+ async start(): Promise<void> {
571
+ try {
572
+ const isConnected = await this.client.testConnection();
573
+ if (!isConnected) {
574
+ throw new Error(
575
+ "PostHog API connection test failed. Check POSTHOG_BASE_URL and POSTHOG_API_KEY."
576
+ );
577
+ }
578
+
579
+ const transport = new StdioServerTransport();
580
+ await this.server.connect(transport);
581
+ console.error("PostHog MCP Server started successfully");
582
+ } catch (error) {
583
+ console.error(
584
+ "Failed to start PostHog MCP Server:",
585
+ error instanceof Error ? error.message : error
586
+ );
587
+ process.exit(1);
588
+ }
589
+ }
590
+
591
+ setupGracefulShutdown(): void {
592
+ const shutdown = async (signal: string): Promise<void> => {
593
+ console.error(`Received ${signal}, shutting down gracefully...`);
594
+ process.exit(0);
595
+ };
596
+
597
+ process.on("SIGINT", () => shutdown("SIGINT"));
598
+ process.on("SIGTERM", () => shutdown("SIGTERM"));
599
+ process.on("uncaughtException", async (error) => {
600
+ console.error("Uncaught exception:", error);
601
+ process.exit(1);
602
+ });
603
+ process.on("unhandledRejection", async (reason) => {
604
+ console.error("Unhandled rejection:", reason);
605
+ process.exit(1);
606
+ });
607
+ }
608
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "./dist",
5
+ "rootDir": "./src"
6
+ },
7
+ "include": ["src/**/*"],
8
+ "exclude": ["node_modules", "dist"]
9
+ }