@herbertgao/pi-extensions 2026.9.17 → 2026.9.18
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/README.md +14 -15
- package/node_modules/@herbertgao/pi-bark/package.json +2 -2
- package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +4 -1
- package/node_modules/@herbertgao/pi-cc-extensions/README.md +4 -1
- package/node_modules/@herbertgao/pi-cc-extensions/package.json +75 -75
- package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +6 -0
- package/node_modules/@herbertgao/pi-subagents/package.json +7 -7
- package/node_modules/@herbertgao/resume-from/package.json +4 -2
- package/node_modules/@herbertgao/sol-pi/package.json +6 -6
- package/node_modules/@juicesharp/rpiv-ask-user-question/package.json +99 -99
- package/node_modules/@pi-plugins/fast-mode/package.json +1 -1
- package/node_modules/@tifan/pi-handoff/package.json +1 -1
- package/node_modules/@tifan/pi-handoff/src/index.ts +56 -26
- package/node_modules/@tifan/pi-mermaid-open/package.json +1 -1
- package/node_modules/@tifan/pi-preferred-thinking/package.json +1 -1
- package/node_modules/@tifan/pi-recap/package.json +1 -1
- package/node_modules/@tifan/pi-rename/package.json +1 -1
- package/node_modules/pi-antigravity/package.json +2 -2
- package/node_modules/pi-lens/package.json +158 -158
- package/node_modules/pi-multi-account/package.json +2 -2
- package/node_modules/pi-typesafe/README.md +1 -1
- package/node_modules/pi-typesafe/dist/auth.d.ts +9 -5
- package/node_modules/pi-typesafe/dist/auth.js +7 -3
- package/node_modules/pi-typesafe/dist/backends.d.ts +33 -3
- package/node_modules/pi-typesafe/dist/backends.js +95 -1
- package/node_modules/pi-typesafe/dist/client.d.ts +5 -5
- package/node_modules/pi-typesafe/dist/client.js +12 -9
- package/node_modules/pi-typesafe/dist/credentials.d.ts +14 -8
- package/node_modules/pi-typesafe/dist/credentials.js +10 -7
- package/node_modules/pi-typesafe/dist/errors.d.ts +2 -2
- package/node_modules/pi-typesafe/dist/index.d.ts +2 -2
- package/node_modules/pi-typesafe/dist/index.js +1 -1
- package/node_modules/pi-typesafe/dist/login.d.ts +2 -2
- package/node_modules/pi-typesafe/dist/login.js +2 -2
- package/node_modules/pi-typesafe/package.json +5 -5
- package/node_modules/pi-web-access/package.json +2 -2
- package/node_modules/remote-pi/package.json +5 -1
- package/package.json +16 -28
- package/node_modules/pi-mcp-adapter/CHANGELOG.md +0 -1013
- package/node_modules/pi-mcp-adapter/LICENSE +0 -21
- package/node_modules/pi-mcp-adapter/OAUTH.md +0 -369
- package/node_modules/pi-mcp-adapter/README.md +0 -1021
- package/node_modules/pi-mcp-adapter/abort.ts +0 -34
- package/node_modules/pi-mcp-adapter/agent-dir.ts +0 -68
- package/node_modules/pi-mcp-adapter/agent-plugin-loader.ts +0 -416
- package/node_modules/pi-mcp-adapter/agent-plugin-provenance.ts +0 -36
- package/node_modules/pi-mcp-adapter/app-bridge.bundle.js +0 -67
- package/node_modules/pi-mcp-adapter/banner.png +0 -0
- package/node_modules/pi-mcp-adapter/bearer-command-resolver.ts +0 -193
- package/node_modules/pi-mcp-adapter/claude-plugin-loader.ts +0 -365
- package/node_modules/pi-mcp-adapter/cli.js +0 -454
- package/node_modules/pi-mcp-adapter/commands.ts +0 -861
- package/node_modules/pi-mcp-adapter/config.ts +0 -1565
- package/node_modules/pi-mcp-adapter/consent-manager.ts +0 -95
- package/node_modules/pi-mcp-adapter/direct-tool-surface.ts +0 -244
- package/node_modules/pi-mcp-adapter/direct-tools.ts +0 -428
- package/node_modules/pi-mcp-adapter/dist/abort.d.ts +0 -2
- package/node_modules/pi-mcp-adapter/dist/abort.js +0 -36
- package/node_modules/pi-mcp-adapter/dist/abort.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/agent-dir.d.ts +0 -10
- package/node_modules/pi-mcp-adapter/dist/agent-dir.js +0 -63
- package/node_modules/pi-mcp-adapter/dist/agent-dir.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/agent-plugin-loader.d.ts +0 -8
- package/node_modules/pi-mcp-adapter/dist/agent-plugin-loader.js +0 -398
- package/node_modules/pi-mcp-adapter/dist/agent-plugin-loader.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/agent-plugin-provenance.d.ts +0 -1
- package/node_modules/pi-mcp-adapter/dist/agent-plugin-provenance.js +0 -31
- package/node_modules/pi-mcp-adapter/dist/agent-plugin-provenance.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/bearer-command-resolver.d.ts +0 -6
- package/node_modules/pi-mcp-adapter/dist/bearer-command-resolver.js +0 -194
- package/node_modules/pi-mcp-adapter/dist/bearer-command-resolver.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/claude-plugin-loader.d.ts +0 -9
- package/node_modules/pi-mcp-adapter/dist/claude-plugin-loader.js +0 -362
- package/node_modules/pi-mcp-adapter/dist/claude-plugin-loader.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/config.d.ts +0 -134
- package/node_modules/pi-mcp-adapter/dist/config.js +0 -1361
- package/node_modules/pi-mcp-adapter/dist/config.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/consent-manager.d.ts +0 -18
- package/node_modules/pi-mcp-adapter/dist/consent-manager.js +0 -88
- package/node_modules/pi-mcp-adapter/dist/consent-manager.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/elicitation-handler.d.ts +0 -17
- package/node_modules/pi-mcp-adapter/dist/elicitation-handler.js +0 -316
- package/node_modules/pi-mcp-adapter/dist/elicitation-handler.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/errors.d.ts +0 -131
- package/node_modules/pi-mcp-adapter/dist/errors.js +0 -278
- package/node_modules/pi-mcp-adapter/dist/errors.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/http-ca.d.ts +0 -8
- package/node_modules/pi-mcp-adapter/dist/http-ca.js +0 -88
- package/node_modules/pi-mcp-adapter/dist/http-ca.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/jev-client.d.ts +0 -14
- package/node_modules/pi-mcp-adapter/dist/jev-client.js +0 -367
- package/node_modules/pi-mcp-adapter/dist/jev-client.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/jev-contracts.d.ts +0 -77
- package/node_modules/pi-mcp-adapter/dist/jev-contracts.js +0 -2
- package/node_modules/pi-mcp-adapter/dist/jev-contracts.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/jev-key-store.d.ts +0 -51
- package/node_modules/pi-mcp-adapter/dist/jev-key-store.js +0 -205
- package/node_modules/pi-mcp-adapter/dist/jev-key-store.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/json-schema-validator.d.ts +0 -2
- package/node_modules/pi-mcp-adapter/dist/json-schema-validator.js +0 -68
- package/node_modules/pi-mcp-adapter/dist/json-schema-validator.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/lifecycle.d.ts +0 -56
- package/node_modules/pi-mcp-adapter/dist/lifecycle.js +0 -410
- package/node_modules/pi-mcp-adapter/dist/lifecycle.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/logger.d.ts +0 -51
- package/node_modules/pi-mcp-adapter/dist/logger.js +0 -131
- package/node_modules/pi-mcp-adapter/dist/logger.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/mcp-auth-fetch.d.ts +0 -26
- package/node_modules/pi-mcp-adapter/dist/mcp-auth-fetch.js +0 -103
- package/node_modules/pi-mcp-adapter/dist/mcp-auth-fetch.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/mcp-auth-flow.d.ts +0 -118
- package/node_modules/pi-mcp-adapter/dist/mcp-auth-flow.js +0 -1097
- package/node_modules/pi-mcp-adapter/dist/mcp-auth-flow.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/mcp-auth.d.ts +0 -170
- package/node_modules/pi-mcp-adapter/dist/mcp-auth.js +0 -1142
- package/node_modules/pi-mcp-adapter/dist/mcp-auth.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/mcp-bearer-store.d.ts +0 -24
- package/node_modules/pi-mcp-adapter/dist/mcp-bearer-store.js +0 -203
- package/node_modules/pi-mcp-adapter/dist/mcp-bearer-store.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/mcp-callback-server.d.ts +0 -53
- package/node_modules/pi-mcp-adapter/dist/mcp-callback-server.js +0 -441
- package/node_modules/pi-mcp-adapter/dist/mcp-callback-server.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/mcp-oauth-provider.d.ts +0 -148
- package/node_modules/pi-mcp-adapter/dist/mcp-oauth-provider.js +0 -689
- package/node_modules/pi-mcp-adapter/dist/mcp-oauth-provider.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/mcp-probe.d.ts +0 -6
- package/node_modules/pi-mcp-adapter/dist/mcp-probe.js +0 -166
- package/node_modules/pi-mcp-adapter/dist/mcp-probe.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/mcp-tasks.d.ts +0 -102
- package/node_modules/pi-mcp-adapter/dist/mcp-tasks.js +0 -369
- package/node_modules/pi-mcp-adapter/dist/mcp-tasks.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/mcp-trace.d.ts +0 -95
- package/node_modules/pi-mcp-adapter/dist/mcp-trace.js +0 -242
- package/node_modules/pi-mcp-adapter/dist/mcp-trace.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/metadata-cache.d.ts +0 -19
- package/node_modules/pi-mcp-adapter/dist/metadata-cache.js +0 -301
- package/node_modules/pi-mcp-adapter/dist/metadata-cache.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/npx-resolver.d.ts +0 -6
- package/node_modules/pi-mcp-adapter/dist/npx-resolver.js +0 -505
- package/node_modules/pi-mcp-adapter/dist/npx-resolver.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/package-mcp-loader.d.ts +0 -2
- package/node_modules/pi-mcp-adapter/dist/package-mcp-loader.js +0 -144
- package/node_modules/pi-mcp-adapter/dist/package-mcp-loader.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/request-headers-command.d.ts +0 -10
- package/node_modules/pi-mcp-adapter/dist/request-headers-command.js +0 -312
- package/node_modules/pi-mcp-adapter/dist/request-headers-command.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/resource-tools.d.ts +0 -1
- package/node_modules/pi-mcp-adapter/dist/resource-tools.js +0 -15
- package/node_modules/pi-mcp-adapter/dist/resource-tools.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/runtime-owner.d.ts +0 -13
- package/node_modules/pi-mcp-adapter/dist/runtime-owner.js +0 -97
- package/node_modules/pi-mcp-adapter/dist/runtime-owner.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/sampling-handler.d.ts +0 -17
- package/node_modules/pi-mcp-adapter/dist/sampling-handler.js +0 -203
- package/node_modules/pi-mcp-adapter/dist/sampling-handler.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/secure-keyring.d.ts +0 -11
- package/node_modules/pi-mcp-adapter/dist/secure-keyring.js +0 -172
- package/node_modules/pi-mcp-adapter/dist/secure-keyring.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/server-manager.d.ts +0 -157
- package/node_modules/pi-mcp-adapter/dist/server-manager.js +0 -1745
- package/node_modules/pi-mcp-adapter/dist/server-manager.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/session-approvals.d.ts +0 -34
- package/node_modules/pi-mcp-adapter/dist/session-approvals.js +0 -140
- package/node_modules/pi-mcp-adapter/dist/session-approvals.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/session-recovery.d.ts +0 -26
- package/node_modules/pi-mcp-adapter/dist/session-recovery.js +0 -142
- package/node_modules/pi-mcp-adapter/dist/session-recovery.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/state.d.ts +0 -73
- package/node_modules/pi-mcp-adapter/dist/state.js +0 -2
- package/node_modules/pi-mcp-adapter/dist/state.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/types.d.ts +0 -642
- package/node_modules/pi-mcp-adapter/dist/types.js +0 -331
- package/node_modules/pi-mcp-adapter/dist/types.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/ui-app-bridge-helpers.d.ts +0 -6
- package/node_modules/pi-mcp-adapter/dist/ui-app-bridge-helpers.js +0 -37
- package/node_modules/pi-mcp-adapter/dist/ui-app-bridge-helpers.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/ui-resource-handler.d.ts +0 -17
- package/node_modules/pi-mcp-adapter/dist/ui-resource-handler.js +0 -219
- package/node_modules/pi-mcp-adapter/dist/ui-resource-handler.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/ui-stream-types.d.ts +0 -104
- package/node_modules/pi-mcp-adapter/dist/ui-stream-types.js +0 -59
- package/node_modules/pi-mcp-adapter/dist/ui-stream-types.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/ui-tool-visibility.d.ts +0 -4
- package/node_modules/pi-mcp-adapter/dist/ui-tool-visibility.js +0 -27
- package/node_modules/pi-mcp-adapter/dist/ui-tool-visibility.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/unix-socket-transport.d.ts +0 -15
- package/node_modules/pi-mcp-adapter/dist/unix-socket-transport.js +0 -85
- package/node_modules/pi-mcp-adapter/dist/unix-socket-transport.js.map +0 -1
- package/node_modules/pi-mcp-adapter/dist/utils.d.ts +0 -41
- package/node_modules/pi-mcp-adapter/dist/utils.js +0 -417
- package/node_modules/pi-mcp-adapter/dist/utils.js.map +0 -1
- package/node_modules/pi-mcp-adapter/elicitation-handler.ts +0 -358
- package/node_modules/pi-mcp-adapter/error-signal.ts +0 -32
- package/node_modules/pi-mcp-adapter/errors.ts +0 -364
- package/node_modules/pi-mcp-adapter/examples/jev-accessibility-loop.mjs +0 -85
- package/node_modules/pi-mcp-adapter/examples/jev-semantic-filter.mjs +0 -34
- package/node_modules/pi-mcp-adapter/failure-backoff.ts +0 -23
- package/node_modules/pi-mcp-adapter/glimpse-ui.ts +0 -80
- package/node_modules/pi-mcp-adapter/host-html-template.ts +0 -515
- package/node_modules/pi-mcp-adapter/http-ca.ts +0 -84
- package/node_modules/pi-mcp-adapter/index.ts +0 -2106
- package/node_modules/pi-mcp-adapter/init.ts +0 -721
- package/node_modules/pi-mcp-adapter/jev-client.ts +0 -300
- package/node_modules/pi-mcp-adapter/jev-contracts.ts +0 -53
- package/node_modules/pi-mcp-adapter/jev-key-store.ts +0 -192
- package/node_modules/pi-mcp-adapter/json-schema-validator.ts +0 -83
- package/node_modules/pi-mcp-adapter/lazy-loader.ts +0 -7
- package/node_modules/pi-mcp-adapter/lifecycle.ts +0 -457
- package/node_modules/pi-mcp-adapter/logger.ts +0 -169
- package/node_modules/pi-mcp-adapter/mcp-auth-fetch.ts +0 -113
- package/node_modules/pi-mcp-adapter/mcp-auth-flow.ts +0 -1296
- package/node_modules/pi-mcp-adapter/mcp-auth.ts +0 -1287
- package/node_modules/pi-mcp-adapter/mcp-bearer-store.ts +0 -250
- package/node_modules/pi-mcp-adapter/mcp-callback-server.ts +0 -534
- package/node_modules/pi-mcp-adapter/mcp-code.ts +0 -495
- package/node_modules/pi-mcp-adapter/mcp-install.ts +0 -60
- package/node_modules/pi-mcp-adapter/mcp-keyring-helper.cjs +0 -89
- package/node_modules/pi-mcp-adapter/mcp-oauth-provider.ts +0 -819
- package/node_modules/pi-mcp-adapter/mcp-output-guard.ts +0 -511
- package/node_modules/pi-mcp-adapter/mcp-panel-theme.ts +0 -104
- package/node_modules/pi-mcp-adapter/mcp-panel.ts +0 -1099
- package/node_modules/pi-mcp-adapter/mcp-probe.ts +0 -201
- package/node_modules/pi-mcp-adapter/mcp-references.ts +0 -373
- package/node_modules/pi-mcp-adapter/mcp-script-worker.mjs +0 -137
- package/node_modules/pi-mcp-adapter/mcp-setup-panel.ts +0 -747
- package/node_modules/pi-mcp-adapter/mcp-status.ts +0 -105
- package/node_modules/pi-mcp-adapter/mcp-tasks.ts +0 -467
- package/node_modules/pi-mcp-adapter/mcp-trace.ts +0 -306
- package/node_modules/pi-mcp-adapter/metadata-cache.ts +0 -362
- package/node_modules/pi-mcp-adapter/namespace-tools.ts +0 -334
- package/node_modules/pi-mcp-adapter/npx-resolver.ts +0 -543
- package/node_modules/pi-mcp-adapter/oauth-handler.ts +0 -30
- package/node_modules/pi-mcp-adapter/oauth.ts +0 -52
- package/node_modules/pi-mcp-adapter/onboarding-state.ts +0 -76
- package/node_modules/pi-mcp-adapter/package-mcp-loader.ts +0 -156
- package/node_modules/pi-mcp-adapter/package.json +0 -219
- package/node_modules/pi-mcp-adapter/panel-keys.ts +0 -53
- package/node_modules/pi-mcp-adapter/prompts.ts +0 -385
- package/node_modules/pi-mcp-adapter/proxy-modes.ts +0 -1735
- package/node_modules/pi-mcp-adapter/request-headers-command.ts +0 -333
- package/node_modules/pi-mcp-adapter/resource-tools.ts +0 -17
- package/node_modules/pi-mcp-adapter/runtime-owner.ts +0 -106
- package/node_modules/pi-mcp-adapter/sampling-handler.ts +0 -261
- package/node_modules/pi-mcp-adapter/sandbox-proxy-template.ts +0 -144
- package/node_modules/pi-mcp-adapter/search-ranking.ts +0 -309
- package/node_modules/pi-mcp-adapter/secure-keyring.ts +0 -170
- package/node_modules/pi-mcp-adapter/semantic-search.ts +0 -186
- package/node_modules/pi-mcp-adapter/server-manager.ts +0 -2088
- package/node_modules/pi-mcp-adapter/session-approvals.ts +0 -201
- package/node_modules/pi-mcp-adapter/session-recovery.ts +0 -158
- package/node_modules/pi-mcp-adapter/skills/mcp-scripting/SKILL.md +0 -49
- package/node_modules/pi-mcp-adapter/state.ts +0 -71
- package/node_modules/pi-mcp-adapter/tool-approval.ts +0 -205
- package/node_modules/pi-mcp-adapter/tool-metadata.ts +0 -302
- package/node_modules/pi-mcp-adapter/tool-registrar.ts +0 -255
- package/node_modules/pi-mcp-adapter/tool-result-renderer.ts +0 -573
- package/node_modules/pi-mcp-adapter/ts-shape.ts +0 -149
- package/node_modules/pi-mcp-adapter/types.ts +0 -1120
- package/node_modules/pi-mcp-adapter/ui-app-bridge-helpers.ts +0 -40
- package/node_modules/pi-mcp-adapter/ui-resource-handler.ts +0 -266
- package/node_modules/pi-mcp-adapter/ui-server.ts +0 -993
- package/node_modules/pi-mcp-adapter/ui-session.ts +0 -624
- package/node_modules/pi-mcp-adapter/ui-stream-types.ts +0 -89
- package/node_modules/pi-mcp-adapter/ui-tool-visibility.ts +0 -25
- package/node_modules/pi-mcp-adapter/unix-socket-transport.ts +0 -85
- package/node_modules/pi-mcp-adapter/utils.ts +0 -464
|
@@ -1,1735 +0,0 @@
|
|
|
1
|
-
import type { AgentToolResult, ToolInfo } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import { UrlElicitationRequiredError, type Client, type JsonSchemaType, type JsonSchemaValidator, type Progress, type RequestOptions } from "@modelcontextprotocol/client";
|
|
3
|
-
import { createRequire } from "node:module";
|
|
4
|
-
import type { McpExtensionState } from "./state.ts";
|
|
5
|
-
import type { ToolMetadata, McpContent } from "./types.ts";
|
|
6
|
-
import { getServerPrefix, getToolNameCandidates, isServerDisabled, parseUiPromptHandoff, resolveToolPrefix, type ServerEntry } from "./types.ts";
|
|
7
|
-
import { lazyConnect, markKeepAliveAfterConnect, notifyToolMetadataUpdated, updateServerMetadata, updateMetadataCache, getFailureAgeSeconds, updateStatusBar, clearFailure, recordFailure } from "./init.ts";
|
|
8
|
-
import { abortable, throwIfAborted } from "./abort.ts";
|
|
9
|
-
import { combineAbortSignals, isAbortError } from "./runtime-owner.ts";
|
|
10
|
-
import { buildToolMetadata, getToolNames, formatSchema } from "./tool-metadata.ts";
|
|
11
|
-
import { renderTsShape } from "./ts-shape.ts";
|
|
12
|
-
import { reconstructPromptMetadata } from "./metadata-cache.ts";
|
|
13
|
-
import { resolveMcpResultContent, transformMcpResourceContents } from "./tool-registrar.ts";
|
|
14
|
-
import { guardMcpOutput, guardedMcpDetails, resolveMcpOutputGuardOptions } from "./mcp-output-guard.ts";
|
|
15
|
-
import { maybeStartUiSession, summarizeUiSessionResult, type UiSessionRuntime } from "./ui-session.ts";
|
|
16
|
-
import { formatAuthRequiredMessage, formatMcpStatus, normalizeToolArguments, resolveServerUrl, truncateAtWord } from "./utils.ts";
|
|
17
|
-
import { authenticate, completeAuthFromInput, getAuthStatus, startAuth, supportsOAuth } from "./mcp-auth-flow.ts";
|
|
18
|
-
import { SessionRecoveryAuthRequiredError, withSessionRecovery } from "./session-recovery.ts";
|
|
19
|
-
import { callToolViaTaskSession } from "./mcp-tasks.ts";
|
|
20
|
-
import { paginate, rankSuggestions, rankToolMatches, resolveSearchKeywords } from "./search-ranking.ts";
|
|
21
|
-
import { ensureToolCallApproved, isToolCallApprovalRequired } from "./tool-approval.ts";
|
|
22
|
-
import { isServerInActiveFailureBackoff } from "./failure-backoff.ts";
|
|
23
|
-
import { semanticSearch, type SemanticSearchBackend, type SemanticSearchEvaluator } from "./semantic-search.ts";
|
|
24
|
-
import { getInputRequiredNeedsUiDetails } from "./errors.ts";
|
|
25
|
-
import { createJsonSchemaValidator } from "./json-schema-validator.ts";
|
|
26
|
-
|
|
27
|
-
type ProxyToolResult = AgentToolResult<Record<string, unknown>>;
|
|
28
|
-
type ClientCallToolResult = Awaited<ReturnType<Client["callTool"]>>;
|
|
29
|
-
type ClientReadResourceResult = Awaited<ReturnType<Client["readResource"]>>;
|
|
30
|
-
|
|
31
|
-
const require = createRequire(import.meta.url);
|
|
32
|
-
const proxyArgumentValidators = new WeakMap<object, JsonSchemaValidator<unknown>>();
|
|
33
|
-
const MAX_REGEX_SEARCH_QUERY_LENGTH = 256;
|
|
34
|
-
|
|
35
|
-
function proxyArgumentValidationError(inputSchema: unknown, args: unknown): string | null {
|
|
36
|
-
if (!inputSchema || typeof inputSchema !== "object" || Array.isArray(inputSchema)) return null;
|
|
37
|
-
try {
|
|
38
|
-
let validate = proxyArgumentValidators.get(inputSchema);
|
|
39
|
-
if (!validate) {
|
|
40
|
-
validate = createJsonSchemaValidator().getValidator(inputSchema as JsonSchemaType);
|
|
41
|
-
proxyArgumentValidators.set(inputSchema, validate);
|
|
42
|
-
}
|
|
43
|
-
const result = validate(args);
|
|
44
|
-
return result.valid ? null : result.errorMessage ?? "arguments do not match the advertised input schema";
|
|
45
|
-
} catch {
|
|
46
|
-
// Preserve server-side validation for schema dialects the adapter cannot evaluate.
|
|
47
|
-
return null;
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
const INSTRUCTIONS_PREVIEW_LENGTH = 300;
|
|
51
|
-
const REGEX_SAFETY_CHECK_PARAMS = {
|
|
52
|
-
attackTimeout: 50,
|
|
53
|
-
incubationTimeout: 50,
|
|
54
|
-
timeout: 250,
|
|
55
|
-
} as const;
|
|
56
|
-
|
|
57
|
-
const backgroundAuthWatchers = new WeakMap<McpExtensionState, Map<string, Promise<void>>>();
|
|
58
|
-
|
|
59
|
-
type AutoAuthResult =
|
|
60
|
-
| { status: "skipped" }
|
|
61
|
-
| { status: "success" }
|
|
62
|
-
| { status: "failed"; message: string };
|
|
63
|
-
|
|
64
|
-
let nextProgressInvocationId = 1;
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* Bridges SDK request-local progress callbacks to the interactive UI notify
|
|
68
|
-
* path (#437 item 3). The SDK owns `_meta.progressToken` injection when
|
|
69
|
-
* `onprogress` is set; this never writes the token manually.
|
|
70
|
-
*/
|
|
71
|
-
function withUiProgressBridge(
|
|
72
|
-
options: RequestOptions | undefined,
|
|
73
|
-
ui: McpExtensionState["ui"],
|
|
74
|
-
serverName: string,
|
|
75
|
-
toolName: string,
|
|
76
|
-
): RequestOptions | undefined {
|
|
77
|
-
if (!ui) return options;
|
|
78
|
-
const label = `MCP ${serverName}/${toolName}#${nextProgressInvocationId++}`;
|
|
79
|
-
return {
|
|
80
|
-
...options,
|
|
81
|
-
onprogress: (progress: Progress) => {
|
|
82
|
-
const ratio = `${progress.progress}${progress.total === undefined ? "" : `/${progress.total}`}`;
|
|
83
|
-
ui.notify(progress.message ? `${label}: ${progress.message} (${ratio})` : `${label}: ${ratio}`, "info");
|
|
84
|
-
},
|
|
85
|
-
};
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
function getToolMatches(metadata: ToolMetadata[] | undefined, toolName: string, exact: boolean): ToolMetadata[] {
|
|
89
|
-
if (!metadata) return [];
|
|
90
|
-
if (exact) return metadata.filter(tool => tool.name === toolName);
|
|
91
|
-
const normalizedName = toolName.replace(/-/g, "_");
|
|
92
|
-
return metadata.filter(tool => tool.name.replace(/-/g, "_") === normalizedName);
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
function getEnabledToolMatches(state: McpExtensionState, toolName: string, exact: boolean): { server: string; tool: ToolMetadata }[] {
|
|
96
|
-
const matches: { server: string; tool: ToolMetadata }[] = [];
|
|
97
|
-
for (const [server, metadata] of state.toolMetadata) {
|
|
98
|
-
if (isServerDisabled(state.config.mcpServers[server])) continue;
|
|
99
|
-
for (const tool of getToolMatches(metadata, toolName, exact)) matches.push({ server, tool });
|
|
100
|
-
}
|
|
101
|
-
return matches;
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
function getEnabledOriginalToolMatches(state: McpExtensionState, toolName: string): { server: string; tool: ToolMetadata }[] {
|
|
105
|
-
const matches: { server: string; tool: ToolMetadata }[] = [];
|
|
106
|
-
for (const [server, metadata] of state.toolMetadata) {
|
|
107
|
-
if (isServerDisabled(state.config.mcpServers[server])) continue;
|
|
108
|
-
for (const tool of metadata) {
|
|
109
|
-
if (tool.originalName === toolName) matches.push({ server, tool });
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
return matches;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
function serverBackoffResult(state: McpExtensionState, mode: string, serverName: string): ProxyToolResult {
|
|
116
|
-
const failedAgo = getFailureAgeSeconds(state, serverName) ?? 0;
|
|
117
|
-
const message = `Server "${serverName}" not available (last failed ${failedAgo}s ago)`;
|
|
118
|
-
return {
|
|
119
|
-
content: [{ type: "text" as const, text: message }],
|
|
120
|
-
details: { mode, error: "server_backoff", server: serverName },
|
|
121
|
-
};
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
function getCandidateToolMatches(
|
|
125
|
-
metadata: ToolMetadata[] | undefined,
|
|
126
|
-
toolName: string,
|
|
127
|
-
serverName: string,
|
|
128
|
-
state: McpExtensionState,
|
|
129
|
-
): ToolMetadata[] {
|
|
130
|
-
if (!metadata) return [];
|
|
131
|
-
const prefix = resolveToolPrefix(state.config.mcpServers[serverName], state.config.settings?.toolPrefix);
|
|
132
|
-
return metadata.filter((tool) => getToolNameCandidates(tool.originalName, serverName, prefix).has(toolName));
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
function getCandidateToolMatch(
|
|
136
|
-
metadata: ToolMetadata[] | undefined,
|
|
137
|
-
toolName: string,
|
|
138
|
-
serverName: string,
|
|
139
|
-
state: McpExtensionState,
|
|
140
|
-
): ToolMetadata | "ambiguous" | undefined {
|
|
141
|
-
const exact = metadata?.filter((tool) => tool.name === toolName) ?? [];
|
|
142
|
-
if (exact.length > 0) return exact.length === 1 ? exact[0] : "ambiguous";
|
|
143
|
-
const candidates = getCandidateToolMatches(metadata, toolName, serverName, state);
|
|
144
|
-
return candidates.length > 1 ? "ambiguous" : candidates[0];
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
function getPrefixedServerScope(state: McpExtensionState, toolName: string): string | undefined {
|
|
148
|
-
const candidates = Object.entries(state.config.mcpServers)
|
|
149
|
-
.filter(([, definition]) => !isServerDisabled(definition))
|
|
150
|
-
.map(([name, definition]) => ({
|
|
151
|
-
name,
|
|
152
|
-
prefix: getServerPrefix(name, resolveToolPrefix(definition, state.config.settings?.toolPrefix)),
|
|
153
|
-
}))
|
|
154
|
-
.filter(({ prefix }) => prefix.length > 0 && toolName.startsWith(`${prefix}_`))
|
|
155
|
-
.sort((a, b) => b.prefix.length - a.prefix.length);
|
|
156
|
-
if (candidates.length === 0) return undefined;
|
|
157
|
-
const longest = candidates[0]!.prefix.length;
|
|
158
|
-
const best = candidates.filter(({ prefix }) => prefix.length === longest);
|
|
159
|
-
return best.length === 1 ? best[0]!.name : undefined;
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
type ServerScopedToolMatch = { tool: ToolMetadata; precedence: number } | "ambiguous";
|
|
163
|
-
|
|
164
|
-
function getServerScopedToolCandidates(
|
|
165
|
-
metadata: ToolMetadata[] | undefined,
|
|
166
|
-
toolName: string,
|
|
167
|
-
): { tools: ToolMetadata[]; precedence: number } | undefined {
|
|
168
|
-
if (!metadata) return undefined;
|
|
169
|
-
const normalizedName = toolName.replace(/-/g, "_");
|
|
170
|
-
const exactDisplayedMatches = metadata.filter((tool) => tool.name === toolName);
|
|
171
|
-
if (exactDisplayedMatches.length > 0) return { tools: exactDisplayedMatches, precedence: 0 };
|
|
172
|
-
const exactOriginalMatches = metadata.filter((tool) => tool.originalName === toolName);
|
|
173
|
-
if (exactOriginalMatches.length > 0) return { tools: exactOriginalMatches, precedence: 1 };
|
|
174
|
-
const normalizedDisplayedMatches = metadata.filter((tool) => tool.name.replace(/-/g, "_") === normalizedName);
|
|
175
|
-
const normalizedOriginalMatches = metadata.filter((tool) => tool.originalName.replace(/-/g, "_") === normalizedName);
|
|
176
|
-
const normalizedMatches = new Set([...normalizedDisplayedMatches, ...normalizedOriginalMatches]);
|
|
177
|
-
if (normalizedMatches.size === 0) return undefined;
|
|
178
|
-
return {
|
|
179
|
-
tools: [...normalizedMatches],
|
|
180
|
-
precedence: normalizedDisplayedMatches.length > 0 ? 2 : 3,
|
|
181
|
-
};
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
function getServerScopedToolMatch(metadata: ToolMetadata[] | undefined, toolName: string): ServerScopedToolMatch | undefined {
|
|
185
|
-
const candidates = getServerScopedToolCandidates(metadata, toolName);
|
|
186
|
-
if (!candidates) return undefined;
|
|
187
|
-
return candidates.tools.length === 1
|
|
188
|
-
? { tool: candidates.tools[0]!, precedence: candidates.precedence }
|
|
189
|
-
: "ambiguous";
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
function ambiguousToolResult(mode: "call" | "describe", toolName: string): ProxyToolResult {
|
|
193
|
-
const message = `Tool "${toolName}" matches multiple servers. Specify a server.`;
|
|
194
|
-
return {
|
|
195
|
-
content: [{ type: "text" as const, text: message }],
|
|
196
|
-
details: { mode, error: "ambiguous_tool", requestedTool: toolName, message },
|
|
197
|
-
};
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
function ambiguousServerToolResult(
|
|
201
|
-
mode: "call" | "describe",
|
|
202
|
-
toolName: string,
|
|
203
|
-
serverName: string,
|
|
204
|
-
): ProxyToolResult {
|
|
205
|
-
const message = `Tool "${toolName}" matches multiple tools on server "${serverName}". Use an exact displayed or upstream tool name; run mcp({ server: "${serverName}" }) to list available tools.`;
|
|
206
|
-
return {
|
|
207
|
-
content: [{ type: "text" as const, text: message }],
|
|
208
|
-
details: { mode, error: "ambiguous_tool", server: serverName, requestedTool: toolName, message },
|
|
209
|
-
};
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
function disabledResult(mode: string, serverName: string): ProxyToolResult {
|
|
213
|
-
const message = `Server "${serverName}" is disabled. Run /mcp enable ${serverName} and /reload to enable it.`;
|
|
214
|
-
return {
|
|
215
|
-
content: [{ type: "text" as const, text: message }],
|
|
216
|
-
details: { mode, error: "server_disabled", server: serverName, message },
|
|
217
|
-
};
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
function emitAuthStatus(state: McpExtensionState, serverName: string, status: "authenticated" | "failed", message: string): void {
|
|
221
|
-
state.ui?.notify(message, status === "authenticated" ? "info" : "error");
|
|
222
|
-
state.sendMessage?.(
|
|
223
|
-
{
|
|
224
|
-
customType: "mcp-oauth-status",
|
|
225
|
-
content: [{ type: "text", text: message }],
|
|
226
|
-
display: message,
|
|
227
|
-
details: {
|
|
228
|
-
server: serverName,
|
|
229
|
-
status,
|
|
230
|
-
...(status === "authenticated" ? { nextAction: { connect: serverName } } : {}),
|
|
231
|
-
},
|
|
232
|
-
},
|
|
233
|
-
{ triggerTurn: true },
|
|
234
|
-
);
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
function ensureBackgroundAuthWatcher(
|
|
238
|
-
state: McpExtensionState,
|
|
239
|
-
serverName: string,
|
|
240
|
-
serverUrl: string,
|
|
241
|
-
definition: ServerEntry,
|
|
242
|
-
): void {
|
|
243
|
-
let watchers = backgroundAuthWatchers.get(state);
|
|
244
|
-
if (!watchers) {
|
|
245
|
-
watchers = new Map();
|
|
246
|
-
backgroundAuthWatchers.set(state, watchers);
|
|
247
|
-
}
|
|
248
|
-
if (watchers.has(serverName)) return;
|
|
249
|
-
|
|
250
|
-
const authOptions = {
|
|
251
|
-
authStorageOptions: state.authStorageOptions,
|
|
252
|
-
runtime: state.oauthRuntime,
|
|
253
|
-
openAuthorizationUrl: state.openBrowser,
|
|
254
|
-
};
|
|
255
|
-
const watcher = authenticate(serverName, serverUrl, definition, authOptions).then(async (status) => {
|
|
256
|
-
throwIfAborted(state.owner.signal);
|
|
257
|
-
if (status !== "authenticated") throw new Error(`OAuth authentication ended with status: ${status}`);
|
|
258
|
-
await state.manager.close(serverName);
|
|
259
|
-
throwIfAborted(state.owner.signal);
|
|
260
|
-
clearFailure(state, serverName, "auth-background-complete");
|
|
261
|
-
updateStatusBar(state);
|
|
262
|
-
emitAuthStatus(
|
|
263
|
-
state,
|
|
264
|
-
serverName,
|
|
265
|
-
"authenticated",
|
|
266
|
-
`OAuth authentication completed for MCP server "${serverName}". Connect it now to load and verify its tools.`,
|
|
267
|
-
);
|
|
268
|
-
});
|
|
269
|
-
watchers.set(serverName, watcher);
|
|
270
|
-
|
|
271
|
-
void watcher.catch(async (error) => {
|
|
272
|
-
if (isAbortError(error, state.owner.signal)) return;
|
|
273
|
-
try {
|
|
274
|
-
if (await getAuthStatus(serverName, authOptions) === "authenticated") return;
|
|
275
|
-
} catch (statusError) {
|
|
276
|
-
if (isAbortError(statusError, state.owner.signal)) return;
|
|
277
|
-
}
|
|
278
|
-
if (state.owner.signal.aborted) return;
|
|
279
|
-
emitAuthStatus(
|
|
280
|
-
state,
|
|
281
|
-
serverName,
|
|
282
|
-
"failed",
|
|
283
|
-
`OAuth authentication failed for MCP server "${serverName}". Start authorization again or inspect trusted logs.`,
|
|
284
|
-
);
|
|
285
|
-
}).finally(() => {
|
|
286
|
-
if (watchers?.get(serverName) === watcher) watchers.delete(serverName);
|
|
287
|
-
});
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
function getAuthRequiredMessage(
|
|
291
|
-
state: McpExtensionState,
|
|
292
|
-
serverName: string,
|
|
293
|
-
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.`,
|
|
294
|
-
): string {
|
|
295
|
-
return formatAuthRequiredMessage(state.config, serverName, defaultMessage);
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
function getAuthFailedMessage(state: McpExtensionState, serverName: string, message: string): string {
|
|
299
|
-
const customGuidance = state.config.settings?.authRequiredMessage;
|
|
300
|
-
if (customGuidance) {
|
|
301
|
-
return `OAuth authentication failed for "${serverName}": ${message}. ${getAuthRequiredMessage(state, serverName)}`;
|
|
302
|
-
}
|
|
303
|
-
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.`;
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
function getRedirectDetails(authorizationUrl: string): { port?: number; remote: boolean } {
|
|
307
|
-
try {
|
|
308
|
-
const redirectUri = new URL(authorizationUrl).searchParams.get("redirect_uri");
|
|
309
|
-
if (!redirectUri) return { remote: false };
|
|
310
|
-
const redirect = new URL(redirectUri);
|
|
311
|
-
const hostname = redirect.hostname.toLowerCase();
|
|
312
|
-
const local = hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
|
|
313
|
-
const port = Number.parseInt(redirect.port, 10);
|
|
314
|
-
return {
|
|
315
|
-
...(Number.isInteger(port) ? { port } : {}),
|
|
316
|
-
remote: !local,
|
|
317
|
-
};
|
|
318
|
-
} catch {
|
|
319
|
-
return { remote: false };
|
|
320
|
-
}
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
function formatManualAuthInstructions(serverName: string, authorizationUrl: string): string {
|
|
324
|
-
const redirect = getRedirectDetails(authorizationUrl);
|
|
325
|
-
const redirectNote = redirect.remote
|
|
326
|
-
? "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."
|
|
327
|
-
: `The adapter is watching${redirect.port ? ` local port ${redirect.port}` : " the local callback"} and will report when authentication completes.`;
|
|
328
|
-
|
|
329
|
-
return [
|
|
330
|
-
`MCP OAuth required for "${serverName}".`,
|
|
331
|
-
"",
|
|
332
|
-
redirect.remote
|
|
333
|
-
? "The adapter is attempting to open this authorization URL in your local browser:"
|
|
334
|
-
: "The adapter is attempting to open this authorization URL and watching for its callback:",
|
|
335
|
-
"",
|
|
336
|
-
authorizationUrl,
|
|
337
|
-
"",
|
|
338
|
-
redirect.remote
|
|
339
|
-
? "After approving, copy the full callback URL from your browser address bar and send it back with:"
|
|
340
|
-
: "If the browser does not open or the callback is not detected, open the URL above and complete manually with:",
|
|
341
|
-
`mcp({ action: "auth-complete", server: "${serverName}", args: { redirectUrl: "PASTE_REDIRECT_URL_HERE" } })`,
|
|
342
|
-
"",
|
|
343
|
-
redirect.remote
|
|
344
|
-
? "Remote HTTPS callbacks must include the full callback URL so the OAuth state can be checked. JSON-string args remain supported."
|
|
345
|
-
: 'You can also pass just the `code` query parameter as `args: { code: "PASTE_CODE_HERE" }`. JSON-string args remain supported.',
|
|
346
|
-
redirectNote,
|
|
347
|
-
].filter(Boolean).join("\n");
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
async function attemptAutoAuth(
|
|
351
|
-
state: McpExtensionState,
|
|
352
|
-
serverName: string,
|
|
353
|
-
signal?: AbortSignal,
|
|
354
|
-
): Promise<AutoAuthResult> {
|
|
355
|
-
if (state.config.settings?.autoAuth !== true) {
|
|
356
|
-
return { status: "skipped" };
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
const definition = state.config.mcpServers[serverName];
|
|
360
|
-
if (!definition || isServerDisabled(definition) || !supportsOAuth(definition)) {
|
|
361
|
-
return { status: "skipped" };
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
let serverUrl: string | undefined;
|
|
365
|
-
try {
|
|
366
|
-
serverUrl = resolveServerUrl(definition);
|
|
367
|
-
} catch (error) {
|
|
368
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
369
|
-
return { status: "failed", message: getAuthFailedMessage(state, serverName, message) };
|
|
370
|
-
}
|
|
371
|
-
if (!serverUrl) {
|
|
372
|
-
return { status: "skipped" };
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
const grantType = definition.oauth ? definition.oauth.grantType ?? "authorization_code" : "authorization_code";
|
|
376
|
-
if (!state.ui && grantType !== "client_credentials") {
|
|
377
|
-
return {
|
|
378
|
-
status: "failed",
|
|
379
|
-
message: getAuthRequiredMessage(
|
|
380
|
-
state,
|
|
381
|
-
serverName,
|
|
382
|
-
`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.`,
|
|
383
|
-
),
|
|
384
|
-
};
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
try {
|
|
388
|
-
if (state.authStorageOptions) {
|
|
389
|
-
await authenticate(
|
|
390
|
-
serverName,
|
|
391
|
-
serverUrl,
|
|
392
|
-
definition,
|
|
393
|
-
signal
|
|
394
|
-
? { authStorageOptions: state.authStorageOptions, signal, runtime: state.oauthRuntime }
|
|
395
|
-
: { authStorageOptions: state.authStorageOptions, runtime: state.oauthRuntime },
|
|
396
|
-
);
|
|
397
|
-
} else {
|
|
398
|
-
if (signal) {
|
|
399
|
-
await authenticate(serverName, serverUrl, definition, { signal, runtime: state.oauthRuntime });
|
|
400
|
-
} else {
|
|
401
|
-
await authenticate(serverName, serverUrl, definition, { runtime: state.oauthRuntime });
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
|
-
return { status: "success" };
|
|
405
|
-
} catch (error) {
|
|
406
|
-
if (isAbortError(error, signal)) throw error;
|
|
407
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
408
|
-
return {
|
|
409
|
-
status: "failed",
|
|
410
|
-
message: getAuthFailedMessage(state, serverName, message),
|
|
411
|
-
};
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
export function executeUiMessages(state: McpExtensionState): ProxyToolResult {
|
|
416
|
-
const sessions = state.completedUiSessions;
|
|
417
|
-
|
|
418
|
-
if (sessions.length === 0) {
|
|
419
|
-
return {
|
|
420
|
-
content: [{ type: "text" as const, text: "No UI session messages available." }],
|
|
421
|
-
details: { sessions: 0 },
|
|
422
|
-
};
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
const output: string[] = [];
|
|
426
|
-
output.push(`UI Session Messages (${sessions.length} session${sessions.length > 1 ? "s" : ""}):\n`);
|
|
427
|
-
|
|
428
|
-
const allPrompts: string[] = [];
|
|
429
|
-
const allIntents = sessions.flatMap((session) => session.messages.intents);
|
|
430
|
-
const allContexts = sessions.flatMap((session) => session.messages.contexts);
|
|
431
|
-
const parsedHandoffs: Array<{ intent: string; params: Record<string, unknown>; raw: string }> = [];
|
|
432
|
-
|
|
433
|
-
for (const session of sessions) {
|
|
434
|
-
const timestamp = session.completedAt.toLocaleTimeString();
|
|
435
|
-
output.push(`\n## ${session.serverName} / ${session.toolName} (${timestamp}, ${session.reason})`);
|
|
436
|
-
|
|
437
|
-
const plainPrompts: string[] = [];
|
|
438
|
-
for (const prompt of session.messages.prompts) {
|
|
439
|
-
allPrompts.push(prompt);
|
|
440
|
-
const handoff = parseUiPromptHandoff(prompt);
|
|
441
|
-
if (handoff) {
|
|
442
|
-
parsedHandoffs.push(handoff);
|
|
443
|
-
} else {
|
|
444
|
-
plainPrompts.push(prompt);
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
if (plainPrompts.length > 0) {
|
|
449
|
-
output.push("\n### Prompts:");
|
|
450
|
-
for (const prompt of plainPrompts) {
|
|
451
|
-
output.push(`- ${prompt}`);
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
const intentsForSession = [
|
|
456
|
-
...session.messages.intents,
|
|
457
|
-
...session.messages.prompts
|
|
458
|
-
.map((prompt) => parseUiPromptHandoff(prompt))
|
|
459
|
-
.filter((handoff): handoff is NonNullable<typeof handoff> => !!handoff)
|
|
460
|
-
.map((handoff) => ({ intent: handoff.intent, params: handoff.params })),
|
|
461
|
-
];
|
|
462
|
-
|
|
463
|
-
if (intentsForSession.length > 0) {
|
|
464
|
-
output.push("\n### Intents:");
|
|
465
|
-
for (const intent of intentsForSession) {
|
|
466
|
-
const params = intent.params ? ` (${JSON.stringify(intent.params)})` : "";
|
|
467
|
-
output.push(`- ${intent.intent}${params}`);
|
|
468
|
-
}
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
const contexts = session.messages.contexts;
|
|
472
|
-
if (contexts.length > 0) {
|
|
473
|
-
output.push("\n### Context updates:");
|
|
474
|
-
for (const context of contexts) {
|
|
475
|
-
output.push(`- ${context.summary}${context.truncated ? " (truncated)" : ""}`);
|
|
476
|
-
}
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
if (session.messages.notifications.length > 0) {
|
|
480
|
-
output.push("\n### Notifications:");
|
|
481
|
-
for (const notification of session.messages.notifications) {
|
|
482
|
-
output.push(`- ${notification}`);
|
|
483
|
-
}
|
|
484
|
-
}
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
const count = sessions.length;
|
|
488
|
-
state.completedUiSessions = [];
|
|
489
|
-
|
|
490
|
-
return {
|
|
491
|
-
content: [{ type: "text" as const, text: output.join("\n") }],
|
|
492
|
-
details: {
|
|
493
|
-
sessions: count,
|
|
494
|
-
prompts: allPrompts,
|
|
495
|
-
intents: [...allIntents, ...parsedHandoffs.map(({ intent, params }) => ({ intent, params }))],
|
|
496
|
-
contexts: allContexts,
|
|
497
|
-
handoffs: parsedHandoffs,
|
|
498
|
-
cleared: true,
|
|
499
|
-
},
|
|
500
|
-
};
|
|
501
|
-
}
|
|
502
|
-
|
|
503
|
-
export function executeStatus(state: McpExtensionState): ProxyToolResult {
|
|
504
|
-
const servers: Array<{ name: string; status: string; listenState: string; catalogStale?: boolean; toolCount: number; failedAgo: number | null; disabled?: boolean }> = [];
|
|
505
|
-
|
|
506
|
-
for (const name of Object.keys(state.config.mcpServers)) {
|
|
507
|
-
const definition = state.config.mcpServers[name];
|
|
508
|
-
const disabled = isServerDisabled(definition);
|
|
509
|
-
const connection = disabled ? undefined : state.manager.getConnection(name);
|
|
510
|
-
const metadata = disabled ? undefined : state.toolMetadata.get(name);
|
|
511
|
-
const failedAgo = disabled ? null : getFailureAgeSeconds(state, name);
|
|
512
|
-
let status = disabled ? "disabled" : "not connected";
|
|
513
|
-
if (!disabled && connection?.status === "connected") {
|
|
514
|
-
status = "connected";
|
|
515
|
-
} else if (!disabled && connection?.status === "needs-auth") {
|
|
516
|
-
status = "needs-auth";
|
|
517
|
-
} else if (!disabled && failedAgo !== null) {
|
|
518
|
-
status = "failed";
|
|
519
|
-
} else if (!disabled && metadata !== undefined) {
|
|
520
|
-
status = "cached";
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
const toolCount = status === "failed" ? 0 : metadata?.length ?? 0;
|
|
524
|
-
|
|
525
|
-
const listenState = connection?.status === "connected" ? connection.listenState : "disconnected";
|
|
526
|
-
servers.push({
|
|
527
|
-
name,
|
|
528
|
-
status,
|
|
529
|
-
listenState,
|
|
530
|
-
...(connection?.status === "connected" && connection.listenCatalogStale ? { catalogStale: true } : {}),
|
|
531
|
-
toolCount,
|
|
532
|
-
failedAgo,
|
|
533
|
-
...(disabled ? { disabled: true } : {}),
|
|
534
|
-
});
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
const disabledCount = servers.filter(s => s.disabled).length;
|
|
538
|
-
const enabledServers = servers.filter(s => !s.disabled);
|
|
539
|
-
const totalTools = enabledServers.reduce((sum, s) => sum + s.toolCount, 0);
|
|
540
|
-
const connectedCount = enabledServers.filter(s => s.status === "connected").length;
|
|
541
|
-
|
|
542
|
-
let text = `MCP: ${connectedCount}/${enabledServers.length} servers, ${totalTools} tools`;
|
|
543
|
-
if (disabledCount > 0) text += ` (${disabledCount} disabled)`;
|
|
544
|
-
text += "\n\n";
|
|
545
|
-
for (const server of servers) {
|
|
546
|
-
if (server.disabled) {
|
|
547
|
-
text += `⊘ ${server.name} (disabled)\n`;
|
|
548
|
-
continue;
|
|
549
|
-
}
|
|
550
|
-
if (server.status === "connected") {
|
|
551
|
-
const listen = server.listenState === "active"
|
|
552
|
-
? server.catalogStale
|
|
553
|
-
? ", listen active, catalog may be stale"
|
|
554
|
-
: ", listen active"
|
|
555
|
-
: server.listenState === "dropped"
|
|
556
|
-
? ", catalog may be stale; will reconcile on next keep-alive or tool use"
|
|
557
|
-
: server.listenState === "re-establishing"
|
|
558
|
-
? ", re-establishing listen"
|
|
559
|
-
: server.listenState === "legacy"
|
|
560
|
-
? ", legacy notification path"
|
|
561
|
-
: ", not listening for catalog updates";
|
|
562
|
-
text += `✓ ${server.name} (${server.toolCount} tools${listen})\n`;
|
|
563
|
-
continue;
|
|
564
|
-
}
|
|
565
|
-
if (server.status === "needs-auth") {
|
|
566
|
-
text += `⚠ ${server.name} (needs auth)\n`;
|
|
567
|
-
continue;
|
|
568
|
-
}
|
|
569
|
-
if (server.status === "cached") {
|
|
570
|
-
text += `○ ${server.name} (${server.toolCount} tools, cached; not listening)\n`;
|
|
571
|
-
continue;
|
|
572
|
-
}
|
|
573
|
-
if (server.status === "failed") {
|
|
574
|
-
text += `✗ ${server.name} (failed ${server.failedAgo ?? 0}s ago)\n`;
|
|
575
|
-
continue;
|
|
576
|
-
}
|
|
577
|
-
text += `○ ${server.name} (not listening; disconnected)\n`;
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
const directToolsFrozen = state.config.settings?.freezeDirectTools === true;
|
|
581
|
-
if (directToolsFrozen) {
|
|
582
|
-
text += "\nDirect tools frozen; active registrations may differ from current metadata.\n";
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
if (servers.length > 0) {
|
|
586
|
-
text += `\nmcp({ server: "name" }) to list tools, mcp({ search: "..." }) to search`;
|
|
587
|
-
}
|
|
588
|
-
|
|
589
|
-
return {
|
|
590
|
-
content: [{ type: "text" as const, text: text.trim() }],
|
|
591
|
-
details: { mode: "status", servers, totalTools, connectedCount, disabledCount, directToolsFrozen },
|
|
592
|
-
};
|
|
593
|
-
}
|
|
594
|
-
|
|
595
|
-
export async function executeAuthStart(state: McpExtensionState, serverName: string, signal?: AbortSignal): Promise<ProxyToolResult> {
|
|
596
|
-
const ownedSignal = combineAbortSignals(state.owner?.signal, signal);
|
|
597
|
-
throwIfAborted(ownedSignal);
|
|
598
|
-
const definition = state.config.mcpServers[serverName];
|
|
599
|
-
if (!definition) {
|
|
600
|
-
return {
|
|
601
|
-
content: [{ type: "text" as const, text: `Server "${serverName}" not found. Use mcp({}) to see available servers.` }],
|
|
602
|
-
details: { mode: "auth-start", error: "not_found", server: serverName },
|
|
603
|
-
};
|
|
604
|
-
}
|
|
605
|
-
if (isServerDisabled(definition)) return disabledResult("auth-start", serverName);
|
|
606
|
-
|
|
607
|
-
try {
|
|
608
|
-
const serverUrl = resolveServerUrl(definition);
|
|
609
|
-
if (!serverUrl || !supportsOAuth(definition)) {
|
|
610
|
-
return {
|
|
611
|
-
content: [{ type: "text" as const, text: `Server "${serverName}" is not configured for OAuth over HTTP.` }],
|
|
612
|
-
details: { mode: "auth-start", error: "oauth_not_supported", server: serverName },
|
|
613
|
-
};
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
const { authorizationUrl } = state.authStorageOptions
|
|
617
|
-
? ownedSignal
|
|
618
|
-
? await startAuth(serverName, serverUrl, definition, { authStorageOptions: state.authStorageOptions, signal: ownedSignal, runtime: state.oauthRuntime })
|
|
619
|
-
: await startAuth(serverName, serverUrl, definition, { authStorageOptions: state.authStorageOptions, runtime: state.oauthRuntime })
|
|
620
|
-
: ownedSignal
|
|
621
|
-
? await startAuth(serverName, serverUrl, definition, { signal: ownedSignal, runtime: state.oauthRuntime })
|
|
622
|
-
: await startAuth(serverName, serverUrl, definition, { runtime: state.oauthRuntime });
|
|
623
|
-
if (!authorizationUrl) {
|
|
624
|
-
return {
|
|
625
|
-
content: [{ type: "text" as const, text: `OAuth authentication successful for "${serverName}".` }],
|
|
626
|
-
details: { mode: "auth-start", server: serverName, authenticated: true },
|
|
627
|
-
};
|
|
628
|
-
}
|
|
629
|
-
|
|
630
|
-
if (getRedirectDetails(authorizationUrl).remote) {
|
|
631
|
-
try {
|
|
632
|
-
await state.openBrowser(authorizationUrl);
|
|
633
|
-
} catch (error) {
|
|
634
|
-
if (isAbortError(error, ownedSignal)) throw error;
|
|
635
|
-
}
|
|
636
|
-
} else {
|
|
637
|
-
ensureBackgroundAuthWatcher(state, serverName, serverUrl, definition);
|
|
638
|
-
}
|
|
639
|
-
|
|
640
|
-
return {
|
|
641
|
-
content: [{ type: "text" as const, text: formatManualAuthInstructions(serverName, authorizationUrl) }],
|
|
642
|
-
details: { mode: "auth-start", server: serverName, authorizationUrl },
|
|
643
|
-
};
|
|
644
|
-
} catch (error) {
|
|
645
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
646
|
-
return {
|
|
647
|
-
content: [{ type: "text" as const, text: `Failed to start OAuth for "${serverName}": ${message}` }],
|
|
648
|
-
details: { mode: "auth-start", error: "auth_start_failed", server: serverName, message },
|
|
649
|
-
};
|
|
650
|
-
}
|
|
651
|
-
}
|
|
652
|
-
|
|
653
|
-
export async function executeAuthComplete(state: McpExtensionState, serverName: string, input: string, signal?: AbortSignal): Promise<ProxyToolResult> {
|
|
654
|
-
const ownedSignal = combineAbortSignals(state.owner?.signal, signal);
|
|
655
|
-
throwIfAborted(ownedSignal);
|
|
656
|
-
const definition = state.config.mcpServers[serverName];
|
|
657
|
-
if (!definition) {
|
|
658
|
-
return {
|
|
659
|
-
content: [{ type: "text" as const, text: `Server "${serverName}" not found. Use mcp({}) to see available servers.` }],
|
|
660
|
-
details: { mode: "auth-complete", error: "not_found", server: serverName },
|
|
661
|
-
};
|
|
662
|
-
}
|
|
663
|
-
if (isServerDisabled(definition)) return disabledResult("auth-complete", serverName);
|
|
664
|
-
|
|
665
|
-
try {
|
|
666
|
-
const status = state.authStorageOptions
|
|
667
|
-
? ownedSignal
|
|
668
|
-
? await completeAuthFromInput(serverName, input, { authStorageOptions: state.authStorageOptions, signal: ownedSignal, runtime: state.oauthRuntime })
|
|
669
|
-
: await completeAuthFromInput(serverName, input, { authStorageOptions: state.authStorageOptions, runtime: state.oauthRuntime })
|
|
670
|
-
: ownedSignal
|
|
671
|
-
? await completeAuthFromInput(serverName, input, { signal: ownedSignal, runtime: state.oauthRuntime })
|
|
672
|
-
: await completeAuthFromInput(serverName, input, { runtime: state.oauthRuntime });
|
|
673
|
-
if (status !== "authenticated") {
|
|
674
|
-
return {
|
|
675
|
-
content: [{ type: "text" as const, text: `OAuth authentication did not complete for "${serverName}".` }],
|
|
676
|
-
details: { mode: "auth-complete", error: "not_authenticated", server: serverName, status },
|
|
677
|
-
};
|
|
678
|
-
}
|
|
679
|
-
|
|
680
|
-
await state.manager.close(serverName);
|
|
681
|
-
clearFailure(state, serverName, "auth-complete");
|
|
682
|
-
updateStatusBar(state);
|
|
683
|
-
return {
|
|
684
|
-
content: [{ type: "text" as const, text: `OAuth authentication successful for "${serverName}". Run mcp({ connect: "${serverName}" }) to connect with the new token.` }],
|
|
685
|
-
details: { mode: "auth-complete", server: serverName, authenticated: true },
|
|
686
|
-
};
|
|
687
|
-
} catch (error) {
|
|
688
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
689
|
-
return {
|
|
690
|
-
content: [{ type: "text" as const, text: `Failed to complete OAuth for "${serverName}": ${message}` }],
|
|
691
|
-
details: { mode: "auth-complete", error: "auth_complete_failed", server: serverName, message },
|
|
692
|
-
};
|
|
693
|
-
}
|
|
694
|
-
}
|
|
695
|
-
|
|
696
|
-
export function executeDescribe(state: McpExtensionState, toolName: string, serverOverride?: string): ProxyToolResult {
|
|
697
|
-
let serverName: string | undefined;
|
|
698
|
-
let toolMeta: ToolMetadata | undefined;
|
|
699
|
-
let disabledMatch: string | undefined;
|
|
700
|
-
let failedMatch: string | undefined;
|
|
701
|
-
|
|
702
|
-
if (serverOverride) {
|
|
703
|
-
if (!state.config.mcpServers[serverOverride]) {
|
|
704
|
-
return {
|
|
705
|
-
content: [{ type: "text" as const, text: `Server "${serverOverride}" not found. Use mcp({}) to see available servers.` }],
|
|
706
|
-
details: { mode: "describe", error: "server_not_found", server: serverOverride, requestedTool: toolName },
|
|
707
|
-
};
|
|
708
|
-
}
|
|
709
|
-
const match = getServerScopedToolMatch(state.toolMetadata.get(serverOverride), toolName);
|
|
710
|
-
if (match === "ambiguous") return ambiguousServerToolResult("describe", toolName, serverOverride);
|
|
711
|
-
if (isServerDisabled(state.config.mcpServers[serverOverride])) return disabledResult("describe", serverOverride);
|
|
712
|
-
if (isServerInActiveFailureBackoff(state, serverOverride)) return serverBackoffResult(state, "describe", serverOverride);
|
|
713
|
-
serverName = serverOverride;
|
|
714
|
-
toolMeta = match?.tool;
|
|
715
|
-
} else {
|
|
716
|
-
const matches: Array<{ server: string; tool: ToolMetadata; precedence: number }> = [];
|
|
717
|
-
for (const [server, metadata] of state.toolMetadata.entries()) {
|
|
718
|
-
const candidates = getServerScopedToolCandidates(metadata, toolName);
|
|
719
|
-
if (!candidates) continue;
|
|
720
|
-
if (isServerDisabled(state.config.mcpServers[server])) {
|
|
721
|
-
disabledMatch ??= server;
|
|
722
|
-
continue;
|
|
723
|
-
}
|
|
724
|
-
if (isServerInActiveFailureBackoff(state, server)) {
|
|
725
|
-
failedMatch ??= server;
|
|
726
|
-
continue;
|
|
727
|
-
}
|
|
728
|
-
for (const tool of candidates.tools) matches.push({ server, tool, precedence: candidates.precedence });
|
|
729
|
-
}
|
|
730
|
-
if (matches.length > 0) {
|
|
731
|
-
const precedence = Math.min(...matches.map(match => match.precedence));
|
|
732
|
-
const bestMatches = matches.filter(match => match.precedence === precedence);
|
|
733
|
-
if (bestMatches.length > 1) return ambiguousToolResult("describe", toolName);
|
|
734
|
-
serverName = bestMatches[0]!.server;
|
|
735
|
-
toolMeta = bestMatches[0]!.tool;
|
|
736
|
-
}
|
|
737
|
-
}
|
|
738
|
-
|
|
739
|
-
if (!serverName || !toolMeta) {
|
|
740
|
-
if (disabledMatch) return disabledResult("describe", disabledMatch);
|
|
741
|
-
if (failedMatch) return serverBackoffResult(state, "describe", failedMatch);
|
|
742
|
-
const suggestions = rankSuggestions(state, toolName, 5, serverOverride);
|
|
743
|
-
const suggestionText = suggestions.length > 0 ? ` Did you mean: ${suggestions.join(", ")}` : "";
|
|
744
|
-
const scopeText = serverOverride ? ` on server "${serverOverride}"` : "";
|
|
745
|
-
const searchHint = serverOverride
|
|
746
|
-
? `mcp({ search: "...", server: "${serverOverride}" })`
|
|
747
|
-
: `mcp({ search: "..." })`;
|
|
748
|
-
return {
|
|
749
|
-
content: [{ type: "text" as const, text: `Tool "${toolName}" not found${scopeText}. Use ${searchHint} to search.${suggestionText}` }],
|
|
750
|
-
details: { mode: "describe", error: "tool_not_found", server: serverOverride, requestedTool: toolName, suggestions },
|
|
751
|
-
};
|
|
752
|
-
}
|
|
753
|
-
|
|
754
|
-
const approvalMarker = isToolCallApprovalRequired(state.config, serverName, toolMeta, state.toolMetadata)
|
|
755
|
-
? " (requires approval)"
|
|
756
|
-
: "";
|
|
757
|
-
let text = `${toolMeta.name}${approvalMarker}\n`;
|
|
758
|
-
text += `Server: ${serverName}\n`;
|
|
759
|
-
if (toolMeta.resourceUri) {
|
|
760
|
-
text += `Type: Resource (reads from ${toolMeta.resourceUri})\n`;
|
|
761
|
-
}
|
|
762
|
-
text += `\n${toolMeta.description || "(no description)"}\n`;
|
|
763
|
-
|
|
764
|
-
if (toolMeta.inputSchema && !toolMeta.resourceUri) {
|
|
765
|
-
const shape = renderTsShape(toolMeta.inputSchema);
|
|
766
|
-
text += shape === null ? `\nParameters:\n${formatSchema(toolMeta.inputSchema)}` : `\nShape:\n${shape}`;
|
|
767
|
-
} else if (toolMeta.resourceUri) {
|
|
768
|
-
text += `\nNo parameters required (resource tool).`;
|
|
769
|
-
} else {
|
|
770
|
-
text += `\nNo parameters defined.`;
|
|
771
|
-
}
|
|
772
|
-
|
|
773
|
-
return {
|
|
774
|
-
content: [{ type: "text" as const, text: text.trim() }],
|
|
775
|
-
details: { mode: "describe", tool: toolMeta, server: serverName },
|
|
776
|
-
};
|
|
777
|
-
}
|
|
778
|
-
|
|
779
|
-
function renderSearchResults(
|
|
780
|
-
state: McpExtensionState,
|
|
781
|
-
query: string,
|
|
782
|
-
server: string | undefined,
|
|
783
|
-
showSchemas: boolean,
|
|
784
|
-
limit: number,
|
|
785
|
-
offset: number,
|
|
786
|
-
matches: Array<{ server: string; tool: ToolMetadata; score: number }>,
|
|
787
|
-
backend?: SemanticSearchBackend,
|
|
788
|
-
): ProxyToolResult {
|
|
789
|
-
const page = paginate(matches, offset, limit);
|
|
790
|
-
if (page.total === 0) {
|
|
791
|
-
const connectingServers = server
|
|
792
|
-
? state.config.mcpServers[server] && state.manager.isConnecting(server) ? [server] : []
|
|
793
|
-
: Object.keys(state.config.mcpServers)
|
|
794
|
-
.filter(name => !isServerDisabled(state.config.mcpServers[name]) && state.manager.isConnecting(name))
|
|
795
|
-
.sort((a, b) => a.localeCompare(b));
|
|
796
|
-
const scope = server ? ` in "${server}"` : "";
|
|
797
|
-
const msg = backend?.requested === "semantic" && backend.used === "semantic" && backend.abstained
|
|
798
|
-
? `Jev found no suitable tool for "${query}"${scope}`
|
|
799
|
-
: `No tools matching "${query}"${scope}`;
|
|
800
|
-
const connectingMessage = connectingServers.length === 1
|
|
801
|
-
? ` Server "${connectingServers[0]}" is still connecting; retry in a moment.`
|
|
802
|
-
: connectingServers.length > 1
|
|
803
|
-
? ` Servers ${connectingServers.map(name => `"${name}"`).join(", ")} are still connecting; retry in a moment.`
|
|
804
|
-
: "";
|
|
805
|
-
return {
|
|
806
|
-
content: [{ type: "text" as const, text: `${msg}${connectingMessage}` }],
|
|
807
|
-
details: {
|
|
808
|
-
mode: "search", matches: [], count: 0, hasMore: false, nextOffset: null, query,
|
|
809
|
-
...(backend ? { backend } : {}),
|
|
810
|
-
...(connectingServers.length > 0 ? { connectingServers } : {}),
|
|
811
|
-
},
|
|
812
|
-
};
|
|
813
|
-
}
|
|
814
|
-
|
|
815
|
-
let text = `Found ${page.total} tool${page.total === 1 ? "" : "s"} matching "${query}":\n\n`;
|
|
816
|
-
for (const match of page.items) {
|
|
817
|
-
const approvalMarker = isToolCallApprovalRequired(state.config, match.server, match.tool, state.toolMetadata)
|
|
818
|
-
? " (requires approval)"
|
|
819
|
-
: "";
|
|
820
|
-
if (showSchemas) {
|
|
821
|
-
text += `${match.tool.name}${approvalMarker}\n`;
|
|
822
|
-
text += ` ${match.tool.description || "(no description)"}\n`;
|
|
823
|
-
if (match.tool.inputSchema && !match.tool.resourceUri) {
|
|
824
|
-
const shape = renderTsShape(match.tool.inputSchema);
|
|
825
|
-
text += shape === null
|
|
826
|
-
? `\n Parameters:\n${formatSchema(match.tool.inputSchema, " ")}\n`
|
|
827
|
-
: `\n Shape:\n${shape.split("\n").map(line => ` ${line}`).join("\n")}\n`;
|
|
828
|
-
} else if (match.tool.resourceUri) {
|
|
829
|
-
text += " No parameters (resource tool).\n";
|
|
830
|
-
}
|
|
831
|
-
text += "\n";
|
|
832
|
-
} else {
|
|
833
|
-
text += `- ${match.tool.name}${approvalMarker}`;
|
|
834
|
-
if (match.tool.description) text += ` - ${truncateAtWord(match.tool.description, 50)}`;
|
|
835
|
-
text += "\n";
|
|
836
|
-
}
|
|
837
|
-
}
|
|
838
|
-
if (page.hasMore) text += `\n${page.items.length} of ${page.total} — offset: ${page.nextOffset} for more\n`;
|
|
839
|
-
|
|
840
|
-
return {
|
|
841
|
-
content: [{ type: "text" as const, text: text.trim() }],
|
|
842
|
-
details: {
|
|
843
|
-
mode: "search",
|
|
844
|
-
matches: page.items.map(match => ({ server: match.server, tool: match.tool.name, score: match.score })),
|
|
845
|
-
count: page.total, hasMore: page.hasMore, nextOffset: page.nextOffset, query,
|
|
846
|
-
...(backend ? { backend } : {}),
|
|
847
|
-
},
|
|
848
|
-
};
|
|
849
|
-
}
|
|
850
|
-
|
|
851
|
-
export function executeSearch(
|
|
852
|
-
state: McpExtensionState,
|
|
853
|
-
query: string,
|
|
854
|
-
regex?: boolean,
|
|
855
|
-
server?: string,
|
|
856
|
-
includeSchemas?: boolean,
|
|
857
|
-
limit = 12,
|
|
858
|
-
offset = 0,
|
|
859
|
-
searchMode: "lexical" | "semantic" = "lexical",
|
|
860
|
-
signal?: AbortSignal,
|
|
861
|
-
semanticEvaluator?: SemanticSearchEvaluator,
|
|
862
|
-
): ProxyToolResult | Promise<ProxyToolResult> {
|
|
863
|
-
const showSchemas = includeSchemas !== false;
|
|
864
|
-
if ((searchMode as string) !== "lexical" && (searchMode as string) !== "semantic") {
|
|
865
|
-
return {
|
|
866
|
-
content: [{ type: "text" as const, text: "Search mode must be lexical or semantic." }],
|
|
867
|
-
details: { mode: "search", error: "invalid_search_mode", query },
|
|
868
|
-
};
|
|
869
|
-
}
|
|
870
|
-
if (server && isServerDisabled(state.config.mcpServers[server])) return disabledResult("search", server);
|
|
871
|
-
if (server && isServerInActiveFailureBackoff(state, server)) return serverBackoffResult(state, "search", server);
|
|
872
|
-
if (searchMode === "semantic" && regex) {
|
|
873
|
-
return {
|
|
874
|
-
content: [{ type: "text" as const, text: "Semantic search cannot be combined with regex search." }],
|
|
875
|
-
details: { mode: "search", error: "invalid_search_mode", query },
|
|
876
|
-
};
|
|
877
|
-
}
|
|
878
|
-
if (searchMode === "semantic") {
|
|
879
|
-
return semanticSearch(state, query, server, signal, semanticEvaluator).then(result => {
|
|
880
|
-
if (!result.ok) {
|
|
881
|
-
return {
|
|
882
|
-
content: [{ type: "text" as const, text: `Semantic search failed: ${result.error.message}` }],
|
|
883
|
-
details: { mode: "search", error: result.error.code, message: result.error.message, query },
|
|
884
|
-
};
|
|
885
|
-
}
|
|
886
|
-
return renderSearchResults(state, query, server, showSchemas, limit, offset, result.matches, result.backend);
|
|
887
|
-
});
|
|
888
|
-
}
|
|
889
|
-
|
|
890
|
-
let matches: Array<{ server: string; tool: ToolMetadata; score: number }>;
|
|
891
|
-
if (regex) {
|
|
892
|
-
let pattern: RegExp;
|
|
893
|
-
try {
|
|
894
|
-
if (query.length > MAX_REGEX_SEARCH_QUERY_LENGTH) {
|
|
895
|
-
return {
|
|
896
|
-
content: [{ type: "text" as const, text: `Regex query is too long; maximum length is ${MAX_REGEX_SEARCH_QUERY_LENGTH} characters.` }],
|
|
897
|
-
details: { mode: "search", error: "query_too_long", query, maxLength: MAX_REGEX_SEARCH_QUERY_LENGTH },
|
|
898
|
-
};
|
|
899
|
-
}
|
|
900
|
-
pattern = new RegExp(query, "i");
|
|
901
|
-
let safety;
|
|
902
|
-
try {
|
|
903
|
-
const { checkSync } = require("recheck") as typeof import("recheck");
|
|
904
|
-
safety = checkSync(query, "i", REGEX_SAFETY_CHECK_PARAMS);
|
|
905
|
-
} catch (error) {
|
|
906
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
907
|
-
return {
|
|
908
|
-
content: [{ type: "text" as const, text: "Regex query rejected because safety analysis failed." }],
|
|
909
|
-
details: { mode: "search", error: "unsafe_pattern", query, reason },
|
|
910
|
-
};
|
|
911
|
-
}
|
|
912
|
-
if (safety.status !== "safe") {
|
|
913
|
-
return {
|
|
914
|
-
content: [{ type: "text" as const, text: `Regex query rejected as unsafe (${safety.status}).` }],
|
|
915
|
-
details: { mode: "search", error: "unsafe_pattern", query, safetyStatus: safety.status },
|
|
916
|
-
};
|
|
917
|
-
}
|
|
918
|
-
} catch {
|
|
919
|
-
return {
|
|
920
|
-
content: [{ type: "text" as const, text: `Invalid regex: ${query}` }],
|
|
921
|
-
details: { mode: "search", error: "invalid_pattern", query },
|
|
922
|
-
};
|
|
923
|
-
}
|
|
924
|
-
|
|
925
|
-
matches = [];
|
|
926
|
-
const globalPrefix = state.config.settings?.toolPrefix ?? "server";
|
|
927
|
-
for (const [serverName, metadata] of state.toolMetadata.entries()) {
|
|
928
|
-
const definition = state.config.mcpServers[serverName];
|
|
929
|
-
if (isServerDisabled(definition)) continue;
|
|
930
|
-
if (isServerInActiveFailureBackoff(state, serverName)) continue;
|
|
931
|
-
if (server && serverName !== server) continue;
|
|
932
|
-
for (const tool of metadata) {
|
|
933
|
-
const matched = pattern.test(tool.name) || pattern.test(tool.description)
|
|
934
|
-
|| resolveSearchKeywords(definition, tool.originalName, serverName, globalPrefix).some(keyword => pattern.test(keyword));
|
|
935
|
-
if (matched) matches.push({ server: serverName, tool, score: 0 });
|
|
936
|
-
}
|
|
937
|
-
}
|
|
938
|
-
} else if (query.trim().length === 0) {
|
|
939
|
-
if (!server) {
|
|
940
|
-
return {
|
|
941
|
-
content: [{ type: "text" as const, text: "Search query cannot be empty" }],
|
|
942
|
-
details: { mode: "search", error: "empty_query" },
|
|
943
|
-
};
|
|
944
|
-
}
|
|
945
|
-
matches = (state.toolMetadata.get(server) ?? [])
|
|
946
|
-
.map(tool => ({ server, tool, score: 0 }))
|
|
947
|
-
.sort((a, b) => a.tool.name.localeCompare(b.tool.name));
|
|
948
|
-
} else {
|
|
949
|
-
matches = rankToolMatches(state, query, server);
|
|
950
|
-
}
|
|
951
|
-
|
|
952
|
-
return renderSearchResults(state, query, server, showSchemas, limit, offset, matches);
|
|
953
|
-
}
|
|
954
|
-
|
|
955
|
-
export function executeList(state: McpExtensionState, server: string): ProxyToolResult {
|
|
956
|
-
const definition = state.config.mcpServers[server];
|
|
957
|
-
if (!definition) {
|
|
958
|
-
return {
|
|
959
|
-
content: [{ type: "text" as const, text: `Server "${server}" not found. Use mcp({}) to see available servers.` }],
|
|
960
|
-
details: { mode: "list", server, tools: [], count: 0, error: "not_found" },
|
|
961
|
-
};
|
|
962
|
-
}
|
|
963
|
-
if (isServerDisabled(definition)) return disabledResult("list", server);
|
|
964
|
-
|
|
965
|
-
const metadata = state.toolMetadata.get(server);
|
|
966
|
-
const toolNames = metadata?.map(m => m.name) ?? [];
|
|
967
|
-
const connection = state.manager.getConnection(server);
|
|
968
|
-
if (isServerInActiveFailureBackoff(state, server)) {
|
|
969
|
-
return {
|
|
970
|
-
...serverBackoffResult(state, "list", server),
|
|
971
|
-
details: { mode: "list", server, tools: [], count: 0, error: "server_backoff" },
|
|
972
|
-
};
|
|
973
|
-
}
|
|
974
|
-
const instructions = state.serverInstructions.get(server);
|
|
975
|
-
let instructionsText = "";
|
|
976
|
-
if (instructions) {
|
|
977
|
-
const preview = truncateAtWord(instructions, INSTRUCTIONS_PREVIEW_LENGTH);
|
|
978
|
-
instructionsText = `\n\nServer instructions:\n${preview}`;
|
|
979
|
-
if (preview !== instructions) {
|
|
980
|
-
instructionsText += `\nUse mcp({ instructions: "${server}" }) for the full text.`;
|
|
981
|
-
}
|
|
982
|
-
}
|
|
983
|
-
|
|
984
|
-
if (toolNames.length === 0) {
|
|
985
|
-
if (connection?.status === "connected") {
|
|
986
|
-
return {
|
|
987
|
-
content: [{ type: "text" as const, text: `Server "${server}" has no tools.${instructionsText}` }],
|
|
988
|
-
details: { mode: "list", server, tools: [], count: 0, hasInstructions: Boolean(instructions) },
|
|
989
|
-
};
|
|
990
|
-
}
|
|
991
|
-
if (metadata !== undefined) {
|
|
992
|
-
return {
|
|
993
|
-
content: [{ type: "text" as const, text: `Server "${server}" has no cached tools (not connected).${instructionsText}` }],
|
|
994
|
-
details: { mode: "list", server, tools: [], count: 0, cached: true, hasInstructions: Boolean(instructions) },
|
|
995
|
-
};
|
|
996
|
-
}
|
|
997
|
-
return {
|
|
998
|
-
content: [{ type: "text" as const, text: `Server "${server}" is configured but not connected. Use mcp({ connect: "${server}" }) or /mcp reconnect ${server} to retry.${instructionsText}` }],
|
|
999
|
-
details: { mode: "list", server, tools: [], count: 0, error: "not_connected", hasInstructions: Boolean(instructions) },
|
|
1000
|
-
};
|
|
1001
|
-
}
|
|
1002
|
-
|
|
1003
|
-
// "not connected" alone reads as an outage while the tools listed below are
|
|
1004
|
-
// real and the connection is simply lazy (tools served from cache).
|
|
1005
|
-
// Distinguish auth from plain laziness so the caller knows which remedy applies.
|
|
1006
|
-
let cachedNote = "";
|
|
1007
|
-
if (connection?.status !== "connected") {
|
|
1008
|
-
if (connection?.status === "needs-auth") {
|
|
1009
|
-
cachedNote = ` (needs auth — run mcp({ action: "auth-start", server: "${server}" }))`;
|
|
1010
|
-
} else {
|
|
1011
|
-
cachedNote = ` (lazy: tools from cache, not connected yet — mcp({ connect: "${server}" }) to connect)`;
|
|
1012
|
-
}
|
|
1013
|
-
}
|
|
1014
|
-
let text = `${server} (${toolNames.length} tools${cachedNote}):\n\n`;
|
|
1015
|
-
|
|
1016
|
-
const descMap = new Map<string, string>();
|
|
1017
|
-
if (metadata) {
|
|
1018
|
-
for (const m of metadata) {
|
|
1019
|
-
descMap.set(m.name, m.description);
|
|
1020
|
-
}
|
|
1021
|
-
}
|
|
1022
|
-
|
|
1023
|
-
for (const tool of toolNames) {
|
|
1024
|
-
const desc = descMap.get(tool) ?? "";
|
|
1025
|
-
const truncated = truncateAtWord(desc, 50);
|
|
1026
|
-
text += `- ${tool}`;
|
|
1027
|
-
if (truncated) text += ` - ${truncated}`;
|
|
1028
|
-
text += "\n";
|
|
1029
|
-
}
|
|
1030
|
-
|
|
1031
|
-
text += instructionsText;
|
|
1032
|
-
|
|
1033
|
-
return {
|
|
1034
|
-
content: [{ type: "text" as const, text: text.trim() }],
|
|
1035
|
-
details: { mode: "list", server, tools: toolNames, count: toolNames.length, hasInstructions: Boolean(instructions) },
|
|
1036
|
-
};
|
|
1037
|
-
}
|
|
1038
|
-
|
|
1039
|
-
export function executeInstructions(state: McpExtensionState, server: string): ProxyToolResult {
|
|
1040
|
-
const definition = state.config.mcpServers[server];
|
|
1041
|
-
if (!definition) {
|
|
1042
|
-
return {
|
|
1043
|
-
content: [{ type: "text" as const, text: `Server "${server}" not found. Use mcp({}) to see available servers.` }],
|
|
1044
|
-
details: { mode: "instructions", server, error: "not_found" },
|
|
1045
|
-
};
|
|
1046
|
-
}
|
|
1047
|
-
if (isServerDisabled(definition)) return disabledResult("instructions", server);
|
|
1048
|
-
if (isServerInActiveFailureBackoff(state, server)) return serverBackoffResult(state, "instructions", server);
|
|
1049
|
-
|
|
1050
|
-
const instructions = state.serverInstructions.get(server);
|
|
1051
|
-
if (instructions) {
|
|
1052
|
-
return {
|
|
1053
|
-
content: [{ type: "text" as const, text: `${server} instructions:\n\n${instructions}` }],
|
|
1054
|
-
details: { mode: "instructions", server, length: instructions.length },
|
|
1055
|
-
};
|
|
1056
|
-
}
|
|
1057
|
-
|
|
1058
|
-
const connection = state.manager.getConnection(server);
|
|
1059
|
-
if (connection?.status === "connected") {
|
|
1060
|
-
return {
|
|
1061
|
-
content: [{ type: "text" as const, text: `Server "${server}" does not provide instructions.` }],
|
|
1062
|
-
details: { mode: "instructions", server, error: "no_instructions" },
|
|
1063
|
-
};
|
|
1064
|
-
}
|
|
1065
|
-
|
|
1066
|
-
return {
|
|
1067
|
-
content: [{ type: "text" as const, text: `No instructions cached for "${server}". Use mcp({ connect: "${server}" }) to connect and refresh.` }],
|
|
1068
|
-
details: { mode: "instructions", server, error: "not_connected" },
|
|
1069
|
-
};
|
|
1070
|
-
}
|
|
1071
|
-
|
|
1072
|
-
export async function executeConnect(state: McpExtensionState, serverName: string, signal?: AbortSignal): Promise<ProxyToolResult> {
|
|
1073
|
-
const ownedSignal = combineAbortSignals(state.owner?.signal, signal);
|
|
1074
|
-
throwIfAborted(ownedSignal);
|
|
1075
|
-
const definition = state.config.mcpServers[serverName];
|
|
1076
|
-
if (!definition) {
|
|
1077
|
-
return {
|
|
1078
|
-
content: [{ type: "text" as const, text: `Server "${serverName}" not found. Use mcp({}) to see available servers.` }],
|
|
1079
|
-
details: { mode: "connect", error: "not_found", server: serverName },
|
|
1080
|
-
};
|
|
1081
|
-
}
|
|
1082
|
-
if (isServerDisabled(definition)) return disabledResult("connect", serverName);
|
|
1083
|
-
|
|
1084
|
-
try {
|
|
1085
|
-
if (state.ui) {
|
|
1086
|
-
state.ui.setStatus("mcp", formatMcpStatus(state.config, `connecting to ${serverName}...`));
|
|
1087
|
-
}
|
|
1088
|
-
const currentConnection = state.manager.getConnection(serverName);
|
|
1089
|
-
let connection = currentConnection?.status === "connected"
|
|
1090
|
-
? await state.manager.reconnect(serverName, definition, currentConnection, ownedSignal)
|
|
1091
|
-
: await state.manager.connect(serverName, definition, ownedSignal);
|
|
1092
|
-
if (connection.status === "needs-auth") {
|
|
1093
|
-
const autoAuth = await attemptAutoAuth(state, serverName, ownedSignal);
|
|
1094
|
-
if (autoAuth.status === "failed") {
|
|
1095
|
-
return {
|
|
1096
|
-
content: [{ type: "text" as const, text: autoAuth.message }],
|
|
1097
|
-
details: { mode: "connect", error: "auth_required", server: serverName, message: autoAuth.message },
|
|
1098
|
-
};
|
|
1099
|
-
}
|
|
1100
|
-
if (autoAuth.status === "success") {
|
|
1101
|
-
await state.manager.close(serverName);
|
|
1102
|
-
throwIfAborted(ownedSignal);
|
|
1103
|
-
connection = ownedSignal
|
|
1104
|
-
? await state.manager.connect(serverName, definition, ownedSignal)
|
|
1105
|
-
: await state.manager.connect(serverName, definition);
|
|
1106
|
-
}
|
|
1107
|
-
if (connection.status === "needs-auth") {
|
|
1108
|
-
const message = getAuthRequiredMessage(state, serverName);
|
|
1109
|
-
return {
|
|
1110
|
-
content: [{ type: "text" as const, text: message }],
|
|
1111
|
-
details: { mode: "connect", error: "auth_required", server: serverName, message },
|
|
1112
|
-
};
|
|
1113
|
-
}
|
|
1114
|
-
}
|
|
1115
|
-
const prefix = state.config.settings?.toolPrefix ?? "server";
|
|
1116
|
-
const { metadata } = buildToolMetadata(connection.tools, connection.resources, definition, serverName, prefix, state.config.mcpServers, state.toolMetadata);
|
|
1117
|
-
state.toolMetadata.set(serverName, metadata);
|
|
1118
|
-
if (!connection.promptDiscoveryFailed) {
|
|
1119
|
-
state.promptMetadata?.set(serverName, reconstructPromptMetadata(serverName, connection.prompts ?? [], prefix, definition));
|
|
1120
|
-
state.promptMetadataLive?.add(serverName);
|
|
1121
|
-
}
|
|
1122
|
-
if (connection.instructions) {
|
|
1123
|
-
state.serverInstructions.set(serverName, connection.instructions);
|
|
1124
|
-
} else {
|
|
1125
|
-
state.serverInstructions.delete(serverName);
|
|
1126
|
-
}
|
|
1127
|
-
updateMetadataCache(state, serverName);
|
|
1128
|
-
const restored = clearFailure(state, serverName, "proxy-connect");
|
|
1129
|
-
if (!restored) notifyToolMetadataUpdated(state, serverName, "proxy-connect");
|
|
1130
|
-
markKeepAliveAfterConnect(state, serverName);
|
|
1131
|
-
updateStatusBar(state);
|
|
1132
|
-
return executeList(state, serverName);
|
|
1133
|
-
} catch (error) {
|
|
1134
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
1135
|
-
if (!isAbortError(error, ownedSignal)) recordFailure(state, serverName, message);
|
|
1136
|
-
updateStatusBar(state);
|
|
1137
|
-
return {
|
|
1138
|
-
content: [{ type: "text" as const, text: `Failed to connect to "${serverName}": ${message}` }],
|
|
1139
|
-
details: { mode: "connect", error: isAbortError(error, ownedSignal) ? "aborted" : "connect_failed", server: serverName, message },
|
|
1140
|
-
};
|
|
1141
|
-
}
|
|
1142
|
-
}
|
|
1143
|
-
|
|
1144
|
-
export async function executeCall(
|
|
1145
|
-
state: McpExtensionState,
|
|
1146
|
-
toolName: string,
|
|
1147
|
-
args?: Record<string, unknown>,
|
|
1148
|
-
serverOverride?: string,
|
|
1149
|
-
getPiTools?: () => ToolInfo[],
|
|
1150
|
-
signal?: AbortSignal,
|
|
1151
|
-
origin?: "proxy" | "script",
|
|
1152
|
-
// Internal consumers own successful data delivery; origin remains approval metadata only.
|
|
1153
|
-
internalDelivery?: { onSuccess: (data: unknown) => void },
|
|
1154
|
-
): Promise<ProxyToolResult> {
|
|
1155
|
-
const ownedSignal = combineAbortSignals(state.owner?.signal, signal);
|
|
1156
|
-
throwIfAborted(ownedSignal);
|
|
1157
|
-
let serverName: string | undefined = serverOverride;
|
|
1158
|
-
let toolMeta: ToolMetadata | undefined;
|
|
1159
|
-
let autoAuthAttempted = false;
|
|
1160
|
-
const prefixMode = state.config.settings?.toolPrefix ?? "server";
|
|
1161
|
-
const disabledCallResult = (disabledServer: string, metadata?: ToolMetadata): ProxyToolResult => {
|
|
1162
|
-
if (!metadata) {
|
|
1163
|
-
const message = `Server "${disabledServer}" is disabled. Run /mcp enable ${disabledServer} and /reload to enable it.`;
|
|
1164
|
-
return {
|
|
1165
|
-
content: [{ type: "text" as const, text: message }],
|
|
1166
|
-
details: { mode: "call", error: "server_disabled", server: disabledServer, requestedTool: toolName, message },
|
|
1167
|
-
};
|
|
1168
|
-
}
|
|
1169
|
-
const message = `Server "${disabledServer}" is disabled. Run /mcp enable ${disabledServer} and /reload to enable it.`;
|
|
1170
|
-
const identity = metadata.resourceUri
|
|
1171
|
-
? { server: disabledServer, resourceUri: metadata.resourceUri }
|
|
1172
|
-
: { server: disabledServer, tool: metadata.originalName };
|
|
1173
|
-
return {
|
|
1174
|
-
content: [{ type: "text" as const, text: message }],
|
|
1175
|
-
details: { mode: "call", error: "server_disabled", ...identity, message },
|
|
1176
|
-
};
|
|
1177
|
-
};
|
|
1178
|
-
|
|
1179
|
-
if (serverName && !state.config.mcpServers[serverName]) {
|
|
1180
|
-
return {
|
|
1181
|
-
content: [{ type: "text" as const, text: `Server "${serverName}" not found. Use mcp({}) to see available servers.` }],
|
|
1182
|
-
details: { mode: "call", error: "server_not_found", server: serverName, requestedTool: toolName },
|
|
1183
|
-
};
|
|
1184
|
-
}
|
|
1185
|
-
if (serverName) {
|
|
1186
|
-
const match = getCandidateToolMatch(state.toolMetadata.get(serverName), toolName, serverName, state);
|
|
1187
|
-
if (match === "ambiguous") return ambiguousServerToolResult("call", toolName, serverName);
|
|
1188
|
-
toolMeta = match;
|
|
1189
|
-
if (isServerDisabled(state.config.mcpServers[serverName])) {
|
|
1190
|
-
return disabledCallResult(serverName, toolMeta);
|
|
1191
|
-
}
|
|
1192
|
-
} else {
|
|
1193
|
-
const exactMatches = getEnabledToolMatches(state, toolName, true);
|
|
1194
|
-
if (exactMatches.length > 1) return ambiguousToolResult("call", toolName);
|
|
1195
|
-
if (exactMatches.length === 1) {
|
|
1196
|
-
serverName = exactMatches[0]!.server;
|
|
1197
|
-
toolMeta = exactMatches[0]!.tool;
|
|
1198
|
-
} else {
|
|
1199
|
-
const originalMatches = getEnabledOriginalToolMatches(state, toolName);
|
|
1200
|
-
if (originalMatches.length > 1) return ambiguousToolResult("call", toolName);
|
|
1201
|
-
if (originalMatches.length === 1) {
|
|
1202
|
-
serverName = originalMatches[0]!.server;
|
|
1203
|
-
toolMeta = originalMatches[0]!.tool;
|
|
1204
|
-
} else {
|
|
1205
|
-
const prefixedScope = getPrefixedServerScope(state, toolName);
|
|
1206
|
-
if (prefixedScope) {
|
|
1207
|
-
serverName = prefixedScope;
|
|
1208
|
-
const match = getCandidateToolMatch(state.toolMetadata.get(prefixedScope), toolName, prefixedScope, state);
|
|
1209
|
-
if (match === "ambiguous") return ambiguousServerToolResult("call", toolName, prefixedScope);
|
|
1210
|
-
toolMeta = match;
|
|
1211
|
-
} else {
|
|
1212
|
-
const matches: Array<{ server: string; tool: ToolMetadata }> = [];
|
|
1213
|
-
for (const [server, metadata] of state.toolMetadata) {
|
|
1214
|
-
if (isServerDisabled(state.config.mcpServers[server])) continue;
|
|
1215
|
-
for (const tool of getCandidateToolMatches(metadata, toolName, server, state)) matches.push({ server, tool });
|
|
1216
|
-
}
|
|
1217
|
-
if (matches.length > 1) return ambiguousToolResult("call", toolName);
|
|
1218
|
-
if (matches.length === 1) {
|
|
1219
|
-
serverName = matches[0]!.server;
|
|
1220
|
-
toolMeta = matches[0]!.tool;
|
|
1221
|
-
}
|
|
1222
|
-
}
|
|
1223
|
-
}
|
|
1224
|
-
}
|
|
1225
|
-
|
|
1226
|
-
if (!toolMeta) {
|
|
1227
|
-
const disabledMatches: Array<{ server: string; tool: ToolMetadata }> = [];
|
|
1228
|
-
for (const [server, metadata] of state.toolMetadata) {
|
|
1229
|
-
if (!isServerDisabled(state.config.mcpServers[server])) continue;
|
|
1230
|
-
for (const tool of getCandidateToolMatches(metadata, toolName, server, state)) disabledMatches.push({ server, tool });
|
|
1231
|
-
}
|
|
1232
|
-
if (disabledMatches.length === 1) return disabledCallResult(disabledMatches[0]!.server, disabledMatches[0]!.tool);
|
|
1233
|
-
}
|
|
1234
|
-
}
|
|
1235
|
-
|
|
1236
|
-
if (serverName && !toolMeta) {
|
|
1237
|
-
const connected = await lazyConnect(state, serverName, ownedSignal);
|
|
1238
|
-
if (connected) {
|
|
1239
|
-
const match = getCandidateToolMatch(state.toolMetadata.get(serverName), toolName, serverName, state);
|
|
1240
|
-
if (match === "ambiguous") return ambiguousServerToolResult("call", toolName, serverName);
|
|
1241
|
-
toolMeta = match;
|
|
1242
|
-
} else {
|
|
1243
|
-
const needsAuthConnection = state.manager.getConnection(serverName);
|
|
1244
|
-
if (needsAuthConnection?.status === "needs-auth") {
|
|
1245
|
-
if (!autoAuthAttempted) {
|
|
1246
|
-
autoAuthAttempted = true;
|
|
1247
|
-
const autoAuth = await attemptAutoAuth(state, serverName, ownedSignal);
|
|
1248
|
-
if (autoAuth.status === "failed") {
|
|
1249
|
-
return {
|
|
1250
|
-
content: [{ type: "text" as const, text: autoAuth.message }],
|
|
1251
|
-
details: { mode: "call", error: "auth_required", server: serverName, requestedTool: toolName, message: autoAuth.message },
|
|
1252
|
-
};
|
|
1253
|
-
}
|
|
1254
|
-
if (autoAuth.status === "success") {
|
|
1255
|
-
await state.manager.close(serverName);
|
|
1256
|
-
clearFailure(state, serverName);
|
|
1257
|
-
const connectedAfterAuth = await lazyConnect(state, serverName, ownedSignal);
|
|
1258
|
-
if (connectedAfterAuth) {
|
|
1259
|
-
const match = getCandidateToolMatch(state.toolMetadata.get(serverName), toolName, serverName, state);
|
|
1260
|
-
if (match === "ambiguous") return ambiguousServerToolResult("call", toolName, serverName);
|
|
1261
|
-
toolMeta = match;
|
|
1262
|
-
if (!toolMeta) {
|
|
1263
|
-
const suggestions = rankSuggestions(state, toolName, 5, serverName);
|
|
1264
|
-
const suggestionText = suggestions.length > 0 ? ` Did you mean: ${suggestions.join(", ")}` : "";
|
|
1265
|
-
return {
|
|
1266
|
-
content: [{ type: "text" as const, text: `Tool "${toolName}" not found on "${serverName}" after reconnect.${suggestionText}` }],
|
|
1267
|
-
details: { mode: "call", error: "tool_not_found_after_reconnect", server: serverName, requestedTool: toolName, suggestions },
|
|
1268
|
-
};
|
|
1269
|
-
}
|
|
1270
|
-
}
|
|
1271
|
-
}
|
|
1272
|
-
}
|
|
1273
|
-
|
|
1274
|
-
if (!toolMeta && state.manager.getConnection(serverName)?.status === "needs-auth") {
|
|
1275
|
-
const message = getAuthRequiredMessage(state, serverName);
|
|
1276
|
-
return {
|
|
1277
|
-
content: [{ type: "text" as const, text: message }],
|
|
1278
|
-
details: { mode: "call", error: "auth_required", server: serverName, requestedTool: toolName, message },
|
|
1279
|
-
};
|
|
1280
|
-
}
|
|
1281
|
-
}
|
|
1282
|
-
|
|
1283
|
-
if (!toolMeta) {
|
|
1284
|
-
const failedAgo = getFailureAgeSeconds(state, serverName);
|
|
1285
|
-
if (failedAgo !== null) {
|
|
1286
|
-
return {
|
|
1287
|
-
content: [{ type: "text" as const, text: `Server "${serverName}" not available (last failed ${failedAgo}s ago)` }],
|
|
1288
|
-
details: { mode: "call", error: "server_backoff", server: serverName, requestedTool: toolName },
|
|
1289
|
-
};
|
|
1290
|
-
}
|
|
1291
|
-
}
|
|
1292
|
-
}
|
|
1293
|
-
}
|
|
1294
|
-
|
|
1295
|
-
let prefixMatchedServer: string | undefined;
|
|
1296
|
-
|
|
1297
|
-
if (!serverName && !toolMeta && prefixMode !== "none") {
|
|
1298
|
-
const lazyExactMatches: { serverName: string; toolMeta: ToolMetadata }[] = [];
|
|
1299
|
-
const lazyFallbackMatches: { serverName: string; toolMeta: ToolMetadata }[] = [];
|
|
1300
|
-
const candidates = Object.keys(state.config.mcpServers)
|
|
1301
|
-
.filter(name => !isServerDisabled(state.config.mcpServers[name]))
|
|
1302
|
-
.map(name => ({ name, prefix: getServerPrefix(name, prefixMode) }))
|
|
1303
|
-
.filter(c => c.prefix && toolName.startsWith(c.prefix + "_"))
|
|
1304
|
-
.sort((a, b) => b.prefix.length - a.prefix.length);
|
|
1305
|
-
|
|
1306
|
-
for (const { name: configuredServer } of candidates) {
|
|
1307
|
-
const existingConnection = state.manager.getConnection(configuredServer);
|
|
1308
|
-
const failedAgo = getFailureAgeSeconds(state, configuredServer);
|
|
1309
|
-
if (failedAgo !== null && existingConnection?.status !== "needs-auth") continue;
|
|
1310
|
-
|
|
1311
|
-
let connected = await lazyConnect(state, configuredServer, ownedSignal);
|
|
1312
|
-
if (!connected && state.manager.getConnection(configuredServer)?.status === "needs-auth" && !autoAuthAttempted) {
|
|
1313
|
-
autoAuthAttempted = true;
|
|
1314
|
-
const autoAuth = await attemptAutoAuth(state, configuredServer, ownedSignal);
|
|
1315
|
-
if (autoAuth.status === "failed") {
|
|
1316
|
-
return {
|
|
1317
|
-
content: [{ type: "text" as const, text: autoAuth.message }],
|
|
1318
|
-
details: { mode: "call", error: "auth_required", server: configuredServer, requestedTool: toolName, message: autoAuth.message },
|
|
1319
|
-
};
|
|
1320
|
-
}
|
|
1321
|
-
if (autoAuth.status === "success") {
|
|
1322
|
-
await state.manager.close(configuredServer);
|
|
1323
|
-
clearFailure(state, configuredServer);
|
|
1324
|
-
connected = await lazyConnect(state, configuredServer, ownedSignal);
|
|
1325
|
-
}
|
|
1326
|
-
}
|
|
1327
|
-
|
|
1328
|
-
if (!connected) continue;
|
|
1329
|
-
if (!prefixMatchedServer) prefixMatchedServer = configuredServer;
|
|
1330
|
-
const metadata = state.toolMetadata.get(configuredServer);
|
|
1331
|
-
const exactMatches = getToolMatches(metadata, toolName, true);
|
|
1332
|
-
if (exactMatches.length > 1) return ambiguousToolResult("call", toolName);
|
|
1333
|
-
if (exactMatches.length === 1) {
|
|
1334
|
-
lazyExactMatches.push({ serverName: configuredServer, toolMeta: exactMatches[0]! });
|
|
1335
|
-
continue;
|
|
1336
|
-
}
|
|
1337
|
-
const fallbackMatches = getCandidateToolMatches(metadata, toolName, configuredServer, state);
|
|
1338
|
-
if (fallbackMatches.length > 1) return ambiguousToolResult("call", toolName);
|
|
1339
|
-
if (fallbackMatches.length === 1) lazyFallbackMatches.push({ serverName: configuredServer, toolMeta: fallbackMatches[0]! });
|
|
1340
|
-
}
|
|
1341
|
-
const lazyMatches = lazyExactMatches.length > 0 ? lazyExactMatches : lazyFallbackMatches;
|
|
1342
|
-
if (lazyMatches.length > 1) return ambiguousToolResult("call", toolName);
|
|
1343
|
-
if (lazyMatches.length === 1) {
|
|
1344
|
-
serverName = lazyMatches[0]!.serverName;
|
|
1345
|
-
toolMeta = lazyMatches[0]!.toolMeta;
|
|
1346
|
-
}
|
|
1347
|
-
}
|
|
1348
|
-
|
|
1349
|
-
if (!serverName || !toolMeta) {
|
|
1350
|
-
const nativeTool = !serverOverride
|
|
1351
|
-
? getPiTools?.().find((tool) => tool.name === toolName && tool.name !== "mcp")
|
|
1352
|
-
: undefined;
|
|
1353
|
-
if (nativeTool) {
|
|
1354
|
-
return {
|
|
1355
|
-
content: [{ type: "text" as const, text: `"${toolName}" is a native Pi tool. Call ${toolName} directly instead of using mcp({ tool: "${toolName}" }).` }],
|
|
1356
|
-
details: { mode: "call", error: "native_tool", requestedTool: toolName },
|
|
1357
|
-
};
|
|
1358
|
-
}
|
|
1359
|
-
|
|
1360
|
-
const hintServer = serverName ?? prefixMatchedServer;
|
|
1361
|
-
const available = hintServer ? getToolNames(state, hintServer) : [];
|
|
1362
|
-
let msg = `Tool "${toolName}" not found.`;
|
|
1363
|
-
if (available.length > 0) {
|
|
1364
|
-
msg += ` Server "${hintServer}" has: ${available.join(", ")}`;
|
|
1365
|
-
} else {
|
|
1366
|
-
msg += ` Use mcp({ search: "..." }) to search.`;
|
|
1367
|
-
}
|
|
1368
|
-
const suggestions = rankSuggestions(state, toolName, 5, serverOverride);
|
|
1369
|
-
if (suggestions.length > 0) msg += ` Did you mean: ${suggestions.join(", ")}`;
|
|
1370
|
-
return {
|
|
1371
|
-
content: [{ type: "text" as const, text: msg }],
|
|
1372
|
-
details: { mode: "call", error: "tool_not_found", requestedTool: toolName, hintServer, suggestions },
|
|
1373
|
-
};
|
|
1374
|
-
}
|
|
1375
|
-
|
|
1376
|
-
const callIdentity = toolMeta.resourceUri
|
|
1377
|
-
? { server: serverName, resourceUri: toolMeta.resourceUri, canonicalTool: toolMeta.name }
|
|
1378
|
-
: { server: serverName, tool: toolMeta.originalName, canonicalTool: toolMeta.name };
|
|
1379
|
-
|
|
1380
|
-
let connection = state.manager.getConnection(serverName);
|
|
1381
|
-
if (connection?.status === "needs-auth") {
|
|
1382
|
-
if (!autoAuthAttempted) {
|
|
1383
|
-
autoAuthAttempted = true;
|
|
1384
|
-
const autoAuth = await attemptAutoAuth(state, serverName, ownedSignal);
|
|
1385
|
-
if (autoAuth.status === "failed") {
|
|
1386
|
-
return {
|
|
1387
|
-
content: [{ type: "text" as const, text: autoAuth.message }],
|
|
1388
|
-
details: { mode: "call", error: "auth_required", ...callIdentity, message: autoAuth.message },
|
|
1389
|
-
};
|
|
1390
|
-
}
|
|
1391
|
-
if (autoAuth.status === "success") {
|
|
1392
|
-
await state.manager.close(serverName);
|
|
1393
|
-
clearFailure(state, serverName);
|
|
1394
|
-
connection = state.manager.getConnection(serverName);
|
|
1395
|
-
}
|
|
1396
|
-
}
|
|
1397
|
-
|
|
1398
|
-
if (connection?.status === "needs-auth") {
|
|
1399
|
-
const message = getAuthRequiredMessage(state, serverName);
|
|
1400
|
-
return {
|
|
1401
|
-
content: [{ type: "text" as const, text: message }],
|
|
1402
|
-
details: { mode: "call", error: "auth_required", ...callIdentity, message },
|
|
1403
|
-
};
|
|
1404
|
-
}
|
|
1405
|
-
}
|
|
1406
|
-
if (!connection || connection.status !== "connected") {
|
|
1407
|
-
const failedAgo = getFailureAgeSeconds(state, serverName);
|
|
1408
|
-
if (failedAgo !== null) {
|
|
1409
|
-
return {
|
|
1410
|
-
content: [{ type: "text" as const, text: `Server "${serverName}" not available (last failed ${failedAgo}s ago)` }],
|
|
1411
|
-
details: { mode: "call", error: "server_backoff", ...callIdentity },
|
|
1412
|
-
};
|
|
1413
|
-
}
|
|
1414
|
-
|
|
1415
|
-
const definition = state.config.mcpServers[serverName];
|
|
1416
|
-
if (!definition) {
|
|
1417
|
-
return {
|
|
1418
|
-
content: [{ type: "text" as const, text: `Server "${serverName}" not connected` }],
|
|
1419
|
-
details: { mode: "call", error: "server_not_connected", ...callIdentity },
|
|
1420
|
-
};
|
|
1421
|
-
}
|
|
1422
|
-
|
|
1423
|
-
try {
|
|
1424
|
-
if (state.ui) {
|
|
1425
|
-
state.ui.setStatus("mcp", formatMcpStatus(state.config, `connecting to ${serverName}...`));
|
|
1426
|
-
}
|
|
1427
|
-
connection = await state.manager.connect(serverName, definition, ownedSignal);
|
|
1428
|
-
if (connection.status === "needs-auth") {
|
|
1429
|
-
if (!autoAuthAttempted) {
|
|
1430
|
-
autoAuthAttempted = true;
|
|
1431
|
-
const autoAuth = await attemptAutoAuth(state, serverName, ownedSignal);
|
|
1432
|
-
if (autoAuth.status === "failed") {
|
|
1433
|
-
return {
|
|
1434
|
-
content: [{ type: "text" as const, text: autoAuth.message }],
|
|
1435
|
-
details: { mode: "call", error: "auth_required", ...callIdentity, message: autoAuth.message },
|
|
1436
|
-
};
|
|
1437
|
-
}
|
|
1438
|
-
if (autoAuth.status === "success") {
|
|
1439
|
-
await state.manager.close(serverName);
|
|
1440
|
-
connection = await state.manager.connect(serverName, definition, ownedSignal);
|
|
1441
|
-
}
|
|
1442
|
-
}
|
|
1443
|
-
|
|
1444
|
-
if (connection.status === "needs-auth") {
|
|
1445
|
-
const message = getAuthRequiredMessage(state, serverName);
|
|
1446
|
-
return {
|
|
1447
|
-
content: [{ type: "text" as const, text: message }],
|
|
1448
|
-
details: { mode: "call", error: "auth_required", ...callIdentity, message },
|
|
1449
|
-
};
|
|
1450
|
-
}
|
|
1451
|
-
}
|
|
1452
|
-
updateServerMetadata(state, serverName);
|
|
1453
|
-
updateMetadataCache(state, serverName);
|
|
1454
|
-
const restored = clearFailure(state, serverName, "proxy-call-reconnect");
|
|
1455
|
-
if (!restored) notifyToolMetadataUpdated(state, serverName, "proxy-call-reconnect");
|
|
1456
|
-
markKeepAliveAfterConnect(state, serverName);
|
|
1457
|
-
updateStatusBar(state);
|
|
1458
|
-
const match = getCandidateToolMatch(state.toolMetadata.get(serverName), toolName, serverName, state);
|
|
1459
|
-
if (match === "ambiguous") return ambiguousServerToolResult("call", toolName, serverName);
|
|
1460
|
-
toolMeta = match;
|
|
1461
|
-
if (!toolMeta) {
|
|
1462
|
-
const available = getToolNames(state, serverName);
|
|
1463
|
-
const hint = available.length > 0
|
|
1464
|
-
? `Available tools on "${serverName}": ${available.join(", ")}`
|
|
1465
|
-
: `Server "${serverName}" has no tools.`;
|
|
1466
|
-
const suggestions = rankSuggestions(state, toolName, 5, serverName);
|
|
1467
|
-
const suggestionText = suggestions.length > 0 ? ` Did you mean: ${suggestions.join(", ")}` : "";
|
|
1468
|
-
return {
|
|
1469
|
-
content: [{ type: "text" as const, text: `Tool "${toolName}" not found on "${serverName}" after reconnect. ${hint}${suggestionText}` }],
|
|
1470
|
-
details: { mode: "call", error: "tool_not_found_after_reconnect", server: serverName, requestedTool: toolName, suggestions },
|
|
1471
|
-
};
|
|
1472
|
-
}
|
|
1473
|
-
} catch (error) {
|
|
1474
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
1475
|
-
if (!isAbortError(error, ownedSignal)) recordFailure(state, serverName, message);
|
|
1476
|
-
updateStatusBar(state);
|
|
1477
|
-
return {
|
|
1478
|
-
content: [{ type: "text" as const, text: `Failed to connect to "${serverName}": ${message}` }],
|
|
1479
|
-
details: { mode: "call", error: isAbortError(error, ownedSignal) ? "aborted" : "connect_failed", ...callIdentity, message },
|
|
1480
|
-
};
|
|
1481
|
-
}
|
|
1482
|
-
}
|
|
1483
|
-
|
|
1484
|
-
if (isServerDisabled(state.config.mcpServers[serverName])) {
|
|
1485
|
-
return disabledCallResult(serverName, toolMeta);
|
|
1486
|
-
}
|
|
1487
|
-
|
|
1488
|
-
const normalizedArgs = toolMeta.resourceUri ? args ?? {} : normalizeToolArguments(args);
|
|
1489
|
-
const validationError = toolMeta.resourceUri ? null : proxyArgumentValidationError(toolMeta.inputSchema, normalizedArgs);
|
|
1490
|
-
if (validationError) {
|
|
1491
|
-
const schemaText = `\n\nExpected parameters:\n${formatSchema(toolMeta.inputSchema)}`;
|
|
1492
|
-
const guarded = await guardMcpOutput(
|
|
1493
|
-
[{ type: "text" as const, text: validationError }],
|
|
1494
|
-
{ ...resolveMcpOutputGuardOptions(state.config.settings), prefix: "Failed to call tool: ", suffix: schemaText },
|
|
1495
|
-
);
|
|
1496
|
-
return {
|
|
1497
|
-
content: guarded.content,
|
|
1498
|
-
details: { mode: "call", error: "call_failed", ...callIdentity, message: validationError, ...guardedMcpDetails(guarded) },
|
|
1499
|
-
};
|
|
1500
|
-
}
|
|
1501
|
-
const approval = await ensureToolCallApproved(
|
|
1502
|
-
state,
|
|
1503
|
-
serverName,
|
|
1504
|
-
toolMeta,
|
|
1505
|
-
normalizedArgs,
|
|
1506
|
-
ownedSignal,
|
|
1507
|
-
origin ?? (toolMeta.resourceUri ? "resource" : "proxy"),
|
|
1508
|
-
);
|
|
1509
|
-
if (approval.ok === false) {
|
|
1510
|
-
const denied = approval.reason === "denied";
|
|
1511
|
-
const message = denied
|
|
1512
|
-
? `The user declined approval to run MCP tool "${toolMeta.originalName}" on server "${serverName}".`
|
|
1513
|
-
: `MCP tool "${toolMeta.originalName}" on server "${serverName}" is approval-gated and requires an interactive session.`;
|
|
1514
|
-
return {
|
|
1515
|
-
content: [{ type: "text" as const, text: message }],
|
|
1516
|
-
details: {
|
|
1517
|
-
mode: "call",
|
|
1518
|
-
error: denied ? "approval_denied" : "approval_required",
|
|
1519
|
-
server: serverName,
|
|
1520
|
-
tool: toolMeta.originalName,
|
|
1521
|
-
},
|
|
1522
|
-
};
|
|
1523
|
-
}
|
|
1524
|
-
|
|
1525
|
-
let uiSession: UiSessionRuntime | null = null;
|
|
1526
|
-
const requestOptions = withUiProgressBridge(
|
|
1527
|
-
state.manager.getRequestOptions?.(serverName, ownedSignal) ?? (ownedSignal ? { signal: ownedSignal } : undefined),
|
|
1528
|
-
state.ui,
|
|
1529
|
-
serverName,
|
|
1530
|
-
toolMeta.originalName,
|
|
1531
|
-
);
|
|
1532
|
-
|
|
1533
|
-
const outputGuardOptions = resolveMcpOutputGuardOptions(state.config.settings);
|
|
1534
|
-
const recoverAuthConnection = async () => {
|
|
1535
|
-
const current = state.manager.getConnection(serverName);
|
|
1536
|
-
if (current?.status === "connected") return current;
|
|
1537
|
-
|
|
1538
|
-
if (!autoAuthAttempted) {
|
|
1539
|
-
autoAuthAttempted = true;
|
|
1540
|
-
const autoAuth = await attemptAutoAuth(state, serverName, ownedSignal);
|
|
1541
|
-
if (autoAuth.status === "failed") {
|
|
1542
|
-
throw new SessionRecoveryAuthRequiredError(serverName, autoAuth.message);
|
|
1543
|
-
}
|
|
1544
|
-
if (autoAuth.status === "success") {
|
|
1545
|
-
const definition = state.config.mcpServers[serverName];
|
|
1546
|
-
if (!definition) return undefined;
|
|
1547
|
-
const afterAuth = state.manager.getConnection(serverName);
|
|
1548
|
-
if (afterAuth?.status === "connected") return afterAuth;
|
|
1549
|
-
if (afterAuth?.status === "needs-auth") {
|
|
1550
|
-
await state.manager.close(serverName);
|
|
1551
|
-
}
|
|
1552
|
-
clearFailure(state, serverName);
|
|
1553
|
-
connection = await state.manager.connect(serverName, definition, ownedSignal);
|
|
1554
|
-
return connection;
|
|
1555
|
-
}
|
|
1556
|
-
}
|
|
1557
|
-
return state.manager.getConnection(serverName);
|
|
1558
|
-
};
|
|
1559
|
-
|
|
1560
|
-
try {
|
|
1561
|
-
state.manager.touch(serverName);
|
|
1562
|
-
state.manager.incrementInFlight(serverName);
|
|
1563
|
-
|
|
1564
|
-
if (toolMeta.resourceUri) {
|
|
1565
|
-
const result = await withSessionRecovery<ClientReadResourceResult>(
|
|
1566
|
-
{
|
|
1567
|
-
manager: state.manager,
|
|
1568
|
-
config: state.config,
|
|
1569
|
-
...(ownedSignal ? { signal: ownedSignal } : {}),
|
|
1570
|
-
onNeedsAuth: recoverAuthConnection,
|
|
1571
|
-
},
|
|
1572
|
-
serverName,
|
|
1573
|
-
async (conn) => {
|
|
1574
|
-
const refreshRead = await state.manager.prepareResourceUse?.(serverName, toolMeta.resourceUri!, conn);
|
|
1575
|
-
return conn.client.readResource(
|
|
1576
|
-
{ uri: toolMeta.resourceUri! },
|
|
1577
|
-
refreshRead ? { ...requestOptions, cacheMode: "refresh" } : requestOptions,
|
|
1578
|
-
);
|
|
1579
|
-
},
|
|
1580
|
-
);
|
|
1581
|
-
const content = transformMcpResourceContents(result.contents ?? [], state.owner?.signal);
|
|
1582
|
-
if (internalDelivery) {
|
|
1583
|
-
throwIfAborted(ownedSignal);
|
|
1584
|
-
internalDelivery.onSuccess(content.length > 0
|
|
1585
|
-
? content.filter(block => block.type === "text").map(block => block.text).join("\n")
|
|
1586
|
-
: "(empty resource)");
|
|
1587
|
-
return { content: [], details: { mode: "call", ...callIdentity } };
|
|
1588
|
-
}
|
|
1589
|
-
const guarded = await guardMcpOutput(content.length > 0 ? content : [{ type: "text" as const, text: "(empty resource)" }], outputGuardOptions);
|
|
1590
|
-
return {
|
|
1591
|
-
content: guarded.content,
|
|
1592
|
-
details: { mode: "call", ...callIdentity, ...guardedMcpDetails(guarded) },
|
|
1593
|
-
};
|
|
1594
|
-
}
|
|
1595
|
-
|
|
1596
|
-
uiSession = toolMeta.uiResourceUri
|
|
1597
|
-
? await maybeStartUiSession(state, {
|
|
1598
|
-
serverName,
|
|
1599
|
-
toolName: toolMeta.originalName,
|
|
1600
|
-
toolArgs: normalizedArgs,
|
|
1601
|
-
uiResourceUri: toolMeta.uiResourceUri,
|
|
1602
|
-
...(toolMeta.uiStreamMode !== undefined ? { streamMode: toolMeta.uiStreamMode } : {}),
|
|
1603
|
-
...(signal ? { signal } : {}),
|
|
1604
|
-
onNeedsAuth: recoverAuthConnection,
|
|
1605
|
-
})
|
|
1606
|
-
: null;
|
|
1607
|
-
|
|
1608
|
-
const result = await withSessionRecovery<ClientCallToolResult>(
|
|
1609
|
-
{
|
|
1610
|
-
manager: state.manager,
|
|
1611
|
-
config: state.config,
|
|
1612
|
-
...(ownedSignal ? { signal: ownedSignal } : {}),
|
|
1613
|
-
onNeedsAuth: recoverAuthConnection,
|
|
1614
|
-
},
|
|
1615
|
-
serverName,
|
|
1616
|
-
async (conn) => {
|
|
1617
|
-
await state.manager.ensureListen?.(serverName, conn);
|
|
1618
|
-
if (conn.taskSession) {
|
|
1619
|
-
return await callToolViaTaskSession(conn.taskSession, {
|
|
1620
|
-
name: toolMeta.originalName,
|
|
1621
|
-
args: normalizedArgs ?? {},
|
|
1622
|
-
meta: uiSession?.requestMeta,
|
|
1623
|
-
signal: ownedSignal,
|
|
1624
|
-
requestTimeoutMs: requestOptions?.timeout,
|
|
1625
|
-
}) as unknown as ClientCallToolResult;
|
|
1626
|
-
}
|
|
1627
|
-
return abortable(conn.client.callTool({
|
|
1628
|
-
name: toolMeta.originalName,
|
|
1629
|
-
arguments: normalizedArgs,
|
|
1630
|
-
_meta: uiSession?.requestMeta,
|
|
1631
|
-
}, requestOptions), ownedSignal);
|
|
1632
|
-
},
|
|
1633
|
-
);
|
|
1634
|
-
|
|
1635
|
-
if (toolMeta.uiResourceUri) {
|
|
1636
|
-
uiSession?.sendToolResult(result as unknown as import("@modelcontextprotocol/client").CallToolResult);
|
|
1637
|
-
}
|
|
1638
|
-
|
|
1639
|
-
if (!result.isError && internalDelivery) {
|
|
1640
|
-
throwIfAborted(ownedSignal);
|
|
1641
|
-
internalDelivery.onSuccess(result);
|
|
1642
|
-
return { content: [], details: { mode: "call", ...callIdentity } };
|
|
1643
|
-
}
|
|
1644
|
-
|
|
1645
|
-
if (toolMeta.uiResourceUri) {
|
|
1646
|
-
if (result.isError) {
|
|
1647
|
-
const content = resolveMcpResultContent(result as Record<string, unknown>, state.owner?.signal);
|
|
1648
|
-
const outputContent = content.length > 0 ? content : [{ type: "text" as const, text: "(empty result)" }];
|
|
1649
|
-
const guarded = await guardMcpOutput(outputContent, { ...outputGuardOptions, prefix: "Error: ", emptyTextFallback: "Tool execution failed", rawMcpResult: result });
|
|
1650
|
-
return {
|
|
1651
|
-
content: guarded.content,
|
|
1652
|
-
details: { mode: "call", error: "tool_error", ...callIdentity, ...guardedMcpDetails(guarded) },
|
|
1653
|
-
};
|
|
1654
|
-
}
|
|
1655
|
-
|
|
1656
|
-
const content = resolveMcpResultContent(result as Record<string, unknown>, state.owner?.signal);
|
|
1657
|
-
const outputContent = content.length > 0 ? content : [{ type: "text" as const, text: "(empty result)" }];
|
|
1658
|
-
const uiSummary = summarizeUiSessionResult(uiSession);
|
|
1659
|
-
const guarded = await guardMcpOutput(outputContent, { ...outputGuardOptions, suffix: `\n\n${uiSummary.message}`, rawMcpResult: result });
|
|
1660
|
-
return {
|
|
1661
|
-
content: guarded.content,
|
|
1662
|
-
details: {
|
|
1663
|
-
mode: "call",
|
|
1664
|
-
...guardedMcpDetails(guarded),
|
|
1665
|
-
...callIdentity,
|
|
1666
|
-
uiOpen: uiSummary.uiOpen,
|
|
1667
|
-
uiViewer: uiSummary.uiViewer,
|
|
1668
|
-
uiUrl: uiSummary.uiUrl,
|
|
1669
|
-
},
|
|
1670
|
-
};
|
|
1671
|
-
}
|
|
1672
|
-
|
|
1673
|
-
if (result.isError) {
|
|
1674
|
-
const content = resolveMcpResultContent(result as Record<string, unknown>, state.owner?.signal);
|
|
1675
|
-
const outputContent = content.length > 0 ? content : [{ type: "text" as const, text: "(empty result)" }];
|
|
1676
|
-
const guarded = await guardMcpOutput(outputContent, { ...outputGuardOptions, prefix: "Error: ", emptyTextFallback: "Tool execution failed", rawMcpResult: result });
|
|
1677
|
-
return {
|
|
1678
|
-
content: guarded.content,
|
|
1679
|
-
details: { mode: "call", error: "tool_error", ...callIdentity, ...guardedMcpDetails(guarded) },
|
|
1680
|
-
};
|
|
1681
|
-
}
|
|
1682
|
-
|
|
1683
|
-
const content = resolveMcpResultContent(result as Record<string, unknown>, state.owner?.signal);
|
|
1684
|
-
const outputContent = content.length > 0 ? content : [{ type: "text" as const, text: "(empty result)" }];
|
|
1685
|
-
const guarded = await guardMcpOutput(outputContent, { ...outputGuardOptions, rawMcpResult: result });
|
|
1686
|
-
return {
|
|
1687
|
-
content: guarded.content,
|
|
1688
|
-
details: { mode: "call", ...guardedMcpDetails(guarded), ...callIdentity },
|
|
1689
|
-
};
|
|
1690
|
-
} catch (error) {
|
|
1691
|
-
if (error instanceof SessionRecoveryAuthRequiredError) {
|
|
1692
|
-
const message = error.authMessage ?? getAuthRequiredMessage(state, serverName);
|
|
1693
|
-
uiSession?.sendToolCancelled(message);
|
|
1694
|
-
return {
|
|
1695
|
-
content: [{ type: "text" as const, text: message }],
|
|
1696
|
-
details: { mode: "call", error: "auth_required", ...callIdentity, message, autoAuthAttempted },
|
|
1697
|
-
};
|
|
1698
|
-
}
|
|
1699
|
-
if (error instanceof UrlElicitationRequiredError) {
|
|
1700
|
-
const action = await state.manager.handleUrlElicitationRequired(serverName, error);
|
|
1701
|
-
const message = action === "accept"
|
|
1702
|
-
? "The original MCP tool did not run. Complete the opened browser interaction, then retry the tool."
|
|
1703
|
-
: `The URL interaction was ${action === "decline" ? "declined" : "cancelled"}.`;
|
|
1704
|
-
uiSession?.sendToolCancelled(message);
|
|
1705
|
-
return {
|
|
1706
|
-
content: [{ type: "text" as const, text: message }],
|
|
1707
|
-
details: { mode: "call", error: "url_elicitation_required", ...callIdentity, action },
|
|
1708
|
-
};
|
|
1709
|
-
}
|
|
1710
|
-
const inputRequired = getInputRequiredNeedsUiDetails(error, callIdentity);
|
|
1711
|
-
if (inputRequired) {
|
|
1712
|
-
uiSession?.sendToolCancelled(inputRequired.message);
|
|
1713
|
-
return {
|
|
1714
|
-
content: [{ type: "text" as const, text: inputRequired.message }],
|
|
1715
|
-
details: { mode: "call", ...inputRequired },
|
|
1716
|
-
};
|
|
1717
|
-
}
|
|
1718
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
1719
|
-
uiSession?.sendToolCancelled(message);
|
|
1720
|
-
|
|
1721
|
-
const schemaText = toolMeta.inputSchema ? `\n\nExpected parameters:\n${formatSchema(toolMeta.inputSchema)}` : "";
|
|
1722
|
-
const guarded = await guardMcpOutput([{ type: "text" as const, text: message }], { ...outputGuardOptions, prefix: "Failed to call tool: ", suffix: schemaText });
|
|
1723
|
-
|
|
1724
|
-
return {
|
|
1725
|
-
content: guarded.content,
|
|
1726
|
-
details: { mode: "call", error: isAbortError(error, ownedSignal) ? "aborted" : "call_failed", ...callIdentity, message: guarded.outputGuard ? "output truncated; see outputGuard.fullOutputPath" : message, ...guardedMcpDetails(guarded) },
|
|
1727
|
-
};
|
|
1728
|
-
} finally {
|
|
1729
|
-
if (uiSession?.reused) {
|
|
1730
|
-
uiSession.close();
|
|
1731
|
-
}
|
|
1732
|
-
state.manager.decrementInFlight(serverName);
|
|
1733
|
-
state.manager.touch(serverName);
|
|
1734
|
-
}
|
|
1735
|
-
}
|