@alpic-ai/insights 0.0.0-dev.g21243dd → 0.0.0-dev.g2126cd1
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 +60 -13
- package/dist/index.mjs +173 -35
- package/dist/react/index.d.mts +67 -0
- package/dist/react/index.mjs +285 -0
- package/package.json +21 -7
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
2
2
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
-
|
|
4
3
|
//#region src/intent-middleware.d.ts
|
|
5
4
|
interface PromptData {
|
|
6
5
|
toolName: string;
|
|
@@ -37,19 +36,39 @@ type McpMiddlewareFn = (request: {
|
|
|
37
36
|
*/
|
|
38
37
|
declare function intentMiddleware(options?: IntentMiddlewareOptions): McpMiddlewareFn;
|
|
39
38
|
//#endregion
|
|
40
|
-
//#region src/
|
|
39
|
+
//#region src/analytics-middleware.d.ts
|
|
40
|
+
interface CaptureOptions {
|
|
41
|
+
message?: string;
|
|
42
|
+
/** Duration of the operation the event describes, in milliseconds. */
|
|
43
|
+
duration?: number;
|
|
44
|
+
isError?: boolean;
|
|
45
|
+
error?: string;
|
|
46
|
+
/** Freeform event detail. Not indexed — filtering on a property key is a query-time scan. */
|
|
47
|
+
properties?: Record<string, unknown>;
|
|
48
|
+
}
|
|
49
|
+
interface Analytics {
|
|
50
|
+
/** Records a custom event on the current session's timeline, interleaved with tool calls. */
|
|
51
|
+
capture(name: string, options?: CaptureOptions): void;
|
|
52
|
+
/**
|
|
53
|
+
* Attaches traits to the current request's user (e.g. email, name, plan). The target user is
|
|
54
|
+
* resolved by Alpic from the request auth context — no id or sessionId is passed.
|
|
55
|
+
*/
|
|
56
|
+
identify(traits: Record<string, string>): void;
|
|
57
|
+
}
|
|
41
58
|
/**
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
* low-level `Server` and patches the `tools/list` and `tools/call` request
|
|
45
|
-
* handlers to surface the captured intent via `options.handler` (or, when
|
|
46
|
-
* `ALPIC_INTENT_META_KEY` is set, via the response `_meta`).
|
|
47
|
-
*
|
|
48
|
-
* Already-registered handlers are wrapped immediately; future registrations
|
|
49
|
-
* (e.g. tools added after this call) are wrapped via a `Map.set` proxy so order
|
|
50
|
-
* of calls relative to `registerTool` does not matter.
|
|
59
|
+
* Shape of the handler `extra` once `analyticsMiddleware()` (or `track(server)`) is installed.
|
|
60
|
+
* Cast the handler's `extra` to this to access `analytics` with types.
|
|
51
61
|
*/
|
|
52
|
-
|
|
62
|
+
interface AnalyticsExtra {
|
|
63
|
+
analytics: Analytics;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Lets MCP server builders record custom analytics events and user traits from inside tool
|
|
67
|
+
* handlers, via `extra.analytics.capture(...)` / `extra.analytics.identify(...)`. Calls are
|
|
68
|
+
* buffered during the request and flushed into the response `_meta`, where the Alpic proxy
|
|
69
|
+
* ingests and strips them before the result reaches the client.
|
|
70
|
+
*/
|
|
71
|
+
declare function analyticsMiddleware(): McpMiddlewareFn;
|
|
53
72
|
//#endregion
|
|
54
73
|
//#region src/feedback-middleware.d.ts
|
|
55
74
|
interface FeedbackData {
|
|
@@ -72,4 +91,32 @@ interface FeedbackMiddlewareOptions {
|
|
|
72
91
|
*/
|
|
73
92
|
declare function feedbackMiddleware(options?: FeedbackMiddlewareOptions): McpMiddlewareFn;
|
|
74
93
|
//#endregion
|
|
75
|
-
|
|
94
|
+
//#region src/capture-feedback.d.ts
|
|
95
|
+
/**
|
|
96
|
+
* Injects a `send_feedback` tool into a vanilla `@modelcontextprotocol/sdk`
|
|
97
|
+
* server and captures feedback submissions. Accepts the high-level `McpServer`
|
|
98
|
+
* or the low-level `Server` and patches the `tools/list` and `tools/call`
|
|
99
|
+
* request handlers to surface captured feedback via `options.handler` (or,
|
|
100
|
+
* when `ALPIC_FEEDBACK_META_KEY` is set, via the response `_meta`).
|
|
101
|
+
*/
|
|
102
|
+
declare const captureFeedback: (server: McpServer | Server, options?: FeedbackMiddlewareOptions) => void;
|
|
103
|
+
//#endregion
|
|
104
|
+
//#region src/capture-intents.d.ts
|
|
105
|
+
/**
|
|
106
|
+
* Captures the user's natural-language intent behind each tool call on a vanilla
|
|
107
|
+
* `@modelcontextprotocol/sdk` server. Accepts the high-level `McpServer` or the
|
|
108
|
+
* low-level `Server` and patches the `tools/list` and `tools/call` request
|
|
109
|
+
* handlers to surface the captured intent via `options.handler` (or, when
|
|
110
|
+
* `ALPIC_INTENT_META_KEY` is set, via the response `_meta`).
|
|
111
|
+
*/
|
|
112
|
+
declare const captureIntents: (server: McpServer | Server, options?: IntentMiddlewareOptions) => void;
|
|
113
|
+
//#endregion
|
|
114
|
+
//#region src/track.d.ts
|
|
115
|
+
/**
|
|
116
|
+
* Enables custom analytics events on a vanilla `@modelcontextprotocol/sdk` server. Accepts the
|
|
117
|
+
* high-level `McpServer` or the low-level `Server` and patches the `tools/call` request handlers
|
|
118
|
+
* so tool handlers can call `extra.analytics.capture(...)` / `extra.analytics.identify(...)`.
|
|
119
|
+
*/
|
|
120
|
+
declare const track: (server: McpServer | Server) => void;
|
|
121
|
+
//#endregion
|
|
122
|
+
export { type Analytics, type AnalyticsExtra, type CaptureOptions, type FeedbackData, type FeedbackMiddlewareOptions, type IntentMiddlewareOptions, type McpMiddlewareFn, type PromptData, analyticsMiddleware, captureFeedback, captureIntents, feedbackMiddleware, intentMiddleware, track };
|
package/dist/index.mjs
CHANGED
|
@@ -1,8 +1,99 @@
|
|
|
1
1
|
import { CallToolRequestSchema, CallToolResultSchema, ListToolsResultSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
2
|
+
//#region src/analytics-middleware.ts
|
|
3
|
+
const ALPIC_EVENTS_META_KEY = "alpic/events";
|
|
4
|
+
const ALPIC_IDENTIFY_META_KEY = "alpic/identify";
|
|
5
|
+
const MAX_EVENTS_PER_REQUEST = 50;
|
|
6
|
+
function warnInDev(message) {
|
|
7
|
+
if (process.env.NODE_ENV !== "production") console.warn(`[insights] ${message}`);
|
|
8
|
+
}
|
|
9
|
+
function createAnalyticsBuffer() {
|
|
10
|
+
const events = [];
|
|
11
|
+
let traits;
|
|
12
|
+
let settled = false;
|
|
13
|
+
return {
|
|
14
|
+
analytics: {
|
|
15
|
+
capture(name, options) {
|
|
16
|
+
if (settled) {
|
|
17
|
+
warnInDev(`analytics.capture("${name}") was called after the request settled; the event was dropped. Capture events before the tool handler returns.`);
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
if (events.length >= MAX_EVENTS_PER_REQUEST) {
|
|
21
|
+
warnInDev(`analytics.capture("${name}") exceeded the ${MAX_EVENTS_PER_REQUEST} events per request limit; the event was dropped.`);
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
events.push({
|
|
25
|
+
...options,
|
|
26
|
+
name,
|
|
27
|
+
timestamp: Date.now()
|
|
28
|
+
});
|
|
29
|
+
},
|
|
30
|
+
identify(newTraits) {
|
|
31
|
+
if (settled) {
|
|
32
|
+
warnInDev("analytics.identify() was called after the request settled; the traits were dropped. Identify before the tool handler returns.");
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
traits = {
|
|
36
|
+
...traits,
|
|
37
|
+
...newTraits
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
settle: () => {
|
|
42
|
+
settled = true;
|
|
43
|
+
},
|
|
44
|
+
get events() {
|
|
45
|
+
return events;
|
|
46
|
+
},
|
|
47
|
+
get traits() {
|
|
48
|
+
return traits;
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Lets MCP server builders record custom analytics events and user traits from inside tool
|
|
54
|
+
* handlers, via `extra.analytics.capture(...)` / `extra.analytics.identify(...)`. Calls are
|
|
55
|
+
* buffered during the request and flushed into the response `_meta`, where the Alpic proxy
|
|
56
|
+
* ingests and strips them before the result reaches the client.
|
|
57
|
+
*/
|
|
58
|
+
function analyticsMiddleware() {
|
|
59
|
+
return async (request, extra, next) => {
|
|
60
|
+
if (request.method !== "tools/call" || extra === null || typeof extra !== "object") return next();
|
|
61
|
+
const buffer = createAnalyticsBuffer();
|
|
62
|
+
extra.analytics = buffer.analytics;
|
|
63
|
+
let rawResult;
|
|
64
|
+
try {
|
|
65
|
+
rawResult = await next();
|
|
66
|
+
} finally {
|
|
67
|
+
buffer.settle();
|
|
68
|
+
}
|
|
69
|
+
if (buffer.events.length === 0 && buffer.traits === void 0) return rawResult;
|
|
70
|
+
if (!CallToolResultSchema.safeParse(rawResult).success) return rawResult;
|
|
71
|
+
const result = rawResult;
|
|
72
|
+
const meta = { ...result._meta };
|
|
73
|
+
if (buffer.events.length > 0) meta[ALPIC_EVENTS_META_KEY] = buffer.events;
|
|
74
|
+
if (buffer.traits !== void 0) meta[ALPIC_IDENTIFY_META_KEY] = buffer.traits;
|
|
75
|
+
return {
|
|
76
|
+
...result,
|
|
77
|
+
_meta: meta
|
|
78
|
+
};
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
//#endregion
|
|
2
82
|
//#region src/feedback-middleware.ts
|
|
3
83
|
const FEEDBACK_TOOL_NAME = "send_feedback";
|
|
4
84
|
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
85
|
const FEEDBACK_RESPONSE_TEXT = "Feedback received. Thanks!";
|
|
86
|
+
const FEEDBACK_OUTPUT_SCHEMA = {
|
|
87
|
+
type: "object",
|
|
88
|
+
properties: { status: {
|
|
89
|
+
type: "string",
|
|
90
|
+
enum: ["received"],
|
|
91
|
+
description: "Confirmation that the feedback was received by the server operators."
|
|
92
|
+
} },
|
|
93
|
+
required: ["status"],
|
|
94
|
+
additionalProperties: false
|
|
95
|
+
};
|
|
96
|
+
const FEEDBACK_STRUCTURED_CONTENT = { status: "received" };
|
|
6
97
|
/**
|
|
7
98
|
* Lets MCP server builders collect qualitative feedback from end users about their
|
|
8
99
|
* tool/server. Injects a `send_feedback` tool at `tools/list` time and intercepts calls
|
|
@@ -36,10 +127,11 @@ function feedbackMiddleware(options) {
|
|
|
36
127
|
},
|
|
37
128
|
required: ["content", "source"]
|
|
38
129
|
},
|
|
130
|
+
outputSchema: FEEDBACK_OUTPUT_SCHEMA,
|
|
39
131
|
annotations: {
|
|
40
|
-
readOnlyHint:
|
|
132
|
+
readOnlyHint: true,
|
|
41
133
|
destructiveHint: false,
|
|
42
|
-
openWorldHint:
|
|
134
|
+
openWorldHint: false,
|
|
43
135
|
idempotentHint: true
|
|
44
136
|
}
|
|
45
137
|
});
|
|
@@ -73,15 +165,70 @@ function feedbackMiddleware(options) {
|
|
|
73
165
|
type: "text",
|
|
74
166
|
text: FEEDBACK_RESPONSE_TEXT
|
|
75
167
|
}],
|
|
168
|
+
structuredContent: FEEDBACK_STRUCTURED_CONTENT,
|
|
76
169
|
_meta: { [metaKeyName]: feedback }
|
|
77
170
|
};
|
|
78
|
-
return {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
171
|
+
return {
|
|
172
|
+
content: [{
|
|
173
|
+
type: "text",
|
|
174
|
+
text: FEEDBACK_RESPONSE_TEXT
|
|
175
|
+
}],
|
|
176
|
+
structuredContent: FEEDBACK_STRUCTURED_CONTENT
|
|
177
|
+
};
|
|
82
178
|
};
|
|
83
179
|
}
|
|
84
180
|
//#endregion
|
|
181
|
+
//#region src/install-capture-middleware.ts
|
|
182
|
+
/**
|
|
183
|
+
* Patches the `tools/list` and `tools/call` request handlers of a vanilla
|
|
184
|
+
* `@modelcontextprotocol/sdk` server (high-level `McpServer` or low-level
|
|
185
|
+
* `Server`) to run the given middleware.
|
|
186
|
+
*
|
|
187
|
+
* Already-registered handlers are wrapped immediately; future registrations
|
|
188
|
+
* (e.g. tools added after this call) are wrapped via a `Map.set` proxy so order
|
|
189
|
+
* of calls relative to `registerTool` does not matter.
|
|
190
|
+
*/
|
|
191
|
+
const installCaptureMiddleware = (server, { middleware, installedMarker, disabledWarning }) => {
|
|
192
|
+
const handlers = ("server" in server ? server.server : server)?._requestHandlers;
|
|
193
|
+
if (!(handlers instanceof Map)) {
|
|
194
|
+
console.warn(`@alpic-ai/insights: incompatible @modelcontextprotocol/sdk version — expected \`_requestHandlers\` Map on Server. ${disabledWarning}`);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
const marked = handlers;
|
|
198
|
+
if (marked[installedMarker]) return;
|
|
199
|
+
marked[installedMarker] = true;
|
|
200
|
+
const targets = /* @__PURE__ */ new Set(["tools/list", "tools/call"]);
|
|
201
|
+
const wrap = (method, handler) => {
|
|
202
|
+
if (!targets.has(method)) return handler;
|
|
203
|
+
return async (...args) => {
|
|
204
|
+
const [request, extra] = args;
|
|
205
|
+
return middleware({
|
|
206
|
+
method,
|
|
207
|
+
params: request.params ?? {}
|
|
208
|
+
}, extra, () => handler(...args));
|
|
209
|
+
};
|
|
210
|
+
};
|
|
211
|
+
for (const [method, handler] of [...handlers]) handlers.set(method, wrap(method, handler));
|
|
212
|
+
const originalSet = handlers.set.bind(handlers);
|
|
213
|
+
handlers.set = (method, handler) => originalSet(method, wrap(method, handler));
|
|
214
|
+
};
|
|
215
|
+
//#endregion
|
|
216
|
+
//#region src/capture-feedback.ts
|
|
217
|
+
/**
|
|
218
|
+
* Injects a `send_feedback` tool into a vanilla `@modelcontextprotocol/sdk`
|
|
219
|
+
* server and captures feedback submissions. Accepts the high-level `McpServer`
|
|
220
|
+
* or the low-level `Server` and patches the `tools/list` and `tools/call`
|
|
221
|
+
* request handlers to surface captured feedback via `options.handler` (or,
|
|
222
|
+
* when `ALPIC_FEEDBACK_META_KEY` is set, via the response `_meta`).
|
|
223
|
+
*/
|
|
224
|
+
const captureFeedback = (server, options) => {
|
|
225
|
+
installCaptureMiddleware(server, {
|
|
226
|
+
middleware: feedbackMiddleware(options),
|
|
227
|
+
installedMarker: "__alpicCaptureFeedbackInstalled",
|
|
228
|
+
disabledWarning: "Feedback capture disabled."
|
|
229
|
+
});
|
|
230
|
+
};
|
|
231
|
+
//#endregion
|
|
85
232
|
//#region src/intent-middleware.ts
|
|
86
233
|
const USER_INTENT_FIELD = "user_intent";
|
|
87
234
|
/**
|
|
@@ -189,42 +336,33 @@ Examples:
|
|
|
189
336
|
}
|
|
190
337
|
//#endregion
|
|
191
338
|
//#region src/capture-intents.ts
|
|
192
|
-
const INSTALLED_MARKER = "__alpicCaptureIntentsInstalled";
|
|
193
339
|
/**
|
|
194
340
|
* Captures the user's natural-language intent behind each tool call on a vanilla
|
|
195
341
|
* `@modelcontextprotocol/sdk` server. Accepts the high-level `McpServer` or the
|
|
196
342
|
* low-level `Server` and patches the `tools/list` and `tools/call` request
|
|
197
343
|
* handlers to surface the captured intent via `options.handler` (or, when
|
|
198
344
|
* `ALPIC_INTENT_META_KEY` is set, via the response `_meta`).
|
|
199
|
-
*
|
|
200
|
-
* Already-registered handlers are wrapped immediately; future registrations
|
|
201
|
-
* (e.g. tools added after this call) are wrapped via a `Map.set` proxy so order
|
|
202
|
-
* of calls relative to `registerTool` does not matter.
|
|
203
345
|
*/
|
|
204
346
|
const captureIntents = (server, options) => {
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
};
|
|
225
|
-
for (const [method, handler] of [...handlers]) handlers.set(method, wrap(method, handler));
|
|
226
|
-
const originalSet = handlers.set.bind(handlers);
|
|
227
|
-
handlers.set = (method, handler) => originalSet(method, wrap(method, handler));
|
|
347
|
+
installCaptureMiddleware(server, {
|
|
348
|
+
middleware: intentMiddleware(options),
|
|
349
|
+
installedMarker: "__alpicCaptureIntentsInstalled",
|
|
350
|
+
disabledWarning: "Prompt capture disabled."
|
|
351
|
+
});
|
|
352
|
+
};
|
|
353
|
+
//#endregion
|
|
354
|
+
//#region src/track.ts
|
|
355
|
+
/**
|
|
356
|
+
* Enables custom analytics events on a vanilla `@modelcontextprotocol/sdk` server. Accepts the
|
|
357
|
+
* high-level `McpServer` or the low-level `Server` and patches the `tools/call` request handlers
|
|
358
|
+
* so tool handlers can call `extra.analytics.capture(...)` / `extra.analytics.identify(...)`.
|
|
359
|
+
*/
|
|
360
|
+
const track = (server) => {
|
|
361
|
+
installCaptureMiddleware(server, {
|
|
362
|
+
middleware: analyticsMiddleware(),
|
|
363
|
+
installedMarker: "__alpicTrackInstalled",
|
|
364
|
+
disabledWarning: "Analytics capture disabled."
|
|
365
|
+
});
|
|
228
366
|
};
|
|
229
367
|
//#endregion
|
|
230
|
-
export { captureIntents, feedbackMiddleware, intentMiddleware };
|
|
368
|
+
export { analyticsMiddleware, captureFeedback, captureIntents, feedbackMiddleware, intentMiddleware, track };
|
|
@@ -0,0 +1,67 @@
|
|
|
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
|
+
/**
|
|
43
|
+
* Provides Alpic Analytics to descendant components and configures itself from the widget host.
|
|
44
|
+
* Wrap the widget once, then call `useAnalytics()` from components that capture events.
|
|
45
|
+
* Events captured before configuration is available are buffered automatically.
|
|
46
|
+
*/
|
|
47
|
+
declare function AlpicAnalytics({ children, beforeSend, autoCapture }: AlpicAnalyticsProps): import("react").JSX.Element;
|
|
48
|
+
/** Returns the analytics client from the nearest `AlpicAnalytics` provider. */
|
|
49
|
+
declare function useAnalytics(): Analytics;
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region src/react/auto-capture.d.ts
|
|
52
|
+
/**
|
|
53
|
+
* Reserved auto-capture event names. The `$` prefix marks events emitted by the SDK itself
|
|
54
|
+
* (lifecycle, errors, interactions) so the analytics UI can distinguish them from custom
|
|
55
|
+
* `capture()` calls. Keep in sync with the server-side reserved namespace.
|
|
56
|
+
*/
|
|
57
|
+
declare const AUTO_EVENT: {
|
|
58
|
+
readonly loaded: "$loaded";
|
|
59
|
+
readonly visible: "$visible";
|
|
60
|
+
readonly hidden: "$hidden";
|
|
61
|
+
readonly closed: "$closed";
|
|
62
|
+
readonly error: "$error";
|
|
63
|
+
};
|
|
64
|
+
/** Public DOM contract for declarative interaction capture: the attribute value is the event name. */
|
|
65
|
+
declare const INTERACTION_ATTRIBUTE = "data-alpic-event";
|
|
66
|
+
//#endregion
|
|
67
|
+
export { AUTO_EVENT, AlpicAnalytics, type AlpicAnalyticsProps, type Analytics, type AutoCaptureOptions, type BeforeSend, type CaptureOptions, INTERACTION_ATTRIBUTE, useAnalytics };
|
|
@@ -0,0 +1,285 @@
|
|
|
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
|
+
/**
|
|
76
|
+
* Reserved auto-capture event names. The `$` prefix marks events emitted by the SDK itself
|
|
77
|
+
* (lifecycle, errors, interactions) so the analytics UI can distinguish them from custom
|
|
78
|
+
* `capture()` calls. Keep in sync with the server-side reserved namespace.
|
|
79
|
+
*/
|
|
80
|
+
const AUTO_EVENT = {
|
|
81
|
+
loaded: "$loaded",
|
|
82
|
+
visible: "$visible",
|
|
83
|
+
hidden: "$hidden",
|
|
84
|
+
closed: "$closed",
|
|
85
|
+
error: "$error"
|
|
86
|
+
};
|
|
87
|
+
/** Public DOM contract for declarative interaction capture: the attribute value is the event name. */
|
|
88
|
+
const INTERACTION_ATTRIBUTE = "data-alpic-event";
|
|
89
|
+
const INTERACTION_DATASET_KEY = "alpicEvent";
|
|
90
|
+
const INTERACTION_DATASET_PREFIX = "alpic";
|
|
91
|
+
/**
|
|
92
|
+
* Resolves the nearest `[data-alpic-event]` ancestor of a click target into an event: the
|
|
93
|
+
* attribute value is the name, and every other `data-alpic-*` attribute becomes a property.
|
|
94
|
+
*/
|
|
95
|
+
function resolveInteractionEvent(target) {
|
|
96
|
+
if (!(target instanceof Element)) return null;
|
|
97
|
+
const element = target.closest(`[${INTERACTION_ATTRIBUTE}]`);
|
|
98
|
+
if (element === null) return null;
|
|
99
|
+
const name = element.dataset[INTERACTION_DATASET_KEY];
|
|
100
|
+
if (name === void 0 || name === "") return null;
|
|
101
|
+
const properties = {};
|
|
102
|
+
for (const [key, value] of Object.entries(element.dataset)) {
|
|
103
|
+
if (key === INTERACTION_DATASET_KEY || !key.startsWith(INTERACTION_DATASET_PREFIX) || value === void 0) continue;
|
|
104
|
+
const unprefixed = key.slice(5);
|
|
105
|
+
const propertyKey = unprefixed.charAt(0).toLowerCase() + unprefixed.slice(1);
|
|
106
|
+
properties[propertyKey] = value;
|
|
107
|
+
}
|
|
108
|
+
return Object.keys(properties).length > 0 ? {
|
|
109
|
+
name,
|
|
110
|
+
properties
|
|
111
|
+
} : { name };
|
|
112
|
+
}
|
|
113
|
+
/** Captures uncaught errors and unhandled rejections as `$error`, mapped onto the ingest error columns. */
|
|
114
|
+
function installErrorCapture(client) {
|
|
115
|
+
const onError = (event) => {
|
|
116
|
+
client.capture(AUTO_EVENT.error, {
|
|
117
|
+
isError: true,
|
|
118
|
+
error: event.message,
|
|
119
|
+
properties: {
|
|
120
|
+
stack: event.error instanceof Error ? event.error.stack : void 0,
|
|
121
|
+
source: event.filename
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
};
|
|
125
|
+
const onRejection = (event) => {
|
|
126
|
+
const reason = event.reason;
|
|
127
|
+
client.capture(AUTO_EVENT.error, {
|
|
128
|
+
isError: true,
|
|
129
|
+
error: reason instanceof Error ? reason.message : String(reason),
|
|
130
|
+
properties: {
|
|
131
|
+
stack: reason instanceof Error ? reason.stack : void 0,
|
|
132
|
+
source: "unhandledrejection"
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
};
|
|
136
|
+
window.addEventListener("error", onError);
|
|
137
|
+
window.addEventListener("unhandledrejection", onRejection);
|
|
138
|
+
return () => {
|
|
139
|
+
window.removeEventListener("error", onError);
|
|
140
|
+
window.removeEventListener("unhandledrejection", onRejection);
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
/** Captures clicks on `[data-alpic-event]` elements via a single delegated `document` listener. */
|
|
144
|
+
function installInteractionCapture(client) {
|
|
145
|
+
const onClick = (event) => {
|
|
146
|
+
const resolved = resolveInteractionEvent(event.target);
|
|
147
|
+
if (resolved === null) return;
|
|
148
|
+
client.capture(resolved.name, resolved.properties ? { properties: resolved.properties } : void 0);
|
|
149
|
+
};
|
|
150
|
+
document.addEventListener("click", onClick);
|
|
151
|
+
return () => {
|
|
152
|
+
document.removeEventListener("click", onClick);
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
//#endregion
|
|
156
|
+
//#region src/react/stamp.ts
|
|
157
|
+
const ANALYTICS_META_KEY = "alpic/analytics";
|
|
158
|
+
function parseAnalyticsStamp(metadata) {
|
|
159
|
+
if (metadata === null || typeof metadata !== "object") return null;
|
|
160
|
+
const candidate = metadata[ANALYTICS_META_KEY];
|
|
161
|
+
if (candidate === null || candidate === void 0 || typeof candidate !== "object") return null;
|
|
162
|
+
const { distinctId, sessionId, ingestUrl } = candidate;
|
|
163
|
+
if (typeof distinctId !== "string" || typeof sessionId !== "string" || typeof ingestUrl !== "string") return null;
|
|
164
|
+
return {
|
|
165
|
+
distinctId,
|
|
166
|
+
sessionId,
|
|
167
|
+
ingestUrl
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
//#endregion
|
|
171
|
+
//#region src/react/stamp-source.ts
|
|
172
|
+
const TOOL_RESULT_METHOD = "ui/notifications/tool-result";
|
|
173
|
+
const SET_GLOBALS_EVENT_TYPE = "openai:set_globals";
|
|
174
|
+
const subscribers = /* @__PURE__ */ new Set();
|
|
175
|
+
let latestProtocolStamp = null;
|
|
176
|
+
let isObservingRuntime = false;
|
|
177
|
+
function subscribeToAnalyticsStamp(onStamp) {
|
|
178
|
+
observeRuntime();
|
|
179
|
+
subscribers.add(onStamp);
|
|
180
|
+
if (latestProtocolStamp !== null) onStamp(latestProtocolStamp);
|
|
181
|
+
else emitOpenAiStamp(onStamp);
|
|
182
|
+
return () => {
|
|
183
|
+
subscribers.delete(onStamp);
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
function observeRuntime() {
|
|
187
|
+
if (isObservingRuntime || typeof window === "undefined") return;
|
|
188
|
+
window.addEventListener("message", handleToolResultMessage);
|
|
189
|
+
window.addEventListener(SET_GLOBALS_EVENT_TYPE, handleOpenAiGlobals, { passive: true });
|
|
190
|
+
isObservingRuntime = true;
|
|
191
|
+
}
|
|
192
|
+
function handleToolResultMessage(event) {
|
|
193
|
+
if (event.source !== window.parent || event.data === null || typeof event.data !== "object") return;
|
|
194
|
+
const message = event.data;
|
|
195
|
+
if (message.jsonrpc !== "2.0" || message.method !== TOOL_RESULT_METHOD) return;
|
|
196
|
+
const params = message.params;
|
|
197
|
+
if (params === null || typeof params !== "object") return;
|
|
198
|
+
const stamp = parseAnalyticsStamp(params._meta);
|
|
199
|
+
if (stamp === null) return;
|
|
200
|
+
latestProtocolStamp = stamp;
|
|
201
|
+
for (const subscriber of subscribers) subscriber(stamp);
|
|
202
|
+
}
|
|
203
|
+
function handleOpenAiGlobals() {
|
|
204
|
+
if (latestProtocolStamp !== null) return;
|
|
205
|
+
const globals = window;
|
|
206
|
+
if (globals.openai === void 0) return;
|
|
207
|
+
const stamp = parseAnalyticsStamp(globals.openai.toolResponseMetadata);
|
|
208
|
+
if (stamp === null) return;
|
|
209
|
+
for (const subscriber of subscribers) subscriber(stamp);
|
|
210
|
+
}
|
|
211
|
+
function emitOpenAiStamp(onStamp) {
|
|
212
|
+
if (typeof window === "undefined") return;
|
|
213
|
+
const stamp = parseAnalyticsStamp(window.openai?.toolResponseMetadata);
|
|
214
|
+
if (stamp !== null) onStamp(stamp);
|
|
215
|
+
}
|
|
216
|
+
observeRuntime();
|
|
217
|
+
//#endregion
|
|
218
|
+
//#region src/react/alpic-analytics.tsx
|
|
219
|
+
const AnalyticsContext = createContext(null);
|
|
220
|
+
/**
|
|
221
|
+
* Provides Alpic Analytics to descendant components and configures itself from the widget host.
|
|
222
|
+
* Wrap the widget once, then call `useAnalytics()` from components that capture events.
|
|
223
|
+
* Events captured before configuration is available are buffered automatically.
|
|
224
|
+
*/
|
|
225
|
+
function AlpicAnalytics({ children, beforeSend, autoCapture }) {
|
|
226
|
+
const beforeSendRef = useRef(beforeSend);
|
|
227
|
+
beforeSendRef.current = beforeSend;
|
|
228
|
+
const [client] = useState(() => new AnalyticsClient({ beforeSend: (event) => {
|
|
229
|
+
const transform = beforeSendRef.current;
|
|
230
|
+
return transform ? transform(event) : event;
|
|
231
|
+
} }));
|
|
232
|
+
const lifecycle = autoCapture?.lifecycle ?? true;
|
|
233
|
+
const errors = autoCapture?.errors ?? true;
|
|
234
|
+
const interactions = autoCapture?.interactions ?? false;
|
|
235
|
+
useEffect(() => {
|
|
236
|
+
return subscribeToAnalyticsStamp((stamp) => {
|
|
237
|
+
client.configure(stamp);
|
|
238
|
+
});
|
|
239
|
+
}, [client]);
|
|
240
|
+
useEffect(() => {
|
|
241
|
+
if (lifecycle) client.capture(AUTO_EVENT.loaded);
|
|
242
|
+
let closed = false;
|
|
243
|
+
const onVisibilityChange = () => {
|
|
244
|
+
if (document.visibilityState === "hidden") {
|
|
245
|
+
if (lifecycle && !closed) client.capture(AUTO_EVENT.hidden);
|
|
246
|
+
client.flush();
|
|
247
|
+
} else {
|
|
248
|
+
closed = false;
|
|
249
|
+
if (lifecycle) client.capture(AUTO_EVENT.visible);
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
const onPageHide = () => {
|
|
253
|
+
if (lifecycle) client.capture(AUTO_EVENT.closed);
|
|
254
|
+
closed = true;
|
|
255
|
+
client.flush();
|
|
256
|
+
};
|
|
257
|
+
document.addEventListener("visibilitychange", onVisibilityChange);
|
|
258
|
+
window.addEventListener("pagehide", onPageHide);
|
|
259
|
+
return () => {
|
|
260
|
+
document.removeEventListener("visibilitychange", onVisibilityChange);
|
|
261
|
+
window.removeEventListener("pagehide", onPageHide);
|
|
262
|
+
client.flush();
|
|
263
|
+
};
|
|
264
|
+
}, [client, lifecycle]);
|
|
265
|
+
useEffect(() => {
|
|
266
|
+
if (!errors) return;
|
|
267
|
+
return installErrorCapture(client);
|
|
268
|
+
}, [client, errors]);
|
|
269
|
+
useEffect(() => {
|
|
270
|
+
if (!interactions) return;
|
|
271
|
+
return installInteractionCapture(client);
|
|
272
|
+
}, [client, interactions]);
|
|
273
|
+
return /* @__PURE__ */ jsx(AnalyticsContext.Provider, {
|
|
274
|
+
value: client,
|
|
275
|
+
children
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
/** Returns the analytics client from the nearest `AlpicAnalytics` provider. */
|
|
279
|
+
function useAnalytics() {
|
|
280
|
+
const analytics = useContext(AnalyticsContext);
|
|
281
|
+
if (analytics === null) throw new Error("useAnalytics must be used within an <AlpicAnalytics> provider");
|
|
282
|
+
return analytics;
|
|
283
|
+
}
|
|
284
|
+
//#endregion
|
|
285
|
+
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.
|
|
3
|
+
"version": "0.0.0-dev.g2126cd1",
|
|
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,22 +22,32 @@
|
|
|
18
22
|
"license": "ISC",
|
|
19
23
|
"peerDependencies": {
|
|
20
24
|
"@modelcontextprotocol/sdk": ">=1.29.0 <2",
|
|
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
37
|
"@modelcontextprotocol/sdk": "^1.29.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.
|
|
41
|
+
"@types/node": "^25.9.5",
|
|
42
|
+
"@types/react": "19.2.17",
|
|
43
|
+
"jsdom": "^29.1.1",
|
|
44
|
+
"react": "^19.2.7",
|
|
45
|
+
"react-dom": "^19.2.7",
|
|
32
46
|
"shx": "^0.4.0",
|
|
33
|
-
"skybridge": "^
|
|
34
|
-
"tsdown": "^0.22.
|
|
47
|
+
"skybridge": "^1.2.7",
|
|
48
|
+
"tsdown": "^0.22.9",
|
|
35
49
|
"typescript": "^6.0.3",
|
|
36
|
-
"vitest": "^4.1.
|
|
50
|
+
"vitest": "^4.1.10",
|
|
37
51
|
"zod": "^4.4.3"
|
|
38
52
|
},
|
|
39
53
|
"scripts": {
|
|
@@ -42,7 +56,7 @@
|
|
|
42
56
|
"test": "pnpm run test:unit && pnpm run test:type && pnpm run test:format",
|
|
43
57
|
"test:unit": "vitest run",
|
|
44
58
|
"test:format": "biome check --error-on-warnings .",
|
|
45
|
-
"test:type": "
|
|
59
|
+
"test:type": "tsgo --noEmit",
|
|
46
60
|
"publish:npm": "pnpm publish --tag \"${NPM_TAG}\" --access public --no-git-checks"
|
|
47
61
|
}
|
|
48
62
|
}
|