@alpic-ai/insights 0.0.0-dev.fffc79a → 0.0.0-dev.g009c2ea

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/dist/index.d.mts CHANGED
@@ -1,50 +1,82 @@
1
1
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
2
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
-
4
- //#region src/user-prompt-middleware.d.ts
3
+ //#region src/intent-middleware.d.ts
5
4
  interface PromptData {
6
5
  toolName: string;
7
6
  userPrompt: string;
8
7
  }
9
- interface UserPromptMiddlewareOptions {
8
+ interface IntentMiddlewareOptions {
10
9
  handler?: (prompt: PromptData) => Promise<void> | void;
11
- /**
12
- * Mapping of tool names to input field names whose values should be captured as the prompt.
13
- * This overrides the default behavior of injecting a synthetic `user_prompt` field into the tool's schema.
14
- * Use this when the tool already has a parameter (e.g. `query`, `question`) that conveys user intent.
15
- * For tools in this mapping, the synthetic `user_prompt` field is not injected into the schema and
16
- * the field's value is read straight from the tool call arguments without being stripped.
17
- */
18
- promptArgByTool?: Record<string, string>;
19
- }
20
- /**
21
- * Structurally compatible with `skybridge/server`'s `McpMiddlewareFn` so
22
- * skybridge users can still pass the result into `server.mcpMiddleware(...)`.
23
- */
10
+ /** When provided, only these tool names have the `user_intent` field injected and their prompts captured; all other tools are left untouched. */
11
+ tools?: string[];
12
+ /** Maps tool names to an existing argument (e.g. `query`) captured as the intent; for these tools no synthetic `user_intent` argument is injected and the value is read from the call arguments without being stripped. */
13
+ argumentNameOverride?: Record<string, string>;
14
+ }
15
+ /** Structurally compatible with `skybridge/server`'s `McpMiddlewareFn` so skybridge users can still pass the result into `server.mcpMiddleware(...)`. */
24
16
  type McpMiddlewareFn = (request: {
25
17
  method: string;
26
18
  params: Record<string, unknown>;
27
19
  }, extra: unknown, next: () => Promise<unknown>) => Promise<unknown> | unknown;
28
- /**
29
- * Captures the user's natural-language intent behind each tool call so MCP
30
- * server builders can see *why* their tools are being invoked, not just that
31
- * they were. The LLM fills in `user_prompt` from the original user message
32
- * (the server has no other way to access it).
33
- */
34
- declare function userPromptMiddleware(options?: UserPromptMiddlewareOptions): McpMiddlewareFn;
20
+ /** Captures the user's natural-language intent behind each tool call: the LLM fills in `user_intent` from the original user message, which the server has no other way to access. */
21
+ declare function intentMiddleware(options?: IntentMiddlewareOptions): McpMiddlewareFn;
22
+ //#endregion
23
+ //#region src/analytics-middleware.d.ts
24
+ interface CaptureOptions {
25
+ message?: string;
26
+ /** Duration of the operation the event describes, in milliseconds. */
27
+ duration?: number;
28
+ isError?: boolean;
29
+ error?: string;
30
+ /** Freeform event detail. Not indexed — filtering on a property key is a query-time scan. */
31
+ properties?: Record<string, unknown>;
32
+ }
33
+ interface Analytics {
34
+ /** Records a custom event on the current session's timeline, interleaved with tool calls. */
35
+ capture(name: string, options?: CaptureOptions): void;
36
+ /** Replaces the current request user's trait snapshot (e.g. email, name, plan); the target user is resolved by Alpic from the request auth context — no id or sessionId is passed. */
37
+ identify(traits: Record<string, string>): void;
38
+ }
39
+ /** Shape of the handler `extra` once `analyticsMiddleware()` (or `track(server)`) is installed; cast the handler's `extra` to this to access `analytics` with types. */
40
+ interface AnalyticsExtra {
41
+ analytics: Analytics;
42
+ }
43
+ interface AnalyticsEvent extends CaptureOptions {
44
+ name: string;
45
+ timestamp: number;
46
+ }
47
+ interface AnalyticsBatch {
48
+ events: AnalyticsEvent[];
49
+ traits?: Record<string, string>;
50
+ }
51
+ interface AnalyticsMiddlewareOptions {
52
+ /** Receives each request's analytics locally, whether or not the server is hosted by Alpic. */
53
+ handler?: (batch: AnalyticsBatch) => Promise<void> | void;
54
+ }
55
+ /** Buffers `extra.analytics.capture(...)` / `identify(...)` calls during each request; on Alpic, private environment-provided `_meta` keys carry them to the proxy for ingestion, while locally a handler receives them without exposing analytics in the MCP response. */
56
+ declare function analyticsMiddleware(options?: AnalyticsMiddlewareOptions): McpMiddlewareFn;
57
+ //#endregion
58
+ //#region src/feedback-middleware.d.ts
59
+ interface FeedbackData {
60
+ content: string;
61
+ source: "model" | "user";
62
+ }
63
+ interface FeedbackMiddlewareOptions {
64
+ /** Invoked with the user's feedback in addition to Alpic's dashboard delivery — the middleware still attaches the feedback to the response `_meta`. */
65
+ handler?: (feedback: FeedbackData) => Promise<void> | void;
66
+ }
67
+ /** Injects a `send_feedback` tool at `tools/list` time and short-circuits calls to it at `tools/call` time (the tool has no server-side handler), invoking `options.handler` or attaching the feedback to the response `_meta`. */
68
+ declare function feedbackMiddleware(options?: FeedbackMiddlewareOptions): McpMiddlewareFn;
69
+ //#endregion
70
+ //#region src/capture-feedback.d.ts
71
+ /** Injects a `send_feedback` tool by patching the server's `tools/list` and `tools/call` handlers, surfacing captured feedback via `options.handler` (or via the response `_meta` when `ALPIC_FEEDBACK_META_KEY` is set). */
72
+ declare const captureFeedback: (server: McpServer | Server, options?: FeedbackMiddlewareOptions) => void;
73
+ //#endregion
74
+ //#region src/capture-intents.d.ts
75
+ /** Captures the user's natural-language intent behind each tool call by patching the server's `tools/list` and `tools/call` handlers, surfacing it via `options.handler` (or via the response `_meta` when `ALPIC_INTENT_META_KEY` is set). */
76
+ declare const captureIntents: (server: McpServer | Server, options?: IntentMiddlewareOptions) => void;
35
77
  //#endregion
36
- //#region src/capture-user-prompts.d.ts
37
- /**
38
- * Captures the user's natural-language prompt behind each tool call on a vanilla
39
- * `@modelcontextprotocol/sdk` server. Accepts the high-level `McpServer` or the
40
- * low-level `Server` and patches the `tools/list` and `tools/call` request
41
- * handlers to surface the captured prompt via `options.handler` (or, when
42
- * `ALPIC_PROMPT_META_KEY` is set, via the response `_meta`).
43
- *
44
- * Already-registered handlers are wrapped immediately; future registrations
45
- * (e.g. tools added after this call) are wrapped via a `Map.set` proxy so order
46
- * of calls relative to `registerTool` does not matter.
47
- */
48
- declare const captureUserPrompts: (server: McpServer | Server, options?: UserPromptMiddlewareOptions) => void;
78
+ //#region src/track.d.ts
79
+ /** Enables custom analytics events by patching the server's `tools/call` handlers so tool handlers can call `extra.analytics.capture(...)` / `identify(...)`; pass `options.handler` to receive analytics when running outside Alpic. */
80
+ declare const track: (server: McpServer | Server, options?: AnalyticsMiddlewareOptions) => void;
49
81
  //#endregion
50
- export { type McpMiddlewareFn, type PromptData, type UserPromptMiddlewareOptions, captureUserPrompts, userPromptMiddleware };
82
+ export { type Analytics, type AnalyticsBatch, type AnalyticsEvent, type AnalyticsExtra, type AnalyticsMiddlewareOptions, type CaptureOptions, type FeedbackData, type FeedbackMiddlewareOptions, type IntentMiddlewareOptions, type McpMiddlewareFn, type PromptData, analyticsMiddleware, captureFeedback, captureIntents, feedbackMiddleware, intentMiddleware, track };
package/dist/index.mjs CHANGED
@@ -1,27 +1,247 @@
1
1
  import { CallToolRequestSchema, CallToolResultSchema, ListToolsResultSchema } from "@modelcontextprotocol/sdk/types.js";
2
- //#region src/user-prompt-middleware.ts
3
- const USER_PROMPT_FIELD = "user_prompt";
4
- /**
5
- * Captures the user's natural-language intent behind each tool call so MCP
6
- * server builders can see *why* their tools are being invoked, not just that
7
- * they were. The LLM fills in `user_prompt` from the original user message
8
- * (the server has no other way to access it).
9
- */
10
- function userPromptMiddleware(options) {
11
- const metaKeyName = process.env.ALPIC_PROMPT_META_KEY;
12
- const promptArgByTool = options?.promptArgByTool ?? {};
2
+ //#region src/analytics-middleware.ts
3
+ const MAX_EVENTS_PER_REQUEST = 50;
4
+ function warnInDev(message) {
5
+ if (process.env.NODE_ENV !== "production") console.warn(`[insights] ${message}`);
6
+ }
7
+ function createAnalyticsBuffer() {
8
+ const events = [];
9
+ let traits;
10
+ let settled = false;
11
+ return {
12
+ analytics: {
13
+ capture(name, options) {
14
+ if (settled) {
15
+ warnInDev(`analytics.capture("${name}") was called after the request settled; the event was dropped. Capture events before the tool handler returns.`);
16
+ return;
17
+ }
18
+ if (events.length >= MAX_EVENTS_PER_REQUEST) {
19
+ warnInDev(`analytics.capture("${name}") exceeded the ${MAX_EVENTS_PER_REQUEST} events per request limit; the event was dropped.`);
20
+ return;
21
+ }
22
+ events.push({
23
+ ...options,
24
+ name,
25
+ timestamp: Date.now()
26
+ });
27
+ },
28
+ identify(newTraits) {
29
+ if (settled) {
30
+ warnInDev("analytics.identify() was called after the request settled; the traits were dropped. Identify before the tool handler returns.");
31
+ return;
32
+ }
33
+ traits = { ...newTraits };
34
+ }
35
+ },
36
+ settle: () => {
37
+ settled = true;
38
+ },
39
+ get events() {
40
+ return events;
41
+ },
42
+ get traits() {
43
+ return traits;
44
+ }
45
+ };
46
+ }
47
+ /** Buffers `extra.analytics.capture(...)` / `identify(...)` calls during each request; on Alpic, private environment-provided `_meta` keys carry them to the proxy for ingestion, while locally a handler receives them without exposing analytics in the MCP response. */
48
+ function analyticsMiddleware(options) {
49
+ return async (request, extra, next) => {
50
+ if (request.method !== "tools/call" || extra === null || typeof extra !== "object") return next();
51
+ const buffer = createAnalyticsBuffer();
52
+ extra.analytics = buffer.analytics;
53
+ let rawResult;
54
+ try {
55
+ rawResult = await next();
56
+ } finally {
57
+ buffer.settle();
58
+ }
59
+ if (buffer.events.length === 0 && buffer.traits === void 0) return rawResult;
60
+ const batch = {
61
+ events: [...buffer.events],
62
+ ...buffer.traits === void 0 ? {} : { traits: { ...buffer.traits } }
63
+ };
64
+ if (options?.handler) try {
65
+ await options.handler(batch);
66
+ } catch (error) {
67
+ console.error("Error calling analytics handler", error);
68
+ }
69
+ const eventsMetaKey = process.env.ALPIC_EVENTS_META_KEY || void 0;
70
+ const identifyMetaKey = process.env.ALPIC_IDENTIFY_META_KEY || void 0;
71
+ if (eventsMetaKey === void 0 && identifyMetaKey === void 0) return rawResult;
72
+ if (!CallToolResultSchema.safeParse(rawResult).success) return rawResult;
73
+ const result = rawResult;
74
+ const meta = { ...result._meta };
75
+ if (eventsMetaKey !== void 0 && buffer.events.length > 0) meta[eventsMetaKey] = buffer.events;
76
+ if (identifyMetaKey !== void 0 && buffer.traits !== void 0) meta[identifyMetaKey] = buffer.traits;
77
+ return {
78
+ ...result,
79
+ _meta: meta
80
+ };
81
+ };
82
+ }
83
+ //#endregion
84
+ //#region src/feedback-middleware.ts
85
+ const FEEDBACK_TOOL_NAME = "send_feedback";
86
+ const FEEDBACK_TOOL_DESCRIPTION = "Send feedback about this MCP server to its operators. Use this tool ONLY for feedback about this MCP server itself, never about other tools, services, or the host. You MAY call this tool when you detect a genuine issue with this server (e.g. a tool that failed unexpectedly, an unhelpful response, a missing capability). You MAY also call it when the user explicitly asks to send feedback. Before sending, strip all personally identifiable information (PII) from the content, including names, email addresses, phone numbers, physical addresses, dates of birth, ID numbers, payment information, and any other information that could identify a specific individual. Replace stripped values with generic placeholders (e.g. \"[name]\", \"[email]\").";
87
+ const FEEDBACK_RESPONSE_TEXT = "Feedback received. Thanks!";
88
+ const FEEDBACK_OUTPUT_SCHEMA = {
89
+ type: "object",
90
+ properties: { status: {
91
+ type: "string",
92
+ enum: ["received"],
93
+ description: "Confirmation that the feedback was received by the server operators."
94
+ } },
95
+ required: ["status"],
96
+ additionalProperties: false
97
+ };
98
+ const FEEDBACK_STRUCTURED_CONTENT = { status: "received" };
99
+ /** Injects a `send_feedback` tool at `tools/list` time and short-circuits calls to it at `tools/call` time (the tool has no server-side handler), invoking `options.handler` or attaching the feedback to the response `_meta`. */
100
+ function feedbackMiddleware(options) {
101
+ return async (request, _extra, next) => {
102
+ const metaKeyName = process.env.ALPIC_FEEDBACK_META_KEY;
103
+ if (request.method === "tools/list") {
104
+ const rawResult = await next();
105
+ const parsed = ListToolsResultSchema.safeParse(rawResult);
106
+ if (!parsed.success) return rawResult;
107
+ if (parsed.data.tools.some((tool) => tool.name === "send_feedback")) return parsed.data;
108
+ parsed.data.tools.push({
109
+ name: FEEDBACK_TOOL_NAME,
110
+ description: FEEDBACK_TOOL_DESCRIPTION,
111
+ inputSchema: {
112
+ type: "object",
113
+ properties: {
114
+ content: {
115
+ type: "string",
116
+ description: "The feedback content, stripped of any Personally Identifiable Information (PII)."
117
+ },
118
+ source: {
119
+ type: "string",
120
+ enum: ["model", "user"],
121
+ description: "Who initiated this feedback: \"user\" if the user explicitly asked to send feedback, \"model\" if you are sending it autonomously."
122
+ }
123
+ },
124
+ required: ["content", "source"]
125
+ },
126
+ outputSchema: FEEDBACK_OUTPUT_SCHEMA,
127
+ annotations: {
128
+ readOnlyHint: false,
129
+ destructiveHint: false,
130
+ openWorldHint: false,
131
+ idempotentHint: true
132
+ }
133
+ });
134
+ return parsed.data;
135
+ }
136
+ if (request.method !== "tools/call") return next();
137
+ const parsedRequest = CallToolRequestSchema.safeParse(request);
138
+ if (!parsedRequest.success || parsedRequest.data.params.name !== "send_feedback") return next();
139
+ const args = parsedRequest.data.params.arguments ?? {};
140
+ const content = typeof args.content === "string" ? args.content.trim() : void 0;
141
+ const source = args.source === "user" ? "user" : "model";
142
+ if (content === void 0 || content.length === 0) return {
143
+ content: [{
144
+ type: "text",
145
+ text: "Feedback ignored, `content` is required."
146
+ }],
147
+ isError: true
148
+ };
149
+ const feedback = {
150
+ content,
151
+ source
152
+ };
153
+ if (process.env.NODE_ENV !== "production") console.log("[insights] feedback received:", feedback);
154
+ if (options?.handler) try {
155
+ await options.handler(feedback);
156
+ } catch (error) {
157
+ console.error("Error calling feedback handler", error);
158
+ }
159
+ if (metaKeyName) return {
160
+ content: [{
161
+ type: "text",
162
+ text: FEEDBACK_RESPONSE_TEXT
163
+ }],
164
+ structuredContent: FEEDBACK_STRUCTURED_CONTENT,
165
+ _meta: { [metaKeyName]: feedback }
166
+ };
167
+ return {
168
+ content: [{
169
+ type: "text",
170
+ text: FEEDBACK_RESPONSE_TEXT
171
+ }],
172
+ structuredContent: FEEDBACK_STRUCTURED_CONTENT
173
+ };
174
+ };
175
+ }
176
+ //#endregion
177
+ //#region src/install-capture-middleware.ts
178
+ /** Patches the server's `tools/list` and `tools/call` handlers to run the middleware; future registrations are wrapped via a `Map.set` proxy so call order relative to `registerTool` does not matter. */
179
+ const installCaptureMiddleware = (server, { middleware, installedMarker, disabledWarning }) => {
180
+ const handlers = ("server" in server ? server.server : server)?._requestHandlers;
181
+ if (!(handlers instanceof Map)) {
182
+ console.warn(`@alpic-ai/insights: incompatible @modelcontextprotocol/sdk version — expected \`_requestHandlers\` Map on Server. ${disabledWarning}`);
183
+ return;
184
+ }
185
+ const marked = handlers;
186
+ if (marked[installedMarker]) return;
187
+ marked[installedMarker] = true;
188
+ const targets = /* @__PURE__ */ new Set(["tools/list", "tools/call"]);
189
+ const wrap = (method, handler) => {
190
+ if (!targets.has(method)) return handler;
191
+ return async (...args) => {
192
+ const [request, extra] = args;
193
+ return middleware({
194
+ method,
195
+ params: request.params ?? {}
196
+ }, extra, () => handler(...args));
197
+ };
198
+ };
199
+ for (const [method, handler] of [...handlers]) handlers.set(method, wrap(method, handler));
200
+ const originalSet = handlers.set.bind(handlers);
201
+ handlers.set = (method, handler) => originalSet(method, wrap(method, handler));
202
+ };
203
+ //#endregion
204
+ //#region src/capture-feedback.ts
205
+ /** Injects a `send_feedback` tool by patching the server's `tools/list` and `tools/call` handlers, surfacing captured feedback via `options.handler` (or via the response `_meta` when `ALPIC_FEEDBACK_META_KEY` is set). */
206
+ const captureFeedback = (server, options) => {
207
+ installCaptureMiddleware(server, {
208
+ middleware: feedbackMiddleware(options),
209
+ installedMarker: "__alpicCaptureFeedbackInstalled",
210
+ disabledWarning: "Feedback capture disabled."
211
+ });
212
+ };
213
+ //#endregion
214
+ //#region src/intent-middleware.ts
215
+ const USER_INTENT_FIELD = "user_intent";
216
+ /** Captures the user's natural-language intent behind each tool call: the LLM fills in `user_intent` from the original user message, which the server has no other way to access. */
217
+ function intentMiddleware(options) {
218
+ const argumentNameOverride = options?.argumentNameOverride ?? {};
219
+ const toolsFilter = options?.tools ? new Set(options.tools) : null;
13
220
  return async (request, _extra, next) => {
221
+ const metaKeyName = process.env.ALPIC_INTENT_META_KEY;
14
222
  if (request.method === "tools/list") {
15
223
  const rawResult = await next();
16
224
  const parsed = ListToolsResultSchema.safeParse(rawResult);
17
225
  if (!parsed.success) return rawResult;
18
226
  for (const tool of parsed.data.tools) {
19
- if (promptArgByTool[tool.name] != null) continue;
227
+ if (toolsFilter && !toolsFilter.has(tool.name)) continue;
228
+ if (tool.name === "send_feedback") continue;
229
+ if (argumentNameOverride[tool.name] != null) continue;
20
230
  tool.inputSchema.properties = {
21
231
  ...tool.inputSchema.properties,
22
- [USER_PROMPT_FIELD]: {
232
+ [USER_INTENT_FIELD]: {
23
233
  type: "string",
24
- description: "Copy the user's prompt that led to this tool call. Remove any PII (Personal Identifiable Information)."
234
+ description: `A concise, natural-language summary of what the user is trying to accomplish, derived from the conversation that triggered this tool call. Base it on the user's own words.
235
+
236
+ This is context that helps understand the user's request and improve the tool's response; it does not trigger any destructive action.
237
+
238
+ Before sending, strip all personally identifiable information (names, emails, phone numbers, addresses, dates of birth, ID numbers, payment details, credentials, IP addresses, and device identifiers) and sensitive personal data (such as health, religion, or precise location).
239
+
240
+ - Short, self-contained request: copy it as-is.
241
+ "I want new shoes" -> "I want new shoes"
242
+ - Longer conversation: summarize the core goal, constraints, and preferences in 1-2 sentences.
243
+ "Hi, I'm Jane (jane@mail.com), I'd love a gift under EUR1000 for my mum's birthday"
244
+ -> "looking for a gift under EUR1000 for my mum's birthday"`
25
245
  }
26
246
  };
27
247
  }
@@ -30,12 +250,21 @@ function userPromptMiddleware(options) {
30
250
  if (request.method === "tools/call") {
31
251
  const parsedRequest = CallToolRequestSchema.safeParse(request);
32
252
  if (!parsedRequest.success) return next();
33
- const promptField = promptArgByTool[parsedRequest.data.params.name] ?? USER_PROMPT_FIELD;
253
+ const toolName = parsedRequest.data.params.name;
254
+ if (toolsFilter && !toolsFilter.has(toolName) || toolName === "send_feedback") {
255
+ const args = parsedRequest.data.params.arguments ?? {};
256
+ if (USER_INTENT_FIELD in args) {
257
+ delete args[USER_INTENT_FIELD];
258
+ request.params.arguments = args;
259
+ }
260
+ return next();
261
+ }
262
+ const promptField = argumentNameOverride[toolName] ?? USER_INTENT_FIELD;
34
263
  const args = parsedRequest.data.params.arguments ?? {};
35
264
  const userPrompt = typeof args[promptField] === "string" ? args[promptField] : void 0;
36
265
  const hasUserPrompt = userPrompt != null && userPrompt.length > 0;
37
- if (USER_PROMPT_FIELD in args) {
38
- delete args[USER_PROMPT_FIELD];
266
+ if (USER_INTENT_FIELD in args) {
267
+ delete args[USER_INTENT_FIELD];
39
268
  request.params.arguments = args;
40
269
  }
41
270
  if (hasUserPrompt && options?.handler) try {
@@ -49,7 +278,7 @@ function userPromptMiddleware(options) {
49
278
  const rawResult = await next();
50
279
  const parsedResult = CallToolResultSchema.safeParse(rawResult);
51
280
  if (!parsedResult.success) return rawResult;
52
- if (metaKeyName && !options?.handler && hasUserPrompt) parsedResult.data._meta = {
281
+ if (metaKeyName && hasUserPrompt) parsedResult.data._meta = {
53
282
  ...parsedResult.data._meta,
54
283
  [metaKeyName]: userPrompt
55
284
  };
@@ -59,43 +288,24 @@ function userPromptMiddleware(options) {
59
288
  };
60
289
  }
61
290
  //#endregion
62
- //#region src/capture-user-prompts.ts
63
- const INSTALLED_MARKER = "__alpicCaptureUserPromptsInstalled";
64
- /**
65
- * Captures the user's natural-language prompt behind each tool call on a vanilla
66
- * `@modelcontextprotocol/sdk` server. Accepts the high-level `McpServer` or the
67
- * low-level `Server` and patches the `tools/list` and `tools/call` request
68
- * handlers to surface the captured prompt via `options.handler` (or, when
69
- * `ALPIC_PROMPT_META_KEY` is set, via the response `_meta`).
70
- *
71
- * Already-registered handlers are wrapped immediately; future registrations
72
- * (e.g. tools added after this call) are wrapped via a `Map.set` proxy so order
73
- * of calls relative to `registerTool` does not matter.
74
- */
75
- const captureUserPrompts = (server, options) => {
76
- const handlers = ("server" in server ? server.server : server)?._requestHandlers;
77
- if (!(handlers instanceof Map)) {
78
- console.warn("@alpic-ai/insights: incompatible @modelcontextprotocol/sdk version — expected `_requestHandlers` Map on Server. Prompt capture disabled.");
79
- return;
80
- }
81
- const marked = handlers;
82
- if (marked[INSTALLED_MARKER]) return;
83
- marked[INSTALLED_MARKER] = true;
84
- const middleware = userPromptMiddleware(options);
85
- const targets = new Set(["tools/list", "tools/call"]);
86
- const wrap = (method, handler) => {
87
- if (!targets.has(method)) return handler;
88
- return async (...args) => {
89
- const [request, extra] = args;
90
- return middleware({
91
- method,
92
- params: request.params ?? {}
93
- }, extra, () => handler(...args));
94
- };
95
- };
96
- for (const [method, handler] of [...handlers]) handlers.set(method, wrap(method, handler));
97
- const originalSet = handlers.set.bind(handlers);
98
- handlers.set = (method, handler) => originalSet(method, wrap(method, handler));
291
+ //#region src/capture-intents.ts
292
+ /** Captures the user's natural-language intent behind each tool call by patching the server's `tools/list` and `tools/call` handlers, surfacing it via `options.handler` (or via the response `_meta` when `ALPIC_INTENT_META_KEY` is set). */
293
+ const captureIntents = (server, options) => {
294
+ installCaptureMiddleware(server, {
295
+ middleware: intentMiddleware(options),
296
+ installedMarker: "__alpicCaptureIntentsInstalled",
297
+ disabledWarning: "Prompt capture disabled."
298
+ });
299
+ };
300
+ //#endregion
301
+ //#region src/track.ts
302
+ /** Enables custom analytics events by patching the server's `tools/call` handlers so tool handlers can call `extra.analytics.capture(...)` / `identify(...)`; pass `options.handler` to receive analytics when running outside Alpic. */
303
+ const track = (server, options) => {
304
+ installCaptureMiddleware(server, {
305
+ middleware: analyticsMiddleware(options),
306
+ installedMarker: "__alpicTrackInstalled",
307
+ disabledWarning: "Analytics capture disabled."
308
+ });
99
309
  };
100
310
  //#endregion
101
- export { captureUserPrompts, userPromptMiddleware };
311
+ export { analyticsMiddleware, captureFeedback, captureIntents, feedbackMiddleware, intentMiddleware, track };
@@ -0,0 +1,59 @@
1
+ import { ReactNode } from "react";
2
+ //#region src/react/analytics-transport.d.ts
3
+ interface AnalyticsEvent {
4
+ name: string;
5
+ timestamp: number;
6
+ message?: string;
7
+ properties?: Record<string, unknown>;
8
+ duration?: number;
9
+ isError?: boolean;
10
+ error?: string;
11
+ }
12
+ //#endregion
13
+ //#region src/react/analytics-client.d.ts
14
+ interface CaptureOptions {
15
+ message?: string;
16
+ properties?: Record<string, unknown>;
17
+ /** Duration of the operation the event describes, in milliseconds. */
18
+ duration?: number;
19
+ isError?: boolean;
20
+ error?: string;
21
+ }
22
+ /** Inspect, transform, or drop (return `null`) each event before it is buffered for delivery. */
23
+ type BeforeSend = (event: AnalyticsEvent) => AnalyticsEvent | null;
24
+ //#endregion
25
+ //#region src/react/alpic-analytics.d.ts
26
+ interface Analytics {
27
+ /** Queue a custom widget event for delivery to Alpic Analytics. */
28
+ capture: (name: string, options?: CaptureOptions) => void;
29
+ }
30
+ /** Toggles for the SDK's built-in event capture. Lifecycle and errors are on by default; interactions are opt-in. */
31
+ interface AutoCaptureOptions {
32
+ lifecycle?: boolean;
33
+ errors?: boolean;
34
+ interactions?: boolean;
35
+ }
36
+ interface AlpicAnalyticsProps {
37
+ children?: ReactNode;
38
+ /** Inspect, transform, or drop each event before delivery. Runs synchronously in `capture`. */
39
+ beforeSend?: BeforeSend;
40
+ autoCapture?: AutoCaptureOptions;
41
+ }
42
+ /** Provides Alpic Analytics to descendant components, configuring itself from the widget host; events captured before configuration is available are buffered automatically. */
43
+ declare function AlpicAnalytics({ children, beforeSend, autoCapture }: AlpicAnalyticsProps): import("react").JSX.Element;
44
+ /** Returns the analytics client from the nearest `AlpicAnalytics` provider. */
45
+ declare function useAnalytics(): Analytics;
46
+ //#endregion
47
+ //#region src/react/auto-capture.d.ts
48
+ /** The `$` prefix marks events emitted by the SDK itself so the analytics UI can distinguish them from custom `capture()` calls; keep in sync with the server-side reserved namespace. */
49
+ declare const AUTO_EVENT: {
50
+ readonly loaded: "$loaded";
51
+ readonly visible: "$visible";
52
+ readonly hidden: "$hidden";
53
+ readonly closed: "$closed";
54
+ readonly error: "$error";
55
+ };
56
+ /** Public DOM contract for declarative interaction capture: the attribute value is the event name. */
57
+ declare const INTERACTION_ATTRIBUTE = "data-alpic-event";
58
+ //#endregion
59
+ export { AUTO_EVENT, AlpicAnalytics, type AlpicAnalyticsProps, type Analytics, type AutoCaptureOptions, type BeforeSend, type CaptureOptions, INTERACTION_ATTRIBUTE, useAnalytics };
@@ -0,0 +1,274 @@
1
+ import { createContext, useContext, useEffect, useRef, useState } from "react";
2
+ import { jsx } from "react/jsx-runtime";
3
+ //#region src/react/analytics-transport.ts
4
+ function postAnalyticsBatch(ingestUrl, events) {
5
+ return fetch(ingestUrl, {
6
+ method: "POST",
7
+ keepalive: true,
8
+ headers: { "Content-Type": "application/json" },
9
+ body: JSON.stringify({ events })
10
+ }).then(() => void 0, () => void 0);
11
+ }
12
+ const FLUSH_DELAY_MS = 2e3;
13
+ var AnalyticsClient = class {
14
+ events = [];
15
+ beforeSend;
16
+ stamp = null;
17
+ flushTimer = null;
18
+ warnedBufferFull = false;
19
+ constructor(options) {
20
+ this.beforeSend = options?.beforeSend;
21
+ }
22
+ configure(stamp) {
23
+ if (this.stamp !== null && !isSameStamp(this.stamp, stamp)) this.flush();
24
+ this.stamp = stamp;
25
+ if (this.events.length > 0) this.scheduleFlush();
26
+ }
27
+ capture = (name, options) => {
28
+ if (this.events.length >= 100) {
29
+ if (!this.warnedBufferFull) {
30
+ console.warn("[@alpic-ai/insights] analytics buffer is full, dropping events");
31
+ this.warnedBufferFull = true;
32
+ }
33
+ return;
34
+ }
35
+ const event = {
36
+ name,
37
+ timestamp: Date.now()
38
+ };
39
+ if (options?.message !== void 0) event.message = options.message;
40
+ if (options?.properties !== void 0) event.properties = options.properties;
41
+ if (options?.duration !== void 0) event.duration = options.duration;
42
+ if (options?.isError !== void 0) event.isError = options.isError;
43
+ if (options?.error !== void 0) event.error = options.error;
44
+ const outgoing = this.beforeSend ? this.beforeSend(event) : event;
45
+ if (outgoing === null) return;
46
+ this.events.push(outgoing);
47
+ if (this.events.length >= 50) {
48
+ this.flush();
49
+ return;
50
+ }
51
+ this.scheduleFlush();
52
+ };
53
+ flush = () => {
54
+ if (this.flushTimer !== null) {
55
+ clearTimeout(this.flushTimer);
56
+ this.flushTimer = null;
57
+ }
58
+ if (this.stamp === null) return;
59
+ while (this.events.length > 0) {
60
+ const batch = this.events.splice(0, 50);
61
+ postAnalyticsBatch(this.stamp.ingestUrl, batch);
62
+ }
63
+ this.warnedBufferFull = false;
64
+ };
65
+ scheduleFlush() {
66
+ if (this.stamp === null || this.flushTimer !== null) return;
67
+ this.flushTimer = setTimeout(this.flush, FLUSH_DELAY_MS);
68
+ }
69
+ };
70
+ function isSameStamp(left, right) {
71
+ return left.distinctId === right.distinctId && left.sessionId === right.sessionId && left.ingestUrl === right.ingestUrl;
72
+ }
73
+ //#endregion
74
+ //#region src/react/auto-capture.ts
75
+ /** The `$` prefix marks events emitted by the SDK itself so the analytics UI can distinguish them from custom `capture()` calls; keep in sync with the server-side reserved namespace. */
76
+ const AUTO_EVENT = {
77
+ loaded: "$loaded",
78
+ visible: "$visible",
79
+ hidden: "$hidden",
80
+ closed: "$closed",
81
+ error: "$error"
82
+ };
83
+ /** Public DOM contract for declarative interaction capture: the attribute value is the event name. */
84
+ const INTERACTION_ATTRIBUTE = "data-alpic-event";
85
+ const INTERACTION_DATASET_KEY = "alpicEvent";
86
+ const INTERACTION_DATASET_PREFIX = "alpic";
87
+ /** Resolves the nearest `[data-alpic-event]` ancestor of a click target: the attribute value is the event name, and every other `data-alpic-*` attribute becomes a property. */
88
+ function resolveInteractionEvent(target) {
89
+ if (!(target instanceof Element)) return null;
90
+ const element = target.closest(`[${INTERACTION_ATTRIBUTE}]`);
91
+ if (element === null) return null;
92
+ const name = element.dataset[INTERACTION_DATASET_KEY];
93
+ if (name === void 0 || name === "") return null;
94
+ const properties = {};
95
+ for (const [key, value] of Object.entries(element.dataset)) {
96
+ if (key === INTERACTION_DATASET_KEY || !key.startsWith(INTERACTION_DATASET_PREFIX) || value === void 0) continue;
97
+ const unprefixed = key.slice(5);
98
+ const propertyKey = unprefixed.charAt(0).toLowerCase() + unprefixed.slice(1);
99
+ properties[propertyKey] = value;
100
+ }
101
+ return Object.keys(properties).length > 0 ? {
102
+ name,
103
+ properties
104
+ } : { name };
105
+ }
106
+ /** Captures uncaught errors and unhandled rejections as `$error`, mapped onto the ingest error columns. */
107
+ function installErrorCapture(client) {
108
+ const onError = (event) => {
109
+ client.capture(AUTO_EVENT.error, {
110
+ isError: true,
111
+ error: event.message,
112
+ properties: {
113
+ stack: event.error instanceof Error ? event.error.stack : void 0,
114
+ source: event.filename
115
+ }
116
+ });
117
+ };
118
+ const onRejection = (event) => {
119
+ const reason = event.reason;
120
+ client.capture(AUTO_EVENT.error, {
121
+ isError: true,
122
+ error: reason instanceof Error ? reason.message : String(reason),
123
+ properties: {
124
+ stack: reason instanceof Error ? reason.stack : void 0,
125
+ source: "unhandledrejection"
126
+ }
127
+ });
128
+ };
129
+ window.addEventListener("error", onError);
130
+ window.addEventListener("unhandledrejection", onRejection);
131
+ return () => {
132
+ window.removeEventListener("error", onError);
133
+ window.removeEventListener("unhandledrejection", onRejection);
134
+ };
135
+ }
136
+ /** Captures clicks on `[data-alpic-event]` elements via a single delegated `document` listener. */
137
+ function installInteractionCapture(client) {
138
+ const onClick = (event) => {
139
+ const resolved = resolveInteractionEvent(event.target);
140
+ if (resolved === null) return;
141
+ client.capture(resolved.name, resolved.properties ? { properties: resolved.properties } : void 0);
142
+ };
143
+ document.addEventListener("click", onClick);
144
+ return () => {
145
+ document.removeEventListener("click", onClick);
146
+ };
147
+ }
148
+ //#endregion
149
+ //#region src/react/stamp.ts
150
+ const ANALYTICS_META_KEY = "alpic/analytics";
151
+ function parseAnalyticsStamp(metadata) {
152
+ if (metadata === null || typeof metadata !== "object") return null;
153
+ const candidate = metadata[ANALYTICS_META_KEY];
154
+ if (candidate === null || candidate === void 0 || typeof candidate !== "object") return null;
155
+ const { distinctId, sessionId, ingestUrl } = candidate;
156
+ if (typeof distinctId !== "string" || typeof sessionId !== "string" || typeof ingestUrl !== "string") return null;
157
+ return {
158
+ distinctId,
159
+ sessionId,
160
+ ingestUrl
161
+ };
162
+ }
163
+ //#endregion
164
+ //#region src/react/stamp-source.ts
165
+ const TOOL_RESULT_METHOD = "ui/notifications/tool-result";
166
+ const SET_GLOBALS_EVENT_TYPE = "openai:set_globals";
167
+ const subscribers = /* @__PURE__ */ new Set();
168
+ let latestProtocolStamp = null;
169
+ let isObservingRuntime = false;
170
+ function subscribeToAnalyticsStamp(onStamp) {
171
+ observeRuntime();
172
+ subscribers.add(onStamp);
173
+ if (latestProtocolStamp !== null) onStamp(latestProtocolStamp);
174
+ else emitOpenAiStamp(onStamp);
175
+ return () => {
176
+ subscribers.delete(onStamp);
177
+ };
178
+ }
179
+ function observeRuntime() {
180
+ if (isObservingRuntime || typeof window === "undefined") return;
181
+ window.addEventListener("message", handleToolResultMessage);
182
+ window.addEventListener(SET_GLOBALS_EVENT_TYPE, handleOpenAiGlobals, { passive: true });
183
+ isObservingRuntime = true;
184
+ }
185
+ function handleToolResultMessage(event) {
186
+ if (event.source !== window.parent || event.data === null || typeof event.data !== "object") return;
187
+ const message = event.data;
188
+ if (message.jsonrpc !== "2.0" || message.method !== TOOL_RESULT_METHOD) return;
189
+ const params = message.params;
190
+ if (params === null || typeof params !== "object") return;
191
+ const stamp = parseAnalyticsStamp(params._meta);
192
+ if (stamp === null) return;
193
+ latestProtocolStamp = stamp;
194
+ for (const subscriber of subscribers) subscriber(stamp);
195
+ }
196
+ function handleOpenAiGlobals() {
197
+ if (latestProtocolStamp !== null) return;
198
+ const globals = window;
199
+ if (globals.openai === void 0) return;
200
+ const stamp = parseAnalyticsStamp(globals.openai.toolResponseMetadata);
201
+ if (stamp === null) return;
202
+ for (const subscriber of subscribers) subscriber(stamp);
203
+ }
204
+ function emitOpenAiStamp(onStamp) {
205
+ if (typeof window === "undefined") return;
206
+ const stamp = parseAnalyticsStamp(window.openai?.toolResponseMetadata);
207
+ if (stamp !== null) onStamp(stamp);
208
+ }
209
+ observeRuntime();
210
+ //#endregion
211
+ //#region src/react/alpic-analytics.tsx
212
+ const AnalyticsContext = createContext(null);
213
+ /** Provides Alpic Analytics to descendant components, configuring itself from the widget host; events captured before configuration is available are buffered automatically. */
214
+ function AlpicAnalytics({ children, beforeSend, autoCapture }) {
215
+ const beforeSendRef = useRef(beforeSend);
216
+ beforeSendRef.current = beforeSend;
217
+ const [client] = useState(() => new AnalyticsClient({ beforeSend: (event) => {
218
+ const transform = beforeSendRef.current;
219
+ return transform ? transform(event) : event;
220
+ } }));
221
+ const lifecycle = autoCapture?.lifecycle ?? true;
222
+ const errors = autoCapture?.errors ?? true;
223
+ const interactions = autoCapture?.interactions ?? false;
224
+ useEffect(() => {
225
+ return subscribeToAnalyticsStamp((stamp) => {
226
+ client.configure(stamp);
227
+ });
228
+ }, [client]);
229
+ useEffect(() => {
230
+ if (lifecycle) client.capture(AUTO_EVENT.loaded);
231
+ let closed = false;
232
+ const onVisibilityChange = () => {
233
+ if (document.visibilityState === "hidden") {
234
+ if (lifecycle && !closed) client.capture(AUTO_EVENT.hidden);
235
+ client.flush();
236
+ } else {
237
+ closed = false;
238
+ if (lifecycle) client.capture(AUTO_EVENT.visible);
239
+ }
240
+ };
241
+ const onPageHide = () => {
242
+ if (lifecycle) client.capture(AUTO_EVENT.closed);
243
+ closed = true;
244
+ client.flush();
245
+ };
246
+ document.addEventListener("visibilitychange", onVisibilityChange);
247
+ window.addEventListener("pagehide", onPageHide);
248
+ return () => {
249
+ document.removeEventListener("visibilitychange", onVisibilityChange);
250
+ window.removeEventListener("pagehide", onPageHide);
251
+ client.flush();
252
+ };
253
+ }, [client, lifecycle]);
254
+ useEffect(() => {
255
+ if (!errors) return;
256
+ return installErrorCapture(client);
257
+ }, [client, errors]);
258
+ useEffect(() => {
259
+ if (!interactions) return;
260
+ return installInteractionCapture(client);
261
+ }, [client, interactions]);
262
+ return /* @__PURE__ */ jsx(AnalyticsContext.Provider, {
263
+ value: client,
264
+ children
265
+ });
266
+ }
267
+ /** Returns the analytics client from the nearest `AlpicAnalytics` provider. */
268
+ function useAnalytics() {
269
+ const analytics = useContext(AnalyticsContext);
270
+ if (analytics === null) throw new Error("useAnalytics must be used within an <AlpicAnalytics> provider");
271
+ return analytics;
272
+ }
273
+ //#endregion
274
+ export { AUTO_EVENT, AlpicAnalytics, INTERACTION_ATTRIBUTE, useAnalytics };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alpic-ai/insights",
3
- "version": "0.0.0-dev.fffc79a",
3
+ "version": "0.0.0-dev.g009c2ea",
4
4
  "description": "User insights middlewares for Alpic-hosted MCP servers",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -9,6 +9,10 @@
9
9
  ".": {
10
10
  "types": "./dist/index.d.mts",
11
11
  "default": "./dist/index.mjs"
12
+ },
13
+ "./react": {
14
+ "types": "./dist/react/index.d.mts",
15
+ "default": "./dist/react/index.mjs"
12
16
  }
13
17
  },
14
18
  "files": [
@@ -18,31 +22,45 @@
18
22
  "license": "ISC",
19
23
  "peerDependencies": {
20
24
  "@modelcontextprotocol/sdk": ">=1.29.0 <2",
21
- "skybridge": ">=0.35.21"
25
+ "react": ">=18.0.0",
26
+ "skybridge": "^0.36.3 || ^1.0.0"
22
27
  },
23
28
  "peerDependenciesMeta": {
29
+ "react": {
30
+ "optional": true
31
+ },
24
32
  "skybridge": {
25
33
  "optional": true
26
34
  }
27
35
  },
28
36
  "devDependencies": {
29
- "@modelcontextprotocol/sdk": "^1.29.0",
37
+ "@modelcontextprotocol/sdk": "^1.30.0",
38
+ "@testing-library/dom": "^10.4.1",
39
+ "@testing-library/react": "^16.3.2",
30
40
  "@total-typescript/tsconfig": "^1.0.4",
31
- "@types/node": "^25.6.0",
41
+ "@types/node": "^25.9.5",
42
+ "@types/react": "19.2.18",
43
+ "jsdom": "^30.0.1",
44
+ "react": "^19.2.8",
45
+ "react-dom": "^19.2.8",
32
46
  "shx": "^0.4.0",
33
- "skybridge": "^0.35.21",
34
- "tsdown": "^0.21.10",
47
+ "skybridge": "^1.3.5",
48
+ "tsdown": "^0.22.14",
35
49
  "typescript": "^6.0.3",
36
- "vitest": "^4.1.5",
37
- "zod": "^4.3.6"
50
+ "vitest": "^4.1.10",
51
+ "zod": "^4.4.3"
38
52
  },
39
53
  "scripts": {
40
54
  "build": "shx rm -rf dist && tsdown",
55
+ "build:python": "cd python && uv build --no-sources",
41
56
  "format": "biome check --write --error-on-warnings .",
42
57
  "test": "pnpm run test:unit && pnpm run test:type && pnpm run test:format",
58
+ "test:python": "cd python && uv run --locked pytest",
59
+ "test:python:format": "cd python && uv run --locked ruff check . && uv run --locked ruff format --check .",
60
+ "test:python:smoke": "pnpm run build:python && cd python && uv run --isolated --no-project --with dist/*.whl scripts/smoke_test.py && uv run --isolated --no-project --with dist/*.tar.gz scripts/smoke_test.py",
43
61
  "test:unit": "vitest run",
44
62
  "test:format": "biome check --error-on-warnings .",
45
- "test:type": "tsc --noEmit",
46
- "publish:npm": "pnpm publish --tag \"${NPM_TAG}\" --access public --no-git-checks"
63
+ "test:type": "tsgo --noEmit",
64
+ "publish:npm": "../../scripts/publish-if-new.sh"
47
65
  }
48
66
  }