@posthog/mcp 0.0.9 → 0.1.16

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.
Files changed (138) hide show
  1. package/LICENSE +307 -3
  2. package/README.md +182 -90
  3. package/dist/extensions/capture.d.ts +13 -0
  4. package/dist/extensions/capture.d.ts.map +1 -0
  5. package/dist/extensions/capture.js +80 -0
  6. package/dist/extensions/capture.mjs +46 -0
  7. package/dist/extensions/compatibility.d.ts +23 -0
  8. package/dist/extensions/compatibility.d.ts.map +1 -0
  9. package/dist/extensions/compatibility.js +113 -0
  10. package/dist/extensions/compatibility.mjs +67 -0
  11. package/dist/extensions/constants.d.ts +39 -0
  12. package/dist/extensions/constants.d.ts.map +1 -0
  13. package/dist/extensions/constants.js +86 -0
  14. package/dist/extensions/constants.mjs +37 -0
  15. package/dist/extensions/context-parameters.d.ts +31 -0
  16. package/dist/extensions/context-parameters.d.ts.map +1 -0
  17. package/dist/extensions/context-parameters.js +93 -0
  18. package/dist/extensions/context-parameters.mjs +50 -0
  19. package/dist/extensions/conversation-id.d.ts +52 -0
  20. package/dist/extensions/conversation-id.d.ts.map +1 -0
  21. package/dist/extensions/conversation-id.js +164 -0
  22. package/dist/extensions/conversation-id.mjs +103 -0
  23. package/dist/extensions/event-types.d.ts +21 -0
  24. package/dist/extensions/event-types.d.ts.map +1 -0
  25. package/dist/extensions/event-types.js +47 -0
  26. package/dist/extensions/event-types.mjs +13 -0
  27. package/dist/extensions/exceptions.d.ts +13 -0
  28. package/dist/extensions/exceptions.d.ts.map +1 -0
  29. package/dist/extensions/exceptions.js +58 -0
  30. package/dist/extensions/exceptions.mjs +24 -0
  31. package/dist/extensions/ids.d.ts +13 -0
  32. package/dist/extensions/ids.d.ts.map +1 -0
  33. package/dist/extensions/ids.js +55 -0
  34. package/dist/extensions/ids.mjs +18 -0
  35. package/dist/extensions/instrument-highlevel.d.ts +3 -0
  36. package/dist/extensions/instrument-highlevel.d.ts.map +1 -0
  37. package/dist/extensions/instrument-highlevel.js +229 -0
  38. package/dist/extensions/instrument-highlevel.mjs +195 -0
  39. package/dist/extensions/instrument-lowlevel.d.ts +8 -0
  40. package/dist/extensions/instrument-lowlevel.d.ts.map +1 -0
  41. package/dist/extensions/instrument-lowlevel.js +85 -0
  42. package/dist/extensions/instrument-lowlevel.mjs +51 -0
  43. package/dist/extensions/instrumentation.d.ts +59 -0
  44. package/dist/extensions/instrumentation.d.ts.map +1 -0
  45. package/dist/extensions/instrumentation.js +237 -0
  46. package/dist/extensions/instrumentation.mjs +194 -0
  47. package/dist/extensions/intent.d.ts +10 -0
  48. package/dist/extensions/intent.d.ts.map +1 -0
  49. package/dist/extensions/intent.js +84 -0
  50. package/dist/extensions/intent.mjs +44 -0
  51. package/dist/extensions/internal.d.ts +32 -0
  52. package/dist/extensions/internal.d.ts.map +1 -0
  53. package/dist/extensions/internal.js +158 -0
  54. package/dist/extensions/internal.mjs +106 -0
  55. package/dist/extensions/logger.d.ts +14 -0
  56. package/dist/extensions/logger.d.ts.map +1 -0
  57. package/dist/extensions/logger.js +47 -0
  58. package/dist/extensions/logger.mjs +10 -0
  59. package/dist/extensions/mcp-payloads.d.ts +5 -0
  60. package/dist/extensions/mcp-payloads.d.ts.map +1 -0
  61. package/dist/extensions/mcp-payloads.js +91 -0
  62. package/dist/extensions/mcp-payloads.mjs +54 -0
  63. package/dist/extensions/mcp-sdk-compat.d.ts +33 -0
  64. package/dist/extensions/mcp-sdk-compat.d.ts.map +1 -0
  65. package/dist/extensions/mcp-sdk-compat.js +112 -0
  66. package/dist/extensions/mcp-sdk-compat.mjs +60 -0
  67. package/dist/extensions/posthog-events.d.ts +14 -0
  68. package/dist/extensions/posthog-events.d.ts.map +1 -0
  69. package/dist/extensions/posthog-events.js +143 -0
  70. package/dist/extensions/posthog-events.mjs +109 -0
  71. package/dist/extensions/sanitization.d.ts +10 -0
  72. package/dist/extensions/sanitization.d.ts.map +1 -0
  73. package/dist/extensions/sanitization.js +96 -0
  74. package/dist/extensions/sanitization.mjs +62 -0
  75. package/dist/extensions/session.d.ts +20 -0
  76. package/dist/extensions/session.d.ts.map +1 -0
  77. package/dist/extensions/session.js +113 -0
  78. package/dist/extensions/session.mjs +67 -0
  79. package/dist/extensions/sink.d.ts +44 -0
  80. package/dist/extensions/sink.d.ts.map +1 -0
  81. package/dist/extensions/sink.js +102 -0
  82. package/dist/extensions/sink.mjs +65 -0
  83. package/dist/extensions/tools.d.ts +9 -0
  84. package/dist/extensions/tools.d.ts.map +1 -0
  85. package/dist/extensions/tools.js +79 -0
  86. package/dist/extensions/tools.mjs +39 -0
  87. package/dist/extensions/tracing-helpers.d.ts +29 -0
  88. package/dist/extensions/tracing-helpers.d.ts.map +1 -0
  89. package/dist/extensions/tracing-helpers.js +59 -0
  90. package/dist/extensions/tracing-helpers.mjs +16 -0
  91. package/dist/extensions/truncation.d.ts +25 -0
  92. package/dist/extensions/truncation.d.ts.map +1 -0
  93. package/dist/extensions/truncation.js +277 -0
  94. package/dist/extensions/truncation.mjs +228 -0
  95. package/dist/index.d.ts +36 -0
  96. package/dist/index.d.ts.map +1 -0
  97. package/dist/index.js +132 -0
  98. package/dist/index.mjs +83 -2929
  99. package/dist/types.d.ts +220 -0
  100. package/dist/types.d.ts.map +1 -0
  101. package/dist/types.js +18 -0
  102. package/dist/types.mjs +0 -0
  103. package/dist/version.d.ts +2 -0
  104. package/dist/version.d.ts.map +1 -0
  105. package/dist/version.js +36 -0
  106. package/dist/version.mjs +2 -0
  107. package/package.json +55 -87
  108. package/src/extensions/capture.ts +68 -0
  109. package/src/extensions/compatibility.ts +138 -0
  110. package/src/extensions/constants.ts +48 -0
  111. package/src/extensions/context-parameters.ts +119 -0
  112. package/src/extensions/conversation-id.ts +177 -0
  113. package/src/extensions/event-types.ts +21 -0
  114. package/src/extensions/exceptions.ts +83 -0
  115. package/src/extensions/ids.ts +32 -0
  116. package/src/extensions/instrument-highlevel.ts +297 -0
  117. package/src/extensions/instrument-lowlevel.ts +83 -0
  118. package/src/extensions/instrumentation.ts +415 -0
  119. package/src/extensions/intent.ts +78 -0
  120. package/src/extensions/internal.ts +193 -0
  121. package/src/extensions/logger.ts +27 -0
  122. package/src/extensions/mcp-payloads.ts +98 -0
  123. package/src/extensions/mcp-sdk-compat.ts +160 -0
  124. package/src/extensions/posthog-events.ts +212 -0
  125. package/src/extensions/sanitization.ts +121 -0
  126. package/src/extensions/session.ts +117 -0
  127. package/src/extensions/sink.ts +130 -0
  128. package/src/extensions/tools.ts +50 -0
  129. package/src/extensions/tracing-helpers.ts +51 -0
  130. package/src/extensions/truncation.ts +453 -0
  131. package/src/index.ts +174 -0
  132. package/src/types.ts +244 -0
  133. package/src/version.ts +1 -0
  134. package/dist/index.cjs +0 -2937
  135. package/dist/index.cjs.map +0 -1
  136. package/dist/index.d.cts +0 -264
  137. package/dist/index.d.mts +0 -263
  138. package/dist/index.mjs.map +0 -1
package/dist/index.d.cts DELETED
@@ -1,264 +0,0 @@
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
- enableConversationId?: boolean;
27
- enableTracing?: boolean;
28
- eventProperties?: (request: MCPRequestLike, extra?: CompatibleRequestHandlerExtra) => JsonRecord | null | Promise<JsonRecord | null>;
29
- eventTags?: (request: MCPRequestLike, extra?: CompatibleRequestHandlerExtra) => Record<string, string> | null | Promise<Record<string, string> | null>;
30
- host?: string;
31
- identify?: ((request: MCPRequestLike, extra?: CompatibleRequestHandlerExtra) => Promise<UserIdentity | null>) | UserIdentity | null;
32
- intentFallback?: (request: MCPRequestLike, extra?: CompatibleRequestHandlerExtra) => MaybePromise<string | null | undefined>;
33
- posthogClient?: PostHogCaptureClient;
34
- posthogOptions?: Pick<PostHogOptions, "fetch" | "flushAt" | "flushInterval" | "host" | "requestTimeout" | "waitUntil" | "waitUntilDebounceMs" | "waitUntilMaxWaitMs">;
35
- redactSensitiveInformation?: RedactFunction;
36
- reportMissing?: boolean;
37
- }
38
- interface MCPAnalyticsContextOptions {
39
- description?: string;
40
- }
41
- type MaybePromise<T> = T | Promise<T>;
42
- type MCPAnalyticsIntentSource = "context_parameter" | "inferred";
43
- type RedactFunction = (text: string) => Promise<string>;
44
- interface CompatibleRequestHandlerExtra {
45
- headers?: Record<string, string | string[]>;
46
- sessionId?: string;
47
- [key: string]: unknown;
48
- }
49
- interface UserIdentity {
50
- userData?: JsonRecord;
51
- userId: string;
52
- userName?: string;
53
- }
54
- interface CustomEventData {
55
- apiKey?: string | null;
56
- duration?: number;
57
- error?: unknown;
58
- isError?: boolean;
59
- message?: string;
60
- parameters?: unknown;
61
- posthogClient?: PostHogCaptureClient;
62
- properties?: JsonRecord;
63
- resourceName?: string;
64
- response?: unknown;
65
- tags?: Record<string, string>;
66
- }
67
- //#endregion
68
- //#region src/modules/constants.d.ts
69
- declare const POSTHOG_MCP_ANALYTICS_SOURCE = "posthog_mcp_analytics";
70
- declare const PostHogMCPAnalyticsEvent: {
71
- readonly AiSpan: "$ai_span";
72
- readonly Custom: "mcp_custom";
73
- readonly Exception: "$exception";
74
- readonly Identify: "$identify";
75
- readonly Initialize: "mcp_initialize";
76
- readonly PromptGet: "mcp_prompt_get";
77
- readonly PromptsList: "mcp_prompts_list";
78
- readonly ResourceRead: "mcp_resource_read";
79
- readonly ResourcesList: "mcp_resources_list";
80
- readonly ToolCall: "mcp_tool_call";
81
- readonly ToolsList: "mcp_tools_list";
82
- };
83
- type PostHogMCPAnalyticsEvent = (typeof PostHogMCPAnalyticsEvent)[keyof typeof PostHogMCPAnalyticsEvent];
84
- declare const PostHogMCPAnalyticsProperty: {
85
- readonly AiInputState: "$ai_input_state";
86
- readonly AiIsError: "$ai_is_error";
87
- readonly AiLatency: "$ai_latency";
88
- readonly AiOutputState: "$ai_output_state";
89
- readonly AiProduct: "$ai_product";
90
- readonly AiSessionId: "$ai_session_id";
91
- readonly AiSpanId: "$ai_span_id";
92
- readonly AiSpanName: "$ai_span_name";
93
- readonly AiTraceId: "$ai_trace_id";
94
- readonly ClientName: "$mcp_client_name";
95
- readonly ClientVersion: "$mcp_client_version";
96
- readonly ConversationId: "$mcp_conversation_id";
97
- readonly DurationMs: "$mcp_duration_ms";
98
- readonly IsError: "$mcp_is_error";
99
- readonly Intent: "$mcp_intent";
100
- readonly IntentSource: "$mcp_intent_source";
101
- readonly ListedToolNames: "$mcp_listed_tool_names";
102
- readonly Parameters: "$mcp_parameters";
103
- readonly ResourceName: "$mcp_resource_name";
104
- readonly Response: "$mcp_response";
105
- readonly ServerName: "$mcp_server_name";
106
- readonly ServerVersion: "$mcp_server_version";
107
- readonly SessionId: "$session_id";
108
- readonly Source: "$mcp_source";
109
- readonly ToolDescription: "$mcp_tool_description";
110
- readonly ToolName: "$mcp_tool_name";
111
- };
112
- type PostHogMCPAnalyticsProperty = (typeof PostHogMCPAnalyticsProperty)[keyof typeof PostHogMCPAnalyticsProperty];
113
- //#endregion
114
- //#region src/index.d.ts
115
- /**
116
- * Integrates PostHog MCP into an MCP server to track tool usage patterns and user interactions.
117
- *
118
- * @param server - The MCP server instance to track. Must be a compatible MCP server implementation.
119
- * @param options - Configuration to customize tracking behavior.
120
- * @param options.apiKey - PostHog project API key (`phc_...`). Optional when using an injected `posthogClient`.
121
- * @param options.host - Custom PostHog ingestion host. Defaults to `https://us.i.posthog.com`.
122
- * @param options.reportMissing - Adds a "get_more_tools" tool that allows LLMs to automatically report missing functionality. Defaults to false.
123
- * @param options.enableAITracing - Emits `$ai_span` events for tool calls so MCP activity appears in PostHog LLM analytics. Defaults to false.
124
- * @param options.enableTracing - Enables tracking of tool calls and usage patterns.
125
- * @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.
126
- * @param options.intentFallback - Optional consumer-supplied callback invoked when a tool call has no explicit `context` argument. Return a short user intent string to capture as `$mcp_intent` (with `$mcp_intent_source = "inferred"`). The SDK does not infer anything on its own — this is purely a slot for your own derivation logic (e.g. a switch on `request.params.name`, an LLM call, etc.). Runs on the hot path of every uncontextualized tool call.
127
- * @param options.identify - Async function to identify users and attach custom data to their sessions.
128
- * @param options.redactSensitiveInformation - Function to redact sensitive data before sending to PostHog.
129
- * @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`.
130
- * @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`.
131
- * @param options.posthogClient - Optional existing posthog-node compatible client. If provided, MCP events are captured with that client instead of creating a new one.
132
- * @param options.posthogOptions - Optional posthog-node options used when the SDK creates its own client.
133
- *
134
- * @returns The tracked server instance.
135
- *
136
- * @remarks
137
- * Analytics data and debug information are logged to `~/posthog-mcp-analytics.log` since console logs interfere
138
- * with STDIO-based MCP servers.
139
- *
140
- * Do not call `track()` multiple times on the same server instance as this will cause unexpected behavior.
141
- *
142
- * @example
143
- * ```typescript
144
- * import { track } from "@posthog/mcp";
145
- *
146
- * const mcpServer = new Server({ name: "my-mcp-server", version: "1.0.0" });
147
- *
148
- * // Track the server with PostHog MCP
149
- * track(mcpServer, { apiKey: "phc_abc123xyz" });
150
- *
151
- * // Register your tools
152
- * mcpServer.setRequestHandler(ListToolsRequestSchema, async () => ({
153
- * tools: [{ name: "my_tool", description: "Does something useful" }]
154
- * }));
155
- * ```
156
- *
157
- * @example
158
- * ```typescript
159
- * // With user identification
160
- * track(mcpServer, {
161
- * apiKey: "phc_abc123xyz",
162
- * identify: async (request, extra) => {
163
- * const user = await getUserFromToken(request.params.arguments.token);
164
- * return {
165
- * userId: user.id,
166
- * userData: { plan: user.plan, company: user.company }
167
- * };
168
- * }
169
- * });
170
- * ```
171
- *
172
- * @example
173
- * ```typescript
174
- * // With custom context description
175
- * track(mcpServer, {
176
- * apiKey: "phc_abc123xyz",
177
- * context: {
178
- * description: "Explain why you're calling this tool and what business objective it helps achieve"
179
- * }
180
- * });
181
- * ```
182
- *
183
- * @example
184
- * ```typescript
185
- * // With sensitive data redaction
186
- * track(mcpServer, {
187
- * apiKey: "phc_abc123xyz",
188
- * redactSensitiveInformation: async (text) => {
189
- * return text.replace(/api_key_\w+/g, "[REDACTED]");
190
- * }
191
- * });
192
- * ```
193
- *
194
- * @example
195
- * ```typescript
196
- * // With event tags and properties
197
- * track(mcpServer, {
198
- * apiKey: "phc_abc123xyz",
199
- * eventTags: async (request, extra) => ({
200
- * trace_id: extra?.requestContext?.traceId,
201
- * env: process.env.NODE_ENV,
202
- * region: "us-east-1",
203
- * }),
204
- * eventProperties: async (request, extra) => ({
205
- * device: "desktop",
206
- * app_version: "2.1.0",
207
- * feature_flags: ["dark_mode", "beta_ui"],
208
- * }),
209
- * });
210
- * ```
211
- *
212
- * @example
213
- * ```typescript
214
- */
215
- declare function track<TServer>(server: TServer, options?: MCPAnalyticsOptions): TServer;
216
- /**
217
- * Publishes a custom event to PostHog MCP with flexible session management.
218
- *
219
- * @param serverOrSessionId - Either a tracked MCP server instance or a MCP session ID string
220
- * @param eventData - Event data to include with the custom event. `apiKey` is required when publishing against a raw session ID.
221
- *
222
- * @returns Promise that resolves when the event is queued for publishing
223
- *
224
- * @example
225
- * ```typescript
226
- * // With a tracked server
227
- * await publishCustomEvent(
228
- * server,
229
- * {
230
- * resourceName: "custom-action",
231
- * parameters: { action: "user-feedback", rating: 5 },
232
- * message: "User provided feedback"
233
- * }
234
- * );
235
- * ```
236
- *
237
- * @example
238
- * ```typescript
239
- * // With a MCP session ID
240
- * await publishCustomEvent(
241
- * "user-session-12345",
242
- * {
243
- * apiKey: "phc_abc123xyz",
244
- * isError: true,
245
- * error: { message: "Custom error occurred", code: "ERR_001" }
246
- * }
247
- * );
248
- * ```
249
- *
250
- * @example
251
- * ```typescript
252
- * await publishCustomEvent(
253
- * server,
254
- * {
255
- * resourceName: "feature-usage",
256
- * }
257
- * );
258
- * ```
259
- */
260
- declare function publishCustomEvent(serverOrSessionId: unknown, eventData?: CustomEventData): Promise<void>;
261
- type IdentifyFunction = MCPAnalyticsOptions["identify"];
262
- //#endregion
263
- export { type CustomEventData, IdentifyFunction, type MCPAnalyticsContextOptions, type MCPAnalyticsIntentSource, type MCPAnalyticsOptions, POSTHOG_MCP_ANALYTICS_SOURCE, PostHogMCPAnalyticsEvent, PostHogMCPAnalyticsProperty, type RedactFunction, type UserIdentity, publishCustomEvent, track };
264
- //# sourceMappingURL=index.d.cts.map
package/dist/index.d.mts DELETED
@@ -1,263 +0,0 @@
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
- enableConversationId?: 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>) | UserIdentity | null;
31
- intentFallback?: (request: MCPRequestLike, extra?: CompatibleRequestHandlerExtra) => MaybePromise<string | null | undefined>;
32
- posthogClient?: PostHogCaptureClient;
33
- posthogOptions?: Pick<PostHogOptions, "fetch" | "flushAt" | "flushInterval" | "host" | "requestTimeout" | "waitUntil" | "waitUntilDebounceMs" | "waitUntilMaxWaitMs">;
34
- redactSensitiveInformation?: RedactFunction;
35
- reportMissing?: boolean;
36
- }
37
- interface MCPAnalyticsContextOptions {
38
- description?: string;
39
- }
40
- type MaybePromise<T> = T | Promise<T>;
41
- type MCPAnalyticsIntentSource = "context_parameter" | "inferred";
42
- type RedactFunction = (text: string) => Promise<string>;
43
- interface CompatibleRequestHandlerExtra {
44
- headers?: Record<string, string | string[]>;
45
- sessionId?: string;
46
- [key: string]: unknown;
47
- }
48
- interface UserIdentity {
49
- userData?: JsonRecord;
50
- userId: string;
51
- userName?: string;
52
- }
53
- interface CustomEventData {
54
- apiKey?: string | null;
55
- duration?: number;
56
- error?: unknown;
57
- isError?: boolean;
58
- message?: string;
59
- parameters?: unknown;
60
- posthogClient?: PostHogCaptureClient;
61
- properties?: JsonRecord;
62
- resourceName?: string;
63
- response?: unknown;
64
- tags?: Record<string, string>;
65
- }
66
- //#endregion
67
- //#region src/modules/constants.d.ts
68
- declare const POSTHOG_MCP_ANALYTICS_SOURCE = "posthog_mcp_analytics";
69
- declare const PostHogMCPAnalyticsEvent: {
70
- readonly AiSpan: "$ai_span";
71
- readonly Custom: "mcp_custom";
72
- readonly Exception: "$exception";
73
- readonly Identify: "$identify";
74
- readonly Initialize: "mcp_initialize";
75
- readonly PromptGet: "mcp_prompt_get";
76
- readonly PromptsList: "mcp_prompts_list";
77
- readonly ResourceRead: "mcp_resource_read";
78
- readonly ResourcesList: "mcp_resources_list";
79
- readonly ToolCall: "mcp_tool_call";
80
- readonly ToolsList: "mcp_tools_list";
81
- };
82
- type PostHogMCPAnalyticsEvent = (typeof PostHogMCPAnalyticsEvent)[keyof typeof PostHogMCPAnalyticsEvent];
83
- declare const PostHogMCPAnalyticsProperty: {
84
- readonly AiInputState: "$ai_input_state";
85
- readonly AiIsError: "$ai_is_error";
86
- readonly AiLatency: "$ai_latency";
87
- readonly AiOutputState: "$ai_output_state";
88
- readonly AiProduct: "$ai_product";
89
- readonly AiSessionId: "$ai_session_id";
90
- readonly AiSpanId: "$ai_span_id";
91
- readonly AiSpanName: "$ai_span_name";
92
- readonly AiTraceId: "$ai_trace_id";
93
- readonly ClientName: "$mcp_client_name";
94
- readonly ClientVersion: "$mcp_client_version";
95
- readonly ConversationId: "$mcp_conversation_id";
96
- readonly DurationMs: "$mcp_duration_ms";
97
- readonly IsError: "$mcp_is_error";
98
- readonly Intent: "$mcp_intent";
99
- readonly IntentSource: "$mcp_intent_source";
100
- readonly ListedToolNames: "$mcp_listed_tool_names";
101
- readonly Parameters: "$mcp_parameters";
102
- readonly ResourceName: "$mcp_resource_name";
103
- readonly Response: "$mcp_response";
104
- readonly ServerName: "$mcp_server_name";
105
- readonly ServerVersion: "$mcp_server_version";
106
- readonly SessionId: "$session_id";
107
- readonly Source: "$mcp_source";
108
- readonly ToolDescription: "$mcp_tool_description";
109
- readonly ToolName: "$mcp_tool_name";
110
- };
111
- type PostHogMCPAnalyticsProperty = (typeof PostHogMCPAnalyticsProperty)[keyof typeof PostHogMCPAnalyticsProperty];
112
- //#endregion
113
- //#region src/index.d.ts
114
- /**
115
- * Integrates PostHog MCP into an MCP server to track tool usage patterns and user interactions.
116
- *
117
- * @param server - The MCP server instance to track. Must be a compatible MCP server implementation.
118
- * @param options - Configuration to customize tracking behavior.
119
- * @param options.apiKey - PostHog project API key (`phc_...`). Optional when using an injected `posthogClient`.
120
- * @param options.host - Custom PostHog ingestion host. Defaults to `https://us.i.posthog.com`.
121
- * @param options.reportMissing - Adds a "get_more_tools" tool that allows LLMs to automatically report missing functionality. Defaults to false.
122
- * @param options.enableAITracing - Emits `$ai_span` events for tool calls so MCP activity appears in PostHog LLM analytics. Defaults to false.
123
- * @param options.enableTracing - Enables tracking of tool calls and usage patterns.
124
- * @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.
125
- * @param options.intentFallback - Optional consumer-supplied callback invoked when a tool call has no explicit `context` argument. Return a short user intent string to capture as `$mcp_intent` (with `$mcp_intent_source = "inferred"`). The SDK does not infer anything on its own — this is purely a slot for your own derivation logic (e.g. a switch on `request.params.name`, an LLM call, etc.). Runs on the hot path of every uncontextualized tool call.
126
- * @param options.identify - Async function to identify users and attach custom data to their sessions.
127
- * @param options.redactSensitiveInformation - Function to redact sensitive data before sending to PostHog.
128
- * @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`.
129
- * @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`.
130
- * @param options.posthogClient - Optional existing posthog-node compatible client. If provided, MCP events are captured with that client instead of creating a new one.
131
- * @param options.posthogOptions - Optional posthog-node options used when the SDK creates its own client.
132
- *
133
- * @returns The tracked server instance.
134
- *
135
- * @remarks
136
- * Analytics data and debug information are logged to `~/posthog-mcp-analytics.log` since console logs interfere
137
- * with STDIO-based MCP servers.
138
- *
139
- * Do not call `track()` multiple times on the same server instance as this will cause unexpected behavior.
140
- *
141
- * @example
142
- * ```typescript
143
- * import { track } from "@posthog/mcp";
144
- *
145
- * const mcpServer = new Server({ name: "my-mcp-server", version: "1.0.0" });
146
- *
147
- * // Track the server with PostHog MCP
148
- * track(mcpServer, { apiKey: "phc_abc123xyz" });
149
- *
150
- * // Register your tools
151
- * mcpServer.setRequestHandler(ListToolsRequestSchema, async () => ({
152
- * tools: [{ name: "my_tool", description: "Does something useful" }]
153
- * }));
154
- * ```
155
- *
156
- * @example
157
- * ```typescript
158
- * // With user identification
159
- * track(mcpServer, {
160
- * apiKey: "phc_abc123xyz",
161
- * identify: async (request, extra) => {
162
- * const user = await getUserFromToken(request.params.arguments.token);
163
- * return {
164
- * userId: user.id,
165
- * userData: { plan: user.plan, company: user.company }
166
- * };
167
- * }
168
- * });
169
- * ```
170
- *
171
- * @example
172
- * ```typescript
173
- * // With custom context description
174
- * track(mcpServer, {
175
- * apiKey: "phc_abc123xyz",
176
- * context: {
177
- * description: "Explain why you're calling this tool and what business objective it helps achieve"
178
- * }
179
- * });
180
- * ```
181
- *
182
- * @example
183
- * ```typescript
184
- * // With sensitive data redaction
185
- * track(mcpServer, {
186
- * apiKey: "phc_abc123xyz",
187
- * redactSensitiveInformation: async (text) => {
188
- * return text.replace(/api_key_\w+/g, "[REDACTED]");
189
- * }
190
- * });
191
- * ```
192
- *
193
- * @example
194
- * ```typescript
195
- * // With event tags and properties
196
- * track(mcpServer, {
197
- * apiKey: "phc_abc123xyz",
198
- * eventTags: async (request, extra) => ({
199
- * trace_id: extra?.requestContext?.traceId,
200
- * env: process.env.NODE_ENV,
201
- * region: "us-east-1",
202
- * }),
203
- * eventProperties: async (request, extra) => ({
204
- * device: "desktop",
205
- * app_version: "2.1.0",
206
- * feature_flags: ["dark_mode", "beta_ui"],
207
- * }),
208
- * });
209
- * ```
210
- *
211
- * @example
212
- * ```typescript
213
- */
214
- declare function track<TServer>(server: TServer, options?: MCPAnalyticsOptions): TServer;
215
- /**
216
- * Publishes a custom event to PostHog MCP with flexible session management.
217
- *
218
- * @param serverOrSessionId - Either a tracked MCP server instance or a MCP session ID string
219
- * @param eventData - Event data to include with the custom event. `apiKey` is required when publishing against a raw session ID.
220
- *
221
- * @returns Promise that resolves when the event is queued for publishing
222
- *
223
- * @example
224
- * ```typescript
225
- * // With a tracked server
226
- * await publishCustomEvent(
227
- * server,
228
- * {
229
- * resourceName: "custom-action",
230
- * parameters: { action: "user-feedback", rating: 5 },
231
- * message: "User provided feedback"
232
- * }
233
- * );
234
- * ```
235
- *
236
- * @example
237
- * ```typescript
238
- * // With a MCP session ID
239
- * await publishCustomEvent(
240
- * "user-session-12345",
241
- * {
242
- * apiKey: "phc_abc123xyz",
243
- * isError: true,
244
- * error: { message: "Custom error occurred", code: "ERR_001" }
245
- * }
246
- * );
247
- * ```
248
- *
249
- * @example
250
- * ```typescript
251
- * await publishCustomEvent(
252
- * server,
253
- * {
254
- * resourceName: "feature-usage",
255
- * }
256
- * );
257
- * ```
258
- */
259
- declare function publishCustomEvent(serverOrSessionId: unknown, eventData?: CustomEventData): Promise<void>;
260
- type IdentifyFunction = MCPAnalyticsOptions["identify"];
261
- //#endregion
262
- export { type CustomEventData, IdentifyFunction, type MCPAnalyticsContextOptions, type MCPAnalyticsIntentSource, type MCPAnalyticsOptions, POSTHOG_MCP_ANALYTICS_SOURCE, PostHogMCPAnalyticsEvent, PostHogMCPAnalyticsProperty, type RedactFunction, type UserIdentity, publishCustomEvent, track };
263
- //# sourceMappingURL=index.d.mts.map