@posthog/mcp 0.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.
@@ -0,0 +1,240 @@
1
+ import { EventMessage, PostHogOptions } from "posthog-node";
2
+
3
+ //#region src/types.d.ts
4
+ type JsonRecord = Record<string, unknown>;
5
+ interface MCPRequestParamsLike {
6
+ arguments?: JsonRecord;
7
+ name?: string;
8
+ [key: string]: unknown;
9
+ }
10
+ interface MCPRequestLike {
11
+ id?: number | string;
12
+ jsonrpc?: string;
13
+ method?: string;
14
+ params?: MCPRequestParamsLike;
15
+ [key: string]: unknown;
16
+ }
17
+ interface PostHogCaptureClient {
18
+ capture(props: EventMessage): void;
19
+ flush?(): Promise<void>;
20
+ shutdown?(shutdownTimeoutMs?: number): Promise<void>;
21
+ }
22
+ interface MCPAnalyticsOptions {
23
+ apiKey?: string | null;
24
+ context?: boolean | MCPAnalyticsContextOptions;
25
+ enableAITracing?: boolean;
26
+ enableTracing?: boolean;
27
+ eventProperties?: (request: MCPRequestLike, extra?: CompatibleRequestHandlerExtra) => JsonRecord | null | Promise<JsonRecord | null>;
28
+ eventTags?: (request: MCPRequestLike, extra?: CompatibleRequestHandlerExtra) => Record<string, string> | null | Promise<Record<string, string> | null>;
29
+ host?: string;
30
+ identify?: (request: MCPRequestLike, extra?: CompatibleRequestHandlerExtra) => Promise<UserIdentity | null>;
31
+ posthogClient?: PostHogCaptureClient;
32
+ posthogOptions?: Pick<PostHogOptions, "fetch" | "flushAt" | "flushInterval" | "host" | "requestTimeout" | "waitUntil" | "waitUntilDebounceMs" | "waitUntilMaxWaitMs">;
33
+ redactSensitiveInformation?: RedactFunction;
34
+ reportMissing?: boolean;
35
+ }
36
+ interface MCPAnalyticsContextOptions {
37
+ description?: string;
38
+ }
39
+ type RedactFunction = (text: string) => Promise<string>;
40
+ interface CompatibleRequestHandlerExtra {
41
+ headers?: Record<string, string | string[]>;
42
+ sessionId?: string;
43
+ [key: string]: unknown;
44
+ }
45
+ interface UserIdentity {
46
+ userData?: JsonRecord;
47
+ userId: string;
48
+ userName?: string;
49
+ }
50
+ interface CustomEventData {
51
+ apiKey?: string | null;
52
+ duration?: number;
53
+ error?: unknown;
54
+ isError?: boolean;
55
+ message?: string;
56
+ parameters?: unknown;
57
+ posthogClient?: PostHogCaptureClient;
58
+ properties?: JsonRecord;
59
+ resourceName?: string;
60
+ response?: unknown;
61
+ tags?: Record<string, string>;
62
+ }
63
+ //#endregion
64
+ //#region src/modules/constants.d.ts
65
+ declare const PostHogMCPAnalyticsProperty: {
66
+ readonly AiInputState: "$ai_input_state";
67
+ readonly AiIsError: "$ai_is_error";
68
+ readonly AiLatency: "$ai_latency";
69
+ readonly AiOutputState: "$ai_output_state";
70
+ readonly AiProduct: "$ai_product";
71
+ readonly AiSessionId: "$ai_session_id";
72
+ readonly AiSpanId: "$ai_span_id";
73
+ readonly AiSpanName: "$ai_span_name";
74
+ readonly AiTraceId: "$ai_trace_id";
75
+ readonly ClientName: "$mcp_client_name";
76
+ readonly ClientVersion: "$mcp_client_version";
77
+ readonly DurationMs: "$mcp_duration_ms";
78
+ readonly IsError: "$mcp_is_error";
79
+ readonly Intent: "$mcp_intent";
80
+ readonly Parameters: "$mcp_parameters";
81
+ readonly ResourceName: "$mcp_resource_name";
82
+ readonly Response: "$mcp_response";
83
+ readonly ServerName: "$mcp_server_name";
84
+ readonly ServerVersion: "$mcp_server_version";
85
+ readonly SessionId: "$session_id";
86
+ readonly Source: "$mcp_source";
87
+ readonly ToolName: "$mcp_tool_name";
88
+ };
89
+ type PostHogMCPAnalyticsProperty = (typeof PostHogMCPAnalyticsProperty)[keyof typeof PostHogMCPAnalyticsProperty];
90
+ //#endregion
91
+ //#region src/index.d.ts
92
+ /**
93
+ * Integrates PostHog MCP into an MCP server to track tool usage patterns and user interactions.
94
+ *
95
+ * @param server - The MCP server instance to track. Must be a compatible MCP server implementation.
96
+ * @param options - Configuration to customize tracking behavior.
97
+ * @param options.apiKey - PostHog project API key (`phc_...`). Optional when using an injected `posthogClient`.
98
+ * @param options.host - Custom PostHog ingestion host. Defaults to `https://us.i.posthog.com`.
99
+ * @param options.reportMissing - Adds a "get_more_tools" tool that allows LLMs to automatically report missing functionality. Defaults to false.
100
+ * @param options.enableAITracing - Emits `$ai_span` events for tool calls so MCP activity appears in PostHog LLM analytics. Defaults to false.
101
+ * @param options.enableTracing - Enables tracking of tool calls and usage patterns.
102
+ * @param options.context - Enables the required "context" parameter on tools to capture user intent. Pass false to disable, or an object with a custom description.
103
+ * @param options.identify - Async function to identify users and attach custom data to their sessions.
104
+ * @param options.redactSensitiveInformation - Function to redact sensitive data before sending to PostHog.
105
+ * @param options.eventTags - Callback invoked on every auto-captured event (tool calls, tool lists, initialize) to attach string key-value tags. Tags are intended to be indexed and queryable in PostHog — use them for structured metadata you'll want to filter or group by (e.g., trace IDs, environments, regions). Tags are validated client-side: keys must be ≤32 chars matching `[a-zA-Z0-9$_.:\- ]`, values must be strings ≤200 chars with no newlines, max 50 entries per event. Invalid entries are silently dropped with a warning logged to `~/posthog-mcp-analytics.log`. If the callback throws or returns null, tags are omitted. Receives the same `(request, extra)` arguments as `identify`.
106
+ * @param options.eventProperties - Callback invoked on every auto-captured event to attach flexible JSON metadata (device info, feature flags, nested context). No constraints beyond standard JSON types. If the callback throws or returns null, properties are omitted. Receives the same `(request, extra)` arguments as `identify`.
107
+ * @param options.posthogClient - Optional existing posthog-node compatible client. If provided, MCP events are captured with that client instead of creating a new one.
108
+ * @param options.posthogOptions - Optional posthog-node options used when the SDK creates its own client.
109
+ *
110
+ * @returns The tracked server instance.
111
+ *
112
+ * @remarks
113
+ * Analytics data and debug information are logged to `~/posthog-mcp-analytics.log` since console logs interfere
114
+ * with STDIO-based MCP servers.
115
+ *
116
+ * Do not call `track()` multiple times on the same server instance as this will cause unexpected behavior.
117
+ *
118
+ * @example
119
+ * ```typescript
120
+ * import { track } from "@posthog/mcp";
121
+ *
122
+ * const mcpServer = new Server({ name: "my-mcp-server", version: "1.0.0" });
123
+ *
124
+ * // Track the server with PostHog MCP
125
+ * track(mcpServer, { apiKey: "phc_abc123xyz" });
126
+ *
127
+ * // Register your tools
128
+ * mcpServer.setRequestHandler(ListToolsRequestSchema, async () => ({
129
+ * tools: [{ name: "my_tool", description: "Does something useful" }]
130
+ * }));
131
+ * ```
132
+ *
133
+ * @example
134
+ * ```typescript
135
+ * // With user identification
136
+ * track(mcpServer, {
137
+ * apiKey: "phc_abc123xyz",
138
+ * identify: async (request, extra) => {
139
+ * const user = await getUserFromToken(request.params.arguments.token);
140
+ * return {
141
+ * userId: user.id,
142
+ * userData: { plan: user.plan, company: user.company }
143
+ * };
144
+ * }
145
+ * });
146
+ * ```
147
+ *
148
+ * @example
149
+ * ```typescript
150
+ * // With custom context description
151
+ * track(mcpServer, {
152
+ * apiKey: "phc_abc123xyz",
153
+ * context: {
154
+ * description: "Explain why you're calling this tool and what business objective it helps achieve"
155
+ * }
156
+ * });
157
+ * ```
158
+ *
159
+ * @example
160
+ * ```typescript
161
+ * // With sensitive data redaction
162
+ * track(mcpServer, {
163
+ * apiKey: "phc_abc123xyz",
164
+ * redactSensitiveInformation: async (text) => {
165
+ * return text.replace(/api_key_\w+/g, "[REDACTED]");
166
+ * }
167
+ * });
168
+ * ```
169
+ *
170
+ * @example
171
+ * ```typescript
172
+ * // With event tags and properties
173
+ * track(mcpServer, {
174
+ * apiKey: "phc_abc123xyz",
175
+ * eventTags: async (request, extra) => ({
176
+ * trace_id: extra?.requestContext?.traceId,
177
+ * env: process.env.NODE_ENV,
178
+ * region: "us-east-1",
179
+ * }),
180
+ * eventProperties: async (request, extra) => ({
181
+ * device: "desktop",
182
+ * app_version: "2.1.0",
183
+ * feature_flags: ["dark_mode", "beta_ui"],
184
+ * }),
185
+ * });
186
+ * ```
187
+ *
188
+ * @example
189
+ * ```typescript
190
+ */
191
+ declare function track<TServer>(server: TServer, options?: MCPAnalyticsOptions): TServer;
192
+ /**
193
+ * Publishes a custom event to PostHog MCP with flexible session management.
194
+ *
195
+ * @param serverOrSessionId - Either a tracked MCP server instance or a MCP session ID string
196
+ * @param eventData - Event data to include with the custom event. `apiKey` is required when publishing against a raw session ID.
197
+ *
198
+ * @returns Promise that resolves when the event is queued for publishing
199
+ *
200
+ * @example
201
+ * ```typescript
202
+ * // With a tracked server
203
+ * await publishCustomEvent(
204
+ * server,
205
+ * {
206
+ * resourceName: "custom-action",
207
+ * parameters: { action: "user-feedback", rating: 5 },
208
+ * message: "User provided feedback"
209
+ * }
210
+ * );
211
+ * ```
212
+ *
213
+ * @example
214
+ * ```typescript
215
+ * // With a MCP session ID
216
+ * await publishCustomEvent(
217
+ * "user-session-12345",
218
+ * {
219
+ * apiKey: "phc_abc123xyz",
220
+ * isError: true,
221
+ * error: { message: "Custom error occurred", code: "ERR_001" }
222
+ * }
223
+ * );
224
+ * ```
225
+ *
226
+ * @example
227
+ * ```typescript
228
+ * await publishCustomEvent(
229
+ * server,
230
+ * {
231
+ * resourceName: "feature-usage",
232
+ * }
233
+ * );
234
+ * ```
235
+ */
236
+ declare function publishCustomEvent(serverOrSessionId: unknown, eventData?: CustomEventData): Promise<void>;
237
+ type IdentifyFunction = MCPAnalyticsOptions["identify"];
238
+ //#endregion
239
+ export { type CustomEventData, IdentifyFunction, type MCPAnalyticsContextOptions, type MCPAnalyticsOptions, PostHogMCPAnalyticsProperty, type RedactFunction, type UserIdentity, publishCustomEvent, track };
240
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1,239 @@
1
+ import { EventMessage, PostHogOptions } from "posthog-node";
2
+ //#region src/types.d.ts
3
+ type JsonRecord = Record<string, unknown>;
4
+ interface MCPRequestParamsLike {
5
+ arguments?: JsonRecord;
6
+ name?: string;
7
+ [key: string]: unknown;
8
+ }
9
+ interface MCPRequestLike {
10
+ id?: number | string;
11
+ jsonrpc?: string;
12
+ method?: string;
13
+ params?: MCPRequestParamsLike;
14
+ [key: string]: unknown;
15
+ }
16
+ interface PostHogCaptureClient {
17
+ capture(props: EventMessage): void;
18
+ flush?(): Promise<void>;
19
+ shutdown?(shutdownTimeoutMs?: number): Promise<void>;
20
+ }
21
+ interface MCPAnalyticsOptions {
22
+ apiKey?: string | null;
23
+ context?: boolean | MCPAnalyticsContextOptions;
24
+ enableAITracing?: boolean;
25
+ enableTracing?: boolean;
26
+ eventProperties?: (request: MCPRequestLike, extra?: CompatibleRequestHandlerExtra) => JsonRecord | null | Promise<JsonRecord | null>;
27
+ eventTags?: (request: MCPRequestLike, extra?: CompatibleRequestHandlerExtra) => Record<string, string> | null | Promise<Record<string, string> | null>;
28
+ host?: string;
29
+ identify?: (request: MCPRequestLike, extra?: CompatibleRequestHandlerExtra) => Promise<UserIdentity | null>;
30
+ posthogClient?: PostHogCaptureClient;
31
+ posthogOptions?: Pick<PostHogOptions, "fetch" | "flushAt" | "flushInterval" | "host" | "requestTimeout" | "waitUntil" | "waitUntilDebounceMs" | "waitUntilMaxWaitMs">;
32
+ redactSensitiveInformation?: RedactFunction;
33
+ reportMissing?: boolean;
34
+ }
35
+ interface MCPAnalyticsContextOptions {
36
+ description?: string;
37
+ }
38
+ type RedactFunction = (text: string) => Promise<string>;
39
+ interface CompatibleRequestHandlerExtra {
40
+ headers?: Record<string, string | string[]>;
41
+ sessionId?: string;
42
+ [key: string]: unknown;
43
+ }
44
+ interface UserIdentity {
45
+ userData?: JsonRecord;
46
+ userId: string;
47
+ userName?: string;
48
+ }
49
+ interface CustomEventData {
50
+ apiKey?: string | null;
51
+ duration?: number;
52
+ error?: unknown;
53
+ isError?: boolean;
54
+ message?: string;
55
+ parameters?: unknown;
56
+ posthogClient?: PostHogCaptureClient;
57
+ properties?: JsonRecord;
58
+ resourceName?: string;
59
+ response?: unknown;
60
+ tags?: Record<string, string>;
61
+ }
62
+ //#endregion
63
+ //#region src/modules/constants.d.ts
64
+ declare const PostHogMCPAnalyticsProperty: {
65
+ readonly AiInputState: "$ai_input_state";
66
+ readonly AiIsError: "$ai_is_error";
67
+ readonly AiLatency: "$ai_latency";
68
+ readonly AiOutputState: "$ai_output_state";
69
+ readonly AiProduct: "$ai_product";
70
+ readonly AiSessionId: "$ai_session_id";
71
+ readonly AiSpanId: "$ai_span_id";
72
+ readonly AiSpanName: "$ai_span_name";
73
+ readonly AiTraceId: "$ai_trace_id";
74
+ readonly ClientName: "$mcp_client_name";
75
+ readonly ClientVersion: "$mcp_client_version";
76
+ readonly DurationMs: "$mcp_duration_ms";
77
+ readonly IsError: "$mcp_is_error";
78
+ readonly Intent: "$mcp_intent";
79
+ readonly Parameters: "$mcp_parameters";
80
+ readonly ResourceName: "$mcp_resource_name";
81
+ readonly Response: "$mcp_response";
82
+ readonly ServerName: "$mcp_server_name";
83
+ readonly ServerVersion: "$mcp_server_version";
84
+ readonly SessionId: "$session_id";
85
+ readonly Source: "$mcp_source";
86
+ readonly ToolName: "$mcp_tool_name";
87
+ };
88
+ type PostHogMCPAnalyticsProperty = (typeof PostHogMCPAnalyticsProperty)[keyof typeof PostHogMCPAnalyticsProperty];
89
+ //#endregion
90
+ //#region src/index.d.ts
91
+ /**
92
+ * Integrates PostHog MCP into an MCP server to track tool usage patterns and user interactions.
93
+ *
94
+ * @param server - The MCP server instance to track. Must be a compatible MCP server implementation.
95
+ * @param options - Configuration to customize tracking behavior.
96
+ * @param options.apiKey - PostHog project API key (`phc_...`). Optional when using an injected `posthogClient`.
97
+ * @param options.host - Custom PostHog ingestion host. Defaults to `https://us.i.posthog.com`.
98
+ * @param options.reportMissing - Adds a "get_more_tools" tool that allows LLMs to automatically report missing functionality. Defaults to false.
99
+ * @param options.enableAITracing - Emits `$ai_span` events for tool calls so MCP activity appears in PostHog LLM analytics. Defaults to false.
100
+ * @param options.enableTracing - Enables tracking of tool calls and usage patterns.
101
+ * @param options.context - Enables the required "context" parameter on tools to capture user intent. Pass false to disable, or an object with a custom description.
102
+ * @param options.identify - Async function to identify users and attach custom data to their sessions.
103
+ * @param options.redactSensitiveInformation - Function to redact sensitive data before sending to PostHog.
104
+ * @param options.eventTags - Callback invoked on every auto-captured event (tool calls, tool lists, initialize) to attach string key-value tags. Tags are intended to be indexed and queryable in PostHog — use them for structured metadata you'll want to filter or group by (e.g., trace IDs, environments, regions). Tags are validated client-side: keys must be ≤32 chars matching `[a-zA-Z0-9$_.:\- ]`, values must be strings ≤200 chars with no newlines, max 50 entries per event. Invalid entries are silently dropped with a warning logged to `~/posthog-mcp-analytics.log`. If the callback throws or returns null, tags are omitted. Receives the same `(request, extra)` arguments as `identify`.
105
+ * @param options.eventProperties - Callback invoked on every auto-captured event to attach flexible JSON metadata (device info, feature flags, nested context). No constraints beyond standard JSON types. If the callback throws or returns null, properties are omitted. Receives the same `(request, extra)` arguments as `identify`.
106
+ * @param options.posthogClient - Optional existing posthog-node compatible client. If provided, MCP events are captured with that client instead of creating a new one.
107
+ * @param options.posthogOptions - Optional posthog-node options used when the SDK creates its own client.
108
+ *
109
+ * @returns The tracked server instance.
110
+ *
111
+ * @remarks
112
+ * Analytics data and debug information are logged to `~/posthog-mcp-analytics.log` since console logs interfere
113
+ * with STDIO-based MCP servers.
114
+ *
115
+ * Do not call `track()` multiple times on the same server instance as this will cause unexpected behavior.
116
+ *
117
+ * @example
118
+ * ```typescript
119
+ * import { track } from "@posthog/mcp";
120
+ *
121
+ * const mcpServer = new Server({ name: "my-mcp-server", version: "1.0.0" });
122
+ *
123
+ * // Track the server with PostHog MCP
124
+ * track(mcpServer, { apiKey: "phc_abc123xyz" });
125
+ *
126
+ * // Register your tools
127
+ * mcpServer.setRequestHandler(ListToolsRequestSchema, async () => ({
128
+ * tools: [{ name: "my_tool", description: "Does something useful" }]
129
+ * }));
130
+ * ```
131
+ *
132
+ * @example
133
+ * ```typescript
134
+ * // With user identification
135
+ * track(mcpServer, {
136
+ * apiKey: "phc_abc123xyz",
137
+ * identify: async (request, extra) => {
138
+ * const user = await getUserFromToken(request.params.arguments.token);
139
+ * return {
140
+ * userId: user.id,
141
+ * userData: { plan: user.plan, company: user.company }
142
+ * };
143
+ * }
144
+ * });
145
+ * ```
146
+ *
147
+ * @example
148
+ * ```typescript
149
+ * // With custom context description
150
+ * track(mcpServer, {
151
+ * apiKey: "phc_abc123xyz",
152
+ * context: {
153
+ * description: "Explain why you're calling this tool and what business objective it helps achieve"
154
+ * }
155
+ * });
156
+ * ```
157
+ *
158
+ * @example
159
+ * ```typescript
160
+ * // With sensitive data redaction
161
+ * track(mcpServer, {
162
+ * apiKey: "phc_abc123xyz",
163
+ * redactSensitiveInformation: async (text) => {
164
+ * return text.replace(/api_key_\w+/g, "[REDACTED]");
165
+ * }
166
+ * });
167
+ * ```
168
+ *
169
+ * @example
170
+ * ```typescript
171
+ * // With event tags and properties
172
+ * track(mcpServer, {
173
+ * apiKey: "phc_abc123xyz",
174
+ * eventTags: async (request, extra) => ({
175
+ * trace_id: extra?.requestContext?.traceId,
176
+ * env: process.env.NODE_ENV,
177
+ * region: "us-east-1",
178
+ * }),
179
+ * eventProperties: async (request, extra) => ({
180
+ * device: "desktop",
181
+ * app_version: "2.1.0",
182
+ * feature_flags: ["dark_mode", "beta_ui"],
183
+ * }),
184
+ * });
185
+ * ```
186
+ *
187
+ * @example
188
+ * ```typescript
189
+ */
190
+ declare function track<TServer>(server: TServer, options?: MCPAnalyticsOptions): TServer;
191
+ /**
192
+ * Publishes a custom event to PostHog MCP with flexible session management.
193
+ *
194
+ * @param serverOrSessionId - Either a tracked MCP server instance or a MCP session ID string
195
+ * @param eventData - Event data to include with the custom event. `apiKey` is required when publishing against a raw session ID.
196
+ *
197
+ * @returns Promise that resolves when the event is queued for publishing
198
+ *
199
+ * @example
200
+ * ```typescript
201
+ * // With a tracked server
202
+ * await publishCustomEvent(
203
+ * server,
204
+ * {
205
+ * resourceName: "custom-action",
206
+ * parameters: { action: "user-feedback", rating: 5 },
207
+ * message: "User provided feedback"
208
+ * }
209
+ * );
210
+ * ```
211
+ *
212
+ * @example
213
+ * ```typescript
214
+ * // With a MCP session ID
215
+ * await publishCustomEvent(
216
+ * "user-session-12345",
217
+ * {
218
+ * apiKey: "phc_abc123xyz",
219
+ * isError: true,
220
+ * error: { message: "Custom error occurred", code: "ERR_001" }
221
+ * }
222
+ * );
223
+ * ```
224
+ *
225
+ * @example
226
+ * ```typescript
227
+ * await publishCustomEvent(
228
+ * server,
229
+ * {
230
+ * resourceName: "feature-usage",
231
+ * }
232
+ * );
233
+ * ```
234
+ */
235
+ declare function publishCustomEvent(serverOrSessionId: unknown, eventData?: CustomEventData): Promise<void>;
236
+ type IdentifyFunction = MCPAnalyticsOptions["identify"];
237
+ //#endregion
238
+ export { type CustomEventData, IdentifyFunction, type MCPAnalyticsContextOptions, type MCPAnalyticsOptions, PostHogMCPAnalyticsProperty, type RedactFunction, type UserIdentity, publishCustomEvent, track };
239
+ //# sourceMappingURL=index.d.mts.map