@arvoretech/posthog-mcp 1.0.0 → 1.0.1

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/src/server.ts DELETED
@@ -1,608 +0,0 @@
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 DELETED
@@ -1,9 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.json",
3
- "compilerOptions": {
4
- "outDir": "./dist",
5
- "rootDir": "./src"
6
- },
7
- "include": ["src/**/*"],
8
- "exclude": ["node_modules", "dist"]
9
- }