@alpic-ai/insights 0.0.0-dev.gb23efa8 → 0.0.0-dev.gb2a9d61

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
@@ -64,6 +64,10 @@ declare function feedbackMiddleware(options?: FeedbackMiddlewareOptions): McpMid
64
64
  * or the low-level `Server` and patches the `tools/list` and `tools/call`
65
65
  * request handlers to surface captured feedback via `options.handler` (or,
66
66
  * when `ALPIC_FEEDBACK_META_KEY` is set, via the response `_meta`).
67
+ *
68
+ * Already-registered handlers are wrapped immediately; future registrations
69
+ * are wrapped via a `Map.set` proxy so order of calls relative to
70
+ * `registerTool` does not matter.
67
71
  */
68
72
  declare const captureFeedback: (server: McpServer | Server, options?: FeedbackMiddlewareOptions) => void;
69
73
  //#endregion
@@ -74,6 +78,10 @@ declare const captureFeedback: (server: McpServer | Server, options?: FeedbackMi
74
78
  * low-level `Server` and patches the `tools/list` and `tools/call` request
75
79
  * handlers to surface the captured intent via `options.handler` (or, when
76
80
  * `ALPIC_INTENT_META_KEY` is set, via the response `_meta`).
81
+ *
82
+ * Already-registered handlers are wrapped immediately; future registrations
83
+ * (e.g. tools added after this call) are wrapped via a `Map.set` proxy so order
84
+ * of calls relative to `registerTool` does not matter.
77
85
  */
78
86
  declare const captureIntents: (server: McpServer | Server, options?: IntentMiddlewareOptions) => void;
79
87
  //#endregion
package/dist/index.mjs CHANGED
@@ -49,7 +49,7 @@ function feedbackMiddleware(options) {
49
49
  },
50
50
  outputSchema: FEEDBACK_OUTPUT_SCHEMA,
51
51
  annotations: {
52
- readOnlyHint: true,
52
+ readOnlyHint: false,
53
53
  destructiveHint: false,
54
54
  openWorldHint: false,
55
55
  idempotentHint: true
@@ -98,25 +98,29 @@ function feedbackMiddleware(options) {
98
98
  };
99
99
  }
100
100
  //#endregion
101
- //#region src/install-capture-middleware.ts
101
+ //#region src/capture-feedback.ts
102
+ const INSTALLED_MARKER$1 = "__alpicCaptureFeedbackInstalled";
102
103
  /**
103
- * Patches the `tools/list` and `tools/call` request handlers of a vanilla
104
- * `@modelcontextprotocol/sdk` server (high-level `McpServer` or low-level
105
- * `Server`) to run the given middleware.
104
+ * Injects a `send_feedback` tool into a vanilla `@modelcontextprotocol/sdk`
105
+ * server and captures feedback submissions. Accepts the high-level `McpServer`
106
+ * or the low-level `Server` and patches the `tools/list` and `tools/call`
107
+ * request handlers to surface captured feedback via `options.handler` (or,
108
+ * when `ALPIC_FEEDBACK_META_KEY` is set, via the response `_meta`).
106
109
  *
107
110
  * Already-registered handlers are wrapped immediately; future registrations
108
- * (e.g. tools added after this call) are wrapped via a `Map.set` proxy so order
109
- * of calls relative to `registerTool` does not matter.
111
+ * are wrapped via a `Map.set` proxy so order of calls relative to
112
+ * `registerTool` does not matter.
110
113
  */
111
- const installCaptureMiddleware = (server, { middleware, installedMarker, disabledWarning }) => {
114
+ const captureFeedback = (server, options) => {
112
115
  const handlers = ("server" in server ? server.server : server)?._requestHandlers;
113
116
  if (!(handlers instanceof Map)) {
114
- console.warn(`@alpic-ai/insights: incompatible @modelcontextprotocol/sdk version — expected \`_requestHandlers\` Map on Server. ${disabledWarning}`);
117
+ console.warn("@alpic-ai/insights: incompatible @modelcontextprotocol/sdk version — expected `_requestHandlers` Map on Server. Feedback capture disabled.");
115
118
  return;
116
119
  }
117
120
  const marked = handlers;
118
- if (marked[installedMarker]) return;
119
- marked[installedMarker] = true;
121
+ if (marked[INSTALLED_MARKER$1]) return;
122
+ marked[INSTALLED_MARKER$1] = true;
123
+ const middleware = feedbackMiddleware(options);
120
124
  const targets = /* @__PURE__ */ new Set(["tools/list", "tools/call"]);
121
125
  const wrap = (method, handler) => {
122
126
  if (!targets.has(method)) return handler;
@@ -133,22 +137,6 @@ const installCaptureMiddleware = (server, { middleware, installedMarker, disable
133
137
  handlers.set = (method, handler) => originalSet(method, wrap(method, handler));
134
138
  };
135
139
  //#endregion
136
- //#region src/capture-feedback.ts
137
- /**
138
- * Injects a `send_feedback` tool into a vanilla `@modelcontextprotocol/sdk`
139
- * server and captures feedback submissions. Accepts the high-level `McpServer`
140
- * or the low-level `Server` and patches the `tools/list` and `tools/call`
141
- * request handlers to surface captured feedback via `options.handler` (or,
142
- * when `ALPIC_FEEDBACK_META_KEY` is set, via the response `_meta`).
143
- */
144
- const captureFeedback = (server, options) => {
145
- installCaptureMiddleware(server, {
146
- middleware: feedbackMiddleware(options),
147
- installedMarker: "__alpicCaptureFeedbackInstalled",
148
- disabledWarning: "Feedback capture disabled."
149
- });
150
- };
151
- //#endregion
152
140
  //#region src/intent-middleware.ts
153
141
  const USER_INTENT_FIELD = "user_intent";
154
142
  /**
@@ -256,19 +244,42 @@ Examples:
256
244
  }
257
245
  //#endregion
258
246
  //#region src/capture-intents.ts
247
+ const INSTALLED_MARKER = "__alpicCaptureIntentsInstalled";
259
248
  /**
260
249
  * Captures the user's natural-language intent behind each tool call on a vanilla
261
250
  * `@modelcontextprotocol/sdk` server. Accepts the high-level `McpServer` or the
262
251
  * low-level `Server` and patches the `tools/list` and `tools/call` request
263
252
  * handlers to surface the captured intent via `options.handler` (or, when
264
253
  * `ALPIC_INTENT_META_KEY` is set, via the response `_meta`).
254
+ *
255
+ * Already-registered handlers are wrapped immediately; future registrations
256
+ * (e.g. tools added after this call) are wrapped via a `Map.set` proxy so order
257
+ * of calls relative to `registerTool` does not matter.
265
258
  */
266
259
  const captureIntents = (server, options) => {
267
- installCaptureMiddleware(server, {
268
- middleware: intentMiddleware(options),
269
- installedMarker: "__alpicCaptureIntentsInstalled",
270
- disabledWarning: "Prompt capture disabled."
271
- });
260
+ const handlers = ("server" in server ? server.server : server)?._requestHandlers;
261
+ if (!(handlers instanceof Map)) {
262
+ console.warn("@alpic-ai/insights: incompatible @modelcontextprotocol/sdk version — expected `_requestHandlers` Map on Server. Prompt capture disabled.");
263
+ return;
264
+ }
265
+ const marked = handlers;
266
+ if (marked[INSTALLED_MARKER]) return;
267
+ marked[INSTALLED_MARKER] = true;
268
+ const middleware = intentMiddleware(options);
269
+ const targets = /* @__PURE__ */ new Set(["tools/list", "tools/call"]);
270
+ const wrap = (method, handler) => {
271
+ if (!targets.has(method)) return handler;
272
+ return async (...args) => {
273
+ const [request, extra] = args;
274
+ return middleware({
275
+ method,
276
+ params: request.params ?? {}
277
+ }, extra, () => handler(...args));
278
+ };
279
+ };
280
+ for (const [method, handler] of [...handlers]) handlers.set(method, wrap(method, handler));
281
+ const originalSet = handlers.set.bind(handlers);
282
+ handlers.set = (method, handler) => originalSet(method, wrap(method, handler));
272
283
  };
273
284
  //#endregion
274
285
  export { captureFeedback, captureIntents, feedbackMiddleware, intentMiddleware };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alpic-ai/insights",
3
- "version": "0.0.0-dev.gb23efa8",
3
+ "version": "0.0.0-dev.gb2a9d61",
4
4
  "description": "User insights middlewares for Alpic-hosted MCP servers",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -9,10 +9,6 @@
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"
16
12
  }
17
13
  },
18
14
  "files": [
@@ -22,27 +18,17 @@
22
18
  "license": "ISC",
23
19
  "peerDependencies": {
24
20
  "@modelcontextprotocol/sdk": ">=1.29.0 <2",
25
- "react": ">=18.0.0",
26
21
  "skybridge": "^0.36.3 || ^1.0.0"
27
22
  },
28
23
  "peerDependenciesMeta": {
29
- "react": {
30
- "optional": true
31
- },
32
24
  "skybridge": {
33
25
  "optional": true
34
26
  }
35
27
  },
36
28
  "devDependencies": {
37
29
  "@modelcontextprotocol/sdk": "^1.29.0",
38
- "@testing-library/dom": "^10.4.1",
39
- "@testing-library/react": "^16.3.2",
40
30
  "@total-typescript/tsconfig": "^1.0.4",
41
31
  "@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",
46
32
  "shx": "^0.4.0",
47
33
  "skybridge": "^1.2.7",
48
34
  "tsdown": "^0.22.5",
@@ -1,24 +0,0 @@
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 };
@@ -1,183 +0,0 @@
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
- //#endregion
13
- //#region src/react/event-queue.ts
14
- var EventQueue = class {
15
- maxSize;
16
- items = [];
17
- constructor(maxSize) {
18
- this.maxSize = maxSize;
19
- }
20
- get length() {
21
- return this.items.length;
22
- }
23
- get isFull() {
24
- return this.items.length >= this.maxSize;
25
- }
26
- push(item) {
27
- if (this.items.length >= this.maxSize) return false;
28
- this.items.push(item);
29
- return true;
30
- }
31
- drain(maxItems) {
32
- return this.items.splice(0, maxItems);
33
- }
34
- };
35
- const FLUSH_DELAY_MS = 2e3;
36
- var AnalyticsClient = class {
37
- queue = new EventQueue(100);
38
- ingestUrl = null;
39
- flushTimer = null;
40
- warnedBufferFull = false;
41
- configure(ingestUrl) {
42
- this.ingestUrl = ingestUrl;
43
- if (this.queue.length > 0) this.scheduleFlush();
44
- }
45
- capture = (name, options) => {
46
- if (this.queue.isFull) {
47
- if (!this.warnedBufferFull) {
48
- console.warn("[@alpic-ai/insights] analytics buffer is full, dropping events");
49
- this.warnedBufferFull = true;
50
- }
51
- return;
52
- }
53
- const event = {
54
- name,
55
- timestamp: Date.now()
56
- };
57
- if (options?.message !== void 0) event.message = options.message;
58
- if (options?.properties !== void 0) event.properties = options.properties;
59
- this.queue.push(event);
60
- if (this.queue.length >= 50) {
61
- this.flush();
62
- return;
63
- }
64
- this.scheduleFlush();
65
- };
66
- flush = () => {
67
- if (this.flushTimer !== null) {
68
- clearTimeout(this.flushTimer);
69
- this.flushTimer = null;
70
- }
71
- if (this.ingestUrl === null) return;
72
- while (this.queue.length > 0) {
73
- const events = this.queue.drain(50);
74
- postAnalyticsBatch(this.ingestUrl, events);
75
- }
76
- this.warnedBufferFull = false;
77
- };
78
- scheduleFlush() {
79
- if (this.ingestUrl === null || this.flushTimer !== null) return;
80
- this.flushTimer = setTimeout(this.flush, FLUSH_DELAY_MS);
81
- }
82
- };
83
- //#endregion
84
- //#region src/react/stamp.ts
85
- const ANALYTICS_META_KEY = "alpic/analytics";
86
- function parseAnalyticsStamp(metadata) {
87
- if (metadata === null || typeof metadata !== "object") return null;
88
- const candidate = metadata[ANALYTICS_META_KEY];
89
- if (candidate === null || candidate === void 0 || typeof candidate !== "object") return null;
90
- const { distinctId, sessionId, ingestUrl } = candidate;
91
- if (typeof distinctId !== "string" || typeof sessionId !== "string" || typeof ingestUrl !== "string") return null;
92
- return {
93
- distinctId,
94
- sessionId,
95
- ingestUrl
96
- };
97
- }
98
- //#endregion
99
- //#region src/react/stamp-source.ts
100
- const TOOL_RESULT_METHOD = "ui/notifications/tool-result";
101
- const SET_GLOBALS_EVENT_TYPE = "openai:set_globals";
102
- const subscribers = /* @__PURE__ */ new Set();
103
- let latestProtocolStamp = null;
104
- let isObservingRuntime = false;
105
- function subscribeToAnalyticsStamp(onStamp) {
106
- observeRuntime();
107
- subscribers.add(onStamp);
108
- if (latestProtocolStamp !== null) onStamp(latestProtocolStamp);
109
- else emitOpenAiStamp(onStamp);
110
- return () => {
111
- subscribers.delete(onStamp);
112
- };
113
- }
114
- function observeRuntime() {
115
- if (isObservingRuntime || typeof window === "undefined") return;
116
- window.addEventListener("message", handleToolResultMessage);
117
- window.addEventListener(SET_GLOBALS_EVENT_TYPE, handleOpenAiGlobals, { passive: true });
118
- isObservingRuntime = true;
119
- }
120
- function handleToolResultMessage(event) {
121
- if (event.source !== window.parent || event.data === null || typeof event.data !== "object") return;
122
- const message = event.data;
123
- if (message.jsonrpc !== "2.0" || message.method !== TOOL_RESULT_METHOD) return;
124
- const params = message.params;
125
- if (params === null || typeof params !== "object") return;
126
- const stamp = parseAnalyticsStamp(params._meta);
127
- if (stamp === null) return;
128
- latestProtocolStamp = stamp;
129
- for (const subscriber of subscribers) subscriber(stamp);
130
- }
131
- function handleOpenAiGlobals() {
132
- if (latestProtocolStamp !== null) return;
133
- const globals = window;
134
- if (globals.openai === void 0) return;
135
- const stamp = parseAnalyticsStamp(globals.openai.toolResponseMetadata);
136
- if (stamp === null) return;
137
- for (const subscriber of subscribers) subscriber(stamp);
138
- }
139
- function emitOpenAiStamp(onStamp) {
140
- if (typeof window === "undefined") return;
141
- const stamp = parseAnalyticsStamp(window.openai?.toolResponseMetadata);
142
- if (stamp !== null) onStamp(stamp);
143
- }
144
- observeRuntime();
145
- //#endregion
146
- //#region src/react/alpic-analytics.tsx
147
- const AnalyticsContext = createContext(null);
148
- /**
149
- * Provides Alpic Analytics to descendant components and configures itself from the widget host.
150
- * Wrap the widget once, then call `useAnalytics()` from components that capture events.
151
- * Events captured before configuration is available are buffered automatically.
152
- */
153
- function AlpicAnalytics({ children }) {
154
- const [client] = useState(() => new AnalyticsClient());
155
- useEffect(() => {
156
- const unsubscribe = subscribeToAnalyticsStamp((stamp) => {
157
- client.configure(stamp.ingestUrl);
158
- });
159
- const flushWhenHidden = () => {
160
- if (document.visibilityState === "hidden") client.flush();
161
- };
162
- document.addEventListener("visibilitychange", flushWhenHidden);
163
- window.addEventListener("pagehide", client.flush);
164
- return () => {
165
- unsubscribe();
166
- document.removeEventListener("visibilitychange", flushWhenHidden);
167
- window.removeEventListener("pagehide", client.flush);
168
- client.flush();
169
- };
170
- }, [client]);
171
- return /* @__PURE__ */ jsx(AnalyticsContext.Provider, {
172
- value: client,
173
- children
174
- });
175
- }
176
- /** Returns the analytics client from the nearest `AlpicAnalytics` provider. */
177
- function useAnalytics() {
178
- const analytics = useContext(AnalyticsContext);
179
- if (analytics === null) throw new Error("useAnalytics must be used within an <AlpicAnalytics> provider");
180
- return analytics;
181
- }
182
- //#endregion
183
- export { AlpicAnalytics, useAnalytics };