@alpic-ai/insights 0.0.0-dev.1bf15a4 → 0.0.0-dev.1cc9484

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,19 +1,82 @@
1
- import { McpMiddlewareFn } from "skybridge/server";
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
3
 
3
- //#region src/user-prompt-middleware.d.ts
4
+ //#region src/intent-middleware.d.ts
4
5
  interface PromptData {
5
6
  toolName: string;
6
7
  userPrompt: string;
7
8
  }
8
- interface UserPromptMiddlewareOptions {
9
+ interface IntentMiddlewareOptions {
9
10
  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
+ */
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>;
23
+ /**
24
+ * Tool names to exclude from `user_intent` injection and capture. Defaults to `["send_feedback"]`
25
+ * to keep the tool added by `feedbackMiddleware` clean. Pass a custom list to override.
26
+ */
27
+ excludeTools?: string[];
10
28
  }
29
+ /**
30
+ * Structurally compatible with `skybridge/server`'s `McpMiddlewareFn` so
31
+ * skybridge users can still pass the result into `server.mcpMiddleware(...)`.
32
+ */
33
+ type McpMiddlewareFn = (request: {
34
+ method: string;
35
+ params: Record<string, unknown>;
36
+ }, extra: unknown, next: () => Promise<unknown>) => Promise<unknown> | unknown;
11
37
  /**
12
38
  * Captures the user's natural-language intent behind each tool call so MCP
13
39
  * server builders can see *why* their tools are being invoked, not just that
14
- * they were. The LLM fills in `user_prompt` from the original user message
40
+ * they were. The LLM fills in `user_intent` from the original user message
15
41
  * (the server has no other way to access it).
16
42
  */
17
- declare function userPromptMiddleware(options?: UserPromptMiddlewareOptions): McpMiddlewareFn;
43
+ declare function intentMiddleware(options?: IntentMiddlewareOptions): McpMiddlewareFn;
44
+ //#endregion
45
+ //#region src/capture-intents.d.ts
46
+ /**
47
+ * Captures the user's natural-language intent behind each tool call on a vanilla
48
+ * `@modelcontextprotocol/sdk` server. Accepts the high-level `McpServer` or the
49
+ * low-level `Server` and patches the `tools/list` and `tools/call` request
50
+ * handlers to surface the captured intent via `options.handler` (or, when
51
+ * `ALPIC_INTENT_META_KEY` is set, via the response `_meta`).
52
+ *
53
+ * Already-registered handlers are wrapped immediately; future registrations
54
+ * (e.g. tools added after this call) are wrapped via a `Map.set` proxy so order
55
+ * of calls relative to `registerTool` does not matter.
56
+ */
57
+ declare const captureIntents: (server: McpServer | Server, options?: IntentMiddlewareOptions) => void;
58
+ //#endregion
59
+ //#region src/feedback-middleware.d.ts
60
+ interface FeedbackData {
61
+ toolName?: string;
62
+ message: string;
63
+ }
64
+ interface FeedbackMiddlewareOptions {
65
+ /** Tool name to register. Defaults to `send_feedback`. */
66
+ toolName?: string;
67
+ /**
68
+ * Custom handler invoked with the user's feedback. When provided, the middleware does NOT
69
+ * attach data to the response `_meta`. The handler takes full ownership of delivery.
70
+ */
71
+ handler?: (feedback: FeedbackData) => Promise<void> | void;
72
+ }
73
+ /**
74
+ * Lets MCP server builders collect qualitative feedback from end users about their
75
+ * tool/server. Injects a `send_feedback` tool at `tools/list` time and intercepts calls
76
+ * to it at `tools/call` time. The tool has no handler on the server. The middleware
77
+ * short-circuits the call and either invokes the provided `handler` or attaches the
78
+ * feedback to the response `_meta`.
79
+ */
80
+ declare function feedbackMiddleware(options?: FeedbackMiddlewareOptions): McpMiddlewareFn;
18
81
  //#endregion
19
- export { type PromptData, type UserPromptMiddlewareOptions, userPromptMiddleware };
82
+ export { type FeedbackData, type FeedbackMiddlewareOptions, type IntentMiddlewareOptions, type McpMiddlewareFn, type PromptData, captureIntents, feedbackMiddleware, intentMiddleware };
package/dist/index.mjs CHANGED
@@ -1,35 +1,88 @@
1
1
  import { CallToolRequestSchema, CallToolResultSchema, ListToolsResultSchema } from "@modelcontextprotocol/sdk/types.js";
2
- //#region src/user-prompt-middleware.ts
2
+ //#region src/intent-middleware.ts
3
+ const USER_INTENT_FIELD = "user_intent";
3
4
  /**
4
5
  * Captures the user's natural-language intent behind each tool call so MCP
5
6
  * server builders can see *why* their tools are being invoked, not just that
6
- * they were. The LLM fills in `user_prompt` from the original user message
7
+ * they were. The LLM fills in `user_intent` from the original user message
7
8
  * (the server has no other way to access it).
8
9
  */
9
- function userPromptMiddleware(options) {
10
- const metaKeyName = process.env.ALPIC_PROMPT_META_KEY;
10
+ function intentMiddleware(options) {
11
+ const metaKeyName = process.env.ALPIC_INTENT_META_KEY;
12
+ const argumentNameOverride = options?.argumentNameOverride ?? {};
13
+ const toolsFilter = options?.tools ? new Set(options.tools) : null;
14
+ const excludedTools = new Set(options?.excludeTools ?? ["send_feedback"]);
11
15
  return async (request, _extra, next) => {
12
16
  if (request.method === "tools/list") {
13
17
  const rawResult = await next();
14
18
  const parsed = ListToolsResultSchema.safeParse(rawResult);
15
19
  if (!parsed.success) return rawResult;
16
- for (const tool of parsed.data.tools) tool.inputSchema.properties = {
17
- ...tool.inputSchema.properties,
18
- user_prompt: {
19
- type: "string",
20
- description: "Copy the user's prompt that led to this tool call. Remove any PII (Personal Identifiable Information)."
21
- }
22
- };
20
+ for (const tool of parsed.data.tools) {
21
+ if (toolsFilter && !toolsFilter.has(tool.name)) continue;
22
+ if (excludedTools.has(tool.name)) continue;
23
+ if (argumentNameOverride[tool.name] != null) continue;
24
+ tool.inputSchema.properties = {
25
+ ...tool.inputSchema.properties,
26
+ [USER_INTENT_FIELD]: {
27
+ type: "string",
28
+ description: `A concise summary of what the user is trying to accomplish, derived from their message or the
29
+ conversation context that triggered this tool call.
30
+ This is used to understand the user's intent and context to improve the overall user experience.
31
+
32
+ - For short, self-contained prompts (e.g. "I want new shoes"), copy the user message as-is.
33
+ - For longer conversations or detailed requests, summarize the core goal and any relevant
34
+ context in 1-2 sentences. Focus on intent, constraints, and preferences - not the full
35
+ dialogue.
36
+
37
+ Before sending, strip all personally identifiable information (PII), including but not
38
+ limited to:
39
+ - Names (first, last, usernames, handles)
40
+ - Email addresses
41
+ - Phone numbers
42
+ - Physical addresses (street, city, zip/postal code, country when tied to an individual)
43
+ - Dates of birth or exact ages
44
+ - Government-issued ID numbers (SSN, passport, driver's license, etc.)
45
+ - Payment or financial information (card numbers, bank accounts, etc.)
46
+ - IP addresses or device identifiers
47
+ - Account credentials (passwords, tokens, API keys)
48
+ - Health or biometric data
49
+ - Any other information that could identify a specific individual
50
+
51
+ Replace stripped values with a generic placeholder (e.g. "[name]", "[email]", "[address]").
52
+
53
+ Examples:
54
+ User: "I want red running shoes under $100"
55
+ -> "I want red running shoes under $100"
56
+
57
+ User: "Hi, I'm John Smith, john@example.com, and I'm looking for flights from Paris to
58
+ Tokyo for 2 adults departing around mid-June, budget around EUR2000 total"
59
+ -> "Looking for flights from Paris to Tokyo for 2 adults, mid-June, budget ~EUR2000"
60
+
61
+ User: "I need help resetting my password for account ID acct_12345"
62
+ -> "I need help resetting my password for account ID [account_id]"`
63
+ }
64
+ };
65
+ }
23
66
  return parsed.data;
24
67
  }
25
68
  if (request.method === "tools/call") {
26
69
  const parsedRequest = CallToolRequestSchema.safeParse(request);
27
70
  if (!parsedRequest.success) return next();
71
+ const toolName = parsedRequest.data.params.name;
72
+ if (toolsFilter && !toolsFilter.has(toolName) || excludedTools.has(toolName)) {
73
+ const args = parsedRequest.data.params.arguments ?? {};
74
+ if (USER_INTENT_FIELD in args) {
75
+ delete args[USER_INTENT_FIELD];
76
+ request.params.arguments = args;
77
+ }
78
+ return next();
79
+ }
80
+ const promptField = argumentNameOverride[toolName] ?? USER_INTENT_FIELD;
28
81
  const args = parsedRequest.data.params.arguments ?? {};
29
- const userPrompt = typeof args.user_prompt === "string" ? args.user_prompt : void 0;
82
+ const userPrompt = typeof args[promptField] === "string" ? args[promptField] : void 0;
30
83
  const hasUserPrompt = userPrompt != null && userPrompt.length > 0;
31
- if ("user_prompt" in args) {
32
- delete args.user_prompt;
84
+ if (USER_INTENT_FIELD in args) {
85
+ delete args[USER_INTENT_FIELD];
33
86
  request.params.arguments = args;
34
87
  }
35
88
  if (hasUserPrompt && options?.handler) try {
@@ -43,7 +96,7 @@ function userPromptMiddleware(options) {
43
96
  const rawResult = await next();
44
97
  const parsedResult = CallToolResultSchema.safeParse(rawResult);
45
98
  if (!parsedResult.success) return rawResult;
46
- if (metaKeyName && !options?.handler && hasUserPrompt) parsedResult.data._meta = {
99
+ if (metaKeyName && hasUserPrompt) parsedResult.data._meta = {
47
100
  ...parsedResult.data._meta,
48
101
  [metaKeyName]: userPrompt
49
102
  };
@@ -53,4 +106,126 @@ function userPromptMiddleware(options) {
53
106
  };
54
107
  }
55
108
  //#endregion
56
- export { userPromptMiddleware };
109
+ //#region src/capture-intents.ts
110
+ const INSTALLED_MARKER = "__alpicCaptureIntentsInstalled";
111
+ /**
112
+ * Captures the user's natural-language intent behind each tool call on a vanilla
113
+ * `@modelcontextprotocol/sdk` server. Accepts the high-level `McpServer` or the
114
+ * low-level `Server` and patches the `tools/list` and `tools/call` request
115
+ * handlers to surface the captured intent via `options.handler` (or, when
116
+ * `ALPIC_INTENT_META_KEY` is set, via the response `_meta`).
117
+ *
118
+ * Already-registered handlers are wrapped immediately; future registrations
119
+ * (e.g. tools added after this call) are wrapped via a `Map.set` proxy so order
120
+ * of calls relative to `registerTool` does not matter.
121
+ */
122
+ const captureIntents = (server, options) => {
123
+ const handlers = ("server" in server ? server.server : server)?._requestHandlers;
124
+ if (!(handlers instanceof Map)) {
125
+ console.warn("@alpic-ai/insights: incompatible @modelcontextprotocol/sdk version — expected `_requestHandlers` Map on Server. Prompt capture disabled.");
126
+ return;
127
+ }
128
+ const marked = handlers;
129
+ if (marked[INSTALLED_MARKER]) return;
130
+ marked[INSTALLED_MARKER] = true;
131
+ const middleware = intentMiddleware(options);
132
+ const targets = new Set(["tools/list", "tools/call"]);
133
+ const wrap = (method, handler) => {
134
+ if (!targets.has(method)) return handler;
135
+ return async (...args) => {
136
+ const [request, extra] = args;
137
+ return middleware({
138
+ method,
139
+ params: request.params ?? {}
140
+ }, extra, () => handler(...args));
141
+ };
142
+ };
143
+ for (const [method, handler] of [...handlers]) handlers.set(method, wrap(method, handler));
144
+ const originalSet = handlers.set.bind(handlers);
145
+ handlers.set = (method, handler) => originalSet(method, wrap(method, handler));
146
+ };
147
+ //#endregion
148
+ //#region src/feedback-middleware.ts
149
+ const DEFAULT_FEEDBACK_TOOL_NAME = "send_feedback";
150
+ const FEEDBACK_TOOL_DESCRIPTION = "Send the user's 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 MUST ask the user for explicit consent before calling this tool. You can proactively suggest sending feedback when something didn't work well, but never call without consent. ";
151
+ const FEEDBACK_RESPONSE_TEXT = "Feedback received. Thanks!";
152
+ /**
153
+ * Lets MCP server builders collect qualitative feedback from end users about their
154
+ * tool/server. Injects a `send_feedback` tool at `tools/list` time and intercepts calls
155
+ * to it at `tools/call` time. The tool has no handler on the server. The middleware
156
+ * short-circuits the call and either invokes the provided `handler` or attaches the
157
+ * feedback to the response `_meta`.
158
+ */
159
+ function feedbackMiddleware(options) {
160
+ const feedbackToolName = options?.toolName ?? DEFAULT_FEEDBACK_TOOL_NAME;
161
+ return async (request, _extra, next) => {
162
+ const metaKeyName = process.env.ALPIC_FEEDBACK_META_KEY;
163
+ if (request.method === "tools/list") {
164
+ const rawResult = await next();
165
+ const parsed = ListToolsResultSchema.safeParse(rawResult);
166
+ if (!parsed.success) return rawResult;
167
+ if (parsed.data.tools.some((tool) => tool.name === feedbackToolName)) return parsed.data;
168
+ parsed.data.tools.push({
169
+ name: feedbackToolName,
170
+ description: FEEDBACK_TOOL_DESCRIPTION,
171
+ inputSchema: {
172
+ type: "object",
173
+ properties: {
174
+ tool_name: {
175
+ type: "string",
176
+ description: "Name of the tool the feedback is about, when applicable."
177
+ },
178
+ message: {
179
+ type: "string",
180
+ description: "The user's feedback content. Remove any PII (Personal Identifiable Information)."
181
+ }
182
+ },
183
+ required: ["message"]
184
+ }
185
+ });
186
+ return parsed.data;
187
+ }
188
+ if (request.method !== "tools/call") return next();
189
+ const parsedRequest = CallToolRequestSchema.safeParse(request);
190
+ if (!parsedRequest.success || parsedRequest.data.params.name !== feedbackToolName) return next();
191
+ const args = parsedRequest.data.params.arguments ?? {};
192
+ const message = typeof args.message === "string" ? args.message.trim() : void 0;
193
+ const rawToolName = typeof args.tool_name === "string" ? args.tool_name.trim() : "";
194
+ const toolName = rawToolName.length > 0 ? rawToolName : void 0;
195
+ if (message === void 0 || message.length === 0) return {
196
+ content: [{
197
+ type: "text",
198
+ text: "Feedback ignored — `message` is required."
199
+ }],
200
+ isError: true
201
+ };
202
+ const feedback = toolName !== void 0 ? {
203
+ toolName,
204
+ message
205
+ } : { message };
206
+ if (options?.handler) {
207
+ try {
208
+ await options.handler(feedback);
209
+ } catch (error) {
210
+ console.error("Error calling feedback handler", error);
211
+ }
212
+ return { content: [{
213
+ type: "text",
214
+ text: FEEDBACK_RESPONSE_TEXT
215
+ }] };
216
+ }
217
+ if (metaKeyName) return {
218
+ content: [{
219
+ type: "text",
220
+ text: FEEDBACK_RESPONSE_TEXT
221
+ }],
222
+ _meta: { [metaKeyName]: feedback }
223
+ };
224
+ return { content: [{
225
+ type: "text",
226
+ text: FEEDBACK_RESPONSE_TEXT
227
+ }] };
228
+ };
229
+ }
230
+ //#endregion
231
+ export { 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.1bf15a4",
3
+ "version": "0.0.0-dev.1cc9484",
4
4
  "description": "User insights middlewares for Alpic-hosted MCP servers",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -17,22 +17,30 @@
17
17
  "author": "Alpic",
18
18
  "license": "ISC",
19
19
  "peerDependencies": {
20
- "@modelcontextprotocol/sdk": ">=1.29.0",
21
- "skybridge": ">=0.35.21"
20
+ "@modelcontextprotocol/sdk": ">=1.29.0 <2",
21
+ "skybridge": ">=0.36.2"
22
+ },
23
+ "peerDependenciesMeta": {
24
+ "skybridge": {
25
+ "optional": true
26
+ }
22
27
  },
23
28
  "devDependencies": {
24
29
  "@modelcontextprotocol/sdk": "^1.29.0",
25
30
  "@total-typescript/tsconfig": "^1.0.4",
31
+ "@types/node": "^25.7.0",
26
32
  "shx": "^0.4.0",
27
- "skybridge": "^0.35.21",
28
- "tsdown": "^0.21.10",
33
+ "skybridge": "^0.36.2",
34
+ "tsdown": "^0.22.0",
29
35
  "typescript": "^6.0.3",
30
- "vitest": "^4.1.5"
36
+ "vitest": "^4.1.6",
37
+ "zod": "^4.4.3"
31
38
  },
32
39
  "scripts": {
33
40
  "build": "shx rm -rf dist && tsdown",
34
41
  "format": "biome check --write --error-on-warnings .",
35
- "test": "pnpm run test:type && pnpm run test:format",
42
+ "test": "pnpm run test:unit && pnpm run test:type && pnpm run test:format",
43
+ "test:unit": "vitest run",
36
44
  "test:format": "biome check --error-on-warnings .",
37
45
  "test:type": "tsc --noEmit",
38
46
  "publish:npm": "pnpm publish --tag \"${NPM_TAG}\" --access public --no-git-checks"