@duckmind/dm-windows-x64 0.63.6 → 0.63.9
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/dm.exe +0 -0
- package/extensions/.dm-extensions.json +174 -11
- package/extensions/dm-mcp-adapter/OAUTH.md +3 -0
- package/extensions/dm-mcp-adapter/THIRD_PARTY_NOTICES.md +4 -0
- package/extensions/dm-mcp-adapter/abort.js +35 -0
- package/extensions/dm-mcp-adapter/agent-dir.js +45 -0
- package/extensions/dm-mcp-adapter/agent-plugin-loader.js +349 -0
- package/extensions/dm-mcp-adapter/app-bridge.bundle.js +5843 -0
- package/extensions/dm-mcp-adapter/cli.js +354 -0
- package/extensions/dm-mcp-adapter/commands.js +619 -0
- package/extensions/dm-mcp-adapter/config.js +1060 -0
- package/extensions/dm-mcp-adapter/consent-manager.js +60 -0
- package/extensions/dm-mcp-adapter/direct-tools.js +544 -0
- package/extensions/dm-mcp-adapter/dist/agent-dir.js +45 -0
- package/extensions/dm-mcp-adapter/dist/agent-plugin-loader.js +349 -0
- package/extensions/dm-mcp-adapter/dist/config.js +1060 -0
- package/extensions/dm-mcp-adapter/dist/mcp-bearer-store.js +311 -0
- package/extensions/dm-mcp-adapter/dist/metadata-cache.js +285 -0
- package/extensions/dm-mcp-adapter/dist/package-mcp-loader.js +144 -0
- package/extensions/dm-mcp-adapter/dist/resource-tools.js +7 -0
- package/extensions/dm-mcp-adapter/dist/types.js +247 -0
- package/extensions/dm-mcp-adapter/dist/ui-app-bridge-helpers.js +36 -0
- package/extensions/dm-mcp-adapter/dist/ui-stream-types.js +58 -0
- package/extensions/dm-mcp-adapter/dist/ui-tool-visibility.js +26 -0
- package/extensions/dm-mcp-adapter/dist/utils.js +307 -0
- package/extensions/dm-mcp-adapter/elicitation-handler.js +306 -0
- package/extensions/dm-mcp-adapter/error-signal.js +16 -0
- package/extensions/dm-mcp-adapter/errors.js +225 -0
- package/extensions/dm-mcp-adapter/failure-backoff.js +19 -0
- package/extensions/dm-mcp-adapter/glimpse-ui.js +61 -0
- package/extensions/dm-mcp-adapter/host-html-template.js +464 -0
- package/extensions/dm-mcp-adapter/index.js +1079 -0
- package/extensions/dm-mcp-adapter/init.js +624 -0
- package/extensions/dm-mcp-adapter/json-schema-validator.js +53 -0
- package/extensions/dm-mcp-adapter/lifecycle.js +385 -0
- package/extensions/dm-mcp-adapter/logger.js +115 -0
- package/extensions/dm-mcp-adapter/mcp-auth-flow.js +824 -0
- package/extensions/dm-mcp-adapter/mcp-auth.js +732 -0
- package/extensions/dm-mcp-adapter/mcp-bearer-store.js +311 -0
- package/extensions/dm-mcp-adapter/mcp-callback-server.js +388 -0
- package/extensions/dm-mcp-adapter/mcp-code.js +291 -0
- package/extensions/dm-mcp-adapter/mcp-keyring-helper.cjs +88 -0
- package/extensions/dm-mcp-adapter/mcp-oauth-provider.js +490 -0
- package/extensions/dm-mcp-adapter/mcp-output-guard.js +386 -0
- package/extensions/dm-mcp-adapter/mcp-panel.js +951 -0
- package/extensions/dm-mcp-adapter/mcp-probe.js +151 -0
- package/extensions/dm-mcp-adapter/mcp-references.js +263 -0
- package/extensions/dm-mcp-adapter/mcp-script-worker.mjs +126 -0
- package/extensions/dm-mcp-adapter/mcp-setup-panel.js +578 -0
- package/extensions/dm-mcp-adapter/mcp-status.js +80 -0
- package/extensions/dm-mcp-adapter/mcp-trace.js +215 -0
- package/extensions/dm-mcp-adapter/metadata-cache.js +292 -0
- package/extensions/dm-mcp-adapter/namespace-tools.js +155 -0
- package/extensions/dm-mcp-adapter/npx-resolver.js +465 -0
- package/extensions/dm-mcp-adapter/oauth-handler.js +17 -0
- package/extensions/dm-mcp-adapter/oauth.js +17 -0
- package/extensions/dm-mcp-adapter/onboarding-state.js +62 -0
- package/extensions/dm-mcp-adapter/package-mcp-loader.js +144 -0
- package/extensions/dm-mcp-adapter/package.json +68 -0
- package/extensions/dm-mcp-adapter/panel-keys.js +26 -0
- package/extensions/dm-mcp-adapter/prompts.js +258 -0
- package/extensions/dm-mcp-adapter/proxy-modes.js +1336 -0
- package/extensions/dm-mcp-adapter/request-headers-command.js +293 -0
- package/extensions/dm-mcp-adapter/resource-tools.js +7 -0
- package/extensions/dm-mcp-adapter/runtime-owner.js +79 -0
- package/extensions/dm-mcp-adapter/sampling-handler.js +222 -0
- package/extensions/dm-mcp-adapter/sandbox-proxy-template.js +190 -0
- package/extensions/dm-mcp-adapter/search-ranking.js +198 -0
- package/extensions/dm-mcp-adapter/server-manager.js +1258 -0
- package/extensions/dm-mcp-adapter/session-recovery.js +82 -0
- package/extensions/dm-mcp-adapter/skills/mcp-scripting/SKILL.md +39 -0
- package/extensions/dm-mcp-adapter/state.js +0 -0
- package/extensions/dm-mcp-adapter/test-runner.mjs +18 -0
- package/extensions/dm-mcp-adapter/tool-approval.js +151 -0
- package/extensions/dm-mcp-adapter/tool-metadata.js +247 -0
- package/extensions/dm-mcp-adapter/tool-registrar.js +212 -0
- package/extensions/dm-mcp-adapter/tool-result-renderer.js +355 -0
- package/extensions/dm-mcp-adapter/ts-shape.js +157 -0
- package/extensions/dm-mcp-adapter/types.js +264 -0
- package/extensions/dm-mcp-adapter/ui-app-bridge-helpers.js +36 -0
- package/extensions/dm-mcp-adapter/ui-resource-handler.js +209 -0
- package/extensions/dm-mcp-adapter/ui-server.js +815 -0
- package/extensions/dm-mcp-adapter/ui-session.js +455 -0
- package/extensions/dm-mcp-adapter/ui-stream-types.js +58 -0
- package/extensions/dm-mcp-adapter/ui-tool-visibility.js +26 -0
- package/extensions/dm-mcp-adapter/unix-socket-transport.js +83 -0
- package/extensions/dm-mcp-adapter/utils.js +307 -0
- package/package.json +13 -1
- package/extensions/dm-localllm-provider/detect.test.js +0 -1051
- package/extensions/dm-localllm-provider/index.test.js +0 -149
- package/extensions/dm-localllm-provider/keychain.test.js +0 -61
|
@@ -0,0 +1,1336 @@
|
|
|
1
|
+
import { UrlElicitationRequiredError } from "@modelcontextprotocol/client";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { getServerPrefix, isServerDisabled, parseUiPromptHandoff } from "./types.js";
|
|
4
|
+
import { lazyConnect, markKeepAliveAfterConnect, notifyToolMetadataUpdated, updateServerMetadata, updateMetadataCache, getFailureAgeSeconds, updateStatusBar, clearFailure, recordFailure } from "./init.js";
|
|
5
|
+
import { abortable, throwIfAborted } from "./abort.js";
|
|
6
|
+
import { combineAbortSignals, isAbortError } from "./runtime-owner.js";
|
|
7
|
+
import { buildToolMetadata, getToolNames, findToolByName, formatSchema } from "./tool-metadata.js";
|
|
8
|
+
import { renderTsShape } from "./ts-shape.js";
|
|
9
|
+
import { reconstructPromptMetadata } from "./metadata-cache.js";
|
|
10
|
+
import { resolveMcpResultContent, transformMcpContent, transformMcpResourceContents } from "./tool-registrar.js";
|
|
11
|
+
import { guardMcpOutput, guardedMcpDetails, resolveMcpOutputGuardOptions } from "./mcp-output-guard.js";
|
|
12
|
+
import { maybeStartUiSession, summarizeUiSessionResult } from "./ui-session.js";
|
|
13
|
+
import { formatAuthRequiredMessage, formatMcpStatus, normalizeToolArguments, resolveServerUrl, truncateAtWord } from "./utils.js";
|
|
14
|
+
import { authenticate, completeAuthFromInput, startAuth, supportsOAuth } from "./mcp-auth-flow.js";
|
|
15
|
+
import { SessionRecoveryAuthRequiredError, withSessionRecovery } from "./session-recovery.js";
|
|
16
|
+
import { paginate, rankSuggestions, rankToolMatches, resolveSearchKeywords } from "./search-ranking.js";
|
|
17
|
+
import { ensureToolCallApproved, isToolCallApprovalRequired } from "./tool-approval.js";
|
|
18
|
+
import { isServerInActiveFailureBackoff } from "./failure-backoff.js";
|
|
19
|
+
import { getInputRequiredNeedsUiDetails } from "./errors.js";
|
|
20
|
+
const require = createRequire(import.meta.url);
|
|
21
|
+
const MAX_REGEX_SEARCH_QUERY_LENGTH = 256;
|
|
22
|
+
const INSTRUCTIONS_PREVIEW_LENGTH = 300;
|
|
23
|
+
const REGEX_SAFETY_CHECK_PARAMS = {
|
|
24
|
+
attackTimeout: 50,
|
|
25
|
+
incubationTimeout: 50,
|
|
26
|
+
timeout: 250
|
|
27
|
+
};
|
|
28
|
+
let nextProgressInvocationId = 1;
|
|
29
|
+
function withUiProgressBridge(options, ui, serverName, toolName) {
|
|
30
|
+
if (!ui)
|
|
31
|
+
return options;
|
|
32
|
+
const label = `MCP ${serverName}/${toolName}#${nextProgressInvocationId++}`;
|
|
33
|
+
return {
|
|
34
|
+
...options,
|
|
35
|
+
onprogress: (progress) => {
|
|
36
|
+
const ratio = `${progress.progress}${progress.total === undefined ? "" : `/${progress.total}`}`;
|
|
37
|
+
ui.notify(progress.message ? `${label}: ${progress.message} (${ratio})` : `${label}: ${ratio}`, "info");
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
function getToolMatches(metadata, toolName, exact) {
|
|
42
|
+
if (!metadata)
|
|
43
|
+
return [];
|
|
44
|
+
if (exact)
|
|
45
|
+
return metadata.filter((tool) => tool.name === toolName);
|
|
46
|
+
const normalizedName = toolName.replace(/-/g, "_");
|
|
47
|
+
return metadata.filter((tool) => tool.name.replace(/-/g, "_") === normalizedName);
|
|
48
|
+
}
|
|
49
|
+
function getEnabledToolMatches(state, toolName, exact) {
|
|
50
|
+
const matches = [];
|
|
51
|
+
for (const [server, metadata] of state.toolMetadata) {
|
|
52
|
+
if (isServerDisabled(state.config.mcpServers[server]))
|
|
53
|
+
continue;
|
|
54
|
+
for (const tool of getToolMatches(metadata, toolName, exact))
|
|
55
|
+
matches.push({ server, tool });
|
|
56
|
+
}
|
|
57
|
+
return matches;
|
|
58
|
+
}
|
|
59
|
+
function serverBackoffResult(state, mode, serverName) {
|
|
60
|
+
const failedAgo = getFailureAgeSeconds(state, serverName) ?? 0;
|
|
61
|
+
const message = `Server "${serverName}" not available (last failed ${failedAgo}s ago)`;
|
|
62
|
+
return {
|
|
63
|
+
content: [{ type: "text", text: message }],
|
|
64
|
+
details: { mode, error: "server_backoff", server: serverName }
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
function getSingleToolMatch(metadata, toolName) {
|
|
68
|
+
const exactMatches = getToolMatches(metadata, toolName, true);
|
|
69
|
+
const matches = exactMatches.length > 0 ? exactMatches : getToolMatches(metadata, toolName, false);
|
|
70
|
+
return matches.length > 1 ? "ambiguous" : matches[0];
|
|
71
|
+
}
|
|
72
|
+
function getServerScopedToolMatch(metadata, toolName) {
|
|
73
|
+
if (!metadata)
|
|
74
|
+
return;
|
|
75
|
+
const normalizedName = toolName.replace(/-/g, "_");
|
|
76
|
+
const matchesByPrecedence = [
|
|
77
|
+
metadata.filter((tool) => tool.name === toolName),
|
|
78
|
+
metadata.filter((tool) => tool.originalName === toolName),
|
|
79
|
+
metadata.filter((tool) => tool.name.replace(/-/g, "_") === normalizedName),
|
|
80
|
+
metadata.filter((tool) => tool.originalName.replace(/-/g, "_") === normalizedName)
|
|
81
|
+
];
|
|
82
|
+
for (const [precedence, matches] of matchesByPrecedence.entries()) {
|
|
83
|
+
if (matches.length > 1)
|
|
84
|
+
return "ambiguous";
|
|
85
|
+
if (matches.length === 1)
|
|
86
|
+
return { tool: matches[0], precedence };
|
|
87
|
+
}
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
function ambiguousToolResult(mode, toolName) {
|
|
91
|
+
const message = `Tool "${toolName}" matches multiple servers. Specify a server.`;
|
|
92
|
+
return {
|
|
93
|
+
content: [{ type: "text", text: message }],
|
|
94
|
+
details: { mode, error: "ambiguous_tool", requestedTool: toolName, message }
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
function disabledResult(mode, serverName) {
|
|
98
|
+
const message = `Server "${serverName}" is disabled. Run /mcp enable ${serverName} and /reload to enable it.`;
|
|
99
|
+
return {
|
|
100
|
+
content: [{ type: "text", text: message }],
|
|
101
|
+
details: { mode, error: "server_disabled", server: serverName, message }
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
function getAuthRequiredMessage(state, serverName, defaultMessage = `Server "${serverName}" requires OAuth authentication. Run mcp({ action: "auth-start", server: "${serverName}" }) to get a browser URL, or /mcp-auth ${serverName} in an interactive local session.`) {
|
|
105
|
+
return formatAuthRequiredMessage(state.config, serverName, defaultMessage);
|
|
106
|
+
}
|
|
107
|
+
function getAuthFailedMessage(state, serverName, message) {
|
|
108
|
+
const customGuidance = state.config.settings?.authRequiredMessage;
|
|
109
|
+
if (customGuidance) {
|
|
110
|
+
return `OAuth authentication failed for "${serverName}": ${message}. ${getAuthRequiredMessage(state, serverName)}`;
|
|
111
|
+
}
|
|
112
|
+
return `OAuth authentication failed for "${serverName}": ${message}. Run mcp({ action: "auth-start", server: "${serverName}" }) to get a browser URL, or /mcp-auth ${serverName} in an interactive local session.`;
|
|
113
|
+
}
|
|
114
|
+
function getRedirectDetails(authorizationUrl) {
|
|
115
|
+
try {
|
|
116
|
+
const redirectUri = new URL(authorizationUrl).searchParams.get("redirect_uri");
|
|
117
|
+
if (!redirectUri)
|
|
118
|
+
return { remote: false };
|
|
119
|
+
const redirect = new URL(redirectUri);
|
|
120
|
+
const hostname = redirect.hostname.toLowerCase();
|
|
121
|
+
const local = hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
|
|
122
|
+
const port = Number.parseInt(redirect.port, 10);
|
|
123
|
+
return {
|
|
124
|
+
...Number.isInteger(port) ? { port } : {},
|
|
125
|
+
remote: !local
|
|
126
|
+
};
|
|
127
|
+
} catch {
|
|
128
|
+
return { remote: false };
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function formatManualAuthInstructions(serverName, authorizationUrl) {
|
|
132
|
+
const redirect = getRedirectDetails(authorizationUrl);
|
|
133
|
+
const redirectNote = redirect.remote ? "The provider uses a pre-registered HTTPS callback. Copy its full URL from the browser address bar, even if the destination page reports an error." : redirect.port ? `The redirect URL will use local port ${redirect.port}. On a remote server it is expected for that localhost page to fail locally; copy the address bar URL anyway.` : "";
|
|
134
|
+
return [
|
|
135
|
+
`MCP OAuth required for "${serverName}".`,
|
|
136
|
+
"",
|
|
137
|
+
"Open this URL in your local browser:",
|
|
138
|
+
"",
|
|
139
|
+
authorizationUrl,
|
|
140
|
+
"",
|
|
141
|
+
"After approving, copy the full callback URL from your browser address bar and send it back with:",
|
|
142
|
+
`mcp({ action: "auth-complete", server: "${serverName}", args: { redirectUrl: "PASTE_REDIRECT_URL_HERE" } })`,
|
|
143
|
+
"",
|
|
144
|
+
redirect.remote ? "Remote HTTPS callbacks must include the full callback URL so the OAuth state can be checked. JSON-string args remain supported." : 'You can also pass just the `code` query parameter as `args: { code: "PASTE_CODE_HERE" }`. JSON-string args remain supported.',
|
|
145
|
+
redirectNote
|
|
146
|
+
].filter(Boolean).join(`
|
|
147
|
+
`);
|
|
148
|
+
}
|
|
149
|
+
async function attemptAutoAuth(state, serverName, signal) {
|
|
150
|
+
if (state.config.settings?.autoAuth !== true) {
|
|
151
|
+
return { status: "skipped" };
|
|
152
|
+
}
|
|
153
|
+
const definition = state.config.mcpServers[serverName];
|
|
154
|
+
if (!definition || isServerDisabled(definition) || !supportsOAuth(definition)) {
|
|
155
|
+
return { status: "skipped" };
|
|
156
|
+
}
|
|
157
|
+
let serverUrl;
|
|
158
|
+
try {
|
|
159
|
+
serverUrl = resolveServerUrl(definition);
|
|
160
|
+
} catch (error) {
|
|
161
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
162
|
+
return { status: "failed", message: getAuthFailedMessage(state, serverName, message) };
|
|
163
|
+
}
|
|
164
|
+
if (!serverUrl) {
|
|
165
|
+
return { status: "skipped" };
|
|
166
|
+
}
|
|
167
|
+
const grantType = definition.oauth ? definition.oauth.grantType ?? "authorization_code" : "authorization_code";
|
|
168
|
+
if (!state.ui && grantType !== "client_credentials") {
|
|
169
|
+
return {
|
|
170
|
+
status: "failed",
|
|
171
|
+
message: getAuthRequiredMessage(state, serverName, `Server "${serverName}" requires OAuth authentication. Run mcp({ action: "auth-start", server: "${serverName}" }) to get a browser URL, or /mcp-auth ${serverName} in an interactive local session.`)
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
try {
|
|
175
|
+
if (state.authStorageOptions) {
|
|
176
|
+
await authenticate(serverName, serverUrl, definition, signal ? { authStorageOptions: state.authStorageOptions, signal, runtime: state.oauthRuntime } : { authStorageOptions: state.authStorageOptions, runtime: state.oauthRuntime });
|
|
177
|
+
} else {
|
|
178
|
+
if (signal) {
|
|
179
|
+
await authenticate(serverName, serverUrl, definition, { signal, runtime: state.oauthRuntime });
|
|
180
|
+
} else {
|
|
181
|
+
await authenticate(serverName, serverUrl, definition, { runtime: state.oauthRuntime });
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return { status: "success" };
|
|
185
|
+
} catch (error) {
|
|
186
|
+
if (isAbortError(error, signal))
|
|
187
|
+
throw error;
|
|
188
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
189
|
+
return {
|
|
190
|
+
status: "failed",
|
|
191
|
+
message: getAuthFailedMessage(state, serverName, message)
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
export function executeUiMessages(state) {
|
|
196
|
+
const sessions = state.completedUiSessions;
|
|
197
|
+
if (sessions.length === 0) {
|
|
198
|
+
return {
|
|
199
|
+
content: [{ type: "text", text: "No UI session messages available." }],
|
|
200
|
+
details: { sessions: 0 }
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
const output = [];
|
|
204
|
+
output.push(`UI Session Messages (${sessions.length} session${sessions.length > 1 ? "s" : ""}):
|
|
205
|
+
`);
|
|
206
|
+
const allPrompts = [];
|
|
207
|
+
const allIntents = sessions.flatMap((session) => session.messages.intents);
|
|
208
|
+
const allContexts = sessions.flatMap((session) => session.messages.contexts);
|
|
209
|
+
const parsedHandoffs = [];
|
|
210
|
+
for (const session of sessions) {
|
|
211
|
+
const timestamp = session.completedAt.toLocaleTimeString();
|
|
212
|
+
output.push(`
|
|
213
|
+
## ${session.serverName} / ${session.toolName} (${timestamp}, ${session.reason})`);
|
|
214
|
+
const plainPrompts = [];
|
|
215
|
+
for (const prompt of session.messages.prompts) {
|
|
216
|
+
allPrompts.push(prompt);
|
|
217
|
+
const handoff = parseUiPromptHandoff(prompt);
|
|
218
|
+
if (handoff) {
|
|
219
|
+
parsedHandoffs.push(handoff);
|
|
220
|
+
} else {
|
|
221
|
+
plainPrompts.push(prompt);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (plainPrompts.length > 0) {
|
|
225
|
+
output.push(`
|
|
226
|
+
### Prompts:`);
|
|
227
|
+
for (const prompt of plainPrompts) {
|
|
228
|
+
output.push(`- ${prompt}`);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
const intentsForSession = [
|
|
232
|
+
...session.messages.intents,
|
|
233
|
+
...session.messages.prompts.map((prompt) => parseUiPromptHandoff(prompt)).filter((handoff) => !!handoff).map((handoff) => ({ intent: handoff.intent, params: handoff.params }))
|
|
234
|
+
];
|
|
235
|
+
if (intentsForSession.length > 0) {
|
|
236
|
+
output.push(`
|
|
237
|
+
### Intents:`);
|
|
238
|
+
for (const intent of intentsForSession) {
|
|
239
|
+
const params = intent.params ? ` (${JSON.stringify(intent.params)})` : "";
|
|
240
|
+
output.push(`- ${intent.intent}${params}`);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
const contexts = session.messages.contexts;
|
|
244
|
+
if (contexts.length > 0) {
|
|
245
|
+
output.push(`
|
|
246
|
+
### Context updates:`);
|
|
247
|
+
for (const context of contexts) {
|
|
248
|
+
output.push(`- ${context.summary}${context.truncated ? " (truncated)" : ""}`);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (session.messages.notifications.length > 0) {
|
|
252
|
+
output.push(`
|
|
253
|
+
### Notifications:`);
|
|
254
|
+
for (const notification of session.messages.notifications) {
|
|
255
|
+
output.push(`- ${notification}`);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
const count = sessions.length;
|
|
260
|
+
state.completedUiSessions = [];
|
|
261
|
+
return {
|
|
262
|
+
content: [{ type: "text", text: output.join(`
|
|
263
|
+
`) }],
|
|
264
|
+
details: {
|
|
265
|
+
sessions: count,
|
|
266
|
+
prompts: allPrompts,
|
|
267
|
+
intents: [...allIntents, ...parsedHandoffs.map(({ intent, params }) => ({ intent, params }))],
|
|
268
|
+
contexts: allContexts,
|
|
269
|
+
handoffs: parsedHandoffs,
|
|
270
|
+
cleared: true
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
export function executeStatus(state) {
|
|
275
|
+
const servers = [];
|
|
276
|
+
for (const name of Object.keys(state.config.mcpServers)) {
|
|
277
|
+
const definition = state.config.mcpServers[name];
|
|
278
|
+
const disabled = isServerDisabled(definition);
|
|
279
|
+
const connection = disabled ? undefined : state.manager.getConnection(name);
|
|
280
|
+
const metadata = disabled ? undefined : state.toolMetadata.get(name);
|
|
281
|
+
const failedAgo = disabled ? null : getFailureAgeSeconds(state, name);
|
|
282
|
+
let status = disabled ? "disabled" : "not connected";
|
|
283
|
+
if (!disabled && connection?.status === "connected") {
|
|
284
|
+
status = "connected";
|
|
285
|
+
} else if (!disabled && connection?.status === "needs-auth") {
|
|
286
|
+
status = "needs-auth";
|
|
287
|
+
} else if (!disabled && failedAgo !== null) {
|
|
288
|
+
status = "failed";
|
|
289
|
+
} else if (!disabled && metadata !== undefined) {
|
|
290
|
+
status = "cached";
|
|
291
|
+
}
|
|
292
|
+
const toolCount = status === "failed" ? 0 : metadata?.length ?? 0;
|
|
293
|
+
const listenState = connection?.status === "connected" ? connection.listenState : "disconnected";
|
|
294
|
+
servers.push({
|
|
295
|
+
name,
|
|
296
|
+
status,
|
|
297
|
+
listenState,
|
|
298
|
+
...connection?.status === "connected" && connection.listenCatalogStale ? { catalogStale: true } : {},
|
|
299
|
+
toolCount,
|
|
300
|
+
failedAgo,
|
|
301
|
+
...disabled ? { disabled: true } : {}
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
const disabledCount = servers.filter((s) => s.disabled).length;
|
|
305
|
+
const enabledServers = servers.filter((s) => !s.disabled);
|
|
306
|
+
const totalTools = enabledServers.reduce((sum, s) => sum + s.toolCount, 0);
|
|
307
|
+
const connectedCount = enabledServers.filter((s) => s.status === "connected").length;
|
|
308
|
+
let text = `MCP: ${connectedCount}/${enabledServers.length} servers, ${totalTools} tools`;
|
|
309
|
+
if (disabledCount > 0)
|
|
310
|
+
text += ` (${disabledCount} disabled)`;
|
|
311
|
+
text += `
|
|
312
|
+
|
|
313
|
+
`;
|
|
314
|
+
for (const server of servers) {
|
|
315
|
+
if (server.disabled) {
|
|
316
|
+
text += `⊘ ${server.name} (disabled)
|
|
317
|
+
`;
|
|
318
|
+
continue;
|
|
319
|
+
}
|
|
320
|
+
if (server.status === "connected") {
|
|
321
|
+
const listen = server.listenState === "active" ? server.catalogStale ? ", listen active, catalog may be stale" : ", listen active" : server.listenState === "dropped" ? ", catalog may be stale; will reconcile on next keep-alive or tool use" : server.listenState === "re-establishing" ? ", re-establishing listen" : server.listenState === "legacy" ? ", legacy notification path" : ", not listening for catalog updates";
|
|
322
|
+
text += `✓ ${server.name} (${server.toolCount} tools${listen})
|
|
323
|
+
`;
|
|
324
|
+
continue;
|
|
325
|
+
}
|
|
326
|
+
if (server.status === "needs-auth") {
|
|
327
|
+
text += `⚠ ${server.name} (needs auth)
|
|
328
|
+
`;
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
if (server.status === "cached") {
|
|
332
|
+
text += `○ ${server.name} (${server.toolCount} tools, cached; not listening)
|
|
333
|
+
`;
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
if (server.status === "failed") {
|
|
337
|
+
text += `✗ ${server.name} (failed ${server.failedAgo ?? 0}s ago)
|
|
338
|
+
`;
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
text += `○ ${server.name} (not listening; disconnected)
|
|
342
|
+
`;
|
|
343
|
+
}
|
|
344
|
+
const directToolsFrozen = state.config.settings?.freezeDirectTools === true;
|
|
345
|
+
if (directToolsFrozen) {
|
|
346
|
+
text += `
|
|
347
|
+
Direct tools frozen; active registrations may differ from current metadata.
|
|
348
|
+
`;
|
|
349
|
+
}
|
|
350
|
+
if (servers.length > 0) {
|
|
351
|
+
text += `
|
|
352
|
+
mcp({ server: "name" }) to list tools, mcp({ search: "..." }) to search`;
|
|
353
|
+
}
|
|
354
|
+
return {
|
|
355
|
+
content: [{ type: "text", text: text.trim() }],
|
|
356
|
+
details: { mode: "status", servers, totalTools, connectedCount, disabledCount, directToolsFrozen }
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
export async function executeAuthStart(state, serverName, signal) {
|
|
360
|
+
const ownedSignal = combineAbortSignals(state.owner?.signal, signal);
|
|
361
|
+
throwIfAborted(ownedSignal);
|
|
362
|
+
const definition = state.config.mcpServers[serverName];
|
|
363
|
+
if (!definition) {
|
|
364
|
+
return {
|
|
365
|
+
content: [{ type: "text", text: `Server "${serverName}" not found. Use mcp({}) to see available servers.` }],
|
|
366
|
+
details: { mode: "auth-start", error: "not_found", server: serverName }
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
if (isServerDisabled(definition))
|
|
370
|
+
return disabledResult("auth-start", serverName);
|
|
371
|
+
try {
|
|
372
|
+
const serverUrl = resolveServerUrl(definition);
|
|
373
|
+
if (!serverUrl || !supportsOAuth(definition)) {
|
|
374
|
+
return {
|
|
375
|
+
content: [{ type: "text", text: `Server "${serverName}" is not configured for OAuth over HTTP.` }],
|
|
376
|
+
details: { mode: "auth-start", error: "oauth_not_supported", server: serverName }
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
const { authorizationUrl } = state.authStorageOptions ? ownedSignal ? await startAuth(serverName, serverUrl, definition, { authStorageOptions: state.authStorageOptions, signal: ownedSignal, runtime: state.oauthRuntime }) : await startAuth(serverName, serverUrl, definition, { authStorageOptions: state.authStorageOptions, runtime: state.oauthRuntime }) : ownedSignal ? await startAuth(serverName, serverUrl, definition, { signal: ownedSignal, runtime: state.oauthRuntime }) : await startAuth(serverName, serverUrl, definition, { runtime: state.oauthRuntime });
|
|
380
|
+
if (!authorizationUrl) {
|
|
381
|
+
return {
|
|
382
|
+
content: [{ type: "text", text: `OAuth authentication successful for "${serverName}".` }],
|
|
383
|
+
details: { mode: "auth-start", server: serverName, authenticated: true }
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
return {
|
|
387
|
+
content: [{ type: "text", text: formatManualAuthInstructions(serverName, authorizationUrl) }],
|
|
388
|
+
details: { mode: "auth-start", server: serverName, authorizationUrl }
|
|
389
|
+
};
|
|
390
|
+
} catch (error) {
|
|
391
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
392
|
+
return {
|
|
393
|
+
content: [{ type: "text", text: `Failed to start OAuth for "${serverName}": ${message}` }],
|
|
394
|
+
details: { mode: "auth-start", error: "auth_start_failed", server: serverName, message }
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
export async function executeAuthComplete(state, serverName, input, signal) {
|
|
399
|
+
const ownedSignal = combineAbortSignals(state.owner?.signal, signal);
|
|
400
|
+
throwIfAborted(ownedSignal);
|
|
401
|
+
const definition = state.config.mcpServers[serverName];
|
|
402
|
+
if (!definition) {
|
|
403
|
+
return {
|
|
404
|
+
content: [{ type: "text", text: `Server "${serverName}" not found. Use mcp({}) to see available servers.` }],
|
|
405
|
+
details: { mode: "auth-complete", error: "not_found", server: serverName }
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
if (isServerDisabled(definition))
|
|
409
|
+
return disabledResult("auth-complete", serverName);
|
|
410
|
+
try {
|
|
411
|
+
const status = state.authStorageOptions ? ownedSignal ? await completeAuthFromInput(serverName, input, { authStorageOptions: state.authStorageOptions, signal: ownedSignal, runtime: state.oauthRuntime }) : await completeAuthFromInput(serverName, input, { authStorageOptions: state.authStorageOptions, runtime: state.oauthRuntime }) : ownedSignal ? await completeAuthFromInput(serverName, input, { signal: ownedSignal, runtime: state.oauthRuntime }) : await completeAuthFromInput(serverName, input, { runtime: state.oauthRuntime });
|
|
412
|
+
if (status !== "authenticated") {
|
|
413
|
+
return {
|
|
414
|
+
content: [{ type: "text", text: `OAuth authentication did not complete for "${serverName}".` }],
|
|
415
|
+
details: { mode: "auth-complete", error: "not_authenticated", server: serverName, status }
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
await state.manager.close(serverName);
|
|
419
|
+
clearFailure(state, serverName, "auth-complete");
|
|
420
|
+
updateStatusBar(state);
|
|
421
|
+
return {
|
|
422
|
+
content: [{ type: "text", text: `OAuth authentication successful for "${serverName}". Run mcp({ connect: "${serverName}" }) to connect with the new token.` }],
|
|
423
|
+
details: { mode: "auth-complete", server: serverName, authenticated: true }
|
|
424
|
+
};
|
|
425
|
+
} catch (error) {
|
|
426
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
427
|
+
return {
|
|
428
|
+
content: [{ type: "text", text: `Failed to complete OAuth for "${serverName}": ${message}` }],
|
|
429
|
+
details: { mode: "auth-complete", error: "auth_complete_failed", server: serverName, message }
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
export function executeDescribe(state, toolName) {
|
|
434
|
+
const exactMatches = getEnabledToolMatches(state, toolName, true).filter((match) => !isServerInActiveFailureBackoff(state, match.server));
|
|
435
|
+
if (exactMatches.length > 1)
|
|
436
|
+
return ambiguousToolResult("describe", toolName);
|
|
437
|
+
if (exactMatches.length === 0 && getEnabledToolMatches(state, toolName, false).filter((match) => !isServerInActiveFailureBackoff(state, match.server)).length > 1) {
|
|
438
|
+
return ambiguousToolResult("describe", toolName);
|
|
439
|
+
}
|
|
440
|
+
let serverName = exactMatches[0]?.server;
|
|
441
|
+
let toolMeta = exactMatches[0]?.tool;
|
|
442
|
+
let disabledMatch;
|
|
443
|
+
let failedMatch;
|
|
444
|
+
if (!toolMeta) {
|
|
445
|
+
for (const [server, metadata] of state.toolMetadata.entries()) {
|
|
446
|
+
const found = findToolByName(metadata, toolName);
|
|
447
|
+
if (!found)
|
|
448
|
+
continue;
|
|
449
|
+
if (isServerDisabled(state.config.mcpServers[server])) {
|
|
450
|
+
disabledMatch ??= server;
|
|
451
|
+
continue;
|
|
452
|
+
}
|
|
453
|
+
if (isServerInActiveFailureBackoff(state, server)) {
|
|
454
|
+
failedMatch ??= server;
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
457
|
+
serverName = server;
|
|
458
|
+
toolMeta = found;
|
|
459
|
+
break;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
if (!serverName || !toolMeta) {
|
|
463
|
+
if (disabledMatch)
|
|
464
|
+
return disabledResult("describe", disabledMatch);
|
|
465
|
+
if (failedMatch)
|
|
466
|
+
return serverBackoffResult(state, "describe", failedMatch);
|
|
467
|
+
const suggestions = rankSuggestions(state, toolName, 5);
|
|
468
|
+
const suggestionText = suggestions.length > 0 ? ` Did you mean: ${suggestions.join(", ")}` : "";
|
|
469
|
+
return {
|
|
470
|
+
content: [{ type: "text", text: `Tool "${toolName}" not found. Use mcp({ search: "..." }) to search.${suggestionText}` }],
|
|
471
|
+
details: { mode: "describe", error: "tool_not_found", requestedTool: toolName, suggestions }
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
const approvalMarker = isToolCallApprovalRequired(state.config, serverName, toolMeta, state.toolMetadata) ? " (requires approval)" : "";
|
|
475
|
+
let text = `${toolMeta.name}${approvalMarker}
|
|
476
|
+
`;
|
|
477
|
+
text += `Server: ${serverName}
|
|
478
|
+
`;
|
|
479
|
+
if (toolMeta.resourceUri) {
|
|
480
|
+
text += `Type: Resource (reads from ${toolMeta.resourceUri})
|
|
481
|
+
`;
|
|
482
|
+
}
|
|
483
|
+
text += `
|
|
484
|
+
${toolMeta.description || "(no description)"}
|
|
485
|
+
`;
|
|
486
|
+
if (toolMeta.inputSchema && !toolMeta.resourceUri) {
|
|
487
|
+
const shape = renderTsShape(toolMeta.inputSchema);
|
|
488
|
+
text += shape === null ? `
|
|
489
|
+
Parameters:
|
|
490
|
+
${formatSchema(toolMeta.inputSchema)}` : `
|
|
491
|
+
Shape:
|
|
492
|
+
${shape}`;
|
|
493
|
+
} else if (toolMeta.resourceUri) {
|
|
494
|
+
text += `
|
|
495
|
+
No parameters required (resource tool).`;
|
|
496
|
+
} else {
|
|
497
|
+
text += `
|
|
498
|
+
No parameters defined.`;
|
|
499
|
+
}
|
|
500
|
+
return {
|
|
501
|
+
content: [{ type: "text", text: text.trim() }],
|
|
502
|
+
details: { mode: "describe", tool: toolMeta, server: serverName }
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
export function executeSearch(state, query, regex, server, includeSchemas, limit = 12, offset = 0) {
|
|
506
|
+
const showSchemas = includeSchemas !== false;
|
|
507
|
+
if (server && isServerDisabled(state.config.mcpServers[server]))
|
|
508
|
+
return disabledResult("search", server);
|
|
509
|
+
if (server && isServerInActiveFailureBackoff(state, server))
|
|
510
|
+
return serverBackoffResult(state, "search", server);
|
|
511
|
+
let matches;
|
|
512
|
+
if (regex) {
|
|
513
|
+
let pattern;
|
|
514
|
+
try {
|
|
515
|
+
if (query.length > MAX_REGEX_SEARCH_QUERY_LENGTH) {
|
|
516
|
+
return {
|
|
517
|
+
content: [{ type: "text", text: `Regex query is too long; maximum length is ${MAX_REGEX_SEARCH_QUERY_LENGTH} characters.` }],
|
|
518
|
+
details: { mode: "search", error: "query_too_long", query, maxLength: MAX_REGEX_SEARCH_QUERY_LENGTH }
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
pattern = new RegExp(query, "i");
|
|
522
|
+
let safety;
|
|
523
|
+
try {
|
|
524
|
+
const { checkSync } = require("recheck");
|
|
525
|
+
safety = checkSync(query, "i", REGEX_SAFETY_CHECK_PARAMS);
|
|
526
|
+
} catch (error) {
|
|
527
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
528
|
+
return {
|
|
529
|
+
content: [{ type: "text", text: "Regex query rejected because safety analysis failed." }],
|
|
530
|
+
details: { mode: "search", error: "unsafe_pattern", query, reason }
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
if (safety.status !== "safe") {
|
|
534
|
+
return {
|
|
535
|
+
content: [{ type: "text", text: `Regex query rejected as unsafe (${safety.status}).` }],
|
|
536
|
+
details: { mode: "search", error: "unsafe_pattern", query, safetyStatus: safety.status }
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
} catch {
|
|
540
|
+
return {
|
|
541
|
+
content: [{ type: "text", text: `Invalid regex: ${query}` }],
|
|
542
|
+
details: { mode: "search", error: "invalid_pattern", query }
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
matches = [];
|
|
546
|
+
const globalPrefix = state.config.settings?.toolPrefix ?? "server";
|
|
547
|
+
for (const [serverName, metadata] of state.toolMetadata.entries()) {
|
|
548
|
+
const definition = state.config.mcpServers[serverName];
|
|
549
|
+
if (isServerDisabled(definition))
|
|
550
|
+
continue;
|
|
551
|
+
if (isServerInActiveFailureBackoff(state, serverName))
|
|
552
|
+
continue;
|
|
553
|
+
if (server && serverName !== server)
|
|
554
|
+
continue;
|
|
555
|
+
for (const tool of metadata) {
|
|
556
|
+
const matched = pattern.test(tool.name) || pattern.test(tool.description) || resolveSearchKeywords(definition, tool.originalName, serverName, globalPrefix).some((keyword) => pattern.test(keyword));
|
|
557
|
+
if (matched)
|
|
558
|
+
matches.push({ server: serverName, tool, score: 0 });
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
} else if (query.trim().length === 0) {
|
|
562
|
+
if (!server) {
|
|
563
|
+
return {
|
|
564
|
+
content: [{ type: "text", text: "Search query cannot be empty" }],
|
|
565
|
+
details: { mode: "search", error: "empty_query" }
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
matches = (state.toolMetadata.get(server) ?? []).map((tool) => ({ server, tool, score: 0 })).sort((a, b) => a.tool.name.localeCompare(b.tool.name));
|
|
569
|
+
} else {
|
|
570
|
+
matches = rankToolMatches(state, query, server);
|
|
571
|
+
}
|
|
572
|
+
const page = paginate(matches, offset, limit);
|
|
573
|
+
if (page.total === 0) {
|
|
574
|
+
const connectingServers = server ? state.config.mcpServers[server] && state.manager.isConnecting(server) ? [server] : [] : Object.keys(state.config.mcpServers).filter((name) => !isServerDisabled(state.config.mcpServers[name]) && state.manager.isConnecting(name)).sort((a, b) => a.localeCompare(b));
|
|
575
|
+
const msg = server ? `No tools matching "${query}" in "${server}"` : `No tools matching "${query}"`;
|
|
576
|
+
const connectingMessage = connectingServers.length === 1 ? ` Server "${connectingServers[0]}" is still connecting; retry in a moment.` : connectingServers.length > 1 ? ` Servers ${connectingServers.map((name) => `"${name}"`).join(", ")} are still connecting; retry in a moment.` : "";
|
|
577
|
+
return {
|
|
578
|
+
content: [{ type: "text", text: `${msg}${connectingMessage}` }],
|
|
579
|
+
details: {
|
|
580
|
+
mode: "search",
|
|
581
|
+
matches: [],
|
|
582
|
+
count: 0,
|
|
583
|
+
hasMore: false,
|
|
584
|
+
nextOffset: null,
|
|
585
|
+
query,
|
|
586
|
+
...connectingServers.length > 0 ? { connectingServers } : {}
|
|
587
|
+
}
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
let text = `Found ${page.total} tool${page.total === 1 ? "" : "s"} matching "${query}":
|
|
591
|
+
|
|
592
|
+
`;
|
|
593
|
+
for (const match of page.items) {
|
|
594
|
+
const approvalMarker = isToolCallApprovalRequired(state.config, match.server, match.tool, state.toolMetadata) ? " (requires approval)" : "";
|
|
595
|
+
if (showSchemas) {
|
|
596
|
+
text += `${match.tool.name}${approvalMarker}
|
|
597
|
+
`;
|
|
598
|
+
text += ` ${match.tool.description || "(no description)"}
|
|
599
|
+
`;
|
|
600
|
+
if (match.tool.inputSchema && !match.tool.resourceUri) {
|
|
601
|
+
const shape = renderTsShape(match.tool.inputSchema);
|
|
602
|
+
text += shape === null ? `
|
|
603
|
+
Parameters:
|
|
604
|
+
${formatSchema(match.tool.inputSchema, " ")}
|
|
605
|
+
` : `
|
|
606
|
+
Shape:
|
|
607
|
+
${shape.split(`
|
|
608
|
+
`).map((line) => ` ${line}`).join(`
|
|
609
|
+
`)}
|
|
610
|
+
`;
|
|
611
|
+
} else if (match.tool.resourceUri) {
|
|
612
|
+
text += ` No parameters (resource tool).
|
|
613
|
+
`;
|
|
614
|
+
}
|
|
615
|
+
text += `
|
|
616
|
+
`;
|
|
617
|
+
} else {
|
|
618
|
+
text += `- ${match.tool.name}${approvalMarker}`;
|
|
619
|
+
if (match.tool.description)
|
|
620
|
+
text += ` - ${truncateAtWord(match.tool.description, 50)}`;
|
|
621
|
+
text += `
|
|
622
|
+
`;
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
if (page.hasMore)
|
|
626
|
+
text += `
|
|
627
|
+
${page.items.length} of ${page.total} — offset: ${page.nextOffset} for more
|
|
628
|
+
`;
|
|
629
|
+
return {
|
|
630
|
+
content: [{ type: "text", text: text.trim() }],
|
|
631
|
+
details: {
|
|
632
|
+
mode: "search",
|
|
633
|
+
matches: page.items.map((match) => ({ server: match.server, tool: match.tool.name, score: match.score })),
|
|
634
|
+
count: page.total,
|
|
635
|
+
hasMore: page.hasMore,
|
|
636
|
+
nextOffset: page.nextOffset,
|
|
637
|
+
query
|
|
638
|
+
}
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
export function executeList(state, server) {
|
|
642
|
+
const definition = state.config.mcpServers[server];
|
|
643
|
+
if (!definition) {
|
|
644
|
+
return {
|
|
645
|
+
content: [{ type: "text", text: `Server "${server}" not found. Use mcp({}) to see available servers.` }],
|
|
646
|
+
details: { mode: "list", server, tools: [], count: 0, error: "not_found" }
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
if (isServerDisabled(definition))
|
|
650
|
+
return disabledResult("list", server);
|
|
651
|
+
const metadata = state.toolMetadata.get(server);
|
|
652
|
+
const toolNames = metadata?.map((m) => m.name) ?? [];
|
|
653
|
+
const connection = state.manager.getConnection(server);
|
|
654
|
+
if (isServerInActiveFailureBackoff(state, server)) {
|
|
655
|
+
return {
|
|
656
|
+
...serverBackoffResult(state, "list", server),
|
|
657
|
+
details: { mode: "list", server, tools: [], count: 0, error: "server_backoff" }
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
const instructions = state.serverInstructions.get(server);
|
|
661
|
+
let instructionsText = "";
|
|
662
|
+
if (instructions) {
|
|
663
|
+
const preview = truncateAtWord(instructions, INSTRUCTIONS_PREVIEW_LENGTH);
|
|
664
|
+
instructionsText = `
|
|
665
|
+
|
|
666
|
+
Server instructions:
|
|
667
|
+
${preview}`;
|
|
668
|
+
if (preview !== instructions) {
|
|
669
|
+
instructionsText += `
|
|
670
|
+
Use mcp({ instructions: "${server}" }) for the full text.`;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
if (toolNames.length === 0) {
|
|
674
|
+
if (connection?.status === "connected") {
|
|
675
|
+
return {
|
|
676
|
+
content: [{ type: "text", text: `Server "${server}" has no tools.${instructionsText}` }],
|
|
677
|
+
details: { mode: "list", server, tools: [], count: 0, hasInstructions: Boolean(instructions) }
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
if (metadata !== undefined) {
|
|
681
|
+
return {
|
|
682
|
+
content: [{ type: "text", text: `Server "${server}" has no cached tools (not connected).${instructionsText}` }],
|
|
683
|
+
details: { mode: "list", server, tools: [], count: 0, cached: true, hasInstructions: Boolean(instructions) }
|
|
684
|
+
};
|
|
685
|
+
}
|
|
686
|
+
return {
|
|
687
|
+
content: [{ type: "text", text: `Server "${server}" is configured but not connected. Use mcp({ connect: "${server}" }) or /mcp reconnect ${server} to retry.${instructionsText}` }],
|
|
688
|
+
details: { mode: "list", server, tools: [], count: 0, error: "not_connected", hasInstructions: Boolean(instructions) }
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
let cachedNote = "";
|
|
692
|
+
if (connection?.status !== "connected") {
|
|
693
|
+
if (connection?.status === "needs-auth") {
|
|
694
|
+
cachedNote = ` (needs auth — run mcp({ action: "auth-start", server: "${server}" }))`;
|
|
695
|
+
} else {
|
|
696
|
+
cachedNote = ` (lazy: tools from cache, not connected yet — mcp({ connect: "${server}" }) to connect)`;
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
let text = `${server} (${toolNames.length} tools${cachedNote}):
|
|
700
|
+
|
|
701
|
+
`;
|
|
702
|
+
const descMap = new Map;
|
|
703
|
+
if (metadata) {
|
|
704
|
+
for (const m of metadata) {
|
|
705
|
+
descMap.set(m.name, m.description);
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
for (const tool of toolNames) {
|
|
709
|
+
const desc = descMap.get(tool) ?? "";
|
|
710
|
+
const truncated = truncateAtWord(desc, 50);
|
|
711
|
+
text += `- ${tool}`;
|
|
712
|
+
if (truncated)
|
|
713
|
+
text += ` - ${truncated}`;
|
|
714
|
+
text += `
|
|
715
|
+
`;
|
|
716
|
+
}
|
|
717
|
+
text += instructionsText;
|
|
718
|
+
return {
|
|
719
|
+
content: [{ type: "text", text: text.trim() }],
|
|
720
|
+
details: { mode: "list", server, tools: toolNames, count: toolNames.length, hasInstructions: Boolean(instructions) }
|
|
721
|
+
};
|
|
722
|
+
}
|
|
723
|
+
export function executeInstructions(state, server) {
|
|
724
|
+
const definition = state.config.mcpServers[server];
|
|
725
|
+
if (!definition) {
|
|
726
|
+
return {
|
|
727
|
+
content: [{ type: "text", text: `Server "${server}" not found. Use mcp({}) to see available servers.` }],
|
|
728
|
+
details: { mode: "instructions", server, error: "not_found" }
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
if (isServerDisabled(definition))
|
|
732
|
+
return disabledResult("instructions", server);
|
|
733
|
+
if (isServerInActiveFailureBackoff(state, server))
|
|
734
|
+
return serverBackoffResult(state, "instructions", server);
|
|
735
|
+
const instructions = state.serverInstructions.get(server);
|
|
736
|
+
if (instructions) {
|
|
737
|
+
return {
|
|
738
|
+
content: [{ type: "text", text: `${server} instructions:
|
|
739
|
+
|
|
740
|
+
${instructions}` }],
|
|
741
|
+
details: { mode: "instructions", server, length: instructions.length }
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
const connection = state.manager.getConnection(server);
|
|
745
|
+
if (connection?.status === "connected") {
|
|
746
|
+
return {
|
|
747
|
+
content: [{ type: "text", text: `Server "${server}" does not provide instructions.` }],
|
|
748
|
+
details: { mode: "instructions", server, error: "no_instructions" }
|
|
749
|
+
};
|
|
750
|
+
}
|
|
751
|
+
return {
|
|
752
|
+
content: [{ type: "text", text: `No instructions cached for "${server}". Use mcp({ connect: "${server}" }) to connect and refresh.` }],
|
|
753
|
+
details: { mode: "instructions", server, error: "not_connected" }
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
export async function executeConnect(state, serverName, signal) {
|
|
757
|
+
const ownedSignal = combineAbortSignals(state.owner?.signal, signal);
|
|
758
|
+
throwIfAborted(ownedSignal);
|
|
759
|
+
const definition = state.config.mcpServers[serverName];
|
|
760
|
+
if (!definition) {
|
|
761
|
+
return {
|
|
762
|
+
content: [{ type: "text", text: `Server "${serverName}" not found. Use mcp({}) to see available servers.` }],
|
|
763
|
+
details: { mode: "connect", error: "not_found", server: serverName }
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
if (isServerDisabled(definition))
|
|
767
|
+
return disabledResult("connect", serverName);
|
|
768
|
+
try {
|
|
769
|
+
if (state.ui) {
|
|
770
|
+
state.ui.setStatus("mcp", formatMcpStatus(state.config, `connecting to ${serverName}...`));
|
|
771
|
+
}
|
|
772
|
+
const currentConnection = state.manager.getConnection(serverName);
|
|
773
|
+
let connection = currentConnection?.status === "connected" ? await state.manager.reconnect(serverName, definition, currentConnection, ownedSignal) : await state.manager.connect(serverName, definition, ownedSignal);
|
|
774
|
+
if (connection.status === "needs-auth") {
|
|
775
|
+
const autoAuth = await attemptAutoAuth(state, serverName, ownedSignal);
|
|
776
|
+
if (autoAuth.status === "failed") {
|
|
777
|
+
return {
|
|
778
|
+
content: [{ type: "text", text: autoAuth.message }],
|
|
779
|
+
details: { mode: "connect", error: "auth_required", server: serverName, message: autoAuth.message }
|
|
780
|
+
};
|
|
781
|
+
}
|
|
782
|
+
if (autoAuth.status === "success") {
|
|
783
|
+
await state.manager.close(serverName);
|
|
784
|
+
throwIfAborted(ownedSignal);
|
|
785
|
+
connection = ownedSignal ? await state.manager.connect(serverName, definition, ownedSignal) : await state.manager.connect(serverName, definition);
|
|
786
|
+
}
|
|
787
|
+
if (connection.status === "needs-auth") {
|
|
788
|
+
const message = getAuthRequiredMessage(state, serverName);
|
|
789
|
+
return {
|
|
790
|
+
content: [{ type: "text", text: message }],
|
|
791
|
+
details: { mode: "connect", error: "auth_required", server: serverName, message }
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
const prefix = state.config.settings?.toolPrefix ?? "server";
|
|
796
|
+
const { metadata } = buildToolMetadata(connection.tools, connection.resources, definition, serverName, prefix, state.config.mcpServers, state.toolMetadata);
|
|
797
|
+
state.toolMetadata.set(serverName, metadata);
|
|
798
|
+
if (!connection.promptDiscoveryFailed) {
|
|
799
|
+
state.promptMetadata?.set(serverName, reconstructPromptMetadata(serverName, connection.prompts ?? [], prefix, definition));
|
|
800
|
+
state.promptMetadataLive?.add(serverName);
|
|
801
|
+
}
|
|
802
|
+
if (connection.instructions) {
|
|
803
|
+
state.serverInstructions.set(serverName, connection.instructions);
|
|
804
|
+
} else {
|
|
805
|
+
state.serverInstructions.delete(serverName);
|
|
806
|
+
}
|
|
807
|
+
updateMetadataCache(state, serverName);
|
|
808
|
+
const restored = clearFailure(state, serverName, "proxy-connect");
|
|
809
|
+
if (!restored)
|
|
810
|
+
notifyToolMetadataUpdated(state, serverName, "proxy-connect");
|
|
811
|
+
markKeepAliveAfterConnect(state, serverName);
|
|
812
|
+
updateStatusBar(state);
|
|
813
|
+
return executeList(state, serverName);
|
|
814
|
+
} catch (error) {
|
|
815
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
816
|
+
if (!isAbortError(error, ownedSignal))
|
|
817
|
+
recordFailure(state, serverName, message);
|
|
818
|
+
updateStatusBar(state);
|
|
819
|
+
return {
|
|
820
|
+
content: [{ type: "text", text: `Failed to connect to "${serverName}": ${message}` }],
|
|
821
|
+
details: { mode: "connect", error: isAbortError(error, ownedSignal) ? "aborted" : "connect_failed", server: serverName, message }
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
export async function executeCall(state, toolName, args, serverOverride, getPiTools, signal, origin) {
|
|
826
|
+
const ownedSignal = combineAbortSignals(state.owner?.signal, signal);
|
|
827
|
+
throwIfAborted(ownedSignal);
|
|
828
|
+
let serverName = serverOverride;
|
|
829
|
+
let toolMeta;
|
|
830
|
+
let autoAuthAttempted = false;
|
|
831
|
+
const prefixMode = state.config.settings?.toolPrefix ?? "server";
|
|
832
|
+
const disabledCallResult = (disabledServer, metadata) => {
|
|
833
|
+
if (!metadata) {
|
|
834
|
+
const message = `Server "${disabledServer}" is disabled. Run /mcp enable ${disabledServer} and /reload to enable it.`;
|
|
835
|
+
return {
|
|
836
|
+
content: [{ type: "text", text: message }],
|
|
837
|
+
details: { mode: "call", error: "server_disabled", server: disabledServer, requestedTool: toolName, message }
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
const message = `Server "${disabledServer}" is disabled. Run /mcp enable ${disabledServer} and /reload to enable it.`;
|
|
841
|
+
const identity = metadata.resourceUri ? { server: disabledServer, resourceUri: metadata.resourceUri } : { server: disabledServer, tool: metadata.originalName };
|
|
842
|
+
return {
|
|
843
|
+
content: [{ type: "text", text: message }],
|
|
844
|
+
details: { mode: "call", error: "server_disabled", ...identity, message }
|
|
845
|
+
};
|
|
846
|
+
};
|
|
847
|
+
if (serverName && !state.config.mcpServers[serverName]) {
|
|
848
|
+
return {
|
|
849
|
+
content: [{ type: "text", text: `Server "${serverName}" not found. Use mcp({}) to see available servers.` }],
|
|
850
|
+
details: { mode: "call", error: "server_not_found", server: serverName, requestedTool: toolName }
|
|
851
|
+
};
|
|
852
|
+
}
|
|
853
|
+
if (serverName) {
|
|
854
|
+
const match = getServerScopedToolMatch(state.toolMetadata.get(serverName), toolName);
|
|
855
|
+
if (match === "ambiguous")
|
|
856
|
+
return ambiguousToolResult("call", toolName);
|
|
857
|
+
toolMeta = match?.tool;
|
|
858
|
+
if (isServerDisabled(state.config.mcpServers[serverName])) {
|
|
859
|
+
return disabledCallResult(serverName, toolMeta);
|
|
860
|
+
}
|
|
861
|
+
} else {
|
|
862
|
+
const exactMatches = getEnabledToolMatches(state, toolName, true);
|
|
863
|
+
if (exactMatches.length > 1)
|
|
864
|
+
return ambiguousToolResult("call", toolName);
|
|
865
|
+
if (exactMatches.length === 0 && getEnabledToolMatches(state, toolName, false).length > 1) {
|
|
866
|
+
return ambiguousToolResult("call", toolName);
|
|
867
|
+
}
|
|
868
|
+
let disabledMatch;
|
|
869
|
+
for (const [server, metadata] of state.toolMetadata.entries()) {
|
|
870
|
+
const found = metadata.find((tool) => tool.name === toolName);
|
|
871
|
+
if (!found)
|
|
872
|
+
continue;
|
|
873
|
+
if (isServerDisabled(state.config.mcpServers[server])) {
|
|
874
|
+
disabledMatch ??= { serverName: server, toolMeta: found };
|
|
875
|
+
continue;
|
|
876
|
+
}
|
|
877
|
+
serverName = server;
|
|
878
|
+
toolMeta = found;
|
|
879
|
+
break;
|
|
880
|
+
}
|
|
881
|
+
if (!toolMeta && !disabledMatch) {
|
|
882
|
+
for (const [server, metadata] of state.toolMetadata.entries()) {
|
|
883
|
+
const found = findToolByName(metadata, toolName);
|
|
884
|
+
if (!found)
|
|
885
|
+
continue;
|
|
886
|
+
if (isServerDisabled(state.config.mcpServers[server])) {
|
|
887
|
+
disabledMatch ??= { serverName: server, toolMeta: found };
|
|
888
|
+
continue;
|
|
889
|
+
}
|
|
890
|
+
serverName = server;
|
|
891
|
+
toolMeta = found;
|
|
892
|
+
break;
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
if (!toolMeta && disabledMatch)
|
|
896
|
+
return disabledCallResult(disabledMatch.serverName, disabledMatch.toolMeta);
|
|
897
|
+
}
|
|
898
|
+
if (serverName && !toolMeta) {
|
|
899
|
+
const connected = await lazyConnect(state, serverName, ownedSignal);
|
|
900
|
+
if (connected) {
|
|
901
|
+
if (serverOverride) {
|
|
902
|
+
const match = getServerScopedToolMatch(state.toolMetadata.get(serverName), toolName);
|
|
903
|
+
if (match === "ambiguous")
|
|
904
|
+
return ambiguousToolResult("call", toolName);
|
|
905
|
+
toolMeta = match?.tool;
|
|
906
|
+
} else {
|
|
907
|
+
const match = getSingleToolMatch(state.toolMetadata.get(serverName), toolName);
|
|
908
|
+
if (match === "ambiguous")
|
|
909
|
+
return ambiguousToolResult("call", toolName);
|
|
910
|
+
toolMeta = match;
|
|
911
|
+
}
|
|
912
|
+
} else {
|
|
913
|
+
const needsAuthConnection = state.manager.getConnection(serverName);
|
|
914
|
+
if (needsAuthConnection?.status === "needs-auth") {
|
|
915
|
+
if (!autoAuthAttempted) {
|
|
916
|
+
autoAuthAttempted = true;
|
|
917
|
+
const autoAuth = await attemptAutoAuth(state, serverName, ownedSignal);
|
|
918
|
+
if (autoAuth.status === "failed") {
|
|
919
|
+
return {
|
|
920
|
+
content: [{ type: "text", text: autoAuth.message }],
|
|
921
|
+
details: { mode: "call", error: "auth_required", server: serverName, requestedTool: toolName, message: autoAuth.message }
|
|
922
|
+
};
|
|
923
|
+
}
|
|
924
|
+
if (autoAuth.status === "success") {
|
|
925
|
+
await state.manager.close(serverName);
|
|
926
|
+
clearFailure(state, serverName);
|
|
927
|
+
const connectedAfterAuth = await lazyConnect(state, serverName, ownedSignal);
|
|
928
|
+
if (connectedAfterAuth) {
|
|
929
|
+
const match = getServerScopedToolMatch(state.toolMetadata.get(serverName), toolName);
|
|
930
|
+
if (match === "ambiguous")
|
|
931
|
+
return ambiguousToolResult("call", toolName);
|
|
932
|
+
toolMeta = match?.tool;
|
|
933
|
+
if (!toolMeta) {
|
|
934
|
+
const suggestions = rankSuggestions(state, toolName, 5);
|
|
935
|
+
const suggestionText = suggestions.length > 0 ? ` Did you mean: ${suggestions.join(", ")}` : "";
|
|
936
|
+
return {
|
|
937
|
+
content: [{ type: "text", text: `Tool "${toolName}" not found on "${serverName}" after reconnect.${suggestionText}` }],
|
|
938
|
+
details: { mode: "call", error: "tool_not_found_after_reconnect", server: serverName, requestedTool: toolName, suggestions }
|
|
939
|
+
};
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
if (!toolMeta && state.manager.getConnection(serverName)?.status === "needs-auth") {
|
|
945
|
+
const message = getAuthRequiredMessage(state, serverName);
|
|
946
|
+
return {
|
|
947
|
+
content: [{ type: "text", text: message }],
|
|
948
|
+
details: { mode: "call", error: "auth_required", server: serverName, requestedTool: toolName, message }
|
|
949
|
+
};
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
if (!toolMeta) {
|
|
953
|
+
const failedAgo = getFailureAgeSeconds(state, serverName);
|
|
954
|
+
if (failedAgo !== null) {
|
|
955
|
+
return {
|
|
956
|
+
content: [{ type: "text", text: `Server "${serverName}" not available (last failed ${failedAgo}s ago)` }],
|
|
957
|
+
details: { mode: "call", error: "server_backoff", server: serverName, requestedTool: toolName }
|
|
958
|
+
};
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
let prefixMatchedServer;
|
|
964
|
+
if (!serverName && !toolMeta && prefixMode !== "none") {
|
|
965
|
+
const lazyExactMatches = [];
|
|
966
|
+
const lazyFallbackMatches = [];
|
|
967
|
+
const candidates = Object.keys(state.config.mcpServers).filter((name) => !isServerDisabled(state.config.mcpServers[name])).map((name) => ({ name, prefix: getServerPrefix(name, prefixMode) })).filter((c) => c.prefix && toolName.startsWith(c.prefix + "_")).sort((a, b) => b.prefix.length - a.prefix.length);
|
|
968
|
+
for (const { name: configuredServer } of candidates) {
|
|
969
|
+
const existingConnection = state.manager.getConnection(configuredServer);
|
|
970
|
+
const failedAgo = getFailureAgeSeconds(state, configuredServer);
|
|
971
|
+
if (failedAgo !== null && existingConnection?.status !== "needs-auth")
|
|
972
|
+
continue;
|
|
973
|
+
let connected = await lazyConnect(state, configuredServer, ownedSignal);
|
|
974
|
+
if (!connected && state.manager.getConnection(configuredServer)?.status === "needs-auth" && !autoAuthAttempted) {
|
|
975
|
+
autoAuthAttempted = true;
|
|
976
|
+
const autoAuth = await attemptAutoAuth(state, configuredServer, ownedSignal);
|
|
977
|
+
if (autoAuth.status === "failed") {
|
|
978
|
+
return {
|
|
979
|
+
content: [{ type: "text", text: autoAuth.message }],
|
|
980
|
+
details: { mode: "call", error: "auth_required", server: configuredServer, requestedTool: toolName, message: autoAuth.message }
|
|
981
|
+
};
|
|
982
|
+
}
|
|
983
|
+
if (autoAuth.status === "success") {
|
|
984
|
+
await state.manager.close(configuredServer);
|
|
985
|
+
clearFailure(state, configuredServer);
|
|
986
|
+
connected = await lazyConnect(state, configuredServer, ownedSignal);
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
if (!connected)
|
|
990
|
+
continue;
|
|
991
|
+
if (!prefixMatchedServer)
|
|
992
|
+
prefixMatchedServer = configuredServer;
|
|
993
|
+
const metadata = state.toolMetadata.get(configuredServer);
|
|
994
|
+
const exactMatches = getToolMatches(metadata, toolName, true);
|
|
995
|
+
if (exactMatches.length > 1)
|
|
996
|
+
return ambiguousToolResult("call", toolName);
|
|
997
|
+
if (exactMatches.length === 1) {
|
|
998
|
+
lazyExactMatches.push({ serverName: configuredServer, toolMeta: exactMatches[0] });
|
|
999
|
+
continue;
|
|
1000
|
+
}
|
|
1001
|
+
const fallbackMatches = getToolMatches(metadata, toolName, false);
|
|
1002
|
+
if (fallbackMatches.length > 1)
|
|
1003
|
+
return ambiguousToolResult("call", toolName);
|
|
1004
|
+
if (fallbackMatches.length === 1)
|
|
1005
|
+
lazyFallbackMatches.push({ serverName: configuredServer, toolMeta: fallbackMatches[0] });
|
|
1006
|
+
}
|
|
1007
|
+
const lazyMatches = lazyExactMatches.length > 0 ? lazyExactMatches : lazyFallbackMatches;
|
|
1008
|
+
if (lazyMatches.length > 1)
|
|
1009
|
+
return ambiguousToolResult("call", toolName);
|
|
1010
|
+
if (lazyMatches.length === 1) {
|
|
1011
|
+
serverName = lazyMatches[0].serverName;
|
|
1012
|
+
toolMeta = lazyMatches[0].toolMeta;
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
if (!serverName || !toolMeta) {
|
|
1016
|
+
const nativeTool = !serverOverride ? getPiTools?.().find((tool) => tool.name === toolName && tool.name !== "mcp") : undefined;
|
|
1017
|
+
if (nativeTool) {
|
|
1018
|
+
return {
|
|
1019
|
+
content: [{ type: "text", text: `"${toolName}" is a native DM tool. Call ${toolName} directly instead of using mcp({ tool: "${toolName}" }).` }],
|
|
1020
|
+
details: { mode: "call", error: "native_tool", requestedTool: toolName }
|
|
1021
|
+
};
|
|
1022
|
+
}
|
|
1023
|
+
const hintServer = serverName ?? prefixMatchedServer;
|
|
1024
|
+
const available = hintServer ? getToolNames(state, hintServer) : [];
|
|
1025
|
+
let msg = `Tool "${toolName}" not found.`;
|
|
1026
|
+
if (available.length > 0) {
|
|
1027
|
+
msg += ` Server "${hintServer}" has: ${available.join(", ")}`;
|
|
1028
|
+
} else {
|
|
1029
|
+
msg += ` Use mcp({ search: "..." }) to search.`;
|
|
1030
|
+
}
|
|
1031
|
+
const suggestions = rankSuggestions(state, toolName, 5);
|
|
1032
|
+
if (suggestions.length > 0)
|
|
1033
|
+
msg += ` Did you mean: ${suggestions.join(", ")}`;
|
|
1034
|
+
return {
|
|
1035
|
+
content: [{ type: "text", text: msg }],
|
|
1036
|
+
details: { mode: "call", error: "tool_not_found", requestedTool: toolName, hintServer, suggestions }
|
|
1037
|
+
};
|
|
1038
|
+
}
|
|
1039
|
+
const callIdentity = toolMeta.resourceUri ? { server: serverName, resourceUri: toolMeta.resourceUri } : { server: serverName, tool: toolMeta.originalName };
|
|
1040
|
+
let connection = state.manager.getConnection(serverName);
|
|
1041
|
+
if (connection?.status === "needs-auth") {
|
|
1042
|
+
if (!autoAuthAttempted) {
|
|
1043
|
+
autoAuthAttempted = true;
|
|
1044
|
+
const autoAuth = await attemptAutoAuth(state, serverName, ownedSignal);
|
|
1045
|
+
if (autoAuth.status === "failed") {
|
|
1046
|
+
return {
|
|
1047
|
+
content: [{ type: "text", text: autoAuth.message }],
|
|
1048
|
+
details: { mode: "call", error: "auth_required", ...callIdentity, message: autoAuth.message }
|
|
1049
|
+
};
|
|
1050
|
+
}
|
|
1051
|
+
if (autoAuth.status === "success") {
|
|
1052
|
+
await state.manager.close(serverName);
|
|
1053
|
+
clearFailure(state, serverName);
|
|
1054
|
+
connection = state.manager.getConnection(serverName);
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
if (connection?.status === "needs-auth") {
|
|
1058
|
+
const message = getAuthRequiredMessage(state, serverName);
|
|
1059
|
+
return {
|
|
1060
|
+
content: [{ type: "text", text: message }],
|
|
1061
|
+
details: { mode: "call", error: "auth_required", ...callIdentity, message }
|
|
1062
|
+
};
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
if (!connection || connection.status !== "connected") {
|
|
1066
|
+
const failedAgo = getFailureAgeSeconds(state, serverName);
|
|
1067
|
+
if (failedAgo !== null) {
|
|
1068
|
+
return {
|
|
1069
|
+
content: [{ type: "text", text: `Server "${serverName}" not available (last failed ${failedAgo}s ago)` }],
|
|
1070
|
+
details: { mode: "call", error: "server_backoff", ...callIdentity }
|
|
1071
|
+
};
|
|
1072
|
+
}
|
|
1073
|
+
const definition = state.config.mcpServers[serverName];
|
|
1074
|
+
if (!definition) {
|
|
1075
|
+
return {
|
|
1076
|
+
content: [{ type: "text", text: `Server "${serverName}" not connected` }],
|
|
1077
|
+
details: { mode: "call", error: "server_not_connected", ...callIdentity }
|
|
1078
|
+
};
|
|
1079
|
+
}
|
|
1080
|
+
try {
|
|
1081
|
+
if (state.ui) {
|
|
1082
|
+
state.ui.setStatus("mcp", formatMcpStatus(state.config, `connecting to ${serverName}...`));
|
|
1083
|
+
}
|
|
1084
|
+
connection = await state.manager.connect(serverName, definition, ownedSignal);
|
|
1085
|
+
if (connection.status === "needs-auth") {
|
|
1086
|
+
if (!autoAuthAttempted) {
|
|
1087
|
+
autoAuthAttempted = true;
|
|
1088
|
+
const autoAuth = await attemptAutoAuth(state, serverName, ownedSignal);
|
|
1089
|
+
if (autoAuth.status === "failed") {
|
|
1090
|
+
return {
|
|
1091
|
+
content: [{ type: "text", text: autoAuth.message }],
|
|
1092
|
+
details: { mode: "call", error: "auth_required", ...callIdentity, message: autoAuth.message }
|
|
1093
|
+
};
|
|
1094
|
+
}
|
|
1095
|
+
if (autoAuth.status === "success") {
|
|
1096
|
+
await state.manager.close(serverName);
|
|
1097
|
+
connection = await state.manager.connect(serverName, definition, ownedSignal);
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
if (connection.status === "needs-auth") {
|
|
1101
|
+
const message = getAuthRequiredMessage(state, serverName);
|
|
1102
|
+
return {
|
|
1103
|
+
content: [{ type: "text", text: message }],
|
|
1104
|
+
details: { mode: "call", error: "auth_required", ...callIdentity, message }
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
updateServerMetadata(state, serverName);
|
|
1109
|
+
updateMetadataCache(state, serverName);
|
|
1110
|
+
const restored = clearFailure(state, serverName, "proxy-call-reconnect");
|
|
1111
|
+
if (!restored)
|
|
1112
|
+
notifyToolMetadataUpdated(state, serverName, "proxy-call-reconnect");
|
|
1113
|
+
markKeepAliveAfterConnect(state, serverName);
|
|
1114
|
+
updateStatusBar(state);
|
|
1115
|
+
if (serverOverride) {
|
|
1116
|
+
const match = getServerScopedToolMatch(state.toolMetadata.get(serverName), toolName);
|
|
1117
|
+
if (match === "ambiguous")
|
|
1118
|
+
return ambiguousToolResult("call", toolName);
|
|
1119
|
+
toolMeta = match?.tool;
|
|
1120
|
+
} else {
|
|
1121
|
+
const match = getSingleToolMatch(state.toolMetadata.get(serverName), toolName);
|
|
1122
|
+
if (match === "ambiguous")
|
|
1123
|
+
return ambiguousToolResult("call", toolName);
|
|
1124
|
+
toolMeta = match;
|
|
1125
|
+
}
|
|
1126
|
+
if (!toolMeta) {
|
|
1127
|
+
const available = getToolNames(state, serverName);
|
|
1128
|
+
const hint = available.length > 0 ? `Available tools on "${serverName}": ${available.join(", ")}` : `Server "${serverName}" has no tools.`;
|
|
1129
|
+
const suggestions = rankSuggestions(state, toolName, 5);
|
|
1130
|
+
const suggestionText = suggestions.length > 0 ? ` Did you mean: ${suggestions.join(", ")}` : "";
|
|
1131
|
+
return {
|
|
1132
|
+
content: [{ type: "text", text: `Tool "${toolName}" not found on "${serverName}" after reconnect. ${hint}${suggestionText}` }],
|
|
1133
|
+
details: { mode: "call", error: "tool_not_found_after_reconnect", server: serverName, requestedTool: toolName, suggestions }
|
|
1134
|
+
};
|
|
1135
|
+
}
|
|
1136
|
+
} catch (error) {
|
|
1137
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1138
|
+
if (!isAbortError(error, ownedSignal))
|
|
1139
|
+
recordFailure(state, serverName, message);
|
|
1140
|
+
updateStatusBar(state);
|
|
1141
|
+
return {
|
|
1142
|
+
content: [{ type: "text", text: `Failed to connect to "${serverName}": ${message}` }],
|
|
1143
|
+
details: { mode: "call", error: isAbortError(error, ownedSignal) ? "aborted" : "connect_failed", ...callIdentity, message }
|
|
1144
|
+
};
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
if (isServerDisabled(state.config.mcpServers[serverName])) {
|
|
1148
|
+
return disabledCallResult(serverName, toolMeta);
|
|
1149
|
+
}
|
|
1150
|
+
const normalizedArgs = toolMeta.resourceUri ? args ?? {} : normalizeToolArguments(args);
|
|
1151
|
+
const approval = await ensureToolCallApproved(state, serverName, toolMeta, normalizedArgs, ownedSignal, origin ?? (toolMeta.resourceUri ? "resource" : "proxy"));
|
|
1152
|
+
if (approval.ok === false) {
|
|
1153
|
+
const denied = approval.reason === "denied";
|
|
1154
|
+
const message = denied ? `The user declined approval to run MCP tool "${toolMeta.originalName}" on server "${serverName}".` : `MCP tool "${toolMeta.originalName}" on server "${serverName}" is approval-gated and requires an interactive session.`;
|
|
1155
|
+
return {
|
|
1156
|
+
content: [{ type: "text", text: message }],
|
|
1157
|
+
details: {
|
|
1158
|
+
mode: "call",
|
|
1159
|
+
error: denied ? "approval_denied" : "approval_required",
|
|
1160
|
+
server: serverName,
|
|
1161
|
+
tool: toolMeta.originalName
|
|
1162
|
+
}
|
|
1163
|
+
};
|
|
1164
|
+
}
|
|
1165
|
+
let uiSession = null;
|
|
1166
|
+
const requestOptions = withUiProgressBridge(state.manager.getRequestOptions?.(serverName, ownedSignal) ?? (ownedSignal ? { signal: ownedSignal } : undefined), state.ui, serverName, toolMeta.originalName);
|
|
1167
|
+
const outputGuardOptions = resolveMcpOutputGuardOptions(state.config.settings);
|
|
1168
|
+
const recoverAuthConnection = async () => {
|
|
1169
|
+
const current = state.manager.getConnection(serverName);
|
|
1170
|
+
if (current?.status === "connected")
|
|
1171
|
+
return current;
|
|
1172
|
+
if (!autoAuthAttempted) {
|
|
1173
|
+
autoAuthAttempted = true;
|
|
1174
|
+
const autoAuth = await attemptAutoAuth(state, serverName, ownedSignal);
|
|
1175
|
+
if (autoAuth.status === "failed") {
|
|
1176
|
+
throw new SessionRecoveryAuthRequiredError(serverName, autoAuth.message);
|
|
1177
|
+
}
|
|
1178
|
+
if (autoAuth.status === "success") {
|
|
1179
|
+
const definition = state.config.mcpServers[serverName];
|
|
1180
|
+
if (!definition)
|
|
1181
|
+
return;
|
|
1182
|
+
const afterAuth = state.manager.getConnection(serverName);
|
|
1183
|
+
if (afterAuth?.status === "connected")
|
|
1184
|
+
return afterAuth;
|
|
1185
|
+
if (afterAuth?.status === "needs-auth") {
|
|
1186
|
+
await state.manager.close(serverName);
|
|
1187
|
+
}
|
|
1188
|
+
clearFailure(state, serverName);
|
|
1189
|
+
connection = await state.manager.connect(serverName, definition, ownedSignal);
|
|
1190
|
+
return connection;
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
return state.manager.getConnection(serverName);
|
|
1194
|
+
};
|
|
1195
|
+
try {
|
|
1196
|
+
state.manager.touch(serverName);
|
|
1197
|
+
state.manager.incrementInFlight(serverName);
|
|
1198
|
+
if (toolMeta.resourceUri) {
|
|
1199
|
+
const result = await withSessionRecovery({
|
|
1200
|
+
manager: state.manager,
|
|
1201
|
+
config: state.config,
|
|
1202
|
+
...ownedSignal ? { signal: ownedSignal } : {},
|
|
1203
|
+
onNeedsAuth: recoverAuthConnection
|
|
1204
|
+
}, serverName, async (conn) => {
|
|
1205
|
+
const refreshRead = await state.manager.prepareResourceUse?.(serverName, toolMeta.resourceUri, conn);
|
|
1206
|
+
return conn.client.readResource({ uri: toolMeta.resourceUri }, refreshRead ? { ...requestOptions, cacheMode: "refresh" } : requestOptions);
|
|
1207
|
+
});
|
|
1208
|
+
const content = transformMcpResourceContents(result.contents ?? [], state.owner?.signal);
|
|
1209
|
+
const guarded = await guardMcpOutput(content.length > 0 ? content : [{ type: "text", text: "(empty resource)" }], outputGuardOptions);
|
|
1210
|
+
return {
|
|
1211
|
+
content: guarded.content,
|
|
1212
|
+
details: { mode: "call", ...callIdentity, ...guardedMcpDetails(guarded) }
|
|
1213
|
+
};
|
|
1214
|
+
}
|
|
1215
|
+
uiSession = toolMeta.uiResourceUri ? await maybeStartUiSession(state, {
|
|
1216
|
+
serverName,
|
|
1217
|
+
toolName: toolMeta.originalName,
|
|
1218
|
+
toolArgs: normalizedArgs,
|
|
1219
|
+
uiResourceUri: toolMeta.uiResourceUri,
|
|
1220
|
+
...toolMeta.uiStreamMode !== undefined ? { streamMode: toolMeta.uiStreamMode } : {},
|
|
1221
|
+
...signal ? { signal } : {},
|
|
1222
|
+
onNeedsAuth: recoverAuthConnection
|
|
1223
|
+
}) : null;
|
|
1224
|
+
const result = await withSessionRecovery({
|
|
1225
|
+
manager: state.manager,
|
|
1226
|
+
config: state.config,
|
|
1227
|
+
...ownedSignal ? { signal: ownedSignal } : {},
|
|
1228
|
+
onNeedsAuth: recoverAuthConnection
|
|
1229
|
+
}, serverName, async (conn) => {
|
|
1230
|
+
await state.manager.ensureListen?.(serverName, conn);
|
|
1231
|
+
return abortable(conn.client.callTool({
|
|
1232
|
+
name: toolMeta.originalName,
|
|
1233
|
+
arguments: normalizedArgs,
|
|
1234
|
+
_meta: uiSession?.requestMeta
|
|
1235
|
+
}, requestOptions), ownedSignal);
|
|
1236
|
+
});
|
|
1237
|
+
if (toolMeta.uiResourceUri) {
|
|
1238
|
+
uiSession?.sendToolResult(result);
|
|
1239
|
+
if (result.isError) {
|
|
1240
|
+
const mcpContent = result.content ?? [];
|
|
1241
|
+
const content = transformMcpContent(mcpContent, state.owner?.signal);
|
|
1242
|
+
const outputContent = content.length > 0 ? content : [{ type: "text", text: "(empty result)" }];
|
|
1243
|
+
const schemaText = toolMeta.inputSchema ? `
|
|
1244
|
+
|
|
1245
|
+
Expected parameters:
|
|
1246
|
+
${formatSchema(toolMeta.inputSchema)}` : "";
|
|
1247
|
+
const guarded = await guardMcpOutput(outputContent, { ...outputGuardOptions, prefix: "Error: ", suffix: schemaText, emptyTextFallback: "Tool execution failed", rawMcpResult: result });
|
|
1248
|
+
return {
|
|
1249
|
+
content: guarded.content,
|
|
1250
|
+
details: { mode: "call", error: "tool_error", ...callIdentity, ...guardedMcpDetails(guarded) }
|
|
1251
|
+
};
|
|
1252
|
+
}
|
|
1253
|
+
const content = resolveMcpResultContent(result, state.owner?.signal);
|
|
1254
|
+
const outputContent = content.length > 0 ? content : [{ type: "text", text: "(empty result)" }];
|
|
1255
|
+
const uiSummary = summarizeUiSessionResult(uiSession);
|
|
1256
|
+
const guarded = await guardMcpOutput(outputContent, { ...outputGuardOptions, suffix: `
|
|
1257
|
+
|
|
1258
|
+
${uiSummary.message}`, rawMcpResult: result });
|
|
1259
|
+
return {
|
|
1260
|
+
content: guarded.content,
|
|
1261
|
+
details: {
|
|
1262
|
+
mode: "call",
|
|
1263
|
+
...guardedMcpDetails(guarded),
|
|
1264
|
+
...callIdentity,
|
|
1265
|
+
uiOpen: uiSummary.uiOpen,
|
|
1266
|
+
uiViewer: uiSummary.uiViewer,
|
|
1267
|
+
uiUrl: uiSummary.uiUrl
|
|
1268
|
+
}
|
|
1269
|
+
};
|
|
1270
|
+
}
|
|
1271
|
+
if (result.isError) {
|
|
1272
|
+
const mcpContent = result.content ?? [];
|
|
1273
|
+
const content = transformMcpContent(mcpContent, state.owner?.signal);
|
|
1274
|
+
const outputContent = content.length > 0 ? content : [{ type: "text", text: "(empty result)" }];
|
|
1275
|
+
const schemaText = toolMeta.inputSchema ? `
|
|
1276
|
+
|
|
1277
|
+
Expected parameters:
|
|
1278
|
+
${formatSchema(toolMeta.inputSchema)}` : "";
|
|
1279
|
+
const guarded = await guardMcpOutput(outputContent, { ...outputGuardOptions, prefix: "Error: ", suffix: schemaText, emptyTextFallback: "Tool execution failed", rawMcpResult: result });
|
|
1280
|
+
return {
|
|
1281
|
+
content: guarded.content,
|
|
1282
|
+
details: { mode: "call", error: "tool_error", ...callIdentity, ...guardedMcpDetails(guarded) }
|
|
1283
|
+
};
|
|
1284
|
+
}
|
|
1285
|
+
const content = resolveMcpResultContent(result, state.owner?.signal);
|
|
1286
|
+
const outputContent = content.length > 0 ? content : [{ type: "text", text: "(empty result)" }];
|
|
1287
|
+
const guarded = await guardMcpOutput(outputContent, { ...outputGuardOptions, rawMcpResult: result });
|
|
1288
|
+
return {
|
|
1289
|
+
content: guarded.content,
|
|
1290
|
+
details: { mode: "call", ...guardedMcpDetails(guarded), ...callIdentity }
|
|
1291
|
+
};
|
|
1292
|
+
} catch (error) {
|
|
1293
|
+
if (error instanceof SessionRecoveryAuthRequiredError) {
|
|
1294
|
+
const message = error.authMessage ?? getAuthRequiredMessage(state, serverName);
|
|
1295
|
+
uiSession?.sendToolCancelled(message);
|
|
1296
|
+
return {
|
|
1297
|
+
content: [{ type: "text", text: message }],
|
|
1298
|
+
details: { mode: "call", error: "auth_required", ...callIdentity, message, autoAuthAttempted }
|
|
1299
|
+
};
|
|
1300
|
+
}
|
|
1301
|
+
if (error instanceof UrlElicitationRequiredError) {
|
|
1302
|
+
const action = await state.manager.handleUrlElicitationRequired(serverName, error);
|
|
1303
|
+
const message = action === "accept" ? "The original MCP tool did not run. Complete the opened browser interaction, then retry the tool." : `The URL interaction was ${action === "decline" ? "declined" : "cancelled"}.`;
|
|
1304
|
+
uiSession?.sendToolCancelled(message);
|
|
1305
|
+
return {
|
|
1306
|
+
content: [{ type: "text", text: message }],
|
|
1307
|
+
details: { mode: "call", error: "url_elicitation_required", ...callIdentity, action }
|
|
1308
|
+
};
|
|
1309
|
+
}
|
|
1310
|
+
const inputRequired = getInputRequiredNeedsUiDetails(error, callIdentity);
|
|
1311
|
+
if (inputRequired) {
|
|
1312
|
+
uiSession?.sendToolCancelled(inputRequired.message);
|
|
1313
|
+
return {
|
|
1314
|
+
content: [{ type: "text", text: inputRequired.message }],
|
|
1315
|
+
details: { mode: "call", ...inputRequired }
|
|
1316
|
+
};
|
|
1317
|
+
}
|
|
1318
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1319
|
+
uiSession?.sendToolCancelled(message);
|
|
1320
|
+
const schemaText = toolMeta.inputSchema ? `
|
|
1321
|
+
|
|
1322
|
+
Expected parameters:
|
|
1323
|
+
${formatSchema(toolMeta.inputSchema)}` : "";
|
|
1324
|
+
const guarded = await guardMcpOutput([{ type: "text", text: message }], { ...outputGuardOptions, prefix: "Failed to call tool: ", suffix: schemaText });
|
|
1325
|
+
return {
|
|
1326
|
+
content: guarded.content,
|
|
1327
|
+
details: { mode: "call", error: isAbortError(error, ownedSignal) ? "aborted" : "call_failed", ...callIdentity, message: guarded.outputGuard ? "output truncated; see outputGuard.fullOutputPath" : message, ...guardedMcpDetails(guarded) }
|
|
1328
|
+
};
|
|
1329
|
+
} finally {
|
|
1330
|
+
if (uiSession?.reused) {
|
|
1331
|
+
uiSession.close();
|
|
1332
|
+
}
|
|
1333
|
+
state.manager.decrementInFlight(serverName);
|
|
1334
|
+
state.manager.touch(serverName);
|
|
1335
|
+
}
|
|
1336
|
+
}
|