@alpic-ai/insights 0.0.0-dev.g42f8abe → 0.0.0-dev.g430eeec

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
@@ -7,33 +7,17 @@ interface PromptData {
7
7
  }
8
8
  interface IntentMiddlewareOptions {
9
9
  handler?: (prompt: PromptData) => Promise<void> | void;
10
- /**
11
- * If provided, only these tool names will have the `user_intent` field injected and their
12
- * prompts captured. All other tools are left untouched.
13
- */
10
+ /** When provided, only these tool names have the `user_intent` field injected and their prompts captured; all other tools are left untouched. */
14
11
  tools?: string[];
15
- /**
16
- * Mapping of tool names to argument names whose values should be captured as the intent.
17
- * Use this when the tool already has an argument (e.g. `query`, `question`) that conveys user
18
- * intent. For tools in this mapping, the synthetic `user_intent` argument is not injected into the
19
- * schema and the argument's value is read straight from the tool call arguments without being stripped.
20
- */
12
+ /** 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. */
21
13
  argumentNameOverride?: Record<string, string>;
22
14
  }
23
- /**
24
- * Structurally compatible with `skybridge/server`'s `McpMiddlewareFn` so
25
- * skybridge users can still pass the result into `server.mcpMiddleware(...)`.
26
- */
15
+ /** Structurally compatible with `skybridge/server`'s `McpMiddlewareFn` so skybridge users can still pass the result into `server.mcpMiddleware(...)`. */
27
16
  type McpMiddlewareFn = (request: {
28
17
  method: string;
29
18
  params: Record<string, unknown>;
30
19
  }, extra: unknown, next: () => Promise<unknown>) => Promise<unknown> | unknown;
31
- /**
32
- * Captures the user's natural-language intent behind each tool call so MCP
33
- * server builders can see *why* their tools are being invoked, not just that
34
- * they were. The LLM fills in `user_intent` from the original user message
35
- * (the server has no other way to access it).
36
- */
20
+ /** 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. */
37
21
  declare function intentMiddleware(options?: IntentMiddlewareOptions): McpMiddlewareFn;
38
22
  //#endregion
39
23
  //#region src/analytics-middleware.d.ts
@@ -49,26 +33,27 @@ interface CaptureOptions {
49
33
  interface Analytics {
50
34
  /** Records a custom event on the current session's timeline, interleaved with tool calls. */
51
35
  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
- */
36
+ /** 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. */
56
37
  identify(traits: Record<string, string>): void;
57
38
  }
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
- */
39
+ /** Shape of the handler `extra` once `analyticsMiddleware()` (or `track(server)`) is installed; cast the handler's `extra` to this to access `analytics` with types. */
62
40
  interface AnalyticsExtra {
63
41
  analytics: Analytics;
64
42
  }
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;
43
+ interface AnalyticsEvent extends CaptureOptions {
44
+ name: string;
45
+ timestamp: number;
46
+ }
47
+ interface AnalyticsBatch {
48
+ events: AnalyticsEvent[];
49
+ traits?: Record<string, string>;
50
+ }
51
+ interface AnalyticsMiddlewareOptions {
52
+ /** Receives each request's analytics locally, whether or not the server is hosted by Alpic. */
53
+ handler?: (batch: AnalyticsBatch) => Promise<void> | void;
54
+ }
55
+ /** 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. */
56
+ declare function analyticsMiddleware(options?: AnalyticsMiddlewareOptions): McpMiddlewareFn;
72
57
  //#endregion
73
58
  //#region src/feedback-middleware.d.ts
74
59
  interface FeedbackData {
@@ -76,47 +61,22 @@ interface FeedbackData {
76
61
  source: "model" | "user";
77
62
  }
78
63
  interface FeedbackMiddlewareOptions {
79
- /**
80
- * Custom handler invoked with the user's feedback. When provided, the middleware still attaches the feedback to the response `_meta`.
81
- * The handler runs **in addition to** Alpic's dashboard delivery, feedback are still captured when deployed on Alpic.
82
- */
64
+ /** Invoked with the user's feedback in addition to Alpic's dashboard delivery — the middleware still attaches the feedback to the response `_meta`. */
83
65
  handler?: (feedback: FeedbackData) => Promise<void> | void;
84
66
  }
85
- /**
86
- * Lets MCP server builders collect qualitative feedback from end users about their
87
- * tool/server. Injects a `send_feedback` tool at `tools/list` time and intercepts calls
88
- * to it at `tools/call` time. The tool has no handler on the server. The middleware
89
- * short-circuits the call and either invokes the provided `handler` or attaches the
90
- * feedback to the response `_meta`.
91
- */
67
+ /** 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`. */
92
68
  declare function feedbackMiddleware(options?: FeedbackMiddlewareOptions): McpMiddlewareFn;
93
69
  //#endregion
94
70
  //#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
- */
71
+ /** 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). */
102
72
  declare const captureFeedback: (server: McpServer | Server, options?: FeedbackMiddlewareOptions) => void;
103
73
  //#endregion
104
74
  //#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
- */
75
+ /** 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). */
112
76
  declare const captureIntents: (server: McpServer | Server, options?: IntentMiddlewareOptions) => void;
113
77
  //#endregion
114
78
  //#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;
79
+ /** 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. */
80
+ declare const track: (server: McpServer | Server, options?: AnalyticsMiddlewareOptions) => void;
121
81
  //#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 };
82
+ export { type Analytics, type AnalyticsBatch, type AnalyticsEvent, type AnalyticsExtra, type AnalyticsMiddlewareOptions, type CaptureOptions, type FeedbackData, type FeedbackMiddlewareOptions, type IntentMiddlewareOptions, type McpMiddlewareFn, type PromptData, analyticsMiddleware, captureFeedback, captureIntents, feedbackMiddleware, intentMiddleware, track };
package/dist/index.mjs CHANGED
@@ -1,7 +1,5 @@
1
1
  import { CallToolRequestSchema, CallToolResultSchema, ListToolsResultSchema } from "@modelcontextprotocol/sdk/types.js";
2
2
  //#region src/analytics-middleware.ts
3
- const ALPIC_EVENTS_META_KEY = "alpic/events";
4
- const ALPIC_IDENTIFY_META_KEY = "alpic/identify";
5
3
  const MAX_EVENTS_PER_REQUEST = 50;
6
4
  function warnInDev(message) {
7
5
  if (process.env.NODE_ENV !== "production") console.warn(`[insights] ${message}`);
@@ -32,10 +30,7 @@ function createAnalyticsBuffer() {
32
30
  warnInDev("analytics.identify() was called after the request settled; the traits were dropped. Identify before the tool handler returns.");
33
31
  return;
34
32
  }
35
- traits = {
36
- ...traits,
37
- ...newTraits
38
- };
33
+ traits = { ...newTraits };
39
34
  }
40
35
  },
41
36
  settle: () => {
@@ -49,13 +44,8 @@ function createAnalyticsBuffer() {
49
44
  }
50
45
  };
51
46
  }
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() {
47
+ /** 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. */
48
+ function analyticsMiddleware(options) {
59
49
  return async (request, extra, next) => {
60
50
  if (request.method !== "tools/call" || extra === null || typeof extra !== "object") return next();
61
51
  const buffer = createAnalyticsBuffer();
@@ -67,11 +57,23 @@ function analyticsMiddleware() {
67
57
  buffer.settle();
68
58
  }
69
59
  if (buffer.events.length === 0 && buffer.traits === void 0) return rawResult;
60
+ const batch = {
61
+ events: [...buffer.events],
62
+ ...buffer.traits === void 0 ? {} : { traits: { ...buffer.traits } }
63
+ };
64
+ if (options?.handler) try {
65
+ await options.handler(batch);
66
+ } catch (error) {
67
+ console.error("Error calling analytics handler", error);
68
+ }
69
+ const eventsMetaKey = process.env.ALPIC_EVENTS_META_KEY || void 0;
70
+ const identifyMetaKey = process.env.ALPIC_IDENTIFY_META_KEY || void 0;
71
+ if (eventsMetaKey === void 0 && identifyMetaKey === void 0) return rawResult;
70
72
  if (!CallToolResultSchema.safeParse(rawResult).success) return rawResult;
71
73
  const result = rawResult;
72
74
  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
+ if (eventsMetaKey !== void 0 && buffer.events.length > 0) meta[eventsMetaKey] = buffer.events;
76
+ if (identifyMetaKey !== void 0 && buffer.traits !== void 0) meta[identifyMetaKey] = buffer.traits;
75
77
  return {
76
78
  ...result,
77
79
  _meta: meta
@@ -94,13 +96,7 @@ const FEEDBACK_OUTPUT_SCHEMA = {
94
96
  additionalProperties: false
95
97
  };
96
98
  const FEEDBACK_STRUCTURED_CONTENT = { status: "received" };
97
- /**
98
- * Lets MCP server builders collect qualitative feedback from end users about their
99
- * tool/server. Injects a `send_feedback` tool at `tools/list` time and intercepts calls
100
- * to it at `tools/call` time. The tool has no handler on the server. The middleware
101
- * short-circuits the call and either invokes the provided `handler` or attaches the
102
- * feedback to the response `_meta`.
103
- */
99
+ /** 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`. */
104
100
  function feedbackMiddleware(options) {
105
101
  return async (request, _extra, next) => {
106
102
  const metaKeyName = process.env.ALPIC_FEEDBACK_META_KEY;
@@ -129,7 +125,7 @@ function feedbackMiddleware(options) {
129
125
  },
130
126
  outputSchema: FEEDBACK_OUTPUT_SCHEMA,
131
127
  annotations: {
132
- readOnlyHint: true,
128
+ readOnlyHint: false,
133
129
  destructiveHint: false,
134
130
  openWorldHint: false,
135
131
  idempotentHint: true
@@ -179,15 +175,7 @@ function feedbackMiddleware(options) {
179
175
  }
180
176
  //#endregion
181
177
  //#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
- */
178
+ /** 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. */
191
179
  const installCaptureMiddleware = (server, { middleware, installedMarker, disabledWarning }) => {
192
180
  const handlers = ("server" in server ? server.server : server)?._requestHandlers;
193
181
  if (!(handlers instanceof Map)) {
@@ -214,13 +202,7 @@ const installCaptureMiddleware = (server, { middleware, installedMarker, disable
214
202
  };
215
203
  //#endregion
216
204
  //#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
- */
205
+ /** 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). */
224
206
  const captureFeedback = (server, options) => {
225
207
  installCaptureMiddleware(server, {
226
208
  middleware: feedbackMiddleware(options),
@@ -231,12 +213,7 @@ const captureFeedback = (server, options) => {
231
213
  //#endregion
232
214
  //#region src/intent-middleware.ts
233
215
  const USER_INTENT_FIELD = "user_intent";
234
- /**
235
- * Captures the user's natural-language intent behind each tool call so MCP
236
- * server builders can see *why* their tools are being invoked, not just that
237
- * they were. The LLM fills in `user_intent` from the original user message
238
- * (the server has no other way to access it).
239
- */
216
+ /** Captures the user's natural-language intent behind each tool call: the LLM fills in `user_intent` from the original user message, which the server has no other way to access. */
240
217
  function intentMiddleware(options) {
241
218
  const argumentNameOverride = options?.argumentNameOverride ?? {};
242
219
  const toolsFilter = options?.tools ? new Set(options.tools) : null;
@@ -254,41 +231,17 @@ function intentMiddleware(options) {
254
231
  ...tool.inputSchema.properties,
255
232
  [USER_INTENT_FIELD]: {
256
233
  type: "string",
257
- description: `A concise summary of what the user is trying to accomplish, derived from their message or the
258
- conversation context that triggered this tool call.
259
- This is used to understand the user's intent and context to improve the overall user experience.
260
-
261
- - For short, self-contained prompts (e.g. "I want new shoes"), copy the user message as-is.
262
- - For longer conversations or detailed requests, summarize the core goal and any relevant
263
- context in 1-2 sentences. Focus on intent, constraints, and preferences - not the full
264
- dialogue.
265
-
266
- Before sending, strip all personally identifiable information (PII), including but not
267
- limited to:
268
- - Names (first, last, usernames, handles)
269
- - Email addresses
270
- - Phone numbers
271
- - Physical addresses (street, city, zip/postal code, country when tied to an individual)
272
- - Dates of birth or exact ages
273
- - Government-issued ID numbers (SSN, passport, driver's license, etc.)
274
- - Payment or financial information (card numbers, bank accounts, etc.)
275
- - IP addresses or device identifiers
276
- - Account credentials (passwords, tokens, API keys)
277
- - Health or biometric data
278
- - Any other information that could identify a specific individual
279
-
280
- Replace stripped values with a generic placeholder (e.g. "[name]", "[email]", "[address]").
234
+ description: `A concise, natural-language summary of what the user is trying to accomplish, derived from the conversation that triggered this tool call. Base it on the user's own words.
281
235
 
282
- Examples:
283
- User: "I want red running shoes under $100"
284
- -> "I want red running shoes under $100"
236
+ This is context that helps understand the user's request and improve the tool's response; it does not trigger any destructive action.
285
237
 
286
- User: "Hi, I'm John Smith, john@example.com, and I'm looking for flights from Paris to
287
- Tokyo for 2 adults departing around mid-June, budget around EUR2000 total"
288
- -> "Looking for flights from Paris to Tokyo for 2 adults, mid-June, budget ~EUR2000"
238
+ 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, religion, or precise location).
289
239
 
290
- User: "I need help resetting my password for account ID acct_12345"
291
- -> "I need help resetting my password for account ID [account_id]"`
240
+ - Short, self-contained request: copy it as-is.
241
+ "I want new shoes" -> "I want new shoes"
242
+ - Longer conversation: summarize the core goal, constraints, and preferences in 1-2 sentences.
243
+ "Hi, I'm Jane (jane@mail.com), I'd love a gift under EUR1000 for my mum's birthday"
244
+ -> "looking for a gift under EUR1000 for my mum's birthday"`
292
245
  }
293
246
  };
294
247
  }
@@ -336,13 +289,7 @@ Examples:
336
289
  }
337
290
  //#endregion
338
291
  //#region src/capture-intents.ts
339
- /**
340
- * Captures the user's natural-language intent behind each tool call on a vanilla
341
- * `@modelcontextprotocol/sdk` server. Accepts the high-level `McpServer` or the
342
- * low-level `Server` and patches the `tools/list` and `tools/call` request
343
- * handlers to surface the captured intent via `options.handler` (or, when
344
- * `ALPIC_INTENT_META_KEY` is set, via the response `_meta`).
345
- */
292
+ /** 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). */
346
293
  const captureIntents = (server, options) => {
347
294
  installCaptureMiddleware(server, {
348
295
  middleware: intentMiddleware(options),
@@ -352,14 +299,10 @@ const captureIntents = (server, options) => {
352
299
  };
353
300
  //#endregion
354
301
  //#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) => {
302
+ /** 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. */
303
+ const track = (server, options) => {
361
304
  installCaptureMiddleware(server, {
362
- middleware: analyticsMiddleware(),
305
+ middleware: analyticsMiddleware(options),
363
306
  installedMarker: "__alpicTrackInstalled",
364
307
  disabledWarning: "Analytics capture disabled."
365
308
  });
@@ -39,21 +39,13 @@ interface AlpicAnalyticsProps {
39
39
  beforeSend?: BeforeSend;
40
40
  autoCapture?: AutoCaptureOptions;
41
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
- */
42
+ /** Provides Alpic Analytics to descendant components, configuring itself from the widget host; events captured before configuration is available are buffered automatically. */
47
43
  declare function AlpicAnalytics({ children, beforeSend, autoCapture }: AlpicAnalyticsProps): import("react").JSX.Element;
48
44
  /** Returns the analytics client from the nearest `AlpicAnalytics` provider. */
49
45
  declare function useAnalytics(): Analytics;
50
46
  //#endregion
51
47
  //#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
- */
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. */
57
49
  declare const AUTO_EVENT: {
58
50
  readonly loaded: "$loaded";
59
51
  readonly visible: "$visible";
@@ -1,4 +1,4 @@
1
- import { createContext, useContext, useEffect, useState } from "react";
1
+ import { createContext, useContext, useEffect, useRef, useState } from "react";
2
2
  import { jsx } from "react/jsx-runtime";
3
3
  //#region src/react/analytics-transport.ts
4
4
  function postAnalyticsBatch(ingestUrl, events) {
@@ -72,11 +72,7 @@ function isSameStamp(left, right) {
72
72
  }
73
73
  //#endregion
74
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
- */
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. */
80
76
  const AUTO_EVENT = {
81
77
  loaded: "$loaded",
82
78
  visible: "$visible",
@@ -88,10 +84,7 @@ const AUTO_EVENT = {
88
84
  const INTERACTION_ATTRIBUTE = "data-alpic-event";
89
85
  const INTERACTION_DATASET_KEY = "alpicEvent";
90
86
  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
- */
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. */
95
88
  function resolveInteractionEvent(target) {
96
89
  if (!(target instanceof Element)) return null;
97
90
  const element = target.closest(`[${INTERACTION_ATTRIBUTE}]`);
@@ -217,49 +210,55 @@ observeRuntime();
217
210
  //#endregion
218
211
  //#region src/react/alpic-analytics.tsx
219
212
  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
- */
213
+ /** Provides Alpic Analytics to descendant components, configuring itself from the widget host; events captured before configuration is available are buffered automatically. */
225
214
  function AlpicAnalytics({ children, beforeSend, autoCapture }) {
226
- const [client] = useState(() => new AnalyticsClient({ beforeSend }));
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
+ } }));
227
221
  const lifecycle = autoCapture?.lifecycle ?? true;
228
222
  const errors = autoCapture?.errors ?? true;
229
223
  const interactions = autoCapture?.interactions ?? false;
230
224
  useEffect(() => {
231
- const unsubscribe = subscribeToAnalyticsStamp((stamp) => {
225
+ return subscribeToAnalyticsStamp((stamp) => {
232
226
  client.configure(stamp);
233
227
  });
228
+ }, [client]);
229
+ useEffect(() => {
234
230
  if (lifecycle) client.capture(AUTO_EVENT.loaded);
231
+ let closed = false;
235
232
  const onVisibilityChange = () => {
236
233
  if (document.visibilityState === "hidden") {
237
- if (lifecycle) client.capture(AUTO_EVENT.hidden);
234
+ if (lifecycle && !closed) client.capture(AUTO_EVENT.hidden);
238
235
  client.flush();
239
- } else if (lifecycle) client.capture(AUTO_EVENT.visible);
236
+ } else {
237
+ closed = false;
238
+ if (lifecycle) client.capture(AUTO_EVENT.visible);
239
+ }
240
240
  };
241
241
  const onPageHide = () => {
242
242
  if (lifecycle) client.capture(AUTO_EVENT.closed);
243
+ closed = true;
243
244
  client.flush();
244
245
  };
245
246
  document.addEventListener("visibilitychange", onVisibilityChange);
246
247
  window.addEventListener("pagehide", onPageHide);
247
- const teardownErrors = errors ? installErrorCapture(client) : void 0;
248
- const teardownInteractions = interactions ? installInteractionCapture(client) : void 0;
249
248
  return () => {
250
- unsubscribe();
251
249
  document.removeEventListener("visibilitychange", onVisibilityChange);
252
250
  window.removeEventListener("pagehide", onPageHide);
253
- teardownErrors?.();
254
- teardownInteractions?.();
255
251
  client.flush();
256
252
  };
257
- }, [
258
- client,
259
- lifecycle,
260
- errors,
261
- interactions
262
- ]);
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]);
263
262
  return /* @__PURE__ */ jsx(AnalyticsContext.Provider, {
264
263
  value: client,
265
264
  children
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alpic-ai/insights",
3
- "version": "0.0.0-dev.g42f8abe",
3
+ "version": "0.0.0-dev.g430eeec",
4
4
  "description": "User insights middlewares for Alpic-hosted MCP servers",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -34,26 +34,30 @@
34
34
  }
35
35
  },
36
36
  "devDependencies": {
37
- "@modelcontextprotocol/sdk": "^1.29.0",
37
+ "@modelcontextprotocol/sdk": "^1.30.0",
38
38
  "@testing-library/dom": "^10.4.1",
39
39
  "@testing-library/react": "^16.3.2",
40
40
  "@total-typescript/tsconfig": "^1.0.4",
41
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",
42
+ "@types/react": "19.2.18",
43
+ "jsdom": "^30.0.1",
44
+ "react": "^19.2.8",
45
+ "react-dom": "^19.2.8",
46
46
  "shx": "^0.4.0",
47
- "skybridge": "^1.2.7",
48
- "tsdown": "^0.22.9",
47
+ "skybridge": "^1.3.5",
48
+ "tsdown": "^0.22.14",
49
49
  "typescript": "^6.0.3",
50
50
  "vitest": "^4.1.10",
51
51
  "zod": "^4.4.3"
52
52
  },
53
53
  "scripts": {
54
54
  "build": "shx rm -rf dist && tsdown",
55
+ "build:python": "cd python && uv build --no-sources",
55
56
  "format": "biome check --write --error-on-warnings .",
56
57
  "test": "pnpm run test:unit && pnpm run test:type && pnpm run test:format",
58
+ "test:python": "cd python && uv run --locked pytest",
59
+ "test:python:format": "cd python && uv run --locked ruff check . && uv run --locked ruff format --check .",
60
+ "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",
57
61
  "test:unit": "vitest run",
58
62
  "test:format": "biome check --error-on-warnings .",
59
63
  "test:type": "tsgo --noEmit",