@njuptlzf/mcp-adapter 2.29.0-0.0.1
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/CHANGELOG.md +1205 -0
- package/LICENSE +21 -0
- package/MAPPING.md +73 -0
- package/README.md +564 -0
- package/abort.ts +34 -0
- package/adapters/pi-renderer.ts +7 -0
- package/adapters/protocol-elicitation-forwarder.ts +164 -0
- package/adapters/protocol-sampling-forwarder.ts +108 -0
- package/adapters/universal-host.ts +213 -0
- package/agent-dir.ts +68 -0
- package/agent-plugin-loader.ts +377 -0
- package/app-bridge.bundle.js +67 -0
- package/banner.png +0 -0
- package/bin/mcp-server.ts +282 -0
- package/cli.js +392 -0
- package/commands.ts +735 -0
- package/config.ts +1284 -0
- package/consent-manager.ts +64 -0
- package/direct-tools.ts +619 -0
- package/dist/agent-dir.d.ts +10 -0
- package/dist/agent-dir.js +63 -0
- package/dist/agent-dir.js.map +1 -0
- package/dist/agent-plugin-loader.d.ts +8 -0
- package/dist/agent-plugin-loader.js +356 -0
- package/dist/agent-plugin-loader.js.map +1 -0
- package/dist/config.d.ts +123 -0
- package/dist/config.js +1087 -0
- package/dist/config.js.map +1 -0
- package/dist/metadata-cache.d.ts +19 -0
- package/dist/metadata-cache.js +319 -0
- package/dist/metadata-cache.js.map +1 -0
- package/dist/package-mcp-loader.d.ts +2 -0
- package/dist/package-mcp-loader.js +156 -0
- package/dist/package-mcp-loader.js.map +1 -0
- package/dist/resource-tools.d.ts +1 -0
- package/dist/resource-tools.js +15 -0
- package/dist/resource-tools.js.map +1 -0
- package/dist/types.d.ts +564 -0
- package/dist/types.js +287 -0
- package/dist/types.js.map +1 -0
- package/dist/ui-app-bridge-helpers.d.ts +6 -0
- package/dist/ui-app-bridge-helpers.js +37 -0
- package/dist/ui-app-bridge-helpers.js.map +1 -0
- package/dist/ui-stream-types.d.ts +104 -0
- package/dist/ui-stream-types.js +59 -0
- package/dist/ui-stream-types.js.map +1 -0
- package/dist/ui-tool-visibility.d.ts +4 -0
- package/dist/ui-tool-visibility.js +27 -0
- package/dist/ui-tool-visibility.js.map +1 -0
- package/dist/utils.d.ts +32 -0
- package/dist/utils.js +338 -0
- package/dist/utils.js.map +1 -0
- package/elicitation-handler.ts +348 -0
- package/error-signal.ts +21 -0
- package/errors.ts +223 -0
- package/failure-backoff.ts +23 -0
- package/glimpse-ui.ts +80 -0
- package/host-html-template.ts +461 -0
- package/index.ts +1291 -0
- package/init.ts +692 -0
- package/interfaces/agent-paths.ts +67 -0
- package/interfaces/host-types.ts +102 -0
- package/interfaces/sampling.ts +57 -0
- package/json-schema-validator.ts +69 -0
- package/lifecycle.ts +446 -0
- package/logger.ts +169 -0
- package/mcp-auth-flow.ts +1026 -0
- package/mcp-auth.ts +1000 -0
- package/mcp-bearer-store.ts +387 -0
- package/mcp-callback-server.ts +534 -0
- package/mcp-code.ts +360 -0
- package/mcp-keyring-helper.cjs +89 -0
- package/mcp-oauth-provider.ts +666 -0
- package/mcp-output-guard.ts +496 -0
- package/mcp-panel.ts +1044 -0
- package/mcp-probe.ts +201 -0
- package/mcp-references.ts +368 -0
- package/mcp-script-worker.mjs +130 -0
- package/mcp-server.mjs +2133 -0
- package/mcp-setup-panel.ts +667 -0
- package/mcp-status.ts +98 -0
- package/mcp-trace.ts +306 -0
- package/metadata-cache.ts +382 -0
- package/namespace-tools.ts +276 -0
- package/npx-resolver.ts +543 -0
- package/oauth-handler.ts +30 -0
- package/oauth.ts +48 -0
- package/onboarding-state.ts +76 -0
- package/package-mcp-loader.ts +168 -0
- package/package.json +225 -0
- package/panel-keys.ts +53 -0
- package/prompts.ts +353 -0
- package/proxy-modes.ts +1418 -0
- package/request-headers-command.ts +330 -0
- package/resource-tools.ts +17 -0
- package/runtime-owner.ts +91 -0
- package/sampling-handler.ts +284 -0
- package/search-ranking.ts +278 -0
- package/server-manager.ts +1318 -0
- package/session-recovery.ts +158 -0
- package/skills/README.md +64 -0
- package/skills/mcp-adapter/SKILL.md +332 -0
- package/skills/mcp-adapter/references/deploy-examples.md +259 -0
- package/skills/mcp-adapter/references/deploy.md +89 -0
- package/skills/mcp-adapter/references/generate.md +144 -0
- package/skills/mcp-adapter/references/resolver.md +105 -0
- package/skills/mcp-adapter/references/verify.md +157 -0
- package/skills/mcp-scripting/SKILL.md +38 -0
- package/skills/resolve-conflicts/SKILL.md +482 -0
- package/skills/resolve-conflicts/references/patterns.md +432 -0
- package/skills/resolve-conflicts/references/sample-plan.md +96 -0
- package/skills/resolve-conflicts/scripts/handle-deleted-modified.sh +183 -0
- package/skills/resolve-conflicts/scripts/validate-conflicts.sh +120 -0
- package/skills/upstream-merge/SKILL.md +486 -0
- package/skills/upstream-merge/references/pi-coupling-markers.md +129 -0
- package/skills/upstream-merge/references/special-cases.md +39 -0
- package/state.ts +60 -0
- package/tool-approval.ts +195 -0
- package/tool-metadata.ts +296 -0
- package/tool-registrar.ts +253 -0
- package/tool-result-renderer.ts +477 -0
- package/ts-shape.ts +149 -0
- package/types.ts +991 -0
- package/ui-app-bridge-helpers.ts +40 -0
- package/ui-resource-handler.ts +250 -0
- package/ui-server.ts +852 -0
- package/ui-session.ts +571 -0
- package/ui-stream-types.ts +89 -0
- package/ui-tool-visibility.ts +25 -0
- package/unix-socket-transport.ts +85 -0
- package/utils.ts +382 -0
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import { complete } from "@earendil-works/pi-ai/compat";
|
|
2
|
+
import type { Api, AssistantMessage, Message, Model, ProviderHeaders, TextContent } from "@earendil-works/pi-ai";
|
|
3
|
+
import { truncateAtWord } from "./utils.ts";
|
|
4
|
+
import { throwIfAborted } from "./abort.ts";
|
|
5
|
+
import type { ExtensionUIContext, ModelRegistry } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import type { Client } from "@modelcontextprotocol/client";
|
|
7
|
+
import {
|
|
8
|
+
type CreateMessageRequest,
|
|
9
|
+
type CreateMessageResult,
|
|
10
|
+
type ModelPreferences,
|
|
11
|
+
type SamplingMessage,
|
|
12
|
+
type SamplingMessageContentBlock,
|
|
13
|
+
} from "@modelcontextprotocol/client";
|
|
14
|
+
|
|
15
|
+
export type SamplingUIContext = Pick<ExtensionUIContext, "confirm">;
|
|
16
|
+
export type SamplingModelRegistry = Pick<ModelRegistry, "getAvailable" | "getApiKeyAndHeaders">;
|
|
17
|
+
|
|
18
|
+
export interface SamplingHandlerOptions {
|
|
19
|
+
serverName: string;
|
|
20
|
+
autoApprove: boolean;
|
|
21
|
+
ui?: SamplingUIContext;
|
|
22
|
+
modelRegistry: SamplingModelRegistry;
|
|
23
|
+
getCurrentModel: () => Model<Api> | undefined;
|
|
24
|
+
getSignal: () => AbortSignal | undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export type ServerSamplingConfig = Omit<SamplingHandlerOptions, "serverName">;
|
|
28
|
+
|
|
29
|
+
export function registerSamplingHandler(client: Client, options: SamplingHandlerOptions): void {
|
|
30
|
+
client.setRequestHandler("sampling/createMessage", request => {
|
|
31
|
+
return handleSamplingRequest(options, request);
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function handleSamplingRequest(
|
|
36
|
+
options: SamplingHandlerOptions,
|
|
37
|
+
request: CreateMessageRequest,
|
|
38
|
+
): Promise<CreateMessageResult> {
|
|
39
|
+
const params = request.params;
|
|
40
|
+
const signal = options.getSignal();
|
|
41
|
+
throwIfAborted(signal);
|
|
42
|
+
|
|
43
|
+
if ("task" in params && params.task) {
|
|
44
|
+
throw new Error("MCP sampling tasks are not supported");
|
|
45
|
+
}
|
|
46
|
+
if (params.includeContext && params.includeContext !== "none") {
|
|
47
|
+
throw new Error("MCP sampling context inclusion is not supported");
|
|
48
|
+
}
|
|
49
|
+
if (params.tools?.length) {
|
|
50
|
+
throw new Error("MCP sampling tool use is not supported");
|
|
51
|
+
}
|
|
52
|
+
if (params.toolChoice) {
|
|
53
|
+
throw new Error("MCP sampling tool choice is not supported");
|
|
54
|
+
}
|
|
55
|
+
if (params.stopSequences?.length) {
|
|
56
|
+
throw new Error("MCP sampling stop sequences are not supported");
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const messages = params.messages.map(convertSamplingMessage);
|
|
60
|
+
const { model, apiKey, headers } = await resolveSamplingModel(options, params.modelPreferences);
|
|
61
|
+
throwIfAborted(signal);
|
|
62
|
+
await confirmSampling(
|
|
63
|
+
options,
|
|
64
|
+
"Approve MCP sampling request",
|
|
65
|
+
formatRequestApproval(options.serverName, `${model.provider}/${model.id}`, params.systemPrompt, messages),
|
|
66
|
+
);
|
|
67
|
+
throwIfAborted(signal);
|
|
68
|
+
|
|
69
|
+
const result = await complete(
|
|
70
|
+
model,
|
|
71
|
+
{
|
|
72
|
+
...(params.systemPrompt !== undefined ? { systemPrompt: params.systemPrompt } : {}),
|
|
73
|
+
messages,
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
...(apiKey !== undefined ? { apiKey } : {}),
|
|
77
|
+
...(headers !== undefined ? { headers } : {}),
|
|
78
|
+
maxTokens: params.maxTokens,
|
|
79
|
+
...(params.temperature !== undefined ? { temperature: params.temperature } : {}),
|
|
80
|
+
...(params.metadata !== undefined ? { metadata: params.metadata as Record<string, unknown> } : {}),
|
|
81
|
+
...(signal ? { signal } : {}),
|
|
82
|
+
},
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
const converted = convertAssistantResult(result);
|
|
86
|
+
throwIfAborted(signal);
|
|
87
|
+
await confirmSampling(
|
|
88
|
+
options,
|
|
89
|
+
"Return MCP sampling response",
|
|
90
|
+
formatResponseApproval(options.serverName, converted),
|
|
91
|
+
);
|
|
92
|
+
return converted;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function formatRequestApproval(
|
|
96
|
+
serverName: string,
|
|
97
|
+
modelName: string,
|
|
98
|
+
systemPrompt: string | undefined,
|
|
99
|
+
messages: Message[],
|
|
100
|
+
): string {
|
|
101
|
+
const lines = [`${serverName} wants to sample ${messages.length} message${messages.length === 1 ? "" : "s"} with ${modelName}.`];
|
|
102
|
+
if (systemPrompt) {
|
|
103
|
+
lines.push(`System: ${truncateAtWord(systemPrompt, 400)}`);
|
|
104
|
+
}
|
|
105
|
+
for (const [index, message] of messages.entries()) {
|
|
106
|
+
lines.push(`${index + 1}. ${message.role}: ${truncateAtWord(messageText(message), 400)}`);
|
|
107
|
+
}
|
|
108
|
+
return lines.join("\n\n");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function formatResponseApproval(serverName: string, response: CreateMessageResult): string {
|
|
112
|
+
const text = response.content.type === "text" ? response.content.text : `[${response.content.type} content]`;
|
|
113
|
+
return `${serverName} will receive this response from ${response.model}:\n\n${truncateAtWord(text, 1000)}`;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function messageText(message: Message): string {
|
|
117
|
+
if (typeof message.content === "string") return message.content;
|
|
118
|
+
return message.content.map((block: { type: string; text?: string; mimeType?: string; name?: string }) => {
|
|
119
|
+
if (block.type === "text") return block.text;
|
|
120
|
+
if (block.type === "image") return `[image: ${block.mimeType}]`;
|
|
121
|
+
if (block.type === "thinking") return "[thinking]";
|
|
122
|
+
if (block.type === "toolCall") return `[tool call: ${block.name}]`;
|
|
123
|
+
return "[content]";
|
|
124
|
+
}).join("\n");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function resolveSamplingModel(
|
|
128
|
+
options: SamplingHandlerOptions,
|
|
129
|
+
modelPreferences: ModelPreferences | undefined,
|
|
130
|
+
): Promise<{
|
|
131
|
+
model: Model<Api>;
|
|
132
|
+
apiKey?: string;
|
|
133
|
+
headers?: ProviderHeaders;
|
|
134
|
+
}> {
|
|
135
|
+
const candidates: Model<Api>[] = [];
|
|
136
|
+
const availableModels = options.modelRegistry.getAvailable();
|
|
137
|
+
|
|
138
|
+
for (const hint of modelPreferences?.hints ?? []) {
|
|
139
|
+
const normalizedHint = hint.name?.trim().toLowerCase();
|
|
140
|
+
if (!normalizedHint) continue;
|
|
141
|
+
for (const model of availableModels) {
|
|
142
|
+
const searchableNames = [`${model.provider}/${model.id}`, model.id, model.name];
|
|
143
|
+
if (searchableNames.some((name) => name.toLowerCase().includes(normalizedHint))) {
|
|
144
|
+
addSamplingCandidate(candidates, model);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const currentModel = options.getCurrentModel();
|
|
150
|
+
if (currentModel) addSamplingCandidate(candidates, currentModel);
|
|
151
|
+
|
|
152
|
+
for (const model of availableModels) {
|
|
153
|
+
addSamplingCandidate(candidates, model);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const errors: string[] = [];
|
|
157
|
+
const signal = options.getSignal();
|
|
158
|
+
for (const model of candidates) {
|
|
159
|
+
throwIfAborted(signal);
|
|
160
|
+
const auth = await options.modelRegistry.getApiKeyAndHeaders(model);
|
|
161
|
+
throwIfAborted(signal);
|
|
162
|
+
if (auth.ok === false) {
|
|
163
|
+
errors.push(`${model.provider}/${model.id}: ${auth.error}`);
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
return {
|
|
167
|
+
model,
|
|
168
|
+
...(auth.apiKey !== undefined ? { apiKey: auth.apiKey } : {}),
|
|
169
|
+
...(auth.headers !== undefined ? { headers: auth.headers } : {}),
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (errors.length > 0) {
|
|
174
|
+
throw new Error(`No configured auth for MCP sampling model. ${errors.join("; ")}`);
|
|
175
|
+
}
|
|
176
|
+
throw new Error("No Pi model is available for MCP sampling");
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function addSamplingCandidate(candidates: Model<Api>[], model: Model<Api>): void {
|
|
180
|
+
if (!candidates.some((candidate) => candidate.provider === model.provider && candidate.id === model.id)) {
|
|
181
|
+
candidates.push(model);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async function confirmSampling(options: SamplingHandlerOptions, title: string, message: string): Promise<void> {
|
|
186
|
+
if (options.autoApprove) return;
|
|
187
|
+
if (!options.ui) {
|
|
188
|
+
throw new Error("MCP sampling requires interactive approval. Set settings.samplingAutoApprove to true to allow it without UI.");
|
|
189
|
+
}
|
|
190
|
+
const approved = await options.ui.confirm(title, message);
|
|
191
|
+
if (!approved) {
|
|
192
|
+
throw new Error("MCP sampling request was declined");
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function convertSamplingMessage(message: SamplingMessage): Message {
|
|
197
|
+
const blocks = Array.isArray(message.content) ? message.content : [message.content];
|
|
198
|
+
if (message.role === "user") {
|
|
199
|
+
return {
|
|
200
|
+
role: "user",
|
|
201
|
+
content: blocks.map(convertUserContent),
|
|
202
|
+
timestamp: Date.now(),
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return {
|
|
207
|
+
role: "assistant",
|
|
208
|
+
content: blocks.map(convertAssistantContent),
|
|
209
|
+
api: "mcp-sampling",
|
|
210
|
+
provider: "mcp",
|
|
211
|
+
model: "sampling-request",
|
|
212
|
+
usage: zeroUsage(),
|
|
213
|
+
stopReason: "stop",
|
|
214
|
+
timestamp: Date.now(),
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function convertUserContent(block: SamplingMessageContentBlock): TextContent {
|
|
219
|
+
if (block.type === "text") {
|
|
220
|
+
return { type: "text", text: block.text };
|
|
221
|
+
}
|
|
222
|
+
throw new Error(`MCP sampling ${block.type} content is not supported`);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function convertAssistantContent(block: SamplingMessageContentBlock): TextContent {
|
|
226
|
+
if (block.type === "text") {
|
|
227
|
+
return { type: "text", text: block.text };
|
|
228
|
+
}
|
|
229
|
+
throw new Error(`MCP sampling assistant ${block.type} content is not supported`);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function convertAssistantResult(message: AssistantMessage): CreateMessageResult {
|
|
233
|
+
if (message.stopReason === "error") {
|
|
234
|
+
throw new Error(message.errorMessage ?? "MCP sampling model call failed");
|
|
235
|
+
}
|
|
236
|
+
if (message.stopReason === "aborted") {
|
|
237
|
+
throw new Error(message.errorMessage ?? "MCP sampling model call was aborted");
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const text = message.content
|
|
241
|
+
.map((block: { type: string; text?: string }) => {
|
|
242
|
+
if (block.type === "text") return block.text;
|
|
243
|
+
if (block.type === "thinking") return undefined;
|
|
244
|
+
throw new Error(`MCP sampling result ${block.type} content is not supported`);
|
|
245
|
+
})
|
|
246
|
+
.filter((value: string | undefined): value is string => value !== undefined)
|
|
247
|
+
.join("\n\n")
|
|
248
|
+
.trim();
|
|
249
|
+
|
|
250
|
+
if (!text) {
|
|
251
|
+
throw new Error("MCP sampling result did not contain text content");
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
return {
|
|
255
|
+
role: "assistant",
|
|
256
|
+
content: { type: "text", text },
|
|
257
|
+
model: `${message.provider}/${message.model}`,
|
|
258
|
+
stopReason: mapStopReason(message.stopReason),
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function mapStopReason(reason: AssistantMessage["stopReason"]): CreateMessageResult["stopReason"] {
|
|
263
|
+
if (reason === "stop") return "endTurn";
|
|
264
|
+
if (reason === "length") return "maxTokens";
|
|
265
|
+
if (reason === "toolUse") return "toolUse";
|
|
266
|
+
return reason;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function zeroUsage(): AssistantMessage["usage"] {
|
|
270
|
+
return {
|
|
271
|
+
input: 0,
|
|
272
|
+
output: 0,
|
|
273
|
+
cacheRead: 0,
|
|
274
|
+
cacheWrite: 0,
|
|
275
|
+
totalTokens: 0,
|
|
276
|
+
cost: {
|
|
277
|
+
input: 0,
|
|
278
|
+
output: 0,
|
|
279
|
+
cacheRead: 0,
|
|
280
|
+
cacheWrite: 0,
|
|
281
|
+
total: 0,
|
|
282
|
+
},
|
|
283
|
+
};
|
|
284
|
+
}
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import type { McpExtensionState } from "./state.ts";
|
|
2
|
+
import type { ServerEntry, ToolMetadata, ToolPrefix } from "./types.ts";
|
|
3
|
+
import { getServerPrefix, getToolNameCandidates, isServerDisabled, matchesToolPattern, resolveToolPrefix } from "./types.ts";
|
|
4
|
+
import { isServerInActiveFailureBackoff } from "./failure-backoff.ts";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Shortest field token allowed to stem-match a longer query token.
|
|
8
|
+
* Real descriptions tokenize possessives into single letters ("project's" -> ["project", "s"]),
|
|
9
|
+
* which would otherwise make every query starting with that letter a match.
|
|
10
|
+
*/
|
|
11
|
+
const MIN_STEM_LENGTH = 4;
|
|
12
|
+
|
|
13
|
+
const FIELD_WEIGHTS = {
|
|
14
|
+
name: 12,
|
|
15
|
+
originalName: 10,
|
|
16
|
+
server: 8,
|
|
17
|
+
description: 5,
|
|
18
|
+
keywords: 5,
|
|
19
|
+
} as const;
|
|
20
|
+
|
|
21
|
+
export interface RankedToolMatch {
|
|
22
|
+
server: string;
|
|
23
|
+
tool: ToolMetadata;
|
|
24
|
+
score: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
type SearchField = Exclude<keyof typeof FIELD_WEIGHTS, "keywords">;
|
|
28
|
+
|
|
29
|
+
interface PreparedToolSearch {
|
|
30
|
+
tool: ToolMetadata;
|
|
31
|
+
fields: Array<[SearchField, string, string[]]>;
|
|
32
|
+
nameTokens: string[];
|
|
33
|
+
keywordPhrases: string[];
|
|
34
|
+
keywordTokens: string[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface CachedServerSearch {
|
|
38
|
+
metadata: ToolMetadata[];
|
|
39
|
+
searchKeywords: ServerEntry["searchKeywords"];
|
|
40
|
+
toolPrefix: ReturnType<typeof resolveToolPrefix>;
|
|
41
|
+
withKeywords?: PreparedToolSearch[];
|
|
42
|
+
withoutKeywords?: PreparedToolSearch[];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const searchCache = new WeakMap<McpExtensionState, Map<string, CachedServerSearch>>();
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Resolve the configured searchKeywords entries that apply to a tool.
|
|
49
|
+
* Keys match by original name, prefixed name, or glob — the same candidate
|
|
50
|
+
* set includeTools/excludeTools use — and all matching entries are unioned.
|
|
51
|
+
*/
|
|
52
|
+
export function resolveSearchKeywords(
|
|
53
|
+
definition: ServerEntry | undefined,
|
|
54
|
+
toolOriginalName: string,
|
|
55
|
+
serverName: string,
|
|
56
|
+
globalPrefix: ToolPrefix,
|
|
57
|
+
): string[] {
|
|
58
|
+
const map = definition?.searchKeywords;
|
|
59
|
+
if (!map || typeof map !== "object" || Array.isArray(map)) return [];
|
|
60
|
+
const candidates = getToolNameCandidates(toolOriginalName, serverName, resolveToolPrefix(definition, globalPrefix));
|
|
61
|
+
const keywords: string[] = [];
|
|
62
|
+
const seen = new Set<string>();
|
|
63
|
+
for (const [pattern, values] of Object.entries(map)) {
|
|
64
|
+
if (!Array.isArray(values)) continue;
|
|
65
|
+
if (!matchesToolPattern(candidates, [pattern])) continue;
|
|
66
|
+
for (const value of values) {
|
|
67
|
+
if (typeof value !== "string") continue;
|
|
68
|
+
const trimmed = value.trim();
|
|
69
|
+
if (!trimmed || seen.has(trimmed)) continue;
|
|
70
|
+
seen.add(trimmed);
|
|
71
|
+
keywords.push(trimmed);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return keywords;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function normalizeSearchText(value: string): string {
|
|
78
|
+
return value
|
|
79
|
+
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
|
80
|
+
.replace(/[_./:-]+/g, " ")
|
|
81
|
+
.toLowerCase();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function tokenize(value: string): string[] {
|
|
85
|
+
return normalizeSearchText(value).split(/[^a-z0-9]+/).filter(Boolean);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function prepareToolSearch(tool: ToolMetadata, server: string, keywords?: string[]): PreparedToolSearch {
|
|
89
|
+
const fields = {
|
|
90
|
+
name: normalizeSearchText(tool.name),
|
|
91
|
+
originalName: normalizeSearchText(tool.originalName),
|
|
92
|
+
server: normalizeSearchText(server),
|
|
93
|
+
description: normalizeSearchText(tool.description),
|
|
94
|
+
};
|
|
95
|
+
const preparedFields = (Object.entries(fields) as Array<[SearchField, string]>)
|
|
96
|
+
.map(([field, value]): [SearchField, string, string[]] => [field, value, tokenize(value)]);
|
|
97
|
+
const keywordPhrases = keywords?.map(keyword => normalizeSearchText(keyword).trim()).filter(Boolean) ?? [];
|
|
98
|
+
return {
|
|
99
|
+
tool,
|
|
100
|
+
fields: preparedFields,
|
|
101
|
+
nameTokens: preparedFields[0]![2],
|
|
102
|
+
keywordPhrases,
|
|
103
|
+
keywordTokens: keywordPhrases.flatMap(tokenize),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function scorePreparedToolMatch(
|
|
108
|
+
prepared: PreparedToolSearch,
|
|
109
|
+
normalizedQuery: string,
|
|
110
|
+
queryTokens: string[],
|
|
111
|
+
): number | null {
|
|
112
|
+
let score = 0;
|
|
113
|
+
let phraseMatched = false;
|
|
114
|
+
let wholeFieldExact = false;
|
|
115
|
+
const matchedTokens = new Set<string>();
|
|
116
|
+
|
|
117
|
+
for (const [field, value, fieldTokens] of prepared.fields) {
|
|
118
|
+
const weight = FIELD_WEIGHTS[field];
|
|
119
|
+
if (value === normalizedQuery) {
|
|
120
|
+
score += weight * 14;
|
|
121
|
+
phraseMatched = true;
|
|
122
|
+
wholeFieldExact = true;
|
|
123
|
+
} else if (value.startsWith(normalizedQuery)) {
|
|
124
|
+
score += weight * 9;
|
|
125
|
+
phraseMatched = true;
|
|
126
|
+
} else if (value.includes(normalizedQuery)) {
|
|
127
|
+
score += weight * 6;
|
|
128
|
+
phraseMatched = true;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
for (const token of queryTokens) {
|
|
132
|
+
if (fieldTokens.includes(token)) {
|
|
133
|
+
score += weight * 4;
|
|
134
|
+
matchedTokens.add(token);
|
|
135
|
+
} else if (fieldTokens.some(fieldToken => fieldToken.startsWith(token) || (fieldToken.length >= MIN_STEM_LENGTH && token.startsWith(fieldToken)))) {
|
|
136
|
+
score += weight * 2;
|
|
137
|
+
matchedTokens.add(token);
|
|
138
|
+
} else if (value.includes(token)) {
|
|
139
|
+
score += weight;
|
|
140
|
+
matchedTokens.add(token);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Configured keywords are discrete phrases, so the phrase-level bonus is
|
|
146
|
+
// computed per phrase (best match wins) rather than on a joined string,
|
|
147
|
+
// which would phrase-match queries spanning two unrelated keywords.
|
|
148
|
+
if (prepared.keywordPhrases.length > 0) {
|
|
149
|
+
const weight = FIELD_WEIGHTS.keywords;
|
|
150
|
+
let phraseScore = 0;
|
|
151
|
+
for (const phrase of prepared.keywordPhrases) {
|
|
152
|
+
if (phrase === normalizedQuery) {
|
|
153
|
+
phraseScore = Math.max(phraseScore, weight * 14);
|
|
154
|
+
phraseMatched = true;
|
|
155
|
+
wholeFieldExact = true;
|
|
156
|
+
} else if (phrase.startsWith(normalizedQuery)) {
|
|
157
|
+
phraseScore = Math.max(phraseScore, weight * 9);
|
|
158
|
+
phraseMatched = true;
|
|
159
|
+
} else if (phrase.includes(normalizedQuery)) {
|
|
160
|
+
phraseScore = Math.max(phraseScore, weight * 6);
|
|
161
|
+
phraseMatched = true;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
score += phraseScore;
|
|
165
|
+
|
|
166
|
+
for (const token of queryTokens) {
|
|
167
|
+
if (prepared.keywordTokens.includes(token)) {
|
|
168
|
+
score += weight * 4;
|
|
169
|
+
matchedTokens.add(token);
|
|
170
|
+
} else if (prepared.keywordTokens.some(keywordToken => keywordToken.startsWith(token) || (keywordToken.length >= MIN_STEM_LENGTH && token.startsWith(keywordToken)))) {
|
|
171
|
+
score += weight * 2;
|
|
172
|
+
matchedTokens.add(token);
|
|
173
|
+
} else if (prepared.keywordPhrases.some(phrase => phrase.includes(token))) {
|
|
174
|
+
score += weight;
|
|
175
|
+
matchedTokens.add(token);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const coverage = matchedTokens.size / queryTokens.length;
|
|
181
|
+
if (!phraseMatched && (queryTokens.length <= 2 ? coverage !== 1 : coverage < 0.6)) return null;
|
|
182
|
+
|
|
183
|
+
score += coverage === 1 ? 25 : Math.round(coverage * 10);
|
|
184
|
+
const firstQueryToken = queryTokens[0];
|
|
185
|
+
if (firstQueryToken !== undefined && prepared.nameTokens.includes(firstQueryToken)) score += 8;
|
|
186
|
+
if (wholeFieldExact) score += 20;
|
|
187
|
+
return score;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export function scoreToolMatch(tool: ToolMetadata, server: string, query: string, keywords?: string[]): number | null {
|
|
191
|
+
const normalizedQuery = normalizeSearchText(query).trim();
|
|
192
|
+
const queryTokens = tokenize(query);
|
|
193
|
+
if (queryTokens.length === 0) return null;
|
|
194
|
+
return scorePreparedToolMatch(prepareToolSearch(tool, server, keywords), normalizedQuery, queryTokens);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function getPreparedTools(
|
|
198
|
+
state: McpExtensionState,
|
|
199
|
+
serverName: string,
|
|
200
|
+
metadata: ToolMetadata[],
|
|
201
|
+
definition: ServerEntry | undefined,
|
|
202
|
+
globalPrefix: ToolPrefix,
|
|
203
|
+
includeKeywords: boolean,
|
|
204
|
+
): PreparedToolSearch[] {
|
|
205
|
+
let stateCache = searchCache.get(state);
|
|
206
|
+
if (!stateCache) {
|
|
207
|
+
stateCache = new Map();
|
|
208
|
+
searchCache.set(state, stateCache);
|
|
209
|
+
}
|
|
210
|
+
const toolPrefix = resolveToolPrefix(definition, globalPrefix);
|
|
211
|
+
let cached = stateCache.get(serverName);
|
|
212
|
+
if (cached?.metadata !== metadata || cached.searchKeywords !== definition?.searchKeywords || cached.toolPrefix !== toolPrefix) {
|
|
213
|
+
cached = { metadata, searchKeywords: definition?.searchKeywords, toolPrefix };
|
|
214
|
+
stateCache.set(serverName, cached);
|
|
215
|
+
}
|
|
216
|
+
const cacheKey = includeKeywords ? "withKeywords" : "withoutKeywords";
|
|
217
|
+
let prepared = cached[cacheKey];
|
|
218
|
+
if (!prepared) {
|
|
219
|
+
prepared = metadata.map(tool => prepareToolSearch(
|
|
220
|
+
tool,
|
|
221
|
+
serverName,
|
|
222
|
+
includeKeywords && definition?.searchKeywords !== undefined
|
|
223
|
+
? resolveSearchKeywords(definition, tool.originalName, serverName, globalPrefix)
|
|
224
|
+
: undefined,
|
|
225
|
+
));
|
|
226
|
+
cached[cacheKey] = prepared;
|
|
227
|
+
}
|
|
228
|
+
return prepared;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export function rankToolMatches(
|
|
232
|
+
state: McpExtensionState,
|
|
233
|
+
query: string,
|
|
234
|
+
server?: string,
|
|
235
|
+
includeKeywords = true,
|
|
236
|
+
): RankedToolMatch[] {
|
|
237
|
+
const matches: RankedToolMatch[] = [];
|
|
238
|
+
const normalizedQuery = normalizeSearchText(query).trim();
|
|
239
|
+
const queryTokens = tokenize(query);
|
|
240
|
+
if (queryTokens.length === 0) return matches;
|
|
241
|
+
const globalPrefix = state.config.settings?.toolPrefix ?? "server";
|
|
242
|
+
for (const [serverName, metadata] of state.toolMetadata.entries()) {
|
|
243
|
+
if (server && serverName !== server) continue;
|
|
244
|
+
const definition = state.config.mcpServers[serverName];
|
|
245
|
+
if (isServerDisabled(definition)) continue;
|
|
246
|
+
if (isServerInActiveFailureBackoff(state, serverName)) continue;
|
|
247
|
+
for (const prepared of getPreparedTools(state, serverName, metadata, definition, globalPrefix, includeKeywords)) {
|
|
248
|
+
const score = scorePreparedToolMatch(prepared, normalizedQuery, queryTokens);
|
|
249
|
+
if (score !== null) matches.push({ server: serverName, tool: prepared.tool, score });
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
return matches.sort((a, b) => b.score - a.score || a.tool.name.localeCompare(b.tool.name));
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export function paginate<T>(items: T[], offset: number, limit: number): { items: T[]; total: number; hasMore: boolean; nextOffset: number | null } {
|
|
256
|
+
const safeOffset = Number.isFinite(offset) ? Math.max(0, Math.trunc(offset)) : 0;
|
|
257
|
+
const safeLimit = Number.isFinite(limit) ? Math.max(1, Math.trunc(limit)) : 1;
|
|
258
|
+
const total = items.length;
|
|
259
|
+
const page = items.slice(safeOffset, safeOffset + safeLimit);
|
|
260
|
+
const nextOffset = safeOffset + page.length;
|
|
261
|
+
return {
|
|
262
|
+
items: page,
|
|
263
|
+
total,
|
|
264
|
+
hasMore: nextOffset < total,
|
|
265
|
+
nextOffset: nextOffset < total ? nextOffset : null,
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export function rankSuggestions(state: McpExtensionState, name: string, limit: number): string[] {
|
|
270
|
+
const stripped = Object.keys(state.config.mcpServers)
|
|
271
|
+
.flatMap(server => (["server", "short", "mcp"] as const)
|
|
272
|
+
.map(prefix => getServerPrefix(server, prefix)))
|
|
273
|
+
.filter((candidate): candidate is string => Boolean(candidate) && name.startsWith(`${candidate}_`))
|
|
274
|
+
.sort((a, b) => b.length - a.length)
|
|
275
|
+
.map(candidate => name.slice(candidate.length + 1));
|
|
276
|
+
const query = stripped[0] ?? name;
|
|
277
|
+
return rankToolMatches(state, query, undefined, false).slice(0, limit).map(match => match.tool.name);
|
|
278
|
+
}
|