@alpic-ai/insights 0.0.0-dev.gb58f99a → 0.0.0-dev.gb5d4532

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,89 +1,68 @@
1
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
-
4
- //#region src/intent-middleware.d.ts
1
+ import { ServerContext } from "@modelcontextprotocol/server";
5
2
  interface PromptData {
6
3
  toolName: string;
7
4
  userPrompt: string;
8
5
  }
9
6
  interface IntentMiddlewareOptions {
10
7
  handler?: (prompt: PromptData) => Promise<void> | void;
11
- /**
12
- * If provided, only these tool names will have the `user_intent` field injected and their
13
- * prompts captured. All other tools are left untouched.
14
- */
8
+ /** When provided, only these tool names have the `user_intent` field injected and their prompts captured; all other tools are left untouched. */
15
9
  tools?: string[];
16
- /**
17
- * Mapping of tool names to argument names whose values should be captured as the intent.
18
- * Use this when the tool already has an argument (e.g. `query`, `question`) that conveys user
19
- * intent. For tools in this mapping, the synthetic `user_intent` argument is not injected into the
20
- * schema and the argument's value is read straight from the tool call arguments without being stripped.
21
- */
10
+ /** 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. */
22
11
  argumentNameOverride?: Record<string, string>;
23
12
  }
24
- /**
25
- * Structurally compatible with `skybridge/server`'s `McpMiddlewareFn` so
26
- * skybridge users can still pass the result into `server.mcpMiddleware(...)`.
27
- */
13
+ /** Structurally compatible with `skybridge/server`'s `McpMiddlewareFn` so skybridge users can still pass the result into `server.mcpMiddleware(...)`. */
28
14
  type McpMiddlewareFn = (request: {
29
15
  method: string;
30
16
  params: Record<string, unknown>;
31
17
  }, extra: unknown, next: () => Promise<unknown>) => Promise<unknown> | unknown;
32
- /**
33
- * Captures the user's natural-language intent behind each tool call so MCP
34
- * server builders can see *why* their tools are being invoked, not just that
35
- * they were. The LLM fills in `user_intent` from the original user message
36
- * (the server has no other way to access it).
37
- */
38
- declare function intentMiddleware(options?: IntentMiddlewareOptions): McpMiddlewareFn;
39
- //#endregion
40
- //#region src/feedback-middleware.d.ts
18
+ /** 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. */
19
+ export declare function intentMiddleware(options?: IntentMiddlewareOptions): McpMiddlewareFn;
20
+ interface CaptureOptions {
21
+ message?: string;
22
+ /** Duration of the operation the event describes, in milliseconds. */
23
+ duration?: number;
24
+ isError?: boolean;
25
+ error?: string;
26
+ /** Freeform event detail. Not indexed — filtering on a property key is a query-time scan. */
27
+ properties?: Record<string, unknown>;
28
+ }
29
+ interface Analytics {
30
+ /** Records a custom event on the current session's timeline, interleaved with tool calls. */
31
+ capture(name: string, options?: CaptureOptions): void;
32
+ /** 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. */
33
+ identify(traits: Record<string, string>): void;
34
+ }
35
+ interface AnalyticsExtra extends ServerContext {
36
+ analytics: Analytics;
37
+ }
38
+ interface AnalyticsEvent extends CaptureOptions {
39
+ name: string;
40
+ timestamp: number;
41
+ }
42
+ interface AnalyticsBatch {
43
+ events: AnalyticsEvent[];
44
+ traits?: Record<string, string>;
45
+ }
46
+ interface AnalyticsMiddlewareOptions {
47
+ /** Receives each request's analytics locally, whether or not the server is hosted by Alpic. */
48
+ handler?: (batch: AnalyticsBatch) => Promise<void> | void;
49
+ }
50
+ /** 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. */
51
+ export declare function analyticsMiddleware(options?: AnalyticsMiddlewareOptions): McpMiddlewareFn;
41
52
  interface FeedbackData {
42
53
  content: string;
43
54
  source: "model" | "user";
44
55
  }
45
56
  interface FeedbackMiddlewareOptions {
46
- /**
47
- * Custom handler invoked with the user's feedback. When provided, the middleware still attaches the feedback to the response `_meta`.
48
- * The handler runs **in addition to** Alpic's dashboard delivery, feedback are still captured when deployed on Alpic.
49
- */
57
+ /** Invoked with the user's feedback in addition to Alpic's dashboard delivery — the middleware still attaches the feedback to the response `_meta`. */
50
58
  handler?: (feedback: FeedbackData) => Promise<void> | void;
51
59
  }
52
- /**
53
- * Lets MCP server builders collect qualitative feedback from end users about their
54
- * tool/server. Injects a `send_feedback` tool at `tools/list` time and intercepts calls
55
- * to it at `tools/call` time. The tool has no handler on the server. The middleware
56
- * short-circuits the call and either invokes the provided `handler` or attaches the
57
- * feedback to the response `_meta`.
58
- */
59
- declare function feedbackMiddleware(options?: FeedbackMiddlewareOptions): McpMiddlewareFn;
60
- //#endregion
61
- //#region src/capture-feedback.d.ts
62
- /**
63
- * Injects a `send_feedback` tool into a vanilla `@modelcontextprotocol/sdk`
64
- * server and captures feedback submissions. Accepts the high-level `McpServer`
65
- * or the low-level `Server` and patches the `tools/list` and `tools/call`
66
- * request handlers to surface captured feedback via `options.handler` (or,
67
- * when `ALPIC_FEEDBACK_META_KEY` is set, via the response `_meta`).
68
- *
69
- * Already-registered handlers are wrapped immediately; future registrations
70
- * are wrapped via a `Map.set` proxy so order of calls relative to
71
- * `registerTool` does not matter.
72
- */
73
- declare const captureFeedback: (server: McpServer | Server, options?: FeedbackMiddlewareOptions) => void;
74
- //#endregion
75
- //#region src/capture-intents.d.ts
76
- /**
77
- * Captures the user's natural-language intent behind each tool call on a vanilla
78
- * `@modelcontextprotocol/sdk` server. Accepts the high-level `McpServer` or the
79
- * low-level `Server` and patches the `tools/list` and `tools/call` request
80
- * handlers to surface the captured intent via `options.handler` (or, when
81
- * `ALPIC_INTENT_META_KEY` is set, via the response `_meta`).
82
- *
83
- * Already-registered handlers are wrapped immediately; future registrations
84
- * (e.g. tools added after this call) are wrapped via a `Map.set` proxy so order
85
- * of calls relative to `registerTool` does not matter.
86
- */
87
- declare const captureIntents: (server: McpServer | Server, options?: IntentMiddlewareOptions) => void;
88
- //#endregion
89
- export { type FeedbackData, type FeedbackMiddlewareOptions, type IntentMiddlewareOptions, type McpMiddlewareFn, type PromptData, captureFeedback, captureIntents, feedbackMiddleware, intentMiddleware };
60
+ /** 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`. */
61
+ export declare function feedbackMiddleware(options?: FeedbackMiddlewareOptions): McpMiddlewareFn;
62
+ /** 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). */
63
+ export declare const captureFeedback: (server: object, options?: FeedbackMiddlewareOptions) => void;
64
+ /** 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). */
65
+ export declare const captureIntents: (server: object, options?: IntentMiddlewareOptions) => void;
66
+ /** 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. */
67
+ export declare const track: (server: object, options?: AnalyticsMiddlewareOptions) => void;
68
+ export type { Analytics, AnalyticsBatch, AnalyticsEvent, AnalyticsExtra, AnalyticsMiddlewareOptions, CaptureOptions, FeedbackData, FeedbackMiddlewareOptions, IntentMiddlewareOptions, McpMiddlewareFn, PromptData };
package/dist/index.mjs CHANGED
@@ -1,5 +1,89 @@
1
- import { CallToolRequestSchema, CallToolResultSchema, ListToolsResultSchema } from "@modelcontextprotocol/sdk/types.js";
2
- //#region src/feedback-middleware.ts
1
+ import { isSpecType } from "@modelcontextprotocol/server";
2
+ // src/is-record.ts
3
+ function isRecord(value) {
4
+ return value !== null && typeof value === "object" && !Array.isArray(value);
5
+ }
6
+ // src/analytics-middleware.ts
7
+ const MAX_EVENTS_PER_REQUEST = 50;
8
+ function warnInDev(message) {
9
+ if (process.env.NODE_ENV !== "production") console.warn(`[insights] ${message}`);
10
+ }
11
+ function createAnalyticsBuffer() {
12
+ const events = [];
13
+ let traits;
14
+ let settled = false;
15
+ return {
16
+ analytics: {
17
+ capture(name, options) {
18
+ if (settled) {
19
+ warnInDev(`analytics.capture("${name}") was called after the request settled; the event was dropped. Capture events before the tool handler returns.`);
20
+ return;
21
+ }
22
+ if (events.length >= MAX_EVENTS_PER_REQUEST) {
23
+ warnInDev(`analytics.capture("${name}") exceeded the ${MAX_EVENTS_PER_REQUEST} events per request limit; the event was dropped.`);
24
+ return;
25
+ }
26
+ events.push({
27
+ ...options,
28
+ name,
29
+ timestamp: Date.now()
30
+ });
31
+ },
32
+ identify(newTraits) {
33
+ if (settled) {
34
+ warnInDev("analytics.identify() was called after the request settled; the traits were dropped. Identify before the tool handler returns.");
35
+ return;
36
+ }
37
+ traits = { ...newTraits };
38
+ }
39
+ },
40
+ settle: () => {
41
+ settled = true;
42
+ },
43
+ get events() {
44
+ return events;
45
+ },
46
+ get traits() {
47
+ return traits;
48
+ }
49
+ };
50
+ }
51
+ /** 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. */
52
+ function analyticsMiddleware(options) {
53
+ return async (request, extra, next) => {
54
+ if (request.method !== "tools/call" || extra === null || typeof extra !== "object") return next();
55
+ const buffer = createAnalyticsBuffer();
56
+ extra.analytics = buffer.analytics;
57
+ let rawResult;
58
+ try {
59
+ rawResult = await next();
60
+ } finally {
61
+ buffer.settle();
62
+ }
63
+ if (buffer.events.length === 0 && buffer.traits === void 0) return rawResult;
64
+ const batch = {
65
+ events: [...buffer.events],
66
+ ...buffer.traits === void 0 ? {} : { traits: { ...buffer.traits } }
67
+ };
68
+ if (options?.handler) try {
69
+ await options.handler(batch);
70
+ } catch (error) {
71
+ console.error("Error calling analytics handler", error);
72
+ }
73
+ const eventsMetaKey = process.env.ALPIC_EVENTS_META_KEY || void 0;
74
+ const identifyMetaKey = process.env.ALPIC_IDENTIFY_META_KEY || void 0;
75
+ if (eventsMetaKey === void 0 && identifyMetaKey === void 0) return rawResult;
76
+ if (!isSpecType.CallToolResult(rawResult)) return rawResult;
77
+ const meta = { ...isRecord(rawResult._meta) ? rawResult._meta : {} };
78
+ if (eventsMetaKey !== void 0 && buffer.events.length > 0) meta[eventsMetaKey] = buffer.events;
79
+ if (identifyMetaKey !== void 0 && buffer.traits !== void 0) meta[identifyMetaKey] = buffer.traits;
80
+ return {
81
+ ...rawResult,
82
+ _meta: meta
83
+ };
84
+ };
85
+ }
86
+ // src/feedback-middleware.ts
3
87
  const FEEDBACK_TOOL_NAME = "send_feedback";
4
88
  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]\").";
5
89
  const FEEDBACK_RESPONSE_TEXT = "Feedback received. Thanks!";
@@ -14,22 +98,15 @@ const FEEDBACK_OUTPUT_SCHEMA = {
14
98
  additionalProperties: false
15
99
  };
16
100
  const FEEDBACK_STRUCTURED_CONTENT = { status: "received" };
17
- /**
18
- * Lets MCP server builders collect qualitative feedback from end users about their
19
- * tool/server. Injects a `send_feedback` tool at `tools/list` time and intercepts calls
20
- * to it at `tools/call` time. The tool has no handler on the server. The middleware
21
- * short-circuits the call and either invokes the provided `handler` or attaches the
22
- * feedback to the response `_meta`.
23
- */
101
+ /** 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`. */
24
102
  function feedbackMiddleware(options) {
25
103
  return async (request, _extra, next) => {
26
104
  const metaKeyName = process.env.ALPIC_FEEDBACK_META_KEY;
27
105
  if (request.method === "tools/list") {
28
106
  const rawResult = await next();
29
- const parsed = ListToolsResultSchema.safeParse(rawResult);
30
- if (!parsed.success) return rawResult;
31
- if (parsed.data.tools.some((tool) => tool.name === "send_feedback")) return parsed.data;
32
- parsed.data.tools.push({
107
+ if (!isSpecType.ListToolsResult(rawResult)) return rawResult;
108
+ if (rawResult.tools.some((tool) => tool.name === "send_feedback")) return rawResult;
109
+ const feedbackTool = {
33
110
  name: FEEDBACK_TOOL_NAME,
34
111
  description: FEEDBACK_TOOL_DESCRIPTION,
35
112
  inputSchema: {
@@ -54,13 +131,15 @@ function feedbackMiddleware(options) {
54
131
  openWorldHint: false,
55
132
  idempotentHint: true
56
133
  }
57
- });
58
- return parsed.data;
134
+ };
135
+ return {
136
+ ...rawResult,
137
+ tools: [...rawResult.tools, feedbackTool]
138
+ };
59
139
  }
60
140
  if (request.method !== "tools/call") return next();
61
- const parsedRequest = CallToolRequestSchema.safeParse(request);
62
- if (!parsedRequest.success || parsedRequest.data.params.name !== "send_feedback") return next();
63
- const args = parsedRequest.data.params.arguments ?? {};
141
+ if (request.params.name !== "send_feedback") return next();
142
+ const args = isRecord(request.params.arguments) ? request.params.arguments : {};
64
143
  const content = typeof args.content === "string" ? args.content.trim() : void 0;
65
144
  const source = args.source === "user" ? "user" : "model";
66
145
  if (content === void 0 || content.length === 0) return {
@@ -97,30 +176,17 @@ function feedbackMiddleware(options) {
97
176
  };
98
177
  };
99
178
  }
100
- //#endregion
101
- //#region src/capture-feedback.ts
102
- const INSTALLED_MARKER$1 = "__alpicCaptureFeedbackInstalled";
103
- /**
104
- * Injects a `send_feedback` tool into a vanilla `@modelcontextprotocol/sdk`
105
- * server and captures feedback submissions. Accepts the high-level `McpServer`
106
- * or the low-level `Server` and patches the `tools/list` and `tools/call`
107
- * request handlers to surface captured feedback via `options.handler` (or,
108
- * when `ALPIC_FEEDBACK_META_KEY` is set, via the response `_meta`).
109
- *
110
- * Already-registered handlers are wrapped immediately; future registrations
111
- * are wrapped via a `Map.set` proxy so order of calls relative to
112
- * `registerTool` does not matter.
113
- */
114
- const captureFeedback = (server, options) => {
179
+ // src/install-capture-middleware.ts
180
+ /** 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. */
181
+ const installCaptureMiddleware = (server, { middleware, installedMarker, disabledWarning }) => {
115
182
  const handlers = ("server" in server ? server.server : server)?._requestHandlers;
116
183
  if (!(handlers instanceof Map)) {
117
- console.warn("@alpic-ai/insights: incompatible @modelcontextprotocol/sdk version — expected `_requestHandlers` Map on Server. Feedback capture disabled.");
184
+ console.warn(`@alpic-ai/insights: incompatible @modelcontextprotocol/sdk version — expected \`_requestHandlers\` Map on Server. ${disabledWarning}`);
118
185
  return;
119
186
  }
120
187
  const marked = handlers;
121
- if (marked[INSTALLED_MARKER$1]) return;
122
- marked[INSTALLED_MARKER$1] = true;
123
- const middleware = feedbackMiddleware(options);
188
+ if (marked[installedMarker]) return;
189
+ marked[installedMarker] = true;
124
190
  const targets = /* @__PURE__ */ new Set(["tools/list", "tools/call"]);
125
191
  const wrap = (method, handler) => {
126
192
  if (!targets.has(method)) return handler;
@@ -136,15 +202,18 @@ const captureFeedback = (server, options) => {
136
202
  const originalSet = handlers.set.bind(handlers);
137
203
  handlers.set = (method, handler) => originalSet(method, wrap(method, handler));
138
204
  };
139
- //#endregion
140
- //#region src/intent-middleware.ts
205
+ // src/capture-feedback.ts
206
+ /** 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). */
207
+ const captureFeedback = (server, options) => {
208
+ installCaptureMiddleware(server, {
209
+ middleware: feedbackMiddleware(options),
210
+ installedMarker: "__alpicCaptureFeedbackInstalled",
211
+ disabledWarning: "Feedback capture disabled."
212
+ });
213
+ };
214
+ // src/intent-middleware.ts
141
215
  const USER_INTENT_FIELD = "user_intent";
142
- /**
143
- * Captures the user's natural-language intent behind each tool call so MCP
144
- * server builders can see *why* their tools are being invoked, not just that
145
- * they were. The LLM fills in `user_intent` from the original user message
146
- * (the server has no other way to access it).
147
- */
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. */
148
217
  function intentMiddleware(options) {
149
218
  const argumentNameOverride = options?.argumentNameOverride ?? {};
150
219
  const toolsFilter = options?.tools ? new Set(options.tools) : null;
@@ -152,134 +221,86 @@ function intentMiddleware(options) {
152
221
  const metaKeyName = process.env.ALPIC_INTENT_META_KEY;
153
222
  if (request.method === "tools/list") {
154
223
  const rawResult = await next();
155
- const parsed = ListToolsResultSchema.safeParse(rawResult);
156
- if (!parsed.success) return rawResult;
157
- for (const tool of parsed.data.tools) {
158
- if (toolsFilter && !toolsFilter.has(tool.name)) continue;
159
- if (tool.name === "send_feedback") continue;
160
- if (argumentNameOverride[tool.name] != null) continue;
161
- tool.inputSchema.properties = {
162
- ...tool.inputSchema.properties,
163
- [USER_INTENT_FIELD]: {
164
- type: "string",
165
- description: `A concise summary of what the user is trying to accomplish, derived from their message or the
166
- conversation context that triggered this tool call.
167
- This is used to understand the user's intent and context to improve the overall user experience.
168
-
169
- - For short, self-contained prompts (e.g. "I want new shoes"), copy the user message as-is.
170
- - For longer conversations or detailed requests, summarize the core goal and any relevant
171
- context in 1-2 sentences. Focus on intent, constraints, and preferences - not the full
172
- dialogue.
173
-
174
- Before sending, strip all personally identifiable information (PII), including but not
175
- limited to:
176
- - Names (first, last, usernames, handles)
177
- - Email addresses
178
- - Phone numbers
179
- - Physical addresses (street, city, zip/postal code, country when tied to an individual)
180
- - Dates of birth or exact ages
181
- - Government-issued ID numbers (SSN, passport, driver's license, etc.)
182
- - Payment or financial information (card numbers, bank accounts, etc.)
183
- - IP addresses or device identifiers
184
- - Account credentials (passwords, tokens, API keys)
185
- - Health or biometric data
186
- - Any other information that could identify a specific individual
187
-
188
- Replace stripped values with a generic placeholder (e.g. "[name]", "[email]", "[address]").
189
-
190
- Examples:
191
- User: "I want red running shoes under $100"
192
- -> "I want red running shoes under $100"
193
-
194
- User: "Hi, I'm John Smith, john@example.com, and I'm looking for flights from Paris to
195
- Tokyo for 2 adults departing around mid-June, budget around EUR2000 total"
196
- -> "Looking for flights from Paris to Tokyo for 2 adults, mid-June, budget ~EUR2000"
197
-
198
- User: "I need help resetting my password for account ID acct_12345"
199
- -> "I need help resetting my password for account ID [account_id]"`
224
+ if (!isSpecType.ListToolsResult(rawResult)) return rawResult;
225
+ const tools = rawResult.tools.map((tool) => {
226
+ if (toolsFilter && !toolsFilter.has(tool.name) || tool.name === "send_feedback" || argumentNameOverride[tool.name] != null) return tool;
227
+ return {
228
+ ...tool,
229
+ inputSchema: {
230
+ ...tool.inputSchema,
231
+ properties: {
232
+ ...tool.inputSchema.properties,
233
+ [USER_INTENT_FIELD]: {
234
+ type: "string",
235
+ description: "A concise summary of the user's goal, based only on what they asked. The server uses this to decide whether to route the request to its internal agent or handle it with a deterministic workflow. Include only details needed for that decision. 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 information, religion, or precise location). Do not ask follow-up questions solely to fill in this summary."
236
+ }
237
+ }
200
238
  }
201
239
  };
202
- }
203
- return parsed.data;
240
+ });
241
+ return {
242
+ ...rawResult,
243
+ tools
244
+ };
204
245
  }
205
246
  if (request.method === "tools/call") {
206
- const parsedRequest = CallToolRequestSchema.safeParse(request);
207
- if (!parsedRequest.success) return next();
208
- const toolName = parsedRequest.data.params.name;
247
+ if (typeof request.params.name !== "string") return next();
248
+ const toolName = request.params.name;
249
+ const args = isRecord(request.params.arguments) ? request.params.arguments : {};
209
250
  if (toolsFilter && !toolsFilter.has(toolName) || toolName === "send_feedback") {
210
- const args = parsedRequest.data.params.arguments ?? {};
211
251
  if (USER_INTENT_FIELD in args) {
212
- delete args[USER_INTENT_FIELD];
213
- request.params.arguments = args;
252
+ const toolArgs = { ...args };
253
+ delete toolArgs[USER_INTENT_FIELD];
254
+ request.params.arguments = toolArgs;
214
255
  }
215
256
  return next();
216
257
  }
217
258
  const promptField = argumentNameOverride[toolName] ?? USER_INTENT_FIELD;
218
- const args = parsedRequest.data.params.arguments ?? {};
219
259
  const userPrompt = typeof args[promptField] === "string" ? args[promptField] : void 0;
220
260
  const hasUserPrompt = userPrompt != null && userPrompt.length > 0;
221
261
  if (USER_INTENT_FIELD in args) {
222
- delete args[USER_INTENT_FIELD];
223
- request.params.arguments = args;
262
+ const toolArgs = { ...args };
263
+ delete toolArgs[USER_INTENT_FIELD];
264
+ request.params.arguments = toolArgs;
224
265
  }
225
266
  if (hasUserPrompt && options?.handler) try {
226
267
  await options.handler({
227
- toolName: parsedRequest.data.params.name,
268
+ toolName,
228
269
  userPrompt
229
270
  });
230
271
  } catch (error) {
231
272
  console.error("Error calling user prompt handler", error);
232
273
  }
233
274
  const rawResult = await next();
234
- const parsedResult = CallToolResultSchema.safeParse(rawResult);
235
- if (!parsedResult.success) return rawResult;
236
- if (metaKeyName && hasUserPrompt) parsedResult.data._meta = {
237
- ...parsedResult.data._meta,
238
- [metaKeyName]: userPrompt
275
+ if (!isSpecType.CallToolResult(rawResult)) return rawResult;
276
+ if (metaKeyName && hasUserPrompt) return {
277
+ ...rawResult,
278
+ _meta: {
279
+ ...isRecord(rawResult._meta) ? rawResult._meta : {},
280
+ [metaKeyName]: userPrompt
281
+ }
239
282
  };
240
- return parsedResult.data;
283
+ return rawResult;
241
284
  }
242
285
  return next();
243
286
  };
244
287
  }
245
- //#endregion
246
- //#region src/capture-intents.ts
247
- const INSTALLED_MARKER = "__alpicCaptureIntentsInstalled";
248
- /**
249
- * Captures the user's natural-language intent behind each tool call on a vanilla
250
- * `@modelcontextprotocol/sdk` server. Accepts the high-level `McpServer` or the
251
- * low-level `Server` and patches the `tools/list` and `tools/call` request
252
- * handlers to surface the captured intent via `options.handler` (or, when
253
- * `ALPIC_INTENT_META_KEY` is set, via the response `_meta`).
254
- *
255
- * Already-registered handlers are wrapped immediately; future registrations
256
- * (e.g. tools added after this call) are wrapped via a `Map.set` proxy so order
257
- * of calls relative to `registerTool` does not matter.
258
- */
288
+ // src/capture-intents.ts
289
+ /** 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). */
259
290
  const captureIntents = (server, options) => {
260
- const handlers = ("server" in server ? server.server : server)?._requestHandlers;
261
- if (!(handlers instanceof Map)) {
262
- console.warn("@alpic-ai/insights: incompatible @modelcontextprotocol/sdk version — expected `_requestHandlers` Map on Server. Prompt capture disabled.");
263
- return;
264
- }
265
- const marked = handlers;
266
- if (marked[INSTALLED_MARKER]) return;
267
- marked[INSTALLED_MARKER] = true;
268
- const middleware = intentMiddleware(options);
269
- const targets = /* @__PURE__ */ new Set(["tools/list", "tools/call"]);
270
- const wrap = (method, handler) => {
271
- if (!targets.has(method)) return handler;
272
- return async (...args) => {
273
- const [request, extra] = args;
274
- return middleware({
275
- method,
276
- params: request.params ?? {}
277
- }, extra, () => handler(...args));
278
- };
279
- };
280
- for (const [method, handler] of [...handlers]) handlers.set(method, wrap(method, handler));
281
- const originalSet = handlers.set.bind(handlers);
282
- handlers.set = (method, handler) => originalSet(method, wrap(method, handler));
291
+ installCaptureMiddleware(server, {
292
+ middleware: intentMiddleware(options),
293
+ installedMarker: "__alpicCaptureIntentsInstalled",
294
+ disabledWarning: "Prompt capture disabled."
295
+ });
296
+ };
297
+ // src/track.ts
298
+ /** 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. */
299
+ const track = (server, options) => {
300
+ installCaptureMiddleware(server, {
301
+ middleware: analyticsMiddleware(options),
302
+ installedMarker: "__alpicTrackInstalled",
303
+ disabledWarning: "Analytics capture disabled."
304
+ });
283
305
  };
284
- //#endregion
285
- export { captureFeedback, captureIntents, feedbackMiddleware, intentMiddleware };
306
+ export { analyticsMiddleware, captureFeedback, captureIntents, feedbackMiddleware, intentMiddleware, track };
@@ -0,0 +1,51 @@
1
+ import { ReactNode } from "react";
2
+ interface AnalyticsEvent {
3
+ name: string;
4
+ timestamp: number;
5
+ message?: string;
6
+ properties?: Record<string, unknown>;
7
+ duration?: number;
8
+ isError?: boolean;
9
+ error?: string;
10
+ }
11
+ interface CaptureOptions {
12
+ message?: string;
13
+ properties?: Record<string, unknown>;
14
+ /** Duration of the operation the event describes, in milliseconds. */
15
+ duration?: number;
16
+ isError?: boolean;
17
+ error?: string;
18
+ }
19
+ /** Inspect, transform, or drop (return `null`) each event before it is buffered for delivery. */
20
+ type BeforeSend = (event: AnalyticsEvent) => AnalyticsEvent | null;
21
+ interface Analytics {
22
+ /** Queue a custom widget event for delivery to Alpic Analytics. */
23
+ capture: (name: string, options?: CaptureOptions) => void;
24
+ }
25
+ /** Toggles for the SDK's built-in event capture. Lifecycle and errors are on by default; interactions are opt-in. */
26
+ interface AutoCaptureOptions {
27
+ lifecycle?: boolean;
28
+ errors?: boolean;
29
+ interactions?: boolean;
30
+ }
31
+ interface AlpicAnalyticsProps {
32
+ children?: ReactNode;
33
+ /** Inspect, transform, or drop each event before delivery. Runs synchronously in `capture`. */
34
+ beforeSend?: BeforeSend;
35
+ autoCapture?: AutoCaptureOptions;
36
+ }
37
+ /** Provides Alpic Analytics to descendant components, configuring itself from the widget host; events captured before configuration is available are buffered automatically. */
38
+ export declare function AlpicAnalytics({ children, beforeSend, autoCapture }: AlpicAnalyticsProps): import("react").JSX.Element;
39
+ /** Returns the analytics client from the nearest `AlpicAnalytics` provider. */
40
+ export declare function useAnalytics(): Analytics;
41
+ /** 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. */
42
+ export declare const AUTO_EVENT: {
43
+ readonly loaded: "$loaded";
44
+ readonly visible: "$visible";
45
+ readonly hidden: "$hidden";
46
+ readonly closed: "$closed";
47
+ readonly error: "$error";
48
+ };
49
+ /** Public DOM contract for declarative interaction capture: the attribute value is the event name. */
50
+ export declare const INTERACTION_ATTRIBUTE = "data-alpic-event";
51
+ export type { AlpicAnalyticsProps, Analytics, AutoCaptureOptions, BeforeSend, CaptureOptions };
@@ -0,0 +1,269 @@
1
+ import { createContext, useContext, useEffect, useRef, useState } from "react";
2
+ import { jsx } from "react/jsx-runtime";
3
+ // 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
+ // src/react/auto-capture.ts
74
+ /** 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. */
75
+ const AUTO_EVENT = {
76
+ loaded: "$loaded",
77
+ visible: "$visible",
78
+ hidden: "$hidden",
79
+ closed: "$closed",
80
+ error: "$error"
81
+ };
82
+ /** Public DOM contract for declarative interaction capture: the attribute value is the event name. */
83
+ const INTERACTION_ATTRIBUTE = "data-alpic-event";
84
+ const INTERACTION_DATASET_KEY = "alpicEvent";
85
+ const INTERACTION_DATASET_PREFIX = "alpic";
86
+ /** 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. */
87
+ function resolveInteractionEvent(target) {
88
+ if (!(target instanceof Element)) return null;
89
+ const element = target.closest(`[${INTERACTION_ATTRIBUTE}]`);
90
+ if (element === null) return null;
91
+ const name = element.dataset[INTERACTION_DATASET_KEY];
92
+ if (name === void 0 || name === "") return null;
93
+ const properties = {};
94
+ for (const [key, value] of Object.entries(element.dataset)) {
95
+ if (key === INTERACTION_DATASET_KEY || !key.startsWith(INTERACTION_DATASET_PREFIX) || value === void 0) continue;
96
+ const unprefixed = key.slice(5);
97
+ const propertyKey = unprefixed.charAt(0).toLowerCase() + unprefixed.slice(1);
98
+ properties[propertyKey] = value;
99
+ }
100
+ return Object.keys(properties).length > 0 ? {
101
+ name,
102
+ properties
103
+ } : { name };
104
+ }
105
+ /** Captures uncaught errors and unhandled rejections as `$error`, mapped onto the ingest error columns. */
106
+ function installErrorCapture(client) {
107
+ const onError = (event) => {
108
+ client.capture(AUTO_EVENT.error, {
109
+ isError: true,
110
+ error: event.message,
111
+ properties: {
112
+ stack: event.error instanceof Error ? event.error.stack : void 0,
113
+ source: event.filename
114
+ }
115
+ });
116
+ };
117
+ const onRejection = (event) => {
118
+ const reason = event.reason;
119
+ client.capture(AUTO_EVENT.error, {
120
+ isError: true,
121
+ error: reason instanceof Error ? reason.message : String(reason),
122
+ properties: {
123
+ stack: reason instanceof Error ? reason.stack : void 0,
124
+ source: "unhandledrejection"
125
+ }
126
+ });
127
+ };
128
+ window.addEventListener("error", onError);
129
+ window.addEventListener("unhandledrejection", onRejection);
130
+ return () => {
131
+ window.removeEventListener("error", onError);
132
+ window.removeEventListener("unhandledrejection", onRejection);
133
+ };
134
+ }
135
+ /** Captures clicks on `[data-alpic-event]` elements via a single delegated `document` listener. */
136
+ function installInteractionCapture(client) {
137
+ const onClick = (event) => {
138
+ const resolved = resolveInteractionEvent(event.target);
139
+ if (resolved === null) return;
140
+ client.capture(resolved.name, resolved.properties ? { properties: resolved.properties } : void 0);
141
+ };
142
+ document.addEventListener("click", onClick);
143
+ return () => {
144
+ document.removeEventListener("click", onClick);
145
+ };
146
+ }
147
+ // src/react/stamp.ts
148
+ const ANALYTICS_META_KEY = "alpic/analytics";
149
+ function parseAnalyticsStamp(metadata) {
150
+ if (metadata === null || typeof metadata !== "object") return null;
151
+ const candidate = metadata[ANALYTICS_META_KEY];
152
+ if (candidate === null || candidate === void 0 || typeof candidate !== "object") return null;
153
+ const { distinctId, sessionId, ingestUrl } = candidate;
154
+ if (typeof distinctId !== "string" || typeof sessionId !== "string" || typeof ingestUrl !== "string") return null;
155
+ return {
156
+ distinctId,
157
+ sessionId,
158
+ ingestUrl
159
+ };
160
+ }
161
+ // src/react/stamp-source.ts
162
+ const TOOL_RESULT_METHOD = "ui/notifications/tool-result";
163
+ const SET_GLOBALS_EVENT_TYPE = "openai:set_globals";
164
+ const subscribers = /* @__PURE__ */ new Set();
165
+ let latestProtocolStamp = null;
166
+ let isObservingRuntime = false;
167
+ function subscribeToAnalyticsStamp(onStamp) {
168
+ observeRuntime();
169
+ subscribers.add(onStamp);
170
+ if (latestProtocolStamp !== null) onStamp(latestProtocolStamp);
171
+ else emitOpenAiStamp(onStamp);
172
+ return () => {
173
+ subscribers.delete(onStamp);
174
+ };
175
+ }
176
+ function observeRuntime() {
177
+ if (isObservingRuntime || typeof window === "undefined") return;
178
+ window.addEventListener("message", handleToolResultMessage);
179
+ window.addEventListener(SET_GLOBALS_EVENT_TYPE, handleOpenAiGlobals, { passive: true });
180
+ isObservingRuntime = true;
181
+ }
182
+ function handleToolResultMessage(event) {
183
+ if (event.source !== window.parent || event.data === null || typeof event.data !== "object") return;
184
+ const message = event.data;
185
+ if (message.jsonrpc !== "2.0" || message.method !== TOOL_RESULT_METHOD) return;
186
+ const params = message.params;
187
+ if (params === null || typeof params !== "object") return;
188
+ const stamp = parseAnalyticsStamp(params._meta);
189
+ if (stamp === null) return;
190
+ latestProtocolStamp = stamp;
191
+ for (const subscriber of subscribers) subscriber(stamp);
192
+ }
193
+ function handleOpenAiGlobals() {
194
+ if (latestProtocolStamp !== null) return;
195
+ const globals = window;
196
+ if (globals.openai === void 0) return;
197
+ const stamp = parseAnalyticsStamp(globals.openai.toolResponseMetadata);
198
+ if (stamp === null) return;
199
+ for (const subscriber of subscribers) subscriber(stamp);
200
+ }
201
+ function emitOpenAiStamp(onStamp) {
202
+ if (typeof window === "undefined") return;
203
+ const stamp = parseAnalyticsStamp(window.openai?.toolResponseMetadata);
204
+ if (stamp !== null) onStamp(stamp);
205
+ }
206
+ observeRuntime();
207
+ // src/react/alpic-analytics.tsx
208
+ const AnalyticsContext = createContext(null);
209
+ /** Provides Alpic Analytics to descendant components, configuring itself from the widget host; events captured before configuration is available are buffered automatically. */
210
+ function AlpicAnalytics({ children, beforeSend, autoCapture }) {
211
+ const beforeSendRef = useRef(beforeSend);
212
+ beforeSendRef.current = beforeSend;
213
+ const [client] = useState(() => new AnalyticsClient({ beforeSend: (event) => {
214
+ const transform = beforeSendRef.current;
215
+ return transform ? transform(event) : event;
216
+ } }));
217
+ const lifecycle = autoCapture?.lifecycle ?? true;
218
+ const errors = autoCapture?.errors ?? true;
219
+ const interactions = autoCapture?.interactions ?? false;
220
+ useEffect(() => {
221
+ return subscribeToAnalyticsStamp((stamp) => {
222
+ client.configure(stamp);
223
+ });
224
+ }, [client]);
225
+ useEffect(() => {
226
+ if (lifecycle) client.capture(AUTO_EVENT.loaded);
227
+ let closed = false;
228
+ const onVisibilityChange = () => {
229
+ if (document.visibilityState === "hidden") {
230
+ if (lifecycle && !closed) client.capture(AUTO_EVENT.hidden);
231
+ client.flush();
232
+ } else {
233
+ closed = false;
234
+ if (lifecycle) client.capture(AUTO_EVENT.visible);
235
+ }
236
+ };
237
+ const onPageHide = () => {
238
+ if (lifecycle) client.capture(AUTO_EVENT.closed);
239
+ closed = true;
240
+ client.flush();
241
+ };
242
+ document.addEventListener("visibilitychange", onVisibilityChange);
243
+ window.addEventListener("pagehide", onPageHide);
244
+ return () => {
245
+ document.removeEventListener("visibilitychange", onVisibilityChange);
246
+ window.removeEventListener("pagehide", onPageHide);
247
+ client.flush();
248
+ };
249
+ }, [client, lifecycle]);
250
+ useEffect(() => {
251
+ if (!errors) return;
252
+ return installErrorCapture(client);
253
+ }, [client, errors]);
254
+ useEffect(() => {
255
+ if (!interactions) return;
256
+ return installInteractionCapture(client);
257
+ }, [client, interactions]);
258
+ return /* @__PURE__ */ jsx(AnalyticsContext.Provider, {
259
+ value: client,
260
+ children
261
+ });
262
+ }
263
+ /** Returns the analytics client from the nearest `AlpicAnalytics` provider. */
264
+ function useAnalytics() {
265
+ const analytics = useContext(AnalyticsContext);
266
+ if (analytics === null) throw new Error("useAnalytics must be used within an <AlpicAnalytics> provider");
267
+ return analytics;
268
+ }
269
+ 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.gb58f99a",
3
+ "version": "0.0.0-dev.gb5d4532",
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": [
@@ -17,32 +21,49 @@
17
21
  "author": "Alpic",
18
22
  "license": "ISC",
19
23
  "peerDependencies": {
20
- "@modelcontextprotocol/sdk": ">=1.29.0 <2",
21
- "skybridge": "^0.36.3 || ^1.0.0"
24
+ "react": ">=18.0.0",
25
+ "skybridge": "^0.36.3 || ^1.0.0 || ^2.0.0-beta.0 || ^2.0.0"
22
26
  },
23
27
  "peerDependenciesMeta": {
28
+ "react": {
29
+ "optional": true
30
+ },
24
31
  "skybridge": {
25
32
  "optional": true
26
33
  }
27
34
  },
35
+ "dependencies": {
36
+ "@modelcontextprotocol/server": "^2.4.0"
37
+ },
28
38
  "devDependencies": {
29
- "@modelcontextprotocol/sdk": "^1.29.0",
39
+ "@modelcontextprotocol/client": "^2.4.0",
40
+ "@modelcontextprotocol/sdk": "^1.32.2",
41
+ "@testing-library/dom": "^10.4.2",
42
+ "@testing-library/react": "^16.3.3",
30
43
  "@total-typescript/tsconfig": "^1.0.4",
31
- "@types/node": "^25.9.4",
44
+ "@types/node": "^26.6.6",
45
+ "@types/react": "19.3.0",
46
+ "jsdom": "^31.0.0",
47
+ "react": "^19.3.1",
48
+ "react-dom": "^19.3.1",
32
49
  "shx": "^0.4.0",
33
- "skybridge": "^1.1.2",
34
- "tsdown": "^0.22.3",
50
+ "skybridge": "^2.1.0",
51
+ "tsdown": "^0.23.7",
35
52
  "typescript": "^6.0.3",
36
- "vitest": "^4.1.9",
37
- "zod": "^4.4.3"
53
+ "vitest": "^5.1.0",
54
+ "zod": "^4.6.7"
38
55
  },
39
56
  "scripts": {
40
57
  "build": "shx rm -rf dist && tsdown",
58
+ "build:python": "cd python && uv build --no-sources",
41
59
  "format": "biome check --write --error-on-warnings .",
42
60
  "test": "pnpm run test:unit && pnpm run test:type && pnpm run test:format",
61
+ "test:python": "cd python && uv run --locked pytest",
62
+ "test:python:format": "cd python && uv run --locked ruff check . && uv run --locked ruff format --check .",
63
+ "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
64
  "test:unit": "vitest run",
44
65
  "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"
66
+ "test:type": "tsgo --noEmit",
67
+ "publish:npm": "../../scripts/publish-if-new.sh"
47
68
  }
48
69
  }