@alpic-ai/insights 0.0.0-dev.gf7a51de → 0.0.0-dev.gf7cb35b
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 +52 -61
- package/dist/index.mjs +191 -146
- package/dist/react/index.d.mts +59 -0
- package/dist/react/index.mjs +274 -0
- package/package.json +32 -11
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
-
|
|
1
|
+
import { ServerContext } from "@modelcontextprotocol/server";
|
|
4
2
|
//#region src/intent-middleware.d.ts
|
|
5
3
|
interface PromptData {
|
|
6
4
|
toolName: string;
|
|
@@ -8,34 +6,52 @@ interface PromptData {
|
|
|
8
6
|
}
|
|
9
7
|
interface IntentMiddlewareOptions {
|
|
10
8
|
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
|
-
*/
|
|
9
|
+
/** When provided, only these tool names have the `user_intent` field injected and their prompts captured; all other tools are left untouched. */
|
|
15
10
|
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
|
-
*/
|
|
11
|
+
/** 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
12
|
argumentNameOverride?: Record<string, string>;
|
|
23
13
|
}
|
|
24
|
-
/**
|
|
25
|
-
* Structurally compatible with `skybridge/server`'s `McpMiddlewareFn` so
|
|
26
|
-
* skybridge users can still pass the result into `server.mcpMiddleware(...)`.
|
|
27
|
-
*/
|
|
14
|
+
/** Structurally compatible with `skybridge/server`'s `McpMiddlewareFn` so skybridge users can still pass the result into `server.mcpMiddleware(...)`. */
|
|
28
15
|
type McpMiddlewareFn = (request: {
|
|
29
16
|
method: string;
|
|
30
17
|
params: Record<string, unknown>;
|
|
31
18
|
}, extra: unknown, next: () => Promise<unknown>) => Promise<unknown> | unknown;
|
|
32
|
-
/**
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
19
|
+
/** 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. */
|
|
20
|
+
export declare function intentMiddleware(options?: IntentMiddlewareOptions): McpMiddlewareFn;
|
|
21
|
+
//#endregion
|
|
22
|
+
//#region src/analytics-middleware.d.ts
|
|
23
|
+
interface CaptureOptions {
|
|
24
|
+
message?: string;
|
|
25
|
+
/** Duration of the operation the event describes, in milliseconds. */
|
|
26
|
+
duration?: number;
|
|
27
|
+
isError?: boolean;
|
|
28
|
+
error?: string;
|
|
29
|
+
/** Freeform event detail. Not indexed — filtering on a property key is a query-time scan. */
|
|
30
|
+
properties?: Record<string, unknown>;
|
|
31
|
+
}
|
|
32
|
+
interface Analytics {
|
|
33
|
+
/** Records a custom event on the current session's timeline, interleaved with tool calls. */
|
|
34
|
+
capture(name: string, options?: CaptureOptions): void;
|
|
35
|
+
/** 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. */
|
|
36
|
+
identify(traits: Record<string, string>): void;
|
|
37
|
+
}
|
|
38
|
+
interface AnalyticsExtra extends ServerContext {
|
|
39
|
+
analytics: Analytics;
|
|
40
|
+
}
|
|
41
|
+
interface AnalyticsEvent extends CaptureOptions {
|
|
42
|
+
name: string;
|
|
43
|
+
timestamp: number;
|
|
44
|
+
}
|
|
45
|
+
interface AnalyticsBatch {
|
|
46
|
+
events: AnalyticsEvent[];
|
|
47
|
+
traits?: Record<string, string>;
|
|
48
|
+
}
|
|
49
|
+
interface AnalyticsMiddlewareOptions {
|
|
50
|
+
/** Receives each request's analytics locally, whether or not the server is hosted by Alpic. */
|
|
51
|
+
handler?: (batch: AnalyticsBatch) => Promise<void> | void;
|
|
52
|
+
}
|
|
53
|
+
/** 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. */
|
|
54
|
+
export declare function analyticsMiddleware(options?: AnalyticsMiddlewareOptions): McpMiddlewareFn;
|
|
39
55
|
//#endregion
|
|
40
56
|
//#region src/feedback-middleware.d.ts
|
|
41
57
|
interface FeedbackData {
|
|
@@ -43,47 +59,22 @@ interface FeedbackData {
|
|
|
43
59
|
source: "model" | "user";
|
|
44
60
|
}
|
|
45
61
|
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
|
-
*/
|
|
62
|
+
/** Invoked with the user's feedback in addition to Alpic's dashboard delivery — the middleware still attaches the feedback to the response `_meta`. */
|
|
50
63
|
handler?: (feedback: FeedbackData) => Promise<void> | void;
|
|
51
64
|
}
|
|
52
|
-
/**
|
|
53
|
-
|
|
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;
|
|
65
|
+
/** 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`. */
|
|
66
|
+
export declare function feedbackMiddleware(options?: FeedbackMiddlewareOptions): McpMiddlewareFn;
|
|
60
67
|
//#endregion
|
|
61
68
|
//#region src/capture-feedback.d.ts
|
|
62
|
-
/**
|
|
63
|
-
|
|
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;
|
|
69
|
+
/** 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). */
|
|
70
|
+
export declare const captureFeedback: (server: object, options?: FeedbackMiddlewareOptions) => void;
|
|
74
71
|
//#endregion
|
|
75
72
|
//#region src/capture-intents.d.ts
|
|
76
|
-
/**
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
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;
|
|
73
|
+
/** 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). */
|
|
74
|
+
export declare const captureIntents: (server: object, options?: IntentMiddlewareOptions) => void;
|
|
75
|
+
//#endregion
|
|
76
|
+
//#region src/track.d.ts
|
|
77
|
+
/** 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. */
|
|
78
|
+
export declare const track: (server: object, options?: AnalyticsMiddlewareOptions) => void;
|
|
88
79
|
//#endregion
|
|
89
|
-
export {
|
|
80
|
+
export type { Analytics, AnalyticsBatch, AnalyticsEvent, AnalyticsExtra, AnalyticsMiddlewareOptions, CaptureOptions, FeedbackData, FeedbackMiddlewareOptions, IntentMiddlewareOptions, McpMiddlewareFn, PromptData };
|
package/dist/index.mjs
CHANGED
|
@@ -1,24 +1,114 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { isSpecType } from "@modelcontextprotocol/server";
|
|
2
|
+
//#region src/is-record.ts
|
|
3
|
+
function isRecord(value) {
|
|
4
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
5
|
+
}
|
|
6
|
+
//#endregion
|
|
7
|
+
//#region src/analytics-middleware.ts
|
|
8
|
+
const MAX_EVENTS_PER_REQUEST = 50;
|
|
9
|
+
function warnInDev(message) {
|
|
10
|
+
if (process.env.NODE_ENV !== "production") console.warn(`[insights] ${message}`);
|
|
11
|
+
}
|
|
12
|
+
function createAnalyticsBuffer() {
|
|
13
|
+
const events = [];
|
|
14
|
+
let traits;
|
|
15
|
+
let settled = false;
|
|
16
|
+
return {
|
|
17
|
+
analytics: {
|
|
18
|
+
capture(name, options) {
|
|
19
|
+
if (settled) {
|
|
20
|
+
warnInDev(`analytics.capture("${name}") was called after the request settled; the event was dropped. Capture events before the tool handler returns.`);
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
if (events.length >= MAX_EVENTS_PER_REQUEST) {
|
|
24
|
+
warnInDev(`analytics.capture("${name}") exceeded the ${MAX_EVENTS_PER_REQUEST} events per request limit; the event was dropped.`);
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
events.push({
|
|
28
|
+
...options,
|
|
29
|
+
name,
|
|
30
|
+
timestamp: Date.now()
|
|
31
|
+
});
|
|
32
|
+
},
|
|
33
|
+
identify(newTraits) {
|
|
34
|
+
if (settled) {
|
|
35
|
+
warnInDev("analytics.identify() was called after the request settled; the traits were dropped. Identify before the tool handler returns.");
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
traits = { ...newTraits };
|
|
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
|
+
/** 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. */
|
|
53
|
+
function analyticsMiddleware(options) {
|
|
54
|
+
return async (request, extra, next) => {
|
|
55
|
+
if (request.method !== "tools/call" || extra === null || typeof extra !== "object") return next();
|
|
56
|
+
const buffer = createAnalyticsBuffer();
|
|
57
|
+
extra.analytics = buffer.analytics;
|
|
58
|
+
let rawResult;
|
|
59
|
+
try {
|
|
60
|
+
rawResult = await next();
|
|
61
|
+
} finally {
|
|
62
|
+
buffer.settle();
|
|
63
|
+
}
|
|
64
|
+
if (buffer.events.length === 0 && buffer.traits === void 0) return rawResult;
|
|
65
|
+
const batch = {
|
|
66
|
+
events: [...buffer.events],
|
|
67
|
+
...buffer.traits === void 0 ? {} : { traits: { ...buffer.traits } }
|
|
68
|
+
};
|
|
69
|
+
if (options?.handler) try {
|
|
70
|
+
await options.handler(batch);
|
|
71
|
+
} catch (error) {
|
|
72
|
+
console.error("Error calling analytics handler", error);
|
|
73
|
+
}
|
|
74
|
+
const eventsMetaKey = process.env.ALPIC_EVENTS_META_KEY || void 0;
|
|
75
|
+
const identifyMetaKey = process.env.ALPIC_IDENTIFY_META_KEY || void 0;
|
|
76
|
+
if (eventsMetaKey === void 0 && identifyMetaKey === void 0) return rawResult;
|
|
77
|
+
if (!isSpecType.CallToolResult(rawResult)) return rawResult;
|
|
78
|
+
const meta = { ...isRecord(rawResult._meta) ? rawResult._meta : {} };
|
|
79
|
+
if (eventsMetaKey !== void 0 && buffer.events.length > 0) meta[eventsMetaKey] = buffer.events;
|
|
80
|
+
if (identifyMetaKey !== void 0 && buffer.traits !== void 0) meta[identifyMetaKey] = buffer.traits;
|
|
81
|
+
return {
|
|
82
|
+
...rawResult,
|
|
83
|
+
_meta: meta
|
|
84
|
+
};
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
//#endregion
|
|
2
88
|
//#region src/feedback-middleware.ts
|
|
3
89
|
const FEEDBACK_TOOL_NAME = "send_feedback";
|
|
4
90
|
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
91
|
const FEEDBACK_RESPONSE_TEXT = "Feedback received. Thanks!";
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
92
|
+
const FEEDBACK_OUTPUT_SCHEMA = {
|
|
93
|
+
type: "object",
|
|
94
|
+
properties: { status: {
|
|
95
|
+
type: "string",
|
|
96
|
+
enum: ["received"],
|
|
97
|
+
description: "Confirmation that the feedback was received by the server operators."
|
|
98
|
+
} },
|
|
99
|
+
required: ["status"],
|
|
100
|
+
additionalProperties: false
|
|
101
|
+
};
|
|
102
|
+
const FEEDBACK_STRUCTURED_CONTENT = { status: "received" };
|
|
103
|
+
/** 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`. */
|
|
13
104
|
function feedbackMiddleware(options) {
|
|
14
105
|
return async (request, _extra, next) => {
|
|
15
106
|
const metaKeyName = process.env.ALPIC_FEEDBACK_META_KEY;
|
|
16
107
|
if (request.method === "tools/list") {
|
|
17
108
|
const rawResult = await next();
|
|
18
|
-
|
|
19
|
-
if (
|
|
20
|
-
|
|
21
|
-
parsed.data.tools.push({
|
|
109
|
+
if (!isSpecType.ListToolsResult(rawResult)) return rawResult;
|
|
110
|
+
if (rawResult.tools.some((tool) => tool.name === "send_feedback")) return rawResult;
|
|
111
|
+
const feedbackTool = {
|
|
22
112
|
name: FEEDBACK_TOOL_NAME,
|
|
23
113
|
description: FEEDBACK_TOOL_DESCRIPTION,
|
|
24
114
|
inputSchema: {
|
|
@@ -36,19 +126,22 @@ function feedbackMiddleware(options) {
|
|
|
36
126
|
},
|
|
37
127
|
required: ["content", "source"]
|
|
38
128
|
},
|
|
129
|
+
outputSchema: FEEDBACK_OUTPUT_SCHEMA,
|
|
39
130
|
annotations: {
|
|
40
131
|
readOnlyHint: false,
|
|
41
132
|
destructiveHint: false,
|
|
42
|
-
openWorldHint:
|
|
133
|
+
openWorldHint: false,
|
|
43
134
|
idempotentHint: true
|
|
44
135
|
}
|
|
45
|
-
}
|
|
46
|
-
return
|
|
136
|
+
};
|
|
137
|
+
return {
|
|
138
|
+
...rawResult,
|
|
139
|
+
tools: [...rawResult.tools, feedbackTool]
|
|
140
|
+
};
|
|
47
141
|
}
|
|
48
142
|
if (request.method !== "tools/call") return next();
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
const args = parsedRequest.data.params.arguments ?? {};
|
|
143
|
+
if (request.params.name !== "send_feedback") return next();
|
|
144
|
+
const args = isRecord(request.params.arguments) ? request.params.arguments : {};
|
|
52
145
|
const content = typeof args.content === "string" ? args.content.trim() : void 0;
|
|
53
146
|
const source = args.source === "user" ? "user" : "model";
|
|
54
147
|
if (content === void 0 || content.length === 0) return {
|
|
@@ -73,39 +166,31 @@ function feedbackMiddleware(options) {
|
|
|
73
166
|
type: "text",
|
|
74
167
|
text: FEEDBACK_RESPONSE_TEXT
|
|
75
168
|
}],
|
|
169
|
+
structuredContent: FEEDBACK_STRUCTURED_CONTENT,
|
|
76
170
|
_meta: { [metaKeyName]: feedback }
|
|
77
171
|
};
|
|
78
|
-
return {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
172
|
+
return {
|
|
173
|
+
content: [{
|
|
174
|
+
type: "text",
|
|
175
|
+
text: FEEDBACK_RESPONSE_TEXT
|
|
176
|
+
}],
|
|
177
|
+
structuredContent: FEEDBACK_STRUCTURED_CONTENT
|
|
178
|
+
};
|
|
82
179
|
};
|
|
83
180
|
}
|
|
84
181
|
//#endregion
|
|
85
|
-
//#region src/capture-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
* Injects a `send_feedback` tool into a vanilla `@modelcontextprotocol/sdk`
|
|
89
|
-
* server and captures feedback submissions. Accepts the high-level `McpServer`
|
|
90
|
-
* or the low-level `Server` and patches the `tools/list` and `tools/call`
|
|
91
|
-
* request handlers to surface captured feedback via `options.handler` (or,
|
|
92
|
-
* when `ALPIC_FEEDBACK_META_KEY` is set, via the response `_meta`).
|
|
93
|
-
*
|
|
94
|
-
* Already-registered handlers are wrapped immediately; future registrations
|
|
95
|
-
* are wrapped via a `Map.set` proxy so order of calls relative to
|
|
96
|
-
* `registerTool` does not matter.
|
|
97
|
-
*/
|
|
98
|
-
const captureFeedback = (server, options) => {
|
|
182
|
+
//#region src/install-capture-middleware.ts
|
|
183
|
+
/** 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. */
|
|
184
|
+
const installCaptureMiddleware = (server, { middleware, installedMarker, disabledWarning }) => {
|
|
99
185
|
const handlers = ("server" in server ? server.server : server)?._requestHandlers;
|
|
100
186
|
if (!(handlers instanceof Map)) {
|
|
101
|
-
console.warn(
|
|
187
|
+
console.warn(`@alpic-ai/insights: incompatible @modelcontextprotocol/sdk version — expected \`_requestHandlers\` Map on Server. ${disabledWarning}`);
|
|
102
188
|
return;
|
|
103
189
|
}
|
|
104
190
|
const marked = handlers;
|
|
105
|
-
if (marked[
|
|
106
|
-
marked[
|
|
107
|
-
const
|
|
108
|
-
const targets = new Set(["tools/list", "tools/call"]);
|
|
191
|
+
if (marked[installedMarker]) return;
|
|
192
|
+
marked[installedMarker] = true;
|
|
193
|
+
const targets = /* @__PURE__ */ new Set(["tools/list", "tools/call"]);
|
|
109
194
|
const wrap = (method, handler) => {
|
|
110
195
|
if (!targets.has(method)) return handler;
|
|
111
196
|
return async (...args) => {
|
|
@@ -121,14 +206,19 @@ const captureFeedback = (server, options) => {
|
|
|
121
206
|
handlers.set = (method, handler) => originalSet(method, wrap(method, handler));
|
|
122
207
|
};
|
|
123
208
|
//#endregion
|
|
209
|
+
//#region src/capture-feedback.ts
|
|
210
|
+
/** 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). */
|
|
211
|
+
const captureFeedback = (server, options) => {
|
|
212
|
+
installCaptureMiddleware(server, {
|
|
213
|
+
middleware: feedbackMiddleware(options),
|
|
214
|
+
installedMarker: "__alpicCaptureFeedbackInstalled",
|
|
215
|
+
disabledWarning: "Feedback capture disabled."
|
|
216
|
+
});
|
|
217
|
+
};
|
|
218
|
+
//#endregion
|
|
124
219
|
//#region src/intent-middleware.ts
|
|
125
220
|
const USER_INTENT_FIELD = "user_intent";
|
|
126
|
-
/**
|
|
127
|
-
* Captures the user's natural-language intent behind each tool call so MCP
|
|
128
|
-
* server builders can see *why* their tools are being invoked, not just that
|
|
129
|
-
* they were. The LLM fills in `user_intent` from the original user message
|
|
130
|
-
* (the server has no other way to access it).
|
|
131
|
-
*/
|
|
221
|
+
/** 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. */
|
|
132
222
|
function intentMiddleware(options) {
|
|
133
223
|
const argumentNameOverride = options?.argumentNameOverride ?? {};
|
|
134
224
|
const toolsFilter = options?.tools ? new Set(options.tools) : null;
|
|
@@ -136,134 +226,89 @@ function intentMiddleware(options) {
|
|
|
136
226
|
const metaKeyName = process.env.ALPIC_INTENT_META_KEY;
|
|
137
227
|
if (request.method === "tools/list") {
|
|
138
228
|
const rawResult = await next();
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
- For short, self-contained prompts (e.g. "I want new shoes"), copy the user message as-is.
|
|
154
|
-
- For longer conversations or detailed requests, summarize the core goal and any relevant
|
|
155
|
-
context in 1-2 sentences. Focus on intent, constraints, and preferences - not the full
|
|
156
|
-
dialogue.
|
|
157
|
-
|
|
158
|
-
Before sending, strip all personally identifiable information (PII), including but not
|
|
159
|
-
limited to:
|
|
160
|
-
- Names (first, last, usernames, handles)
|
|
161
|
-
- Email addresses
|
|
162
|
-
- Phone numbers
|
|
163
|
-
- Physical addresses (street, city, zip/postal code, country when tied to an individual)
|
|
164
|
-
- Dates of birth or exact ages
|
|
165
|
-
- Government-issued ID numbers (SSN, passport, driver's license, etc.)
|
|
166
|
-
- Payment or financial information (card numbers, bank accounts, etc.)
|
|
167
|
-
- IP addresses or device identifiers
|
|
168
|
-
- Account credentials (passwords, tokens, API keys)
|
|
169
|
-
- Health or biometric data
|
|
170
|
-
- Any other information that could identify a specific individual
|
|
171
|
-
|
|
172
|
-
Replace stripped values with a generic placeholder (e.g. "[name]", "[email]", "[address]").
|
|
173
|
-
|
|
174
|
-
Examples:
|
|
175
|
-
User: "I want red running shoes under $100"
|
|
176
|
-
-> "I want red running shoes under $100"
|
|
177
|
-
|
|
178
|
-
User: "Hi, I'm John Smith, john@example.com, and I'm looking for flights from Paris to
|
|
179
|
-
Tokyo for 2 adults departing around mid-June, budget around EUR2000 total"
|
|
180
|
-
-> "Looking for flights from Paris to Tokyo for 2 adults, mid-June, budget ~EUR2000"
|
|
181
|
-
|
|
182
|
-
User: "I need help resetting my password for account ID acct_12345"
|
|
183
|
-
-> "I need help resetting my password for account ID [account_id]"`
|
|
229
|
+
if (!isSpecType.ListToolsResult(rawResult)) return rawResult;
|
|
230
|
+
const tools = rawResult.tools.map((tool) => {
|
|
231
|
+
if (toolsFilter && !toolsFilter.has(tool.name) || tool.name === "send_feedback" || argumentNameOverride[tool.name] != null) return tool;
|
|
232
|
+
return {
|
|
233
|
+
...tool,
|
|
234
|
+
inputSchema: {
|
|
235
|
+
...tool.inputSchema,
|
|
236
|
+
properties: {
|
|
237
|
+
...tool.inputSchema.properties,
|
|
238
|
+
[USER_INTENT_FIELD]: {
|
|
239
|
+
type: "string",
|
|
240
|
+
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."
|
|
241
|
+
}
|
|
242
|
+
}
|
|
184
243
|
}
|
|
185
244
|
};
|
|
186
|
-
}
|
|
187
|
-
return
|
|
245
|
+
});
|
|
246
|
+
return {
|
|
247
|
+
...rawResult,
|
|
248
|
+
tools
|
|
249
|
+
};
|
|
188
250
|
}
|
|
189
251
|
if (request.method === "tools/call") {
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
const
|
|
252
|
+
if (typeof request.params.name !== "string") return next();
|
|
253
|
+
const toolName = request.params.name;
|
|
254
|
+
const args = isRecord(request.params.arguments) ? request.params.arguments : {};
|
|
193
255
|
if (toolsFilter && !toolsFilter.has(toolName) || toolName === "send_feedback") {
|
|
194
|
-
const args = parsedRequest.data.params.arguments ?? {};
|
|
195
256
|
if (USER_INTENT_FIELD in args) {
|
|
196
|
-
|
|
197
|
-
|
|
257
|
+
const toolArgs = { ...args };
|
|
258
|
+
delete toolArgs[USER_INTENT_FIELD];
|
|
259
|
+
request.params.arguments = toolArgs;
|
|
198
260
|
}
|
|
199
261
|
return next();
|
|
200
262
|
}
|
|
201
263
|
const promptField = argumentNameOverride[toolName] ?? USER_INTENT_FIELD;
|
|
202
|
-
const args = parsedRequest.data.params.arguments ?? {};
|
|
203
264
|
const userPrompt = typeof args[promptField] === "string" ? args[promptField] : void 0;
|
|
204
265
|
const hasUserPrompt = userPrompt != null && userPrompt.length > 0;
|
|
205
266
|
if (USER_INTENT_FIELD in args) {
|
|
206
|
-
|
|
207
|
-
|
|
267
|
+
const toolArgs = { ...args };
|
|
268
|
+
delete toolArgs[USER_INTENT_FIELD];
|
|
269
|
+
request.params.arguments = toolArgs;
|
|
208
270
|
}
|
|
209
271
|
if (hasUserPrompt && options?.handler) try {
|
|
210
272
|
await options.handler({
|
|
211
|
-
toolName
|
|
273
|
+
toolName,
|
|
212
274
|
userPrompt
|
|
213
275
|
});
|
|
214
276
|
} catch (error) {
|
|
215
277
|
console.error("Error calling user prompt handler", error);
|
|
216
278
|
}
|
|
217
279
|
const rawResult = await next();
|
|
218
|
-
|
|
219
|
-
if (
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
280
|
+
if (!isSpecType.CallToolResult(rawResult)) return rawResult;
|
|
281
|
+
if (metaKeyName && hasUserPrompt) return {
|
|
282
|
+
...rawResult,
|
|
283
|
+
_meta: {
|
|
284
|
+
...isRecord(rawResult._meta) ? rawResult._meta : {},
|
|
285
|
+
[metaKeyName]: userPrompt
|
|
286
|
+
}
|
|
223
287
|
};
|
|
224
|
-
return
|
|
288
|
+
return rawResult;
|
|
225
289
|
}
|
|
226
290
|
return next();
|
|
227
291
|
};
|
|
228
292
|
}
|
|
229
293
|
//#endregion
|
|
230
294
|
//#region src/capture-intents.ts
|
|
231
|
-
|
|
232
|
-
/**
|
|
233
|
-
* Captures the user's natural-language intent behind each tool call on a vanilla
|
|
234
|
-
* `@modelcontextprotocol/sdk` server. Accepts the high-level `McpServer` or the
|
|
235
|
-
* low-level `Server` and patches the `tools/list` and `tools/call` request
|
|
236
|
-
* handlers to surface the captured intent via `options.handler` (or, when
|
|
237
|
-
* `ALPIC_INTENT_META_KEY` is set, via the response `_meta`).
|
|
238
|
-
*
|
|
239
|
-
* Already-registered handlers are wrapped immediately; future registrations
|
|
240
|
-
* (e.g. tools added after this call) are wrapped via a `Map.set` proxy so order
|
|
241
|
-
* of calls relative to `registerTool` does not matter.
|
|
242
|
-
*/
|
|
295
|
+
/** 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). */
|
|
243
296
|
const captureIntents = (server, options) => {
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
method,
|
|
260
|
-
params: request.params ?? {}
|
|
261
|
-
}, extra, () => handler(...args));
|
|
262
|
-
};
|
|
263
|
-
};
|
|
264
|
-
for (const [method, handler] of [...handlers]) handlers.set(method, wrap(method, handler));
|
|
265
|
-
const originalSet = handlers.set.bind(handlers);
|
|
266
|
-
handlers.set = (method, handler) => originalSet(method, wrap(method, handler));
|
|
297
|
+
installCaptureMiddleware(server, {
|
|
298
|
+
middleware: intentMiddleware(options),
|
|
299
|
+
installedMarker: "__alpicCaptureIntentsInstalled",
|
|
300
|
+
disabledWarning: "Prompt capture disabled."
|
|
301
|
+
});
|
|
302
|
+
};
|
|
303
|
+
//#endregion
|
|
304
|
+
//#region src/track.ts
|
|
305
|
+
/** 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. */
|
|
306
|
+
const track = (server, options) => {
|
|
307
|
+
installCaptureMiddleware(server, {
|
|
308
|
+
middleware: analyticsMiddleware(options),
|
|
309
|
+
installedMarker: "__alpicTrackInstalled",
|
|
310
|
+
disabledWarning: "Analytics capture disabled."
|
|
311
|
+
});
|
|
267
312
|
};
|
|
268
313
|
//#endregion
|
|
269
|
-
export { captureFeedback, captureIntents, feedbackMiddleware, intentMiddleware };
|
|
314
|
+
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
|
+
export declare function AlpicAnalytics({ children, beforeSend, autoCapture }: AlpicAnalyticsProps): import("react").JSX.Element;
|
|
44
|
+
/** Returns the analytics client from the nearest `AlpicAnalytics` provider. */
|
|
45
|
+
export 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
|
+
export 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
|
+
export declare const INTERACTION_ATTRIBUTE = "data-alpic-event";
|
|
58
|
+
//#endregion
|
|
59
|
+
export type { AlpicAnalyticsProps, Analytics, AutoCaptureOptions, BeforeSend, CaptureOptions };
|
|
@@ -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.
|
|
3
|
+
"version": "0.0.0-dev.gf7cb35b",
|
|
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
|
-
"
|
|
21
|
-
"skybridge": "
|
|
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.3.1"
|
|
37
|
+
},
|
|
28
38
|
"devDependencies": {
|
|
29
|
-
"@modelcontextprotocol/
|
|
39
|
+
"@modelcontextprotocol/client": "^2.3.1",
|
|
40
|
+
"@modelcontextprotocol/sdk": "^1.32.1",
|
|
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.
|
|
44
|
+
"@types/node": "^25.9.9",
|
|
45
|
+
"@types/react": "19.3.0",
|
|
46
|
+
"jsdom": "^30.1.3",
|
|
47
|
+
"react": "^19.3.1",
|
|
48
|
+
"react-dom": "^19.3.1",
|
|
32
49
|
"shx": "^0.4.0",
|
|
33
|
-
"skybridge": "^0.
|
|
34
|
-
"tsdown": "^0.
|
|
50
|
+
"skybridge": "^2.0.4",
|
|
51
|
+
"tsdown": "^0.23.1",
|
|
35
52
|
"typescript": "^6.0.3",
|
|
36
|
-
"vitest": "^
|
|
37
|
-
"zod": "^4.
|
|
53
|
+
"vitest": "^5.0.5",
|
|
54
|
+
"zod": "^4.6.6"
|
|
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": "
|
|
46
|
-
"publish:npm": "
|
|
66
|
+
"test:type": "tsgo --noEmit",
|
|
67
|
+
"publish:npm": "../../scripts/publish-if-new.sh"
|
|
47
68
|
}
|
|
48
69
|
}
|