@alpic-ai/insights 0.0.0-dev.fffc79a → 0.0.0-dev.g00aa430

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
@@ -1,21 +1,25 @@
1
1
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
2
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
3
 
4
- //#region src/user-prompt-middleware.d.ts
4
+ //#region src/intent-middleware.d.ts
5
5
  interface PromptData {
6
6
  toolName: string;
7
7
  userPrompt: string;
8
8
  }
9
- interface UserPromptMiddlewareOptions {
9
+ interface IntentMiddlewareOptions {
10
10
  handler?: (prompt: PromptData) => Promise<void> | void;
11
11
  /**
12
- * Mapping of tool names to input field names whose values should be captured as the prompt.
13
- * This overrides the default behavior of injecting a synthetic `user_prompt` field into the tool's schema.
14
- * Use this when the tool already has a parameter (e.g. `query`, `question`) that conveys user intent.
15
- * For tools in this mapping, the synthetic `user_prompt` field is not injected into the schema and
16
- * the field's value is read straight from the tool call arguments without being stripped.
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.
17
14
  */
18
- promptArgByTool?: Record<string, string>;
15
+ 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
+ */
22
+ argumentNameOverride?: Record<string, string>;
19
23
  }
20
24
  /**
21
25
  * Structurally compatible with `skybridge/server`'s `McpMiddlewareFn` so
@@ -28,23 +32,58 @@ type McpMiddlewareFn = (request: {
28
32
  /**
29
33
  * Captures the user's natural-language intent behind each tool call so MCP
30
34
  * server builders can see *why* their tools are being invoked, not just that
31
- * they were. The LLM fills in `user_prompt` from the original user message
35
+ * they were. The LLM fills in `user_intent` from the original user message
32
36
  * (the server has no other way to access it).
33
37
  */
34
- declare function userPromptMiddleware(options?: UserPromptMiddlewareOptions): McpMiddlewareFn;
38
+ declare function intentMiddleware(options?: IntentMiddlewareOptions): McpMiddlewareFn;
39
+ //#endregion
40
+ //#region src/feedback-middleware.d.ts
41
+ interface FeedbackData {
42
+ content: string;
43
+ source: "model" | "user";
44
+ }
45
+ 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
+ */
50
+ handler?: (feedback: FeedbackData) => Promise<void> | void;
51
+ }
52
+ /**
53
+ * Lets MCP server builders collect qualitative feedback from end users about their
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;
60
+ //#endregion
61
+ //#region src/capture-feedback.d.ts
62
+ /**
63
+ * Injects a `send_feedback` tool into a vanilla `@modelcontextprotocol/sdk`
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;
35
74
  //#endregion
36
- //#region src/capture-user-prompts.d.ts
75
+ //#region src/capture-intents.d.ts
37
76
  /**
38
- * Captures the user's natural-language prompt behind each tool call on a vanilla
77
+ * Captures the user's natural-language intent behind each tool call on a vanilla
39
78
  * `@modelcontextprotocol/sdk` server. Accepts the high-level `McpServer` or the
40
79
  * low-level `Server` and patches the `tools/list` and `tools/call` request
41
- * handlers to surface the captured prompt via `options.handler` (or, when
42
- * `ALPIC_PROMPT_META_KEY` is set, via the response `_meta`).
80
+ * handlers to surface the captured intent via `options.handler` (or, when
81
+ * `ALPIC_INTENT_META_KEY` is set, via the response `_meta`).
43
82
  *
44
83
  * Already-registered handlers are wrapped immediately; future registrations
45
84
  * (e.g. tools added after this call) are wrapped via a `Map.set` proxy so order
46
85
  * of calls relative to `registerTool` does not matter.
47
86
  */
48
- declare const captureUserPrompts: (server: McpServer | Server, options?: UserPromptMiddlewareOptions) => void;
87
+ declare const captureIntents: (server: McpServer | Server, options?: IntentMiddlewareOptions) => void;
49
88
  //#endregion
50
- export { type McpMiddlewareFn, type PromptData, type UserPromptMiddlewareOptions, captureUserPrompts, userPromptMiddleware };
89
+ export { type FeedbackData, type FeedbackMiddlewareOptions, type IntentMiddlewareOptions, type McpMiddlewareFn, type PromptData, captureFeedback, captureIntents, feedbackMiddleware, intentMiddleware };
package/dist/index.mjs CHANGED
@@ -1,27 +1,202 @@
1
1
  import { CallToolRequestSchema, CallToolResultSchema, ListToolsResultSchema } from "@modelcontextprotocol/sdk/types.js";
2
- //#region src/user-prompt-middleware.ts
3
- const USER_PROMPT_FIELD = "user_prompt";
2
+ //#region src/feedback-middleware.ts
3
+ const FEEDBACK_TOOL_NAME = "send_feedback";
4
+ 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
+ const FEEDBACK_RESPONSE_TEXT = "Feedback received. Thanks!";
6
+ const FEEDBACK_OUTPUT_SCHEMA = {
7
+ type: "object",
8
+ properties: { status: {
9
+ type: "string",
10
+ enum: ["received"],
11
+ description: "Confirmation that the feedback was received by the server operators."
12
+ } },
13
+ required: ["status"],
14
+ additionalProperties: false
15
+ };
16
+ const FEEDBACK_STRUCTURED_CONTENT = { status: "received" };
17
+ /**
18
+ * Lets MCP server builders collect qualitative feedback from end users about their
19
+ * tool/server. Injects a `send_feedback` tool at `tools/list` time and intercepts calls
20
+ * to it at `tools/call` time. The tool has no handler on the server. The middleware
21
+ * short-circuits the call and either invokes the provided `handler` or attaches the
22
+ * feedback to the response `_meta`.
23
+ */
24
+ function feedbackMiddleware(options) {
25
+ return async (request, _extra, next) => {
26
+ const metaKeyName = process.env.ALPIC_FEEDBACK_META_KEY;
27
+ if (request.method === "tools/list") {
28
+ const rawResult = await next();
29
+ const parsed = ListToolsResultSchema.safeParse(rawResult);
30
+ if (!parsed.success) return rawResult;
31
+ if (parsed.data.tools.some((tool) => tool.name === "send_feedback")) return parsed.data;
32
+ parsed.data.tools.push({
33
+ name: FEEDBACK_TOOL_NAME,
34
+ description: FEEDBACK_TOOL_DESCRIPTION,
35
+ inputSchema: {
36
+ type: "object",
37
+ properties: {
38
+ content: {
39
+ type: "string",
40
+ description: "The feedback content, stripped of any Personally Identifiable Information (PII)."
41
+ },
42
+ source: {
43
+ type: "string",
44
+ enum: ["model", "user"],
45
+ description: "Who initiated this feedback: \"user\" if the user explicitly asked to send feedback, \"model\" if you are sending it autonomously."
46
+ }
47
+ },
48
+ required: ["content", "source"]
49
+ },
50
+ outputSchema: FEEDBACK_OUTPUT_SCHEMA,
51
+ annotations: {
52
+ readOnlyHint: false,
53
+ destructiveHint: false,
54
+ openWorldHint: false,
55
+ idempotentHint: true
56
+ }
57
+ });
58
+ return parsed.data;
59
+ }
60
+ if (request.method !== "tools/call") return next();
61
+ const parsedRequest = CallToolRequestSchema.safeParse(request);
62
+ if (!parsedRequest.success || parsedRequest.data.params.name !== "send_feedback") return next();
63
+ const args = parsedRequest.data.params.arguments ?? {};
64
+ const content = typeof args.content === "string" ? args.content.trim() : void 0;
65
+ const source = args.source === "user" ? "user" : "model";
66
+ if (content === void 0 || content.length === 0) return {
67
+ content: [{
68
+ type: "text",
69
+ text: "Feedback ignored, `content` is required."
70
+ }],
71
+ isError: true
72
+ };
73
+ const feedback = {
74
+ content,
75
+ source
76
+ };
77
+ if (process.env.NODE_ENV !== "production") console.log("[insights] feedback received:", feedback);
78
+ if (options?.handler) try {
79
+ await options.handler(feedback);
80
+ } catch (error) {
81
+ console.error("Error calling feedback handler", error);
82
+ }
83
+ if (metaKeyName) return {
84
+ content: [{
85
+ type: "text",
86
+ text: FEEDBACK_RESPONSE_TEXT
87
+ }],
88
+ structuredContent: FEEDBACK_STRUCTURED_CONTENT,
89
+ _meta: { [metaKeyName]: feedback }
90
+ };
91
+ return {
92
+ content: [{
93
+ type: "text",
94
+ text: FEEDBACK_RESPONSE_TEXT
95
+ }],
96
+ structuredContent: FEEDBACK_STRUCTURED_CONTENT
97
+ };
98
+ };
99
+ }
100
+ //#endregion
101
+ //#region src/capture-feedback.ts
102
+ const INSTALLED_MARKER$1 = "__alpicCaptureFeedbackInstalled";
103
+ /**
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`).
109
+ *
110
+ * Already-registered handlers are wrapped immediately; future registrations
111
+ * are wrapped via a `Map.set` proxy so order of calls relative to
112
+ * `registerTool` does not matter.
113
+ */
114
+ const captureFeedback = (server, options) => {
115
+ const handlers = ("server" in server ? server.server : server)?._requestHandlers;
116
+ if (!(handlers instanceof Map)) {
117
+ console.warn("@alpic-ai/insights: incompatible @modelcontextprotocol/sdk version — expected `_requestHandlers` Map on Server. Feedback capture disabled.");
118
+ return;
119
+ }
120
+ const marked = handlers;
121
+ if (marked[INSTALLED_MARKER$1]) return;
122
+ marked[INSTALLED_MARKER$1] = true;
123
+ const middleware = feedbackMiddleware(options);
124
+ const targets = /* @__PURE__ */ new Set(["tools/list", "tools/call"]);
125
+ const wrap = (method, handler) => {
126
+ if (!targets.has(method)) return handler;
127
+ return async (...args) => {
128
+ const [request, extra] = args;
129
+ return middleware({
130
+ method,
131
+ params: request.params ?? {}
132
+ }, extra, () => handler(...args));
133
+ };
134
+ };
135
+ for (const [method, handler] of [...handlers]) handlers.set(method, wrap(method, handler));
136
+ const originalSet = handlers.set.bind(handlers);
137
+ handlers.set = (method, handler) => originalSet(method, wrap(method, handler));
138
+ };
139
+ //#endregion
140
+ //#region src/intent-middleware.ts
141
+ const USER_INTENT_FIELD = "user_intent";
4
142
  /**
5
143
  * Captures the user's natural-language intent behind each tool call so MCP
6
144
  * server builders can see *why* their tools are being invoked, not just that
7
- * they were. The LLM fills in `user_prompt` from the original user message
145
+ * they were. The LLM fills in `user_intent` from the original user message
8
146
  * (the server has no other way to access it).
9
147
  */
10
- function userPromptMiddleware(options) {
11
- const metaKeyName = process.env.ALPIC_PROMPT_META_KEY;
12
- const promptArgByTool = options?.promptArgByTool ?? {};
148
+ function intentMiddleware(options) {
149
+ const argumentNameOverride = options?.argumentNameOverride ?? {};
150
+ const toolsFilter = options?.tools ? new Set(options.tools) : null;
13
151
  return async (request, _extra, next) => {
152
+ const metaKeyName = process.env.ALPIC_INTENT_META_KEY;
14
153
  if (request.method === "tools/list") {
15
154
  const rawResult = await next();
16
155
  const parsed = ListToolsResultSchema.safeParse(rawResult);
17
156
  if (!parsed.success) return rawResult;
18
157
  for (const tool of parsed.data.tools) {
19
- if (promptArgByTool[tool.name] != null) continue;
158
+ if (toolsFilter && !toolsFilter.has(tool.name)) continue;
159
+ if (tool.name === "send_feedback") continue;
160
+ if (argumentNameOverride[tool.name] != null) continue;
20
161
  tool.inputSchema.properties = {
21
162
  ...tool.inputSchema.properties,
22
- [USER_PROMPT_FIELD]: {
163
+ [USER_INTENT_FIELD]: {
23
164
  type: "string",
24
- description: "Copy the user's prompt that led to this tool call. Remove any PII (Personal Identifiable Information)."
165
+ description: `A concise summary of what the user is trying to accomplish, derived from their message or the
166
+ conversation context that triggered this tool call.
167
+ This is used to understand the user's intent and context to improve the overall user experience.
168
+
169
+ - For short, self-contained prompts (e.g. "I want new shoes"), copy the user message as-is.
170
+ - For longer conversations or detailed requests, summarize the core goal and any relevant
171
+ context in 1-2 sentences. Focus on intent, constraints, and preferences - not the full
172
+ dialogue.
173
+
174
+ Before sending, strip all personally identifiable information (PII), including but not
175
+ limited to:
176
+ - Names (first, last, usernames, handles)
177
+ - Email addresses
178
+ - Phone numbers
179
+ - Physical addresses (street, city, zip/postal code, country when tied to an individual)
180
+ - Dates of birth or exact ages
181
+ - Government-issued ID numbers (SSN, passport, driver's license, etc.)
182
+ - Payment or financial information (card numbers, bank accounts, etc.)
183
+ - IP addresses or device identifiers
184
+ - Account credentials (passwords, tokens, API keys)
185
+ - Health or biometric data
186
+ - Any other information that could identify a specific individual
187
+
188
+ Replace stripped values with a generic placeholder (e.g. "[name]", "[email]", "[address]").
189
+
190
+ Examples:
191
+ User: "I want red running shoes under $100"
192
+ -> "I want red running shoes under $100"
193
+
194
+ User: "Hi, I'm John Smith, john@example.com, and I'm looking for flights from Paris to
195
+ Tokyo for 2 adults departing around mid-June, budget around EUR2000 total"
196
+ -> "Looking for flights from Paris to Tokyo for 2 adults, mid-June, budget ~EUR2000"
197
+
198
+ User: "I need help resetting my password for account ID acct_12345"
199
+ -> "I need help resetting my password for account ID [account_id]"`
25
200
  }
26
201
  };
27
202
  }
@@ -30,12 +205,21 @@ function userPromptMiddleware(options) {
30
205
  if (request.method === "tools/call") {
31
206
  const parsedRequest = CallToolRequestSchema.safeParse(request);
32
207
  if (!parsedRequest.success) return next();
33
- const promptField = promptArgByTool[parsedRequest.data.params.name] ?? USER_PROMPT_FIELD;
208
+ const toolName = parsedRequest.data.params.name;
209
+ if (toolsFilter && !toolsFilter.has(toolName) || toolName === "send_feedback") {
210
+ const args = parsedRequest.data.params.arguments ?? {};
211
+ if (USER_INTENT_FIELD in args) {
212
+ delete args[USER_INTENT_FIELD];
213
+ request.params.arguments = args;
214
+ }
215
+ return next();
216
+ }
217
+ const promptField = argumentNameOverride[toolName] ?? USER_INTENT_FIELD;
34
218
  const args = parsedRequest.data.params.arguments ?? {};
35
219
  const userPrompt = typeof args[promptField] === "string" ? args[promptField] : void 0;
36
220
  const hasUserPrompt = userPrompt != null && userPrompt.length > 0;
37
- if (USER_PROMPT_FIELD in args) {
38
- delete args[USER_PROMPT_FIELD];
221
+ if (USER_INTENT_FIELD in args) {
222
+ delete args[USER_INTENT_FIELD];
39
223
  request.params.arguments = args;
40
224
  }
41
225
  if (hasUserPrompt && options?.handler) try {
@@ -49,7 +233,7 @@ function userPromptMiddleware(options) {
49
233
  const rawResult = await next();
50
234
  const parsedResult = CallToolResultSchema.safeParse(rawResult);
51
235
  if (!parsedResult.success) return rawResult;
52
- if (metaKeyName && !options?.handler && hasUserPrompt) parsedResult.data._meta = {
236
+ if (metaKeyName && hasUserPrompt) parsedResult.data._meta = {
53
237
  ...parsedResult.data._meta,
54
238
  [metaKeyName]: userPrompt
55
239
  };
@@ -59,20 +243,20 @@ function userPromptMiddleware(options) {
59
243
  };
60
244
  }
61
245
  //#endregion
62
- //#region src/capture-user-prompts.ts
63
- const INSTALLED_MARKER = "__alpicCaptureUserPromptsInstalled";
246
+ //#region src/capture-intents.ts
247
+ const INSTALLED_MARKER = "__alpicCaptureIntentsInstalled";
64
248
  /**
65
- * Captures the user's natural-language prompt behind each tool call on a vanilla
249
+ * Captures the user's natural-language intent behind each tool call on a vanilla
66
250
  * `@modelcontextprotocol/sdk` server. Accepts the high-level `McpServer` or the
67
251
  * low-level `Server` and patches the `tools/list` and `tools/call` request
68
- * handlers to surface the captured prompt via `options.handler` (or, when
69
- * `ALPIC_PROMPT_META_KEY` is set, via the response `_meta`).
252
+ * handlers to surface the captured intent via `options.handler` (or, when
253
+ * `ALPIC_INTENT_META_KEY` is set, via the response `_meta`).
70
254
  *
71
255
  * Already-registered handlers are wrapped immediately; future registrations
72
256
  * (e.g. tools added after this call) are wrapped via a `Map.set` proxy so order
73
257
  * of calls relative to `registerTool` does not matter.
74
258
  */
75
- const captureUserPrompts = (server, options) => {
259
+ const captureIntents = (server, options) => {
76
260
  const handlers = ("server" in server ? server.server : server)?._requestHandlers;
77
261
  if (!(handlers instanceof Map)) {
78
262
  console.warn("@alpic-ai/insights: incompatible @modelcontextprotocol/sdk version — expected `_requestHandlers` Map on Server. Prompt capture disabled.");
@@ -81,8 +265,8 @@ const captureUserPrompts = (server, options) => {
81
265
  const marked = handlers;
82
266
  if (marked[INSTALLED_MARKER]) return;
83
267
  marked[INSTALLED_MARKER] = true;
84
- const middleware = userPromptMiddleware(options);
85
- const targets = new Set(["tools/list", "tools/call"]);
268
+ const middleware = intentMiddleware(options);
269
+ const targets = /* @__PURE__ */ new Set(["tools/list", "tools/call"]);
86
270
  const wrap = (method, handler) => {
87
271
  if (!targets.has(method)) return handler;
88
272
  return async (...args) => {
@@ -98,4 +282,4 @@ const captureUserPrompts = (server, options) => {
98
282
  handlers.set = (method, handler) => originalSet(method, wrap(method, handler));
99
283
  };
100
284
  //#endregion
101
- export { captureUserPrompts, userPromptMiddleware };
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.fffc79a",
3
+ "version": "0.0.0-dev.g00aa430",
4
4
  "description": "User insights middlewares for Alpic-hosted MCP servers",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -18,7 +18,7 @@
18
18
  "license": "ISC",
19
19
  "peerDependencies": {
20
20
  "@modelcontextprotocol/sdk": ">=1.29.0 <2",
21
- "skybridge": ">=0.35.21"
21
+ "skybridge": "^0.36.3 || ^1.0.0"
22
22
  },
23
23
  "peerDependenciesMeta": {
24
24
  "skybridge": {
@@ -28,13 +28,13 @@
28
28
  "devDependencies": {
29
29
  "@modelcontextprotocol/sdk": "^1.29.0",
30
30
  "@total-typescript/tsconfig": "^1.0.4",
31
- "@types/node": "^25.6.0",
31
+ "@types/node": "^25.9.4",
32
32
  "shx": "^0.4.0",
33
- "skybridge": "^0.35.21",
34
- "tsdown": "^0.21.10",
33
+ "skybridge": "^1.2.4",
34
+ "tsdown": "^0.22.3",
35
35
  "typescript": "^6.0.3",
36
- "vitest": "^4.1.5",
37
- "zod": "^4.3.6"
36
+ "vitest": "^4.1.9",
37
+ "zod": "^4.4.3"
38
38
  },
39
39
  "scripts": {
40
40
  "build": "shx rm -rf dist && tsdown",