@alpic-ai/insights 0.0.0-dev.g2a45f1b → 0.0.0-dev.g2a6be45

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
@@ -36,6 +36,40 @@ type McpMiddlewareFn = (request: {
36
36
  */
37
37
  declare function intentMiddleware(options?: IntentMiddlewareOptions): McpMiddlewareFn;
38
38
  //#endregion
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
+ }
58
+ /**
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.
61
+ */
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;
72
+ //#endregion
39
73
  //#region src/feedback-middleware.d.ts
40
74
  interface FeedbackData {
41
75
  content: string;
@@ -77,4 +111,12 @@ declare const captureFeedback: (server: McpServer | Server, options?: FeedbackMi
77
111
  */
78
112
  declare const captureIntents: (server: McpServer | Server, options?: IntentMiddlewareOptions) => void;
79
113
  //#endregion
80
- export { type FeedbackData, type FeedbackMiddlewareOptions, type IntentMiddlewareOptions, type McpMiddlewareFn, type PromptData, captureFeedback, captureIntents, feedbackMiddleware, intentMiddleware };
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,4 +1,84 @@
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]\").";
@@ -271,4 +351,18 @@ const captureIntents = (server, options) => {
271
351
  });
272
352
  };
273
353
  //#endregion
274
- export { captureFeedback, captureIntents, feedbackMiddleware, intentMiddleware };
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
+ });
366
+ };
367
+ //#endregion
368
+ export { analyticsMiddleware, captureFeedback, captureIntents, feedbackMiddleware, intentMiddleware, track };
@@ -0,0 +1,24 @@
1
+ import { ReactNode } from "react";
2
+ //#region src/react/analytics-client.d.ts
3
+ interface CaptureOptions {
4
+ message?: string;
5
+ properties?: Record<string, unknown>;
6
+ }
7
+ //#endregion
8
+ //#region src/react/alpic-analytics.d.ts
9
+ interface Analytics {
10
+ /** Queue a custom widget event for delivery to Alpic Analytics. */
11
+ capture: (name: string, options?: CaptureOptions) => void;
12
+ }
13
+ /**
14
+ * Provides Alpic Analytics to descendant components and configures itself from the widget host.
15
+ * Wrap the widget once, then call `useAnalytics()` from components that capture events.
16
+ * Events captured before configuration is available are buffered automatically.
17
+ */
18
+ declare function AlpicAnalytics({ children }: {
19
+ children?: ReactNode;
20
+ }): import("react").JSX.Element;
21
+ /** Returns the analytics client from the nearest `AlpicAnalytics` provider. */
22
+ declare function useAnalytics(): Analytics;
23
+ //#endregion
24
+ export { AlpicAnalytics, type Analytics, type CaptureOptions, useAnalytics };
@@ -0,0 +1,164 @@
1
+ import { createContext, useContext, useEffect, 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
+ stamp = null;
16
+ flushTimer = null;
17
+ warnedBufferFull = false;
18
+ configure(stamp) {
19
+ if (this.stamp !== null && !isSameStamp(this.stamp, stamp)) this.flush();
20
+ this.stamp = stamp;
21
+ if (this.events.length > 0) this.scheduleFlush();
22
+ }
23
+ capture = (name, options) => {
24
+ if (this.events.length >= 100) {
25
+ if (!this.warnedBufferFull) {
26
+ console.warn("[@alpic-ai/insights] analytics buffer is full, dropping events");
27
+ this.warnedBufferFull = true;
28
+ }
29
+ return;
30
+ }
31
+ const event = {
32
+ name,
33
+ timestamp: Date.now()
34
+ };
35
+ if (options?.message !== void 0) event.message = options.message;
36
+ if (options?.properties !== void 0) event.properties = options.properties;
37
+ this.events.push(event);
38
+ if (this.events.length >= 50) {
39
+ this.flush();
40
+ return;
41
+ }
42
+ this.scheduleFlush();
43
+ };
44
+ flush = () => {
45
+ if (this.flushTimer !== null) {
46
+ clearTimeout(this.flushTimer);
47
+ this.flushTimer = null;
48
+ }
49
+ if (this.stamp === null) return;
50
+ while (this.events.length > 0) {
51
+ const batch = this.events.splice(0, 50);
52
+ postAnalyticsBatch(this.stamp.ingestUrl, batch);
53
+ }
54
+ this.warnedBufferFull = false;
55
+ };
56
+ scheduleFlush() {
57
+ if (this.stamp === null || this.flushTimer !== null) return;
58
+ this.flushTimer = setTimeout(this.flush, FLUSH_DELAY_MS);
59
+ }
60
+ };
61
+ function isSameStamp(left, right) {
62
+ return left.distinctId === right.distinctId && left.sessionId === right.sessionId && left.ingestUrl === right.ingestUrl;
63
+ }
64
+ //#endregion
65
+ //#region src/react/stamp.ts
66
+ const ANALYTICS_META_KEY = "alpic/analytics";
67
+ function parseAnalyticsStamp(metadata) {
68
+ if (metadata === null || typeof metadata !== "object") return null;
69
+ const candidate = metadata[ANALYTICS_META_KEY];
70
+ if (candidate === null || candidate === void 0 || typeof candidate !== "object") return null;
71
+ const { distinctId, sessionId, ingestUrl } = candidate;
72
+ if (typeof distinctId !== "string" || typeof sessionId !== "string" || typeof ingestUrl !== "string") return null;
73
+ return {
74
+ distinctId,
75
+ sessionId,
76
+ ingestUrl
77
+ };
78
+ }
79
+ //#endregion
80
+ //#region src/react/stamp-source.ts
81
+ const TOOL_RESULT_METHOD = "ui/notifications/tool-result";
82
+ const SET_GLOBALS_EVENT_TYPE = "openai:set_globals";
83
+ const subscribers = /* @__PURE__ */ new Set();
84
+ let latestProtocolStamp = null;
85
+ let isObservingRuntime = false;
86
+ function subscribeToAnalyticsStamp(onStamp) {
87
+ observeRuntime();
88
+ subscribers.add(onStamp);
89
+ if (latestProtocolStamp !== null) onStamp(latestProtocolStamp);
90
+ else emitOpenAiStamp(onStamp);
91
+ return () => {
92
+ subscribers.delete(onStamp);
93
+ };
94
+ }
95
+ function observeRuntime() {
96
+ if (isObservingRuntime || typeof window === "undefined") return;
97
+ window.addEventListener("message", handleToolResultMessage);
98
+ window.addEventListener(SET_GLOBALS_EVENT_TYPE, handleOpenAiGlobals, { passive: true });
99
+ isObservingRuntime = true;
100
+ }
101
+ function handleToolResultMessage(event) {
102
+ if (event.source !== window.parent || event.data === null || typeof event.data !== "object") return;
103
+ const message = event.data;
104
+ if (message.jsonrpc !== "2.0" || message.method !== TOOL_RESULT_METHOD) return;
105
+ const params = message.params;
106
+ if (params === null || typeof params !== "object") return;
107
+ const stamp = parseAnalyticsStamp(params._meta);
108
+ if (stamp === null) return;
109
+ latestProtocolStamp = stamp;
110
+ for (const subscriber of subscribers) subscriber(stamp);
111
+ }
112
+ function handleOpenAiGlobals() {
113
+ if (latestProtocolStamp !== null) return;
114
+ const globals = window;
115
+ if (globals.openai === void 0) return;
116
+ const stamp = parseAnalyticsStamp(globals.openai.toolResponseMetadata);
117
+ if (stamp === null) return;
118
+ for (const subscriber of subscribers) subscriber(stamp);
119
+ }
120
+ function emitOpenAiStamp(onStamp) {
121
+ if (typeof window === "undefined") return;
122
+ const stamp = parseAnalyticsStamp(window.openai?.toolResponseMetadata);
123
+ if (stamp !== null) onStamp(stamp);
124
+ }
125
+ observeRuntime();
126
+ //#endregion
127
+ //#region src/react/alpic-analytics.tsx
128
+ const AnalyticsContext = createContext(null);
129
+ /**
130
+ * Provides Alpic Analytics to descendant components and configures itself from the widget host.
131
+ * Wrap the widget once, then call `useAnalytics()` from components that capture events.
132
+ * Events captured before configuration is available are buffered automatically.
133
+ */
134
+ function AlpicAnalytics({ children }) {
135
+ const [client] = useState(() => new AnalyticsClient());
136
+ useEffect(() => {
137
+ const unsubscribe = subscribeToAnalyticsStamp((stamp) => {
138
+ client.configure(stamp);
139
+ });
140
+ const flushWhenHidden = () => {
141
+ if (document.visibilityState === "hidden") client.flush();
142
+ };
143
+ document.addEventListener("visibilitychange", flushWhenHidden);
144
+ window.addEventListener("pagehide", client.flush);
145
+ return () => {
146
+ unsubscribe();
147
+ document.removeEventListener("visibilitychange", flushWhenHidden);
148
+ window.removeEventListener("pagehide", client.flush);
149
+ client.flush();
150
+ };
151
+ }, [client]);
152
+ return /* @__PURE__ */ jsx(AnalyticsContext.Provider, {
153
+ value: client,
154
+ children
155
+ });
156
+ }
157
+ /** Returns the analytics client from the nearest `AlpicAnalytics` provider. */
158
+ function useAnalytics() {
159
+ const analytics = useContext(AnalyticsContext);
160
+ if (analytics === null) throw new Error("useAnalytics must be used within an <AlpicAnalytics> provider");
161
+ return analytics;
162
+ }
163
+ //#endregion
164
+ export { AlpicAnalytics, useAnalytics };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alpic-ai/insights",
3
- "version": "0.0.0-dev.g2a45f1b",
3
+ "version": "0.0.0-dev.g2a6be45",
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,17 +22,27 @@
18
22
  "license": "ISC",
19
23
  "peerDependencies": {
20
24
  "@modelcontextprotocol/sdk": ">=1.29.0 <2",
25
+ "react": ">=18.0.0",
21
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
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
47
  "skybridge": "^1.2.7",
34
48
  "tsdown": "^0.22.9",