@akon-labs/nexus-cli 0.1.10 → 0.1.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/require-login.d.ts.map +1 -1
- package/dist/cli/require-login.js +2 -2
- package/dist/cli/require-login.js.map +1 -1
- package/dist/cli.js +2492 -1088
- package/dist/core/agent-session.d.ts +3 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +4 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +6 -0
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +7 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +14 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +18 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/graph-rail-store.d.ts +10 -0
- package/dist/core/graph-rail-store.d.ts.map +1 -1
- package/dist/core/graph-rail-store.js +9 -0
- package/dist/core/graph-rail-store.js.map +1 -1
- package/dist/core/keybindings.d.ts +2 -1
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +4 -1
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +1 -1
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +1 -1
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/extensions/gitnexus/client.d.ts.map +1 -1
- package/dist/extensions/gitnexus/client.js +45 -14
- package/dist/extensions/gitnexus/client.js.map +1 -1
- package/dist/extensions/gitnexus/config.d.ts +15 -1
- package/dist/extensions/gitnexus/config.d.ts.map +1 -1
- package/dist/extensions/gitnexus/config.js +86 -2
- package/dist/extensions/gitnexus/config.js.map +1 -1
- package/dist/extensions/gitnexus/hub-api.d.ts +56 -0
- package/dist/extensions/gitnexus/hub-api.d.ts.map +1 -0
- package/dist/extensions/gitnexus/hub-api.js +105 -0
- package/dist/extensions/gitnexus/hub-api.js.map +1 -0
- package/dist/extensions/gitnexus/index-repo.d.ts +50 -0
- package/dist/extensions/gitnexus/index-repo.d.ts.map +1 -0
- package/dist/extensions/gitnexus/index-repo.js +162 -0
- package/dist/extensions/gitnexus/index-repo.js.map +1 -0
- package/dist/extensions/gitnexus/index.d.ts.map +1 -1
- package/dist/extensions/gitnexus/index.js +137 -17
- package/dist/extensions/gitnexus/index.js.map +1 -1
- package/dist/extensions/gitnexus/observatory.d.ts.map +1 -1
- package/dist/extensions/gitnexus/observatory.js +2 -2
- package/dist/extensions/gitnexus/observatory.js.map +1 -1
- package/dist/extensions/gitnexus/resolve.d.ts +9 -0
- package/dist/extensions/gitnexus/resolve.d.ts.map +1 -1
- package/dist/extensions/gitnexus/resolve.js +52 -2
- package/dist/extensions/gitnexus/resolve.js.map +1 -1
- package/dist/extensions/index.d.ts.map +1 -1
- package/dist/extensions/index.js +3 -0
- package/dist/extensions/index.js.map +1 -1
- package/dist/extensions/mcp/commands.d.ts +22 -2
- package/dist/extensions/mcp/commands.d.ts.map +1 -1
- package/dist/extensions/mcp/commands.js +201 -9
- package/dist/extensions/mcp/commands.js.map +1 -1
- package/dist/extensions/mcp/config.d.ts +2 -0
- package/dist/extensions/mcp/config.d.ts.map +1 -1
- package/dist/extensions/mcp/config.js +6 -1
- package/dist/extensions/mcp/config.js.map +1 -1
- package/dist/extensions/mcp/index.d.ts.map +1 -1
- package/dist/extensions/mcp/index.js +54 -5
- package/dist/extensions/mcp/index.js.map +1 -1
- package/dist/extensions/mcp/mcp-setup-panel.d.ts +63 -2
- package/dist/extensions/mcp/mcp-setup-panel.d.ts.map +1 -1
- package/dist/extensions/mcp/mcp-setup-panel.js +563 -77
- package/dist/extensions/mcp/mcp-setup-panel.js.map +1 -1
- package/dist/extensions/subagent/index.d.ts +2 -1
- package/dist/extensions/subagent/index.d.ts.map +1 -1
- package/dist/extensions/subagent/index.js +19 -6
- package/dist/extensions/subagent/index.js.map +1 -1
- package/dist/extensions/subagent-render.d.ts +3 -0
- package/dist/extensions/subagent-render.d.ts.map +1 -0
- package/dist/extensions/subagent-render.js +39 -0
- package/dist/extensions/subagent-render.js.map +1 -0
- package/dist/index.js +2524 -1120
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +2 -0
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/command-palette.d.ts +2 -1
- package/dist/modes/interactive/components/command-palette.d.ts.map +1 -1
- package/dist/modes/interactive/components/command-palette.js +11 -4
- package/dist/modes/interactive/components/command-palette.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +9 -3
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/graph-rail.d.ts.map +1 -1
- package/dist/modes/interactive/components/graph-rail.js +18 -3
- package/dist/modes/interactive/components/graph-rail.js.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.d.ts +1 -0
- package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.js +7 -1
- package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
- package/dist/modes/interactive/components/landing-panel.d.ts.map +1 -1
- package/dist/modes/interactive/components/landing-panel.js +15 -2
- package/dist/modes/interactive/components/landing-panel.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +3 -2
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +12 -2
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +3 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +42 -8
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/rpc-entry.js +2492 -1088
- package/dist/utils/hidden-spawn.d.ts +29 -0
- package/dist/utils/hidden-spawn.d.ts.map +1 -0
- package/dist/utils/hidden-spawn.js +101 -0
- package/dist/utils/hidden-spawn.js.map +1 -0
- package/dist/vendor/ai.js +233 -233
- package/dist/vendor/tui.js +1 -1
- package/native/win32/build.mjs +95 -0
- package/native/win32/prebuilds/win32-x64/hidden-spawn.exe +0 -0
- package/native/win32/src/hidden-spawn.c +157 -0
- package/npm-shrinkwrap.json +2 -37
- package/package.json +7 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/extensions/mcp/index.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAA2B,YAAY,EAA8B,MAAM,gCAAgC,CAAC;AAmDxH,OAAO,KAAK,EAAkB,iBAAiB,EAA6B,WAAW,EAAE,MAAM,YAAY,CAAC;AAG5G,YAAY,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACjE,OAAO,EACN,gBAAgB,EAChB,2BAA2B,EAC3B,+BAA+B,EAC/B,KAAK,sBAAsB,EAC3B,KAAK,uBAAuB,EAC5B,KAAK,iBAAiB,EACtB,KAAK,uBAAuB,EAC5B,KAAK,sBAAsB,EAC3B,KAAK,qBAAqB,EAC1B,KAAK,sBAAsB,GAC3B,MAAM,YAAY,CAAC;AAKpB,MAAM,WAAW,qBAAqB;IACrC,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACzB;AAkrCD,wBAAgB,gBAAgB,CAAC,OAAO,GAAE,iBAAsB,iCAQ/D;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE;IAC1C,KAAK,EAAE,YAAY,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,WAAW,CAAC;CACxB,GAAG,qBAAqB,CAOxB;;AAED,wBAAkC","sourcesContent":["import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { Api, Model } from \"@earendil-works/pi-ai\";\nimport type { TSchema } from \"typebox\";\nimport { Type } from \"typebox\";\nimport type { AgentToolUpdateCallback, ExtensionAPI, ExtensionContext, ToolInfo } from \"../../core/extensions/types.ts\";\nimport {\n\tauthenticateServer,\n\tlogoutServer,\n\tmanageBearerToken,\n\topenMcpAuthPanel,\n\topenMcpPanel,\n\topenMcpSetup,\n\treconnectServer,\n\treconnectServers,\n\tshowPrompts,\n\tshowStatus,\n\tshowTools,\n} from \"./commands.ts\";\nimport { cloneMcpConfig, loadMcpConfig, writeProjectServerDisabledOverride } from \"./config.ts\";\nimport {\n\tbuildProxyDescription,\n\tcreateDirectToolExecutor,\n\tgetMissingConfiguredDirectToolServers,\n\tresolveDirectTools,\n} from \"./direct-tools.ts\";\nimport { toolErrorOverride } from \"./error-signal.ts\";\nimport { flushMetadataCache, initializeMcp, updateStatusBar } from \"./init.ts\";\nimport { logger } from \"./logger.ts\";\nimport type { McpOAuthRuntime } from \"./mcp-auth-flow.ts\";\nimport { createOAuthRuntime, shutdownOAuth } from \"./mcp-auth-flow.ts\";\nimport { runMcpScript } from \"./mcp-code.ts\";\nimport { publishMcpStatusShutdown } from \"./mcp-status.ts\";\nimport { loadMetadataCache, type MetadataCache } from \"./metadata-cache.ts\";\nimport { createPromptCommand, resolveCachedPrompts } from \"./prompts.ts\";\nimport {\n\texecuteAuthComplete,\n\texecuteAuthStart,\n\texecuteCall,\n\texecuteConnect,\n\texecuteDescribe,\n\texecuteInstructions,\n\texecuteList,\n\texecuteSearch,\n\texecuteStatus,\n\texecuteUiMessages,\n} from \"./proxy-modes.ts\";\nimport { createMcpRuntimeOwner, createOwnedUi, isAbortError, type McpRuntimeOwner } from \"./runtime-owner.ts\";\nimport type { McpExtensionState } from \"./state.ts\";\nimport { cleanupMaterializedBinaryResources } from \"./tool-registrar.ts\";\nimport {\n\tcreateMcpDirectToolCallRenderer,\n\tcreateMcpProxyToolCallRenderer,\n\tcreateMcpToolResultRenderer,\n\tresolveMcpToolRenderOptions,\n} from \"./tool-result-renderer.ts\";\nimport type { DirectToolSpec, McpAdapterOptions, McpConfig, PromptMetadata, ServerEntry } from \"./types.ts\";\nimport { formatTerminalError, getConfigPathFromArgv, normalizeDirectToolInputSchema, truncateAtWord } from \"./utils.ts\";\n\nexport type { McpAdapterOptions, ServerEntry } from \"./types.ts\";\nexport {\n\tMCP_STATUS_EVENT,\n\tMCP_STATUS_SNAPSHOT_VERSION,\n\tMCP_TOOL_APPROVAL_REQUEST_EVENT,\n\ttype McpServerRuntimeStatus,\n\ttype McpServerStatusSnapshot,\n\ttype McpStatusSnapshot,\n\ttype McpToolApprovalDecision,\n\ttype McpToolApprovalHandler,\n\ttype McpToolApprovalOrigin,\n\ttype McpToolApprovalRequest,\n} from \"./types.ts\";\n\nconst INIT_WAIT_TIMEOUT_MS = 30_000;\nconst INIT_WAIT_TIMED_OUT: unique symbol = Symbol(\"init-wait-timed-out\");\n\nexport interface McpServerRegistration {\n\tdispose(): Promise<void>;\n}\n\n// Routes runtime registrations to the adapter installed for a specific Nexus\n// instance, so a process with several adapters cannot cross-register.\nconst runtimeRegistrars = new WeakMap<ExtensionAPI, (name: string, definition: ServerEntry) => McpServerRegistration>();\n\nasync function awaitWithTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T | typeof INIT_WAIT_TIMED_OUT> {\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\ttry {\n\t\treturn await Promise.race([\n\t\t\tpromise,\n\t\t\tnew Promise<typeof INIT_WAIT_TIMED_OUT>((resolve) => {\n\t\t\t\ttimer = setTimeout(() => resolve(INIT_WAIT_TIMED_OUT), timeoutMs);\n\t\t\t\ttimer.unref?.();\n\t\t\t}),\n\t\t]);\n\t} finally {\n\t\tclearTimeout(timer);\n\t}\n}\n\n// TypeBox 1.x annotates raw objects passed to Type.Optional with an enumerable\n// \"~optional\" key that survives serialization into provider tool schemas (Gemini\n// rejects it with 400 INVALID_ARGUMENT). Prefer a real Type.Number schema; fall\n// back to a plain raw schema for host TypeBox shims that omit Type.Number, since\n// a property left out of `required` is optional by default.\nfunction optionalNumber(options: { minimum?: number; description: string }): TSchema {\n\tconst number = (Type as { Number?: (opts: typeof options) => TSchema }).Number;\n\treturn typeof number === \"function\"\n\t\t? Type.Optional(number(options))\n\t\t: ({ type: \"number\", ...options } as unknown as TSchema);\n}\n\nfunction installMcpAdapter(nexus: ExtensionAPI, options: McpAdapterOptions) {\n\tconst sessionConfig = options.config !== undefined ? cloneMcpConfig(options.config) : undefined;\n\tconst programmaticConfig = sessionConfig !== undefined;\n\tlet state: McpExtensionState | null = null;\n\tlet initPromise: Promise<McpExtensionState> | null = null;\n\tlet currentOwner: McpRuntimeOwner | null = null;\n\tlet currentOAuthRuntime: McpOAuthRuntime | null = null;\n\tlet currentModel: Model<Api> | undefined;\n\tlet lifecycleGeneration = 0;\n\n\tasync function shutdownState(currentState: McpExtensionState | null, reason: string): Promise<void> {\n\t\tif (!currentState) {\n\t\t\tpublishMcpStatusShutdown(nexus.events);\n\t\t\treturn;\n\t\t}\n\n\t\tpublishMcpStatusShutdown(currentState.statusEvents);\n\n\t\tif (currentState.uiServer) {\n\t\t\tcurrentState.uiServer.close(reason);\n\t\t\tcurrentState.uiServer = null;\n\t\t}\n\n\t\tlet flushError: unknown;\n\t\ttry {\n\t\t\tflushMetadataCache(currentState);\n\t\t} catch (error) {\n\t\t\tflushError = error;\n\t\t}\n\n\t\ttry {\n\t\t\tif (currentState.owner) {\n\t\t\t\tawait currentState.owner.stop(reason);\n\t\t\t} else {\n\t\t\t\tawait currentState.lifecycle.gracefulShutdown();\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (flushError) {\n\t\t\t\tconsole.error(`MCP: graceful shutdown failed after metadata flush error: ${formatTerminalError(error)}`);\n\t\t\t} else {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\n\t\tif (flushError) {\n\t\t\tthrow flushError;\n\t\t}\n\t}\n\n\tconst earlyConfigPath = programmaticConfig ? undefined : (options.configPath ?? getConfigPathFromArgv());\n\tconst earlyConfig = programmaticConfig\n\t\t? cloneMcpConfig(sessionConfig)\n\t\t: loadMcpConfig(earlyConfigPath, process.cwd(), false);\n\tconst earlyCache = loadMetadataCache();\n\tconst envRaw = process.env.MCP_DIRECT_TOOLS;\n\tconst envDirectToolOverride = envRaw\n\t\t?.split(\",\")\n\t\t.map((s) => s.trim())\n\t\t.filter(Boolean);\n\tconst registeredDirectTools = new Map<string, string>();\n\tconst fallbackDeactivatedTools = new Set<string>();\n\tconst toolRenderOptions = resolveMcpToolRenderOptions(earlyConfig.settings);\n\tconst toolRenderShell = toolRenderOptions.resultRendering === \"compact\" ? \"self\" : \"default\";\n\tconst renderMcpToolResult = createMcpToolResultRenderer(toolRenderOptions);\n\tlet proxyToolRegistered = false;\n\tlet proxyToolDescription: string | null = null;\n\tlet directToolsFrozen = false;\n\t// Session/runtime scoped server registrations from other extensions. They\n\t// survive session restarts within this install and die with the process.\n\tconst runtimeServers = new Map<string, ServerEntry>();\n\n\t// Mirrors init's per-server lifecycle registration so runtime servers get\n\t// idle cleanup and keep-alive health recovery like configured servers.\n\tfunction attachRuntimeServerLifecycle(targetState: McpExtensionState, name: string, definition: ServerEntry): void {\n\t\tconst lifecycleMode = definition.lifecycle ?? \"lazy\";\n\t\tconst persistsAfterFirstSpawn = lifecycleMode === \"eager\" || lifecycleMode === \"lazy-keep-alive\";\n\t\tconst idleOverride = definition.idleTimeout ?? (persistsAfterFirstSpawn ? 0 : undefined);\n\t\ttargetState.lifecycle.registerServer(\n\t\t\tname,\n\t\t\tdefinition,\n\t\t\tidleOverride !== undefined ? { idleTimeout: idleOverride } : undefined,\n\t\t);\n\t\tif (lifecycleMode === \"keep-alive\") targetState.lifecycle.markKeepAlive(name, definition);\n\t}\n\n\t// OMP remaps `typebox` to a host shim that historically lacked Type.Unsafe.\n\t// Prefer Unsafe when present (real TypeBox / fixed OMP shim); otherwise pass\n\t// the normalized JSON Schema through as a plain object so toolWireSchema and\n\t// validateToolArguments still treat it as JSON Schema.\n\tconst toToolParameters = (schema: Record<string, unknown>) =>\n\t\ttypeof (Type as { Unsafe?: (value: never) => unknown }).Unsafe === \"function\"\n\t\t\t? (Type as { Unsafe: (value: never) => unknown }).Unsafe(schema as never)\n\t\t\t: schema;\n\n\tfunction directToolFingerprint(spec: DirectToolSpec): string {\n\t\treturn JSON.stringify({\n\t\t\tserverName: spec.serverName,\n\t\t\toriginalName: spec.originalName,\n\t\t\tprefixedName: spec.prefixedName,\n\t\t\tdescription: spec.description,\n\t\t\tinputSchema: spec.inputSchema,\n\t\t\tresourceUri: spec.resourceUri,\n\t\t\tuiResourceUri: spec.uiResourceUri,\n\t\t\tuiStreamMode: spec.uiStreamMode,\n\t\t});\n\t}\n\n\tfunction registerDirectTool(spec: DirectToolSpec): void {\n\t\t(nexus.registerTool as (tool: unknown) => unknown)({\n\t\t\tname: spec.prefixedName,\n\t\t\tlabel: `MCP: ${spec.originalName}`,\n\t\t\tdescription: spec.description || \"(no description)\",\n\t\t\tpromptSnippet: truncateAtWord(spec.description, 100) || `MCP tool from ${spec.serverName}`,\n\t\t\tparameters: toToolParameters(normalizeDirectToolInputSchema(spec.inputSchema)),\n\t\t\texecute: createDirectToolExecutor(\n\t\t\t\t() => state,\n\t\t\t\t() => initPromise,\n\t\t\t\tspec,\n\t\t\t),\n\t\t\trenderShell: toolRenderShell,\n\t\t\trenderCall: createMcpDirectToolCallRenderer(spec.prefixedName, toolRenderOptions),\n\t\t\trenderResult: renderMcpToolResult,\n\t\t});\n\t}\n\n\tfunction resolveCurrentDirectTools(config: McpConfig, cache: MetadataCache | null): DirectToolSpec[] {\n\t\tif (envRaw === \"__none__\") return [];\n\t\tconst prefix = config.settings?.toolPrefix ?? \"server\";\n\t\treturn resolveDirectTools(config, cache, prefix, envDirectToolOverride);\n\t}\n\n\tfunction getActiveToolsIfReady(): string[] | undefined {\n\t\ttry {\n\t\t\treturn nexus.getActiveTools?.();\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\terror instanceof Error &&\n\t\t\t\terror.message.includes(\"Action methods cannot be called during extension loading\")\n\t\t\t)\n\t\t\t\treturn undefined;\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tfunction deactivateTools(toolNames: string[]): string[] {\n\t\tif (toolNames.length === 0) return [];\n\t\tconst unregisterTool = (nexus as ExtensionAPI & { unregisterTool?: (name: string) => boolean }).unregisterTool;\n\t\tconst unregistered = toolNames.filter((toolName) => unregisterTool?.(toolName) === true);\n\t\tconst fallbackNames = toolNames.filter((toolName) => !unregistered.includes(toolName));\n\t\tconst remove = new Set(toolNames);\n\t\tconst activeTools = getActiveToolsIfReady();\n\t\tif (!activeTools || activeTools.length === 0) {\n\t\t\tfor (const toolName of fallbackNames) fallbackDeactivatedTools.add(toolName);\n\t\t\treturn unregistered;\n\t\t}\n\t\tconst nextActiveTools = activeTools.filter((name) => !remove.has(name));\n\t\tif (nextActiveTools.length !== activeTools.length) {\n\t\t\tfor (const toolName of fallbackNames) fallbackDeactivatedTools.add(toolName);\n\t\t\tnexus.setActiveTools(nextActiveTools);\n\t\t}\n\t\treturn unregistered;\n\t}\n\n\tfunction syncDirectTools(\n\t\tconfig: McpConfig,\n\t\tcache: MetadataCache | null,\n\t): {\n\t\tspecs: DirectToolSpec[];\n\t\tadded: string[];\n\t\tupdated: string[];\n\t\tdeactivated: string[];\n\t} {\n\t\tconst specs = resolveCurrentDirectTools(config, cache);\n\t\tconst nextNames = new Set(specs.map((spec) => spec.prefixedName));\n\t\tconst added: string[] = [];\n\t\tconst updated: string[] = [];\n\t\tconst deactivated: string[] = [];\n\n\t\tfor (const spec of specs) {\n\t\t\tconst fingerprint = directToolFingerprint(spec);\n\t\t\tconst previous = registeredDirectTools.get(spec.prefixedName);\n\t\t\tif (previous !== fingerprint) {\n\t\t\t\tregisterDirectTool(spec);\n\t\t\t\tregisteredDirectTools.set(spec.prefixedName, fingerprint);\n\t\t\t\tif (fallbackDeactivatedTools.delete(spec.prefixedName)) {\n\t\t\t\t\tconst activeTools = getActiveToolsIfReady();\n\t\t\t\t\tif (activeTools && !activeTools.includes(spec.prefixedName)) {\n\t\t\t\t\t\tnexus.setActiveTools([...activeTools, spec.prefixedName]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t(previous ? updated : added).push(spec.prefixedName);\n\t\t\t}\n\t\t}\n\n\t\tfor (const toolName of [...registeredDirectTools.keys()]) {\n\t\t\tif (nextNames.has(toolName)) continue;\n\t\t\tregisteredDirectTools.delete(toolName);\n\t\t\tdeactivated.push(toolName);\n\t\t}\n\n\t\tdeactivateTools(deactivated);\n\t\treturn { specs, added, updated, deactivated };\n\t}\n\n\tfunction applyDirectToolConfigChanges(changes: Map<string, true | string[] | false>): void {\n\t\tif (!state) return;\n\t\tfor (const [serverName, value] of changes) {\n\t\t\tconst definition = state.config.mcpServers[serverName];\n\t\t\tif (!definition) continue;\n\t\t\tstate.config.mcpServers[serverName] = { ...definition, directTools: value };\n\t\t}\n\t}\n\n\tfunction syncToolSurface(ctx?: ExtensionContext): void {\n\t\tconst config = state?.config ?? earlyConfig;\n\t\tconst cache = loadMetadataCache();\n\t\tconst result = syncDirectTools(config, cache);\n\t\tsyncProxyTool(config, cache, result.specs);\n\t\tconst changed = result.added.length + result.updated.length + result.deactivated.length;\n\t\tif (changed > 0 && ctx?.hasUI) {\n\t\t\tctx.ui.notify(\n\t\t\t\t`MCP: direct tools refreshed (+${result.added.length}, ~${result.updated.length}, -${result.deactivated.length})`,\n\t\t\t\t\"info\",\n\t\t\t);\n\t\t}\n\t}\n\n\tconst registeredPromptCommands = new Set<string>();\n\n\tfunction registerPromptCommands(specs: Iterable<PromptMetadata>): void {\n\t\tfor (const spec of specs) {\n\t\t\tif (registeredPromptCommands.has(spec.commandName)) {\n\t\t\t\tlogger.debug(\n\t\t\t\t\t`MCP: prompt \"${spec.originalName}\" on ${spec.serverName} skipped; /${spec.commandName} is already registered`,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tregisteredPromptCommands.add(spec.commandName);\n\t\t\tnexus.registerCommand(\n\t\t\t\tspec.commandName,\n\t\t\t\tcreatePromptCommand(nexus, () => state, spec),\n\t\t\t);\n\t\t}\n\t}\n\n\tfunction syncPromptCommands(): void {\n\t\tregisterPromptCommands([...(state?.promptMetadata?.values() ?? [])].flat());\n\t}\n\n\tregisterPromptCommands(resolveCachedPrompts(earlyConfig));\n\n\truntimeRegistrars.set(nexus, (name: string, definition: ServerEntry): McpServerRegistration => {\n\t\tif (typeof name !== \"string\" || name.trim() === \"\") {\n\t\t\tthrow new Error(\"MCP server name must be a non-empty string\");\n\t\t}\n\t\tif (typeof definition !== \"object\" || definition === null || Array.isArray(definition)) {\n\t\t\tthrow new Error(`MCP server definition for \"${name}\" must be an object`);\n\t\t}\n\t\tconst effective = state?.config ?? earlyConfig;\n\t\tif (runtimeServers.has(name) || Object.hasOwn(effective.mcpServers, name)) {\n\t\t\tthrow new Error(`MCP server \"${name}\" is already registered`);\n\t\t}\n\t\t// Runtime-registered servers are proxy-tool-only: direct tools are frozen\n\t\t// at startup and must not be rebuilt for late registrations.\n\t\tconst entry: ServerEntry = { ...structuredClone(definition), directTools: false };\n\t\truntimeServers.set(name, entry);\n\t\tconst registeredState = state;\n\t\tif (registeredState) {\n\t\t\tregisteredState.config.mcpServers[name] = entry;\n\t\t\tattachRuntimeServerLifecycle(registeredState, name, entry);\n\t\t\tsyncToolSurface();\n\t\t\tupdateStatusBar(registeredState);\n\t\t}\n\t\tlet disposed = false;\n\t\treturn {\n\t\t\tdispose: async (): Promise<void> => {\n\t\t\t\tif (disposed) return;\n\t\t\t\tdisposed = true;\n\t\t\t\truntimeServers.delete(name);\n\t\t\t\tconst currentState = state;\n\t\t\t\tif (!currentState || currentState.config.mcpServers[name] !== entry) return;\n\t\t\t\tdelete currentState.config.mcpServers[name];\n\t\t\t\tcurrentState.lifecycle.unregisterServer(name);\n\t\t\t\tawait currentState.manager.close(name);\n\t\t\t\tsyncToolSurface();\n\t\t\t\tupdateStatusBar(currentState);\n\t\t\t},\n\t\t};\n\t});\n\n\tconst getNexusTools = (): ToolInfo[] => nexus.getAllTools();\n\n\tnexus.registerFlag(\"mcp-config\", {\n\t\tdescription: \"Path to MCP config file\",\n\t\ttype: \"string\",\n\t});\n\n\tfunction startInitialization(\n\t\tctx: ExtensionContext,\n\t\towner: McpRuntimeOwner,\n\t\toauthRuntime: McpOAuthRuntime,\n\t\tgeneration: number,\n\t\tstaleReason: string,\n\t): Promise<void> {\n\t\towner.addCleanup(() => cleanupMaterializedBinaryResources(owner.signal));\n\t\tconst promise = initializeMcp(nexus, ctx, owner, {\n\t\t\t...(programmaticConfig || options.configPath !== undefined\n\t\t\t\t? {\n\t\t\t\t\t\t...(earlyConfigPath !== undefined ? { configPath: earlyConfigPath } : {}),\n\t\t\t\t\t\t...(sessionConfig !== undefined ? { config: sessionConfig } : {}),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\toauthRuntime,\n\t\t\tgetCurrentModel: () => currentModel,\n\t\t});\n\t\tinitPromise = promise;\n\n\t\treturn promise\n\t\t\t.then(async (nextState) => {\n\t\t\t\tif (!owner.isActive() || generation !== lifecycleGeneration || initPromise !== promise) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait shutdownState(nextState, staleReason);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconsole.error(`MCP: failed to clean stale initialization state: ${formatTerminalError(error)}`);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tstate = nextState;\n\t\t\t\tfor (const [name, definition] of runtimeServers) {\n\t\t\t\t\tif (Object.hasOwn(nextState.config.mcpServers, name)) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t`MCP: runtime-registered server \"${name}\" now collides with a configured server; keeping the configured server`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tnextState.config.mcpServers[name] = definition;\n\t\t\t\t\tattachRuntimeServerLifecycle(nextState, name, definition);\n\t\t\t\t}\n\t\t\t\tnextState.onToolMetadataUpdated = (_serverName, _reason) => {\n\t\t\t\t\tif (state !== nextState || !owner.isActive()) return;\n\t\t\t\t\tsyncPromptCommands();\n\t\t\t\t\tif (directToolsFrozen) {\n\t\t\t\t\t\tlogger.debug(`MCP: metadata update for ${_serverName} (${_reason}) skipped — directTools frozen`);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tsyncToolSurface(ctx);\n\t\t\t\t};\n\t\t\t\tsyncPromptCommands();\n\t\t\t\tsyncToolSurface(ctx);\n\t\t\t\t// A connected snapshot is readiness-like external state. Publish it only\n\t\t\t\t// after Nexus's model-facing direct-tool surface reflects live metadata.\n\t\t\t\tnextState.statusEvents = nexus.events;\n\t\t\t\tupdateStatusBar(nextState);\n\t\t\t\tinitPromise = null;\n\t\t\t\tif (nextState.config.settings?.freezeDirectTools === true) {\n\t\t\t\t\tdirectToolsFrozen = true;\n\t\t\t\t\tlogger.info(\n\t\t\t\t\t\t'MCP: direct tools frozen after initial sync — reconnects won\\'t rebuild the system prompt; use mcp({ connect: \"server\" }) to rediscover',\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t})\n\t\t\t.catch(async (err) => {\n\t\t\t\tif (!owner.isActive() || generation !== lifecycleGeneration) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (initPromise !== promise && initPromise !== null) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconsole.error(`MCP initialization failed: ${formatTerminalError(err)}`);\n\t\t\t\tinitPromise = null;\n\t\t\t\tif (state) return;\n\n\t\t\t\ttry {\n\t\t\t\t\tawait Promise.all([owner.stop(\"MCP initialization failed\"), shutdownOAuth(oauthRuntime)]);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconsole.error(`MCP: failed to clean rejected initialization: ${formatTerminalError(error)}`);\n\t\t\t\t}\n\t\t\t});\n\t}\n\n\tfunction startLoadTimeInitialization(): void {\n\t\tconst hasStartupServer = Object.values(earlyConfig.mcpServers).some((definition) => {\n\t\t\tif (definition.disabled === true) return false;\n\t\t\treturn definition.lifecycle === \"eager\" || definition.lifecycle === \"keep-alive\";\n\t\t});\n\t\tif (!hasStartupServer) return;\n\t\tsetImmediate(() => {\n\t\t\tif (lifecycleGeneration !== 0 || state || initPromise) return;\n\t\t\tconst generation = ++lifecycleGeneration;\n\t\t\tconst owner = createMcpRuntimeOwner();\n\t\t\tconst oauthRuntime = createOAuthRuntime(owner.signal);\n\t\t\tcurrentOwner = owner;\n\t\t\tcurrentOAuthRuntime = oauthRuntime;\n\t\t\tstartInitialization(\n\t\t\t\t{\n\t\t\t\t\tmode: \"print\",\n\t\t\t\t\thasUI: false,\n\t\t\t\t\tcwd: process.cwd(),\n\t\t\t\t\tmodel: undefined,\n\t\t\t\t\tmodelRegistry: undefined,\n\t\t\t\t\tsignal: undefined,\n\t\t\t\t\tisProjectTrusted: () => false,\n\t\t\t\t} as unknown as ExtensionContext,\n\t\t\t\towner,\n\t\t\t\toauthRuntime,\n\t\t\t\tgeneration,\n\t\t\t\t\"stale_load_time_initialization\",\n\t\t\t);\n\t\t});\n\t}\n\n\tnexus.on(\"session_start\", async (_event, ctx) => {\n\t\tcurrentModel = ctx.model;\n\t\tdirectToolsFrozen = false;\n\t\tconst generation = ++lifecycleGeneration;\n\t\tconst previousState = state;\n\t\tconst previousOwner = currentOwner;\n\t\tconst previousOAuthRuntime = currentOAuthRuntime;\n\t\tconst owner = createMcpRuntimeOwner();\n\t\tconst oauthRuntime = createOAuthRuntime(owner.signal);\n\t\tcurrentOwner = owner;\n\t\tcurrentOAuthRuntime = oauthRuntime;\n\t\tstate = null;\n\t\tinitPromise = null;\n\n\t\t// Abort synchronously before awaiting cleanup so old callbacks and startup\n\t\t// work cannot resume into a stale ExtensionContext.\n\t\tconst stopPrevious = previousOwner?.stop(\"MCP extension session restarted\") ?? Promise.resolve();\n\t\ttry {\n\t\t\tawait Promise.all([\n\t\t\t\tstopPrevious,\n\t\t\t\tshutdownState(previousState, \"session_restart\"),\n\t\t\t\tpreviousOAuthRuntime ? shutdownOAuth(previousOAuthRuntime) : Promise.resolve(),\n\t\t\t]);\n\t\t} catch (error) {\n\t\t\tconsole.error(`MCP: failed to shut down previous session state: ${formatTerminalError(error)}`);\n\t\t}\n\n\t\tif (generation !== lifecycleGeneration || !owner.isActive()) return;\n\n\t\tconst initialization = startInitialization(ctx, owner, oauthRuntime, generation, \"stale_session_start\");\n\t\tif (envRaw !== undefined && envRaw !== \"__none__\") {\n\t\t\tconst missingEnvDirectTools = getMissingConfiguredDirectToolServers(\n\t\t\t\tearlyConfig,\n\t\t\t\tloadMetadataCache(),\n\t\t\t\tenvDirectToolOverride,\n\t\t\t);\n\t\t\tif (missingEnvDirectTools.length > 0) {\n\t\t\t\tawait initialization;\n\t\t\t}\n\t\t}\n\t});\n\n\tnexus.on(\"model_select\", (event) => {\n\t\tcurrentModel = event.model;\n\t});\n\n\tnexus.on(\"input\", async () => {\n\t\tconst inputOwner = currentOwner;\n\t\tif (!inputOwner?.isActive()) return;\n\n\t\tif (!state && initPromise) {\n\t\t\ttry {\n\t\t\t\tawait awaitWithTimeout(initPromise, INIT_WAIT_TIMEOUT_MS);\n\t\t\t} catch {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tconst inputState = state;\n\t\tif (!inputState || !inputOwner.isActive()) return;\n\t\ttry {\n\t\t\tawait inputState.lifecycle.ensureConverged(inputOwner.signal);\n\t\t} catch (error) {\n\t\t\tif (!isAbortError(error, inputOwner.signal)) {\n\t\t\t\tlogger.debug(`MCP: keep-alive convergence failed before input: ${formatTerminalError(error)}`);\n\t\t\t}\n\t\t}\n\t});\n\n\tnexus.on(\"session_shutdown\", async () => {\n\t\t++lifecycleGeneration;\n\t\tconst currentState = state;\n\t\tconst owner = currentOwner;\n\t\tconst oauthRuntime = currentOAuthRuntime;\n\t\tcurrentOwner = null;\n\t\tcurrentOAuthRuntime = null;\n\t\tcurrentModel = undefined;\n\t\tstate = null;\n\t\tinitPromise = null;\n\n\t\t// Abort before awaiting cleanup so delayed initialization cannot touch stale\n\t\t// Nexus context after session shutdown.\n\t\tconst stopOwner = owner?.stop(\"MCP extension session shutdown\") ?? Promise.resolve();\n\t\ttry {\n\t\t\tawait Promise.all([\n\t\t\t\tstopOwner,\n\t\t\t\tshutdownState(currentState, \"session_shutdown\"),\n\t\t\t\toauthRuntime ? shutdownOAuth(oauthRuntime) : Promise.resolve(),\n\t\t\t]);\n\t\t} catch (error) {\n\t\t\tconsole.error(`MCP: session shutdown cleanup failed: ${formatTerminalError(error)}`);\n\t\t}\n\t});\n\n\t// Re-flag returned MCP tool failures so nexus registers them as errors (see toolErrorOverride).\n\tnexus.on(\"tool_result\", (event) => toolErrorOverride(event.details));\n\n\tconst registerMcpCommand = (commandName: string) =>\n\t\tnexus.registerCommand(commandName, {\n\t\t\tdescription: \"Show MCP server status\",\n\t\t\tgetArgumentCompletions: (prefix: string) => {\n\t\t\t\tconst normalized = prefix.trimStart();\n\t\t\t\tconst argumentMatch = normalized.match(/^(\\S+)\\s+(.*)$/);\n\t\t\t\tif (!argumentMatch) {\n\t\t\t\t\tconst subcommands = [\n\t\t\t\t\t\t{ value: \"reconnect\", label: \"reconnect — Reconnect servers\" },\n\t\t\t\t\t\t{ value: \"tools\", label: \"tools — List all tools\" },\n\t\t\t\t\t\t{ value: \"prompts\", label: \"prompts — List all MCP prompts\" },\n\t\t\t\t\t\t{ value: \"setup\", label: \"setup — Configure MCP servers\" },\n\t\t\t\t\t\t{ value: \"logout\", label: \"logout — Clear server credentials\" },\n\t\t\t\t\t\t{ value: \"token\", label: \"token — Manage stored bearer tokens\" },\n\t\t\t\t\t\t{ value: \"disable\", label: \"disable — Disable a server\" },\n\t\t\t\t\t\t{ value: \"enable\", label: \"enable — Enable a server\" },\n\t\t\t\t\t\t{ value: \"status\", label: \"status — Show server status\" },\n\t\t\t\t\t].filter(({ value }) => value.startsWith(normalized));\n\t\t\t\t\treturn subcommands.length > 0 ? subcommands : null;\n\t\t\t\t}\n\n\t\t\t\tconst [, subcommand, argumentPrefix] = argumentMatch;\n\t\t\t\tif (\n\t\t\t\t\t(subcommand !== \"reconnect\" &&\n\t\t\t\t\t\tsubcommand !== \"logout\" &&\n\t\t\t\t\t\tsubcommand !== \"disable\" &&\n\t\t\t\t\t\tsubcommand !== \"enable\" &&\n\t\t\t\t\t\tsubcommand !== \"token\") ||\n\t\t\t\t\targumentPrefix === undefined ||\n\t\t\t\t\t!state\n\t\t\t\t)\n\t\t\t\t\treturn null;\n\n\t\t\t\tif (subcommand === \"token\") {\n\t\t\t\t\tconst tokenMatch = argumentPrefix.trimStart().match(/^(set|remove|status)\\s+(.*)$/);\n\t\t\t\t\tif (!tokenMatch) {\n\t\t\t\t\t\tconst actions = [\"set\", \"remove\", \"status\"]\n\t\t\t\t\t\t\t.filter((action) => action.startsWith(argumentPrefix.trimStart()))\n\t\t\t\t\t\t\t.map((action) => ({ value: `token ${action} `, label: `${action} — Bearer token ${action}` }));\n\t\t\t\t\t\treturn actions.length > 0 ? actions : null;\n\t\t\t\t\t}\n\t\t\t\t\tconst action = tokenMatch[1] ?? \"\";\n\t\t\t\t\tconst serverPrefix = tokenMatch[2] ?? \"\";\n\t\t\t\t\tconst servers = Object.keys(state.config.mcpServers)\n\t\t\t\t\t\t.filter((serverName) => serverName.startsWith(serverPrefix.trimStart()))\n\t\t\t\t\t\t.map((serverName) => ({ value: `token ${action} ${serverName}`, label: serverName }));\n\t\t\t\t\treturn servers.length > 0 ? servers : null;\n\t\t\t\t}\n\n\t\t\t\tconst servers = Object.keys(state.config.mcpServers)\n\t\t\t\t\t.filter((serverName) => serverName.startsWith(argumentPrefix.trimStart()))\n\t\t\t\t\t.map((serverName) => ({ value: `${subcommand} ${serverName}`, label: serverName }));\n\t\t\t\treturn servers.length > 0 ? servers : null;\n\t\t\t},\n\t\t\thandler: async (args, ctx) => {\n\t\t\t\tconst commandOwner = currentOwner;\n\t\t\t\tconst commandReload = typeof ctx.reload === \"function\" ? ctx.reload.bind(ctx) : async () => {};\n\t\t\t\tconst commandHasUI = ctx.hasUI;\n\t\t\t\tconst commandCtx = {\n\t\t\t\t\thasUI: commandHasUI,\n\t\t\t\t\tui: commandHasUI ? (commandOwner ? createOwnedUi(ctx.ui, commandOwner) : ctx.ui) : undefined,\n\t\t\t\t\tcwd: ctx.cwd,\n\t\t\t\t\tmode: ctx.mode,\n\t\t\t\t\tsignal: commandOwner?.signal ?? ctx.signal,\n\t\t\t\t\tisProjectTrusted: () => ctx.isProjectTrusted(),\n\t\t\t\t} as unknown as ExtensionContext;\n\t\t\t\tif (!state && initPromise) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst initialized = await initPromise;\n\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\tstate = initialized;\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\tif (commandCtx.hasUI) commandCtx.ui?.notify(`MCP initialization failed: ${message}`, \"error\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!state) {\n\t\t\t\t\tif (commandCtx.hasUI) commandCtx.ui?.notify(\"MCP not initialized\", \"error\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst parts = args?.trim()?.split(/\\s+/) ?? [];\n\t\t\t\tconst subcommand = parts[0] ?? \"\";\n\t\t\t\tconst targetServer = parts[1];\n\t\t\t\tconst rest = parts.slice(1).join(\" \");\n\n\t\t\t\tswitch (subcommand) {\n\t\t\t\t\tcase \"reconnect\":\n\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\tawait reconnectServers(state, commandCtx, targetServer);\n\t\t\t\t\t\tif (directToolsFrozen) syncToolSurface(commandCtx);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"tools\":\n\t\t\t\t\t\tawait showTools(state, commandCtx);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"prompts\":\n\t\t\t\t\t\tawait showPrompts(state, commandCtx);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"setup\": {\n\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\tif (!ctx.isProjectTrusted()) {\n\t\t\t\t\t\t\tcommandCtx.ui?.notify(\"Trust this project before opening MCP setup.\", \"warning\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (programmaticConfig) {\n\t\t\t\t\t\t\tcommandCtx.ui?.notify(\n\t\t\t\t\t\t\t\t\"MCP setup is unavailable when config is supplied by createMcpAdapter().\",\n\t\t\t\t\t\t\t\t\"info\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst result = await openMcpSetup(state, nexus, commandCtx, earlyConfigPath, \"setup\");\n\t\t\t\t\t\tif (result?.configChanged) {\n\t\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\t\tawait commandReload();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"logout\": {\n\t\t\t\t\t\tconst serverName = rest;\n\t\t\t\t\t\tif (!serverName) {\n\t\t\t\t\t\t\tif (commandCtx.hasUI) commandCtx.ui?.notify(\"Usage: /mcp logout <server>\", \"error\");\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\tawait logoutServer(serverName, state, commandCtx);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"token\": {\n\t\t\t\t\t\tconst action = parts[1];\n\t\t\t\t\t\tconst serverName = parts.slice(2).join(\" \");\n\t\t\t\t\t\tif (action !== \"set\" && action !== \"remove\" && action !== \"status\") {\n\t\t\t\t\t\t\tif (commandCtx.hasUI)\n\t\t\t\t\t\t\t\tcommandCtx.ui?.notify(\"Usage: /mcp token set|remove|status <server>\", \"error\");\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!serverName) {\n\t\t\t\t\t\t\tif (commandCtx.hasUI)\n\t\t\t\t\t\t\t\tcommandCtx.ui?.notify(\"Usage: /mcp token set|remove|status <server>\", \"error\");\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\tawait manageBearerToken(action, serverName, state, commandCtx);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"disable\":\n\t\t\t\t\tcase \"enable\": {\n\t\t\t\t\t\tconst serverName = rest;\n\t\t\t\t\t\tif (!ctx.isProjectTrusted()) {\n\t\t\t\t\t\t\tcommandCtx.ui?.notify(`Trust this project before running /mcp ${subcommand}.`, \"warning\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (programmaticConfig) {\n\t\t\t\t\t\t\tcommandCtx.ui?.notify(\n\t\t\t\t\t\t\t\t`/mcp ${subcommand} is unavailable when config is supplied by createMcpAdapter().`,\n\t\t\t\t\t\t\t\t\"info\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!serverName) {\n\t\t\t\t\t\t\tcommandCtx.ui?.notify(`Usage: /mcp ${subcommand} <server>`, \"error\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!state.config.mcpServers[serverName]) {\n\t\t\t\t\t\t\tcommandCtx.ui?.notify(`Server \"${serverName}\" not found in effective config`, \"error\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\tconst result = writeProjectServerDisabledOverride(\n\t\t\t\t\t\t\tearlyConfigPath,\n\t\t\t\t\t\t\tcommandCtx.cwd,\n\t\t\t\t\t\t\tserverName,\n\t\t\t\t\t\t\tsubcommand === \"disable\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (result.changed) {\n\t\t\t\t\t\t\tcommandCtx.ui?.notify(\n\t\t\t\t\t\t\t\t`${subcommand === \"disable\" ? \"Disabled\" : \"Enabled\"} server \"${serverName}\" in ${result.path} — run /reload to apply`,\n\t\t\t\t\t\t\t\t\"info\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcommandCtx.ui?.notify(\n\t\t\t\t\t\t\t\t`Server \"${serverName}\" is already ${subcommand === \"disable\" ? \"disabled\" : \"enabled\"}`,\n\t\t\t\t\t\t\t\t\"info\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tif (commandCtx.hasUI) {\n\t\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\t\tif (programmaticConfig || !ctx.isProjectTrusted()) {\n\t\t\t\t\t\t\t\tif (programmaticConfig) {\n\t\t\t\t\t\t\t\t\tcommandCtx.ui?.notify(\n\t\t\t\t\t\t\t\t\t\t\"MCP status is shown from the in-memory SDK config; configuration discovery is unavailable.\",\n\t\t\t\t\t\t\t\t\t\t\"info\",\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tawait showStatus(state, commandCtx);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst result = await openMcpPanel(state, nexus, commandCtx, earlyConfigPath, (changes) => {\n\t\t\t\t\t\t\t\tapplyDirectToolConfigChanges(changes);\n\t\t\t\t\t\t\t\tsyncToolSurface(commandCtx);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (result?.configChanged) {\n\t\t\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\t\t\tawait commandReload();\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tawait showStatus(state, commandCtx);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\tregisterMcpCommand(\"mcp\");\n\n\tnexus.registerCommand(\"mcp-auth\", {\n\t\tdescription: \"Authenticate with an MCP server (OAuth)\",\n\t\thandler: async (args, ctx) => {\n\t\t\tconst commandOwner = currentOwner;\n\t\t\tconst commandHasUI = ctx.hasUI;\n\t\t\tconst commandCtx = {\n\t\t\t\thasUI: commandHasUI,\n\t\t\t\tui: commandHasUI ? (commandOwner ? createOwnedUi(ctx.ui, commandOwner) : ctx.ui) : undefined,\n\t\t\t\tcwd: ctx.cwd,\n\t\t\t\tmode: ctx.mode,\n\t\t\t\tsignal: commandOwner?.signal ?? ctx.signal,\n\t\t\t\tisProjectTrusted: () => ctx.isProjectTrusted(),\n\t\t\t} as unknown as ExtensionContext;\n\t\t\tconst serverName = args?.trim();\n\t\t\tif (!serverName && !commandCtx.hasUI) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!state && initPromise) {\n\t\t\t\ttry {\n\t\t\t\t\tconst initialized = await initPromise;\n\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\tstate = initialized;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\tif (commandCtx.hasUI) commandCtx.ui?.notify(`MCP initialization failed: ${message}`, \"error\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!state) {\n\t\t\t\tif (commandCtx.hasUI) commandCtx.ui?.notify(\"MCP not initialized\", \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!serverName) {\n\t\t\t\tif (!ctx.isProjectTrusted()) {\n\t\t\t\t\tcommandCtx.ui?.notify(\n\t\t\t\t\t\t\"Trust this project or specify a global MCP server with /mcp-auth <server>.\",\n\t\t\t\t\t\t\"warning\",\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (programmaticConfig) {\n\t\t\t\t\tcommandCtx.ui?.notify(\n\t\t\t\t\t\t\"Use /mcp-auth <server> to authenticate a server from the in-memory SDK config.\",\n\t\t\t\t\t\t\"info\",\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait openMcpAuthPanel(state, nexus, commandCtx, earlyConfigPath);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst result = await authenticateServer(\n\t\t\t\tserverName,\n\t\t\t\tstate.config,\n\t\t\t\tcommandCtx,\n\t\t\t\tcommandCtx.signal,\n\t\t\t\tstate.oauthRuntime,\n\t\t\t);\n\t\t\tif (result.ok) {\n\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\tawait reconnectServer(state, commandCtx, serverName);\n\t\t\t}\n\t\t},\n\t});\n\n\tif (earlyConfig.settings?.scriptMode !== false) {\n\t\t(nexus.registerTool as (tool: unknown) => unknown)({\n\t\t\tname: \"mcpScript\",\n\t\t\tlabel: \"MCP Script\",\n\t\t\tdescription:\n\t\t\t\t\"Run trusted JavaScript that makes multiple MCP tool calls in one request — loop, filter, chain, or fan out between calls. For a single MCP call, search, describe, status check, or auth action, use the mcp tool instead. Discover with await tools.search({ query }) — resolves to { items: [{ path, name, server, description? }], total, hasMore, nextOffset }, not an { ok, data } envelope. Inspect with await tools.describe({ path }) — resolves to the tool descriptor with inputTypeScript, or { path, error: { code, message, suggestions } }. Then call tools.call(path, args) — resolves to { ok: true, data } or { ok: false, error: { code, message } } — or use direct flat calls when the name is already known; use emit(value) for user-visible output. Load the mcp-scripting skill for the full workflow guide.\",\n\t\t\tpromptSnippet: \"Batch multiple MCP tool calls in one JavaScript request (loop, filter, chain)\",\n\t\t\tparameters: Type.Object({\n\t\t\t\tcode: Type.String({\n\t\t\t\t\tdescription: \"Trusted JavaScript MCP script. Use tools.<prefixedToolName>(args) and emit(value).\",\n\t\t\t\t}),\n\t\t\t\ttimeoutMs: optionalNumber({\n\t\t\t\t\tminimum: 1,\n\t\t\t\t\tdescription: \"Execution timeout in milliseconds (default: 30000)\",\n\t\t\t\t}),\n\t\t\t}),\n\t\t\trenderResult: renderMcpToolResult,\n\t\t\tasync execute(\n\t\t\t\t_toolCallId: string,\n\t\t\t\tparams: { code: string; timeoutMs?: number },\n\t\t\t\tsignal: AbortSignal | undefined,\n\t\t\t) {\n\t\t\t\tconst executeOwner = currentOwner;\n\t\t\t\tif (!state && initPromise) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst initialized = await awaitWithTimeout(initPromise, INIT_WAIT_TIMEOUT_MS);\n\t\t\t\t\t\tif (initialized === INIT_WAIT_TIMED_OUT) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\t\t\t\ttext: \"MCP initialization is still in progress. Try again shortly.\",\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\tdetails: { mode: \"script\", error: \"init_timeout\", timeoutMs: INIT_WAIT_TIMEOUT_MS },\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\texecuteOwner?.throwIfInactive();\n\t\t\t\t\t\tstate = initialized;\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (executeOwner && isAbortError(error, executeOwner.signal)) throw error;\n\t\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: `MCP initialization failed: ${message}` }],\n\t\t\t\t\t\t\tdetails: { mode: \"script\", error: \"init_failed\", message },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!state) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: \"MCP not initialized\" }],\n\t\t\t\t\t\tdetails: { mode: \"script\", error: \"not_initialized\" },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\texecuteOwner?.throwIfInactive();\n\t\t\t\treturn runMcpScript(state, params.code, params.timeoutMs, getNexusTools, signal);\n\t\t\t},\n\t\t});\n\t}\n\n\tfunction registerProxyTool(description: string): void {\n\t\t(nexus.registerTool as (tool: unknown) => unknown)({\n\t\t\tname: \"mcp\",\n\t\t\tlabel: \"MCP\",\n\t\t\tdescription,\n\t\t\tpromptSnippet: \"MCP gateway — status, search, describe, auth, and single MCP tool calls\",\n\t\t\trenderShell: toolRenderShell,\n\t\t\trenderCall: createMcpProxyToolCallRenderer(toolRenderOptions),\n\t\t\tparameters: Type.Object({\n\t\t\t\ttool: Type.Optional(Type.String({ description: \"Tool name to call (e.g., 'xcodebuild_list_sims')\" })),\n\t\t\t\targs: Type.Optional(\n\t\t\t\t\tType.Union(\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\tType.String({ description: 'Arguments as a JSON string (e.g., \\'{\"key\": \"value\"}\\')' }),\n\t\t\t\t\t\t\tType.Object(\n\t\t\t\t\t\t\t\t{},\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tadditionalProperties: true,\n\t\t\t\t\t\t\t\t\tdescription: 'Arguments as a JSON object (e.g., { \"key\": \"value\" })',\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t],\n\t\t\t\t\t\t{ description: \"Tool arguments as a JSON object, or as a JSON string encoding one\" },\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tconnect: Type.Optional(\n\t\t\t\t\tType.String({ description: \"Server name to connect (lazy connect + metadata refresh)\" }),\n\t\t\t\t),\n\t\t\t\tdescribe: Type.Optional(Type.String({ description: \"Tool name to describe (shows parameters)\" })),\n\t\t\t\tinstructions: Type.Optional(\n\t\t\t\t\tType.String({ description: \"Server name to show that server's usage instructions\" }),\n\t\t\t\t),\n\t\t\t\tsearch: Type.Optional(Type.String({ description: \"Search tools by name/description\" })),\n\t\t\t\tregex: Type.Optional(Type.Boolean({ description: \"Treat search as regex (default: substring match)\" })),\n\t\t\t\tincludeSchemas: Type.Optional(\n\t\t\t\t\tType.Boolean({ description: \"Include parameter schemas in search results (default: true)\" }),\n\t\t\t\t),\n\t\t\t\tlimit: optionalNumber({ minimum: 1, description: \"Maximum search results to return (default: 12)\" }),\n\t\t\t\toffset: optionalNumber({ minimum: 0, description: \"Search result offset (default: 0)\" }),\n\t\t\t\tserver: Type.Optional(\n\t\t\t\t\tType.String({ description: \"Filter to specific server (also disambiguates tool calls)\" }),\n\t\t\t\t),\n\t\t\t\taction: Type.Optional(\n\t\t\t\t\tType.String({ description: \"Action: 'ui-messages', 'auth-start', or 'auth-complete'\" }),\n\t\t\t\t),\n\t\t\t}),\n\t\t\trenderResult: renderMcpToolResult,\n\t\t\tasync execute(\n\t\t\t\t_toolCallId: string,\n\t\t\t\tparams: {\n\t\t\t\t\ttool?: string;\n\t\t\t\t\targs?: string | Record<string, unknown>;\n\t\t\t\t\tconnect?: string;\n\t\t\t\t\tdescribe?: string;\n\t\t\t\t\tinstructions?: string;\n\t\t\t\t\tsearch?: string;\n\t\t\t\t\tregex?: boolean;\n\t\t\t\t\tincludeSchemas?: boolean;\n\t\t\t\t\tlimit?: number;\n\t\t\t\t\toffset?: number;\n\t\t\t\t\tserver?: string;\n\t\t\t\t\taction?: string;\n\t\t\t\t},\n\t\t\t\tsignal: AbortSignal | undefined,\n\t\t\t\t_onUpdate: AgentToolUpdateCallback<Record<string, unknown>> | undefined,\n\t\t\t\t_ctx: ExtensionContext,\n\t\t\t) {\n\t\t\t\tconst executeOwner = currentOwner;\n\t\t\t\tconst parseArgs = (\n\t\t\t\t\tvalue: string | Record<string, unknown> | undefined,\n\t\t\t\t): Record<string, unknown> | undefined => {\n\t\t\t\t\tif (value === undefined || value === \"\") return undefined;\n\t\t\t\t\tlet args: unknown;\n\t\t\t\t\tif (typeof value === \"string\") {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\targs = JSON.parse(value);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif (error instanceof SyntaxError) {\n\t\t\t\t\t\t\t\tthrow new Error(`Invalid args JSON: ${error.message}`, { cause: error });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\targs = value;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (typeof args !== \"object\" || args === null || Array.isArray(args)) {\n\t\t\t\t\t\tconst gotType = Array.isArray(args) ? \"array\" : args === null ? \"null\" : typeof args;\n\t\t\t\t\t\tthrow new Error(`Invalid args: expected a JSON object, got ${gotType}`);\n\t\t\t\t\t}\n\t\t\t\t\treturn args as Record<string, unknown>;\n\t\t\t\t};\n\t\t\t\tconst validateNestedGatewayParams = (value: Record<string, unknown>): typeof params => {\n\t\t\t\t\tfor (const key of [\n\t\t\t\t\t\t\"tool\",\n\t\t\t\t\t\t\"connect\",\n\t\t\t\t\t\t\"describe\",\n\t\t\t\t\t\t\"instructions\",\n\t\t\t\t\t\t\"search\",\n\t\t\t\t\t\t\"server\",\n\t\t\t\t\t\t\"action\",\n\t\t\t\t\t] as const) {\n\t\t\t\t\t\tif (value[key] !== undefined && typeof value[key] !== \"string\") {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`Invalid nested gateway param \\`${key}\\`: expected string, got ${Array.isArray(value[key]) ? \"array\" : typeof value[key]}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor (const key of [\"regex\", \"includeSchemas\"] as const) {\n\t\t\t\t\t\tif (value[key] !== undefined && typeof value[key] !== \"boolean\") {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`Invalid nested gateway param \\`${key}\\`: expected boolean, got ${Array.isArray(value[key]) ? \"array\" : typeof value[key]}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor (const key of [\"limit\", \"offset\"] as const) {\n\t\t\t\t\t\tif (value[key] !== undefined && typeof value[key] !== \"number\") {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`Invalid nested gateway param \\`${key}\\`: expected number, got ${Array.isArray(value[key]) ? \"array\" : typeof value[key]}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst args = value.args;\n\t\t\t\t\tif (\n\t\t\t\t\t\targs !== undefined &&\n\t\t\t\t\t\ttypeof args !== \"string\" &&\n\t\t\t\t\t\t(typeof args !== \"object\" || args === null || Array.isArray(args))\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Invalid nested gateway param \\`args\\`: expected JSON object or JSON string, got ${Array.isArray(args) ? \"array\" : args === null ? \"null\" : typeof args}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn value as typeof params;\n\t\t\t\t};\n\t\t\t\tlet parsedArgs = parseArgs(params.args);\n\t\t\t\tlet dispatchParams = params;\n\t\t\t\tconst hasGatewayMode = (value: typeof params): boolean =>\n\t\t\t\t\tvalue.tool !== undefined ||\n\t\t\t\t\tvalue.connect !== undefined ||\n\t\t\t\t\tvalue.describe !== undefined ||\n\t\t\t\t\tvalue.instructions !== undefined ||\n\t\t\t\t\tvalue.search !== undefined ||\n\t\t\t\t\tvalue.server !== undefined ||\n\t\t\t\t\tvalue.action !== undefined;\n\t\t\t\tif (!hasGatewayMode(params) && parsedArgs) {\n\t\t\t\t\tconst nestedParams = validateNestedGatewayParams(parsedArgs);\n\t\t\t\t\tif (hasGatewayMode(nestedParams)) {\n\t\t\t\t\t\tdispatchParams = nestedParams;\n\t\t\t\t\t\tparsedArgs = parseArgs(nestedParams.args);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'Gateway params were nested inside `args`; pass them top-level (for example, mcp({ search: \"...\" }) or mcp({ tool: \"...\", args: {} })).',\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else if (!hasGatewayMode(params) && params.args !== undefined) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'Gateway params were nested inside `args`; pass them top-level (for example, mcp({ search: \"...\" }) or mcp({ tool: \"...\", args: {} })).',\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (!state && initPromise) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst initialized = await awaitWithTimeout(initPromise, INIT_WAIT_TIMEOUT_MS);\n\t\t\t\t\t\tif (initialized === INIT_WAIT_TIMED_OUT) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\t\t\t\ttext: \"MCP initialization is still in progress. Try again shortly.\",\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\tdetails: { error: \"init_timeout\", timeoutMs: INIT_WAIT_TIMEOUT_MS },\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\texecuteOwner?.throwIfInactive();\n\t\t\t\t\t\tstate = initialized;\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (executeOwner && isAbortError(error, executeOwner.signal)) throw error;\n\t\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: `MCP initialization failed: ${message}` }],\n\t\t\t\t\t\t\tdetails: { error: \"init_failed\", message },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!state) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: \"MCP not initialized\" }],\n\t\t\t\t\t\tdetails: { error: \"not_initialized\" },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\texecuteOwner?.throwIfInactive();\n\n\t\t\t\tif (dispatchParams.action === \"ui-messages\") {\n\t\t\t\t\treturn executeUiMessages(state);\n\t\t\t\t}\n\t\t\t\tif (dispatchParams.action === \"auth-start\") {\n\t\t\t\t\tif (!dispatchParams.server) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\t\t\ttext: 'auth-start requires `server`. Example: mcp({ action: \"auth-start\", server: \"linear-server\" })',\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tdetails: { mode: \"auth-start\", error: \"missing_server\" },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\treturn signal\n\t\t\t\t\t\t? executeAuthStart(state, dispatchParams.server, signal)\n\t\t\t\t\t\t: executeAuthStart(state, dispatchParams.server);\n\t\t\t\t}\n\t\t\t\tif (dispatchParams.action === \"auth-complete\") {\n\t\t\t\t\tif (!dispatchParams.server) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: \"auth-complete requires `server`.\" }],\n\t\t\t\t\t\t\tdetails: { mode: \"auth-complete\", error: \"missing_server\" },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tconst input = parsedArgs?.redirectUrl ?? parsedArgs?.code ?? parsedArgs?.input;\n\t\t\t\t\tif (typeof input !== \"string\" || input.trim().length === 0) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\t\t\ttext: \"auth-complete requires args with `redirectUrl`, `code`, or `input`.\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tdetails: { mode: \"auth-complete\", error: \"missing_input\" },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\treturn signal\n\t\t\t\t\t\t? executeAuthComplete(state, dispatchParams.server, input, signal)\n\t\t\t\t\t\t: executeAuthComplete(state, dispatchParams.server, input);\n\t\t\t\t}\n\t\t\t\tif (dispatchParams.tool) {\n\t\t\t\t\treturn executeCall(state, dispatchParams.tool, parsedArgs, dispatchParams.server, getNexusTools, signal);\n\t\t\t\t}\n\t\t\t\tif (dispatchParams.connect) {\n\t\t\t\t\tconst result = await executeConnect(state, dispatchParams.connect, signal);\n\t\t\t\t\tsyncToolSurface(_ctx as ExtensionContext);\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t\tif (dispatchParams.describe) {\n\t\t\t\t\treturn executeDescribe(state, dispatchParams.describe);\n\t\t\t\t}\n\t\t\t\tif (dispatchParams.instructions) {\n\t\t\t\t\treturn executeInstructions(state, dispatchParams.instructions);\n\t\t\t\t}\n\t\t\t\tif (dispatchParams.search !== undefined) {\n\t\t\t\t\treturn executeSearch(\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\tdispatchParams.search,\n\t\t\t\t\t\tdispatchParams.regex,\n\t\t\t\t\t\tdispatchParams.server,\n\t\t\t\t\t\tdispatchParams.includeSchemas,\n\t\t\t\t\t\tdispatchParams.limit,\n\t\t\t\t\t\tdispatchParams.offset,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (dispatchParams.server) {\n\t\t\t\t\treturn executeList(state, dispatchParams.server);\n\t\t\t\t}\n\t\t\t\treturn executeStatus(state);\n\t\t\t},\n\t\t});\n\t\tproxyToolRegistered = true;\n\t\tproxyToolDescription = description;\n\t}\n\n\tfunction syncProxyTool(config: McpConfig, cache: MetadataCache | null, directSpecs: DirectToolSpec[]): void {\n\t\tconst missingConfiguredDirectToolServers = getMissingConfiguredDirectToolServers(\n\t\t\tconfig,\n\t\t\tcache,\n\t\t\tenvRaw === undefined || envRaw === \"__none__\" ? undefined : envDirectToolOverride,\n\t\t);\n\t\tconst shouldRegisterProxyTool =\n\t\t\tconfig.settings?.disableProxyTool !== true ||\n\t\t\tdirectSpecs.length === 0 ||\n\t\t\tmissingConfiguredDirectToolServers.length > 0;\n\n\t\tif (shouldRegisterProxyTool) {\n\t\t\tconst description = buildProxyDescription(config, cache, directSpecs);\n\t\t\tif (!proxyToolRegistered || proxyToolDescription !== description) {\n\t\t\t\tregisterProxyTool(description);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst activeTools = getActiveToolsIfReady();\n\t\t\tif (activeTools && !activeTools.includes(\"mcp\")) {\n\t\t\t\tnexus.setActiveTools([...activeTools, \"mcp\"]);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (proxyToolRegistered) {\n\t\t\tconst unregistered = deactivateTools([\"mcp\"]);\n\t\t\tif (unregistered.includes(\"mcp\")) {\n\t\t\t\tproxyToolRegistered = false;\n\t\t\t\tproxyToolDescription = null;\n\t\t\t}\n\t\t}\n\t}\n\n\tnexus.on(\"resources_discover\", () => {\n\t\tconst skillsPath = join(import.meta.dirname, \"skills\");\n\t\tif (existsSync(skillsPath)) return { skillPaths: [skillsPath] };\n\t});\n\n\tconst initialDirectTools = syncDirectTools(earlyConfig, earlyCache).specs;\n\tsyncProxyTool(earlyConfig, earlyCache, initialDirectTools);\n\tstartLoadTimeInitialization();\n}\n\nexport function createMcpAdapter(options: McpAdapterOptions = {}) {\n\tconst factoryConfig = options.config !== undefined ? cloneMcpConfig(options.config) : undefined;\n\treturn function mcpAdapter(nexus: ExtensionAPI) {\n\t\tinstallMcpAdapter(nexus, {\n\t\t\t...(options.configPath !== undefined ? { configPath: options.configPath } : {}),\n\t\t\t...(factoryConfig !== undefined ? { config: cloneMcpConfig(factoryConfig) } : {}),\n\t\t});\n\t};\n}\n\n/**\n * Register an MCP server with the adapter installed for this Nexus instance.\n * Registrations are session/runtime scoped and never persisted. Duplicate\n * names fail closed. Registered servers are proxy-tool-only; their tools\n * become visible at the next tool sync. To change a definition, dispose the\n * registration and register again.\n */\nexport function registerMcpServer(options: {\n\tnexus: ExtensionAPI;\n\tname: string;\n\tdefinition: ServerEntry;\n}): McpServerRegistration {\n\tconst { nexus, name, definition } = options;\n\tconst register = runtimeRegistrars.get(nexus);\n\tif (!register) {\n\t\tthrow new Error(\"The native Nexus MCP runtime is not installed for this instance\");\n\t}\n\treturn register(name, definition);\n}\n\nexport default createMcpAdapter();\n"]}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/extensions/mcp/index.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAA2B,YAAY,EAA8B,MAAM,gCAAgC,CAAC;AAsDxH,OAAO,KAAK,EAAkB,iBAAiB,EAA6B,WAAW,EAAE,MAAM,YAAY,CAAC;AAG5G,YAAY,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACjE,OAAO,EACN,gBAAgB,EAChB,2BAA2B,EAC3B,+BAA+B,EAC/B,KAAK,sBAAsB,EAC3B,KAAK,uBAAuB,EAC5B,KAAK,iBAAiB,EACtB,KAAK,uBAAuB,EAC5B,KAAK,sBAAsB,EAC3B,KAAK,qBAAqB,EAC1B,KAAK,sBAAsB,GAC3B,MAAM,YAAY,CAAC;AAKpB,MAAM,WAAW,qBAAqB;IACrC,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACzB;AAyuCD,wBAAgB,gBAAgB,CAAC,OAAO,GAAE,iBAAsB,iCAQ/D;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE;IAC1C,KAAK,EAAE,YAAY,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,WAAW,CAAC;CACxB,GAAG,qBAAqB,CAOxB;;AAED,wBAAkC","sourcesContent":["import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { Api, Model } from \"@earendil-works/pi-ai\";\nimport type { TSchema } from \"typebox\";\nimport { Type } from \"typebox\";\nimport type { AgentToolUpdateCallback, ExtensionAPI, ExtensionContext, ToolInfo } from \"../../core/extensions/types.ts\";\nimport {\n\tADD_SERVER_USAGE,\n\taddCustomServer,\n\tauthenticateServer,\n\tlogoutServer,\n\tmanageBearerToken,\n\topenMcpAuthPanel,\n\topenMcpPanel,\n\topenMcpSetup,\n\tparseAddServerArgs,\n\treconnectServer,\n\treconnectServers,\n\tshowPrompts,\n\tshowStatus,\n\tshowTools,\n} from \"./commands.ts\";\nimport { cloneMcpConfig, loadMcpConfig, writeProjectServerDisabledOverride } from \"./config.ts\";\nimport {\n\tbuildProxyDescription,\n\tcreateDirectToolExecutor,\n\tgetMissingConfiguredDirectToolServers,\n\tresolveDirectTools,\n} from \"./direct-tools.ts\";\nimport { toolErrorOverride } from \"./error-signal.ts\";\nimport { flushMetadataCache, initializeMcp, updateStatusBar } from \"./init.ts\";\nimport { logger } from \"./logger.ts\";\nimport type { McpOAuthRuntime } from \"./mcp-auth-flow.ts\";\nimport { createOAuthRuntime, shutdownOAuth } from \"./mcp-auth-flow.ts\";\nimport { runMcpScript } from \"./mcp-code.ts\";\nimport { publishMcpStatusShutdown } from \"./mcp-status.ts\";\nimport { loadMetadataCache, type MetadataCache } from \"./metadata-cache.ts\";\nimport { createPromptCommand, resolveCachedPrompts } from \"./prompts.ts\";\nimport {\n\texecuteAuthComplete,\n\texecuteAuthStart,\n\texecuteCall,\n\texecuteConnect,\n\texecuteDescribe,\n\texecuteInstructions,\n\texecuteList,\n\texecuteSearch,\n\texecuteStatus,\n\texecuteUiMessages,\n} from \"./proxy-modes.ts\";\nimport { createMcpRuntimeOwner, createOwnedUi, isAbortError, type McpRuntimeOwner } from \"./runtime-owner.ts\";\nimport type { McpExtensionState } from \"./state.ts\";\nimport { cleanupMaterializedBinaryResources } from \"./tool-registrar.ts\";\nimport {\n\tcreateMcpDirectToolCallRenderer,\n\tcreateMcpProxyToolCallRenderer,\n\tcreateMcpToolResultRenderer,\n\tresolveMcpToolRenderOptions,\n} from \"./tool-result-renderer.ts\";\nimport type { DirectToolSpec, McpAdapterOptions, McpConfig, PromptMetadata, ServerEntry } from \"./types.ts\";\nimport { formatTerminalError, getConfigPathFromArgv, normalizeDirectToolInputSchema, truncateAtWord } from \"./utils.ts\";\n\nexport type { McpAdapterOptions, ServerEntry } from \"./types.ts\";\nexport {\n\tMCP_STATUS_EVENT,\n\tMCP_STATUS_SNAPSHOT_VERSION,\n\tMCP_TOOL_APPROVAL_REQUEST_EVENT,\n\ttype McpServerRuntimeStatus,\n\ttype McpServerStatusSnapshot,\n\ttype McpStatusSnapshot,\n\ttype McpToolApprovalDecision,\n\ttype McpToolApprovalHandler,\n\ttype McpToolApprovalOrigin,\n\ttype McpToolApprovalRequest,\n} from \"./types.ts\";\n\nconst INIT_WAIT_TIMEOUT_MS = 30_000;\nconst INIT_WAIT_TIMED_OUT: unique symbol = Symbol(\"init-wait-timed-out\");\n\nexport interface McpServerRegistration {\n\tdispose(): Promise<void>;\n}\n\n// Routes runtime registrations to the adapter installed for a specific Nexus\n// instance, so a process with several adapters cannot cross-register.\nconst runtimeRegistrars = new WeakMap<ExtensionAPI, (name: string, definition: ServerEntry) => McpServerRegistration>();\n\nasync function awaitWithTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T | typeof INIT_WAIT_TIMED_OUT> {\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\ttry {\n\t\treturn await Promise.race([\n\t\t\tpromise,\n\t\t\tnew Promise<typeof INIT_WAIT_TIMED_OUT>((resolve) => {\n\t\t\t\ttimer = setTimeout(() => resolve(INIT_WAIT_TIMED_OUT), timeoutMs);\n\t\t\t\ttimer.unref?.();\n\t\t\t}),\n\t\t]);\n\t} finally {\n\t\tclearTimeout(timer);\n\t}\n}\n\n// TypeBox 1.x annotates raw objects passed to Type.Optional with an enumerable\n// \"~optional\" key that survives serialization into provider tool schemas (Gemini\n// rejects it with 400 INVALID_ARGUMENT). Prefer a real Type.Number schema; fall\n// back to a plain raw schema for host TypeBox shims that omit Type.Number, since\n// a property left out of `required` is optional by default.\nfunction optionalNumber(options: { minimum?: number; description: string }): TSchema {\n\tconst number = (Type as { Number?: (opts: typeof options) => TSchema }).Number;\n\treturn typeof number === \"function\"\n\t\t? Type.Optional(number(options))\n\t\t: ({ type: \"number\", ...options } as unknown as TSchema);\n}\n\nfunction installMcpAdapter(nexus: ExtensionAPI, options: McpAdapterOptions) {\n\tconst sessionConfig = options.config !== undefined ? cloneMcpConfig(options.config) : undefined;\n\tconst programmaticConfig = sessionConfig !== undefined;\n\tlet state: McpExtensionState | null = null;\n\tlet initPromise: Promise<McpExtensionState> | null = null;\n\tlet currentOwner: McpRuntimeOwner | null = null;\n\tlet currentOAuthRuntime: McpOAuthRuntime | null = null;\n\tlet currentModel: Model<Api> | undefined;\n\tlet lifecycleGeneration = 0;\n\n\tasync function shutdownState(currentState: McpExtensionState | null, reason: string): Promise<void> {\n\t\tif (!currentState) {\n\t\t\tpublishMcpStatusShutdown(nexus.events);\n\t\t\treturn;\n\t\t}\n\n\t\tpublishMcpStatusShutdown(currentState.statusEvents);\n\n\t\tif (currentState.uiServer) {\n\t\t\tcurrentState.uiServer.close(reason);\n\t\t\tcurrentState.uiServer = null;\n\t\t}\n\n\t\tlet flushError: unknown;\n\t\ttry {\n\t\t\tflushMetadataCache(currentState);\n\t\t} catch (error) {\n\t\t\tflushError = error;\n\t\t}\n\n\t\ttry {\n\t\t\tif (currentState.owner) {\n\t\t\t\tawait currentState.owner.stop(reason);\n\t\t\t} else {\n\t\t\t\tawait currentState.lifecycle.gracefulShutdown();\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (flushError) {\n\t\t\t\tconsole.error(`MCP: graceful shutdown failed after metadata flush error: ${formatTerminalError(error)}`);\n\t\t\t} else {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\n\t\tif (flushError) {\n\t\t\tthrow flushError;\n\t\t}\n\t}\n\n\tconst earlyConfigPath = programmaticConfig ? undefined : (options.configPath ?? getConfigPathFromArgv());\n\tconst earlyConfig = programmaticConfig\n\t\t? cloneMcpConfig(sessionConfig)\n\t\t: loadMcpConfig(earlyConfigPath, process.cwd(), false);\n\tconst earlyCache = loadMetadataCache();\n\tconst envRaw = process.env.MCP_DIRECT_TOOLS;\n\tconst envDirectToolOverride = envRaw\n\t\t?.split(\",\")\n\t\t.map((s) => s.trim())\n\t\t.filter(Boolean);\n\tconst registeredDirectTools = new Map<string, string>();\n\tconst fallbackDeactivatedTools = new Set<string>();\n\tconst toolRenderOptions = resolveMcpToolRenderOptions(earlyConfig.settings);\n\tconst toolRenderShell = toolRenderOptions.resultRendering === \"compact\" ? \"self\" : \"default\";\n\tconst renderMcpToolResult = createMcpToolResultRenderer(toolRenderOptions);\n\tlet proxyToolRegistered = false;\n\tlet proxyToolDescription: string | null = null;\n\tlet directToolsFrozen = false;\n\t// Session/runtime scoped server registrations from other extensions. They\n\t// survive session restarts within this install and die with the process.\n\tconst runtimeServers = new Map<string, ServerEntry>();\n\n\t// Mirrors init's per-server lifecycle registration so runtime servers get\n\t// idle cleanup and keep-alive health recovery like configured servers.\n\tfunction attachRuntimeServerLifecycle(targetState: McpExtensionState, name: string, definition: ServerEntry): void {\n\t\tconst lifecycleMode = definition.lifecycle ?? \"lazy\";\n\t\tconst persistsAfterFirstSpawn = lifecycleMode === \"eager\" || lifecycleMode === \"lazy-keep-alive\";\n\t\tconst idleOverride = definition.idleTimeout ?? (persistsAfterFirstSpawn ? 0 : undefined);\n\t\ttargetState.lifecycle.registerServer(\n\t\t\tname,\n\t\t\tdefinition,\n\t\t\tidleOverride !== undefined ? { idleTimeout: idleOverride } : undefined,\n\t\t);\n\t\tif (lifecycleMode === \"keep-alive\") targetState.lifecycle.markKeepAlive(name, definition);\n\t}\n\n\t// OMP remaps `typebox` to a host shim that historically lacked Type.Unsafe.\n\t// Prefer Unsafe when present (real TypeBox / fixed OMP shim); otherwise pass\n\t// the normalized JSON Schema through as a plain object so toolWireSchema and\n\t// validateToolArguments still treat it as JSON Schema.\n\tconst toToolParameters = (schema: Record<string, unknown>) =>\n\t\ttypeof (Type as { Unsafe?: (value: never) => unknown }).Unsafe === \"function\"\n\t\t\t? (Type as { Unsafe: (value: never) => unknown }).Unsafe(schema as never)\n\t\t\t: schema;\n\n\tfunction directToolFingerprint(spec: DirectToolSpec): string {\n\t\treturn JSON.stringify({\n\t\t\tserverName: spec.serverName,\n\t\t\toriginalName: spec.originalName,\n\t\t\tprefixedName: spec.prefixedName,\n\t\t\tdescription: spec.description,\n\t\t\tinputSchema: spec.inputSchema,\n\t\t\tresourceUri: spec.resourceUri,\n\t\t\tuiResourceUri: spec.uiResourceUri,\n\t\t\tuiStreamMode: spec.uiStreamMode,\n\t\t});\n\t}\n\n\tfunction registerDirectTool(spec: DirectToolSpec): void {\n\t\t(nexus.registerTool as (tool: unknown) => unknown)({\n\t\t\tname: spec.prefixedName,\n\t\t\tlabel: `MCP: ${spec.originalName}`,\n\t\t\tdescription: spec.description || \"(no description)\",\n\t\t\tpromptSnippet: truncateAtWord(spec.description, 100) || `MCP tool from ${spec.serverName}`,\n\t\t\tparameters: toToolParameters(normalizeDirectToolInputSchema(spec.inputSchema)),\n\t\t\texecute: createDirectToolExecutor(\n\t\t\t\t() => state,\n\t\t\t\t() => initPromise,\n\t\t\t\tspec,\n\t\t\t),\n\t\t\trenderShell: toolRenderShell,\n\t\t\trenderCall: createMcpDirectToolCallRenderer(spec.prefixedName, toolRenderOptions),\n\t\t\trenderResult: renderMcpToolResult,\n\t\t});\n\t}\n\n\tfunction resolveCurrentDirectTools(config: McpConfig, cache: MetadataCache | null): DirectToolSpec[] {\n\t\tif (envRaw === \"__none__\") return [];\n\t\tconst prefix = config.settings?.toolPrefix ?? \"server\";\n\t\treturn resolveDirectTools(config, cache, prefix, envDirectToolOverride);\n\t}\n\n\tfunction getActiveToolsIfReady(): string[] | undefined {\n\t\ttry {\n\t\t\treturn nexus.getActiveTools?.();\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\terror instanceof Error &&\n\t\t\t\terror.message.includes(\"Action methods cannot be called during extension loading\")\n\t\t\t)\n\t\t\t\treturn undefined;\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tfunction deactivateTools(toolNames: string[]): string[] {\n\t\tif (toolNames.length === 0) return [];\n\t\tconst unregisterTool = (nexus as ExtensionAPI & { unregisterTool?: (name: string) => boolean }).unregisterTool;\n\t\tconst unregistered = toolNames.filter((toolName) => unregisterTool?.(toolName) === true);\n\t\tconst fallbackNames = toolNames.filter((toolName) => !unregistered.includes(toolName));\n\t\tconst remove = new Set(toolNames);\n\t\tconst activeTools = getActiveToolsIfReady();\n\t\tif (!activeTools || activeTools.length === 0) {\n\t\t\tfor (const toolName of fallbackNames) fallbackDeactivatedTools.add(toolName);\n\t\t\treturn unregistered;\n\t\t}\n\t\tconst nextActiveTools = activeTools.filter((name) => !remove.has(name));\n\t\tif (nextActiveTools.length !== activeTools.length) {\n\t\t\tfor (const toolName of fallbackNames) fallbackDeactivatedTools.add(toolName);\n\t\t\tnexus.setActiveTools(nextActiveTools);\n\t\t}\n\t\treturn unregistered;\n\t}\n\n\tfunction syncDirectTools(\n\t\tconfig: McpConfig,\n\t\tcache: MetadataCache | null,\n\t): {\n\t\tspecs: DirectToolSpec[];\n\t\tadded: string[];\n\t\tupdated: string[];\n\t\tdeactivated: string[];\n\t} {\n\t\tconst specs = resolveCurrentDirectTools(config, cache);\n\t\tconst nextNames = new Set(specs.map((spec) => spec.prefixedName));\n\t\tconst added: string[] = [];\n\t\tconst updated: string[] = [];\n\t\tconst deactivated: string[] = [];\n\n\t\tfor (const spec of specs) {\n\t\t\tconst fingerprint = directToolFingerprint(spec);\n\t\t\tconst previous = registeredDirectTools.get(spec.prefixedName);\n\t\t\tif (previous !== fingerprint) {\n\t\t\t\tregisterDirectTool(spec);\n\t\t\t\tregisteredDirectTools.set(spec.prefixedName, fingerprint);\n\t\t\t\tif (fallbackDeactivatedTools.delete(spec.prefixedName)) {\n\t\t\t\t\tconst activeTools = getActiveToolsIfReady();\n\t\t\t\t\tif (activeTools && !activeTools.includes(spec.prefixedName)) {\n\t\t\t\t\t\tnexus.setActiveTools([...activeTools, spec.prefixedName]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t(previous ? updated : added).push(spec.prefixedName);\n\t\t\t}\n\t\t}\n\n\t\tfor (const toolName of [...registeredDirectTools.keys()]) {\n\t\t\tif (nextNames.has(toolName)) continue;\n\t\t\tregisteredDirectTools.delete(toolName);\n\t\t\tdeactivated.push(toolName);\n\t\t}\n\n\t\tdeactivateTools(deactivated);\n\t\treturn { specs, added, updated, deactivated };\n\t}\n\n\tfunction applyDirectToolConfigChanges(changes: Map<string, true | string[] | false>): void {\n\t\tif (!state) return;\n\t\tfor (const [serverName, value] of changes) {\n\t\t\tconst definition = state.config.mcpServers[serverName];\n\t\t\tif (!definition) continue;\n\t\t\tstate.config.mcpServers[serverName] = { ...definition, directTools: value };\n\t\t}\n\t}\n\n\tfunction syncToolSurface(ctx?: ExtensionContext): void {\n\t\tconst config = state?.config ?? earlyConfig;\n\t\tconst cache = loadMetadataCache();\n\t\tconst result = syncDirectTools(config, cache);\n\t\tsyncProxyTool(config, cache, result.specs);\n\t\tconst changed = result.added.length + result.updated.length + result.deactivated.length;\n\t\tif (changed > 0 && ctx?.hasUI) {\n\t\t\tctx.ui.notify(\n\t\t\t\t`MCP: direct tools refreshed (+${result.added.length}, ~${result.updated.length}, -${result.deactivated.length})`,\n\t\t\t\t\"info\",\n\t\t\t);\n\t\t}\n\t}\n\n\tconst registeredPromptCommands = new Set<string>();\n\n\tfunction registerPromptCommands(specs: Iterable<PromptMetadata>): void {\n\t\tfor (const spec of specs) {\n\t\t\tif (registeredPromptCommands.has(spec.commandName)) {\n\t\t\t\tlogger.debug(\n\t\t\t\t\t`MCP: prompt \"${spec.originalName}\" on ${spec.serverName} skipped; /${spec.commandName} is already registered`,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tregisteredPromptCommands.add(spec.commandName);\n\t\t\tnexus.registerCommand(\n\t\t\t\tspec.commandName,\n\t\t\t\tcreatePromptCommand(nexus, () => state, spec),\n\t\t\t);\n\t\t}\n\t}\n\n\tfunction syncPromptCommands(): void {\n\t\tregisterPromptCommands([...(state?.promptMetadata?.values() ?? [])].flat());\n\t}\n\n\tregisterPromptCommands(resolveCachedPrompts(earlyConfig));\n\n\truntimeRegistrars.set(nexus, (name: string, definition: ServerEntry): McpServerRegistration => {\n\t\tif (typeof name !== \"string\" || name.trim() === \"\") {\n\t\t\tthrow new Error(\"MCP server name must be a non-empty string\");\n\t\t}\n\t\tif (typeof definition !== \"object\" || definition === null || Array.isArray(definition)) {\n\t\t\tthrow new Error(`MCP server definition for \"${name}\" must be an object`);\n\t\t}\n\t\tconst effective = state?.config ?? earlyConfig;\n\t\tif (runtimeServers.has(name) || Object.hasOwn(effective.mcpServers, name)) {\n\t\t\tthrow new Error(`MCP server \"${name}\" is already registered`);\n\t\t}\n\t\t// Runtime-registered servers are proxy-tool-only: direct tools are frozen\n\t\t// at startup and must not be rebuilt for late registrations.\n\t\tconst entry: ServerEntry = { ...structuredClone(definition), directTools: false };\n\t\truntimeServers.set(name, entry);\n\t\tconst registeredState = state;\n\t\tif (registeredState) {\n\t\t\tregisteredState.config.mcpServers[name] = entry;\n\t\t\tattachRuntimeServerLifecycle(registeredState, name, entry);\n\t\t\tsyncToolSurface();\n\t\t\tupdateStatusBar(registeredState);\n\t\t}\n\t\tlet disposed = false;\n\t\treturn {\n\t\t\tdispose: async (): Promise<void> => {\n\t\t\t\tif (disposed) return;\n\t\t\t\tdisposed = true;\n\t\t\t\truntimeServers.delete(name);\n\t\t\t\tconst currentState = state;\n\t\t\t\tif (!currentState || currentState.config.mcpServers[name] !== entry) return;\n\t\t\t\tdelete currentState.config.mcpServers[name];\n\t\t\t\tcurrentState.lifecycle.unregisterServer(name);\n\t\t\t\tawait currentState.manager.close(name);\n\t\t\t\tsyncToolSurface();\n\t\t\t\tupdateStatusBar(currentState);\n\t\t\t},\n\t\t};\n\t});\n\n\tconst getNexusTools = (): ToolInfo[] => nexus.getAllTools();\n\n\tnexus.registerFlag(\"mcp-config\", {\n\t\tdescription: \"Path to MCP config file\",\n\t\ttype: \"string\",\n\t});\n\n\tfunction startInitialization(\n\t\tctx: ExtensionContext,\n\t\towner: McpRuntimeOwner,\n\t\toauthRuntime: McpOAuthRuntime,\n\t\tgeneration: number,\n\t\tstaleReason: string,\n\t): Promise<void> {\n\t\towner.addCleanup(() => cleanupMaterializedBinaryResources(owner.signal));\n\t\tconst promise = initializeMcp(nexus, ctx, owner, {\n\t\t\t...(programmaticConfig || options.configPath !== undefined\n\t\t\t\t? {\n\t\t\t\t\t\t...(earlyConfigPath !== undefined ? { configPath: earlyConfigPath } : {}),\n\t\t\t\t\t\t...(sessionConfig !== undefined ? { config: sessionConfig } : {}),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\toauthRuntime,\n\t\t\tgetCurrentModel: () => currentModel,\n\t\t});\n\t\tinitPromise = promise;\n\n\t\treturn promise\n\t\t\t.then(async (nextState) => {\n\t\t\t\tif (!owner.isActive() || generation !== lifecycleGeneration || initPromise !== promise) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait shutdownState(nextState, staleReason);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconsole.error(`MCP: failed to clean stale initialization state: ${formatTerminalError(error)}`);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tstate = nextState;\n\t\t\t\tfor (const [name, definition] of runtimeServers) {\n\t\t\t\t\tif (Object.hasOwn(nextState.config.mcpServers, name)) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t`MCP: runtime-registered server \"${name}\" now collides with a configured server; keeping the configured server`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tnextState.config.mcpServers[name] = definition;\n\t\t\t\t\tattachRuntimeServerLifecycle(nextState, name, definition);\n\t\t\t\t}\n\t\t\t\tnextState.onToolMetadataUpdated = (_serverName, _reason) => {\n\t\t\t\t\tif (state !== nextState || !owner.isActive()) return;\n\t\t\t\t\tsyncPromptCommands();\n\t\t\t\t\tif (directToolsFrozen) {\n\t\t\t\t\t\tlogger.debug(`MCP: metadata update for ${_serverName} (${_reason}) skipped — directTools frozen`);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tsyncToolSurface(ctx);\n\t\t\t\t};\n\t\t\t\tsyncPromptCommands();\n\t\t\t\tsyncToolSurface(ctx);\n\t\t\t\t// A connected snapshot is readiness-like external state. Publish it only\n\t\t\t\t// after Nexus's model-facing direct-tool surface reflects live metadata.\n\t\t\t\tnextState.statusEvents = nexus.events;\n\t\t\t\tupdateStatusBar(nextState);\n\t\t\t\tinitPromise = null;\n\t\t\t\tif (nextState.config.settings?.freezeDirectTools === true) {\n\t\t\t\t\tdirectToolsFrozen = true;\n\t\t\t\t\tlogger.info(\n\t\t\t\t\t\t'MCP: direct tools frozen after initial sync — reconnects won\\'t rebuild the system prompt; use mcp({ connect: \"server\" }) to rediscover',\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t})\n\t\t\t.catch(async (err) => {\n\t\t\t\tif (!owner.isActive() || generation !== lifecycleGeneration) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (initPromise !== promise && initPromise !== null) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconsole.error(`MCP initialization failed: ${formatTerminalError(err)}`);\n\t\t\t\tinitPromise = null;\n\t\t\t\tif (state) return;\n\n\t\t\t\ttry {\n\t\t\t\t\tawait Promise.all([owner.stop(\"MCP initialization failed\"), shutdownOAuth(oauthRuntime)]);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconsole.error(`MCP: failed to clean rejected initialization: ${formatTerminalError(error)}`);\n\t\t\t\t}\n\t\t\t});\n\t}\n\n\tfunction startLoadTimeInitialization(): void {\n\t\tconst hasStartupServer = Object.values(earlyConfig.mcpServers).some((definition) => {\n\t\t\tif (definition.disabled === true) return false;\n\t\t\treturn definition.lifecycle === \"eager\" || definition.lifecycle === \"keep-alive\";\n\t\t});\n\t\tif (!hasStartupServer) return;\n\t\tsetImmediate(() => {\n\t\t\tif (lifecycleGeneration !== 0 || state || initPromise) return;\n\t\t\tconst generation = ++lifecycleGeneration;\n\t\t\tconst owner = createMcpRuntimeOwner();\n\t\t\tconst oauthRuntime = createOAuthRuntime(owner.signal);\n\t\t\tcurrentOwner = owner;\n\t\t\tcurrentOAuthRuntime = oauthRuntime;\n\t\t\tstartInitialization(\n\t\t\t\t{\n\t\t\t\t\tmode: \"print\",\n\t\t\t\t\thasUI: false,\n\t\t\t\t\tcwd: process.cwd(),\n\t\t\t\t\tmodel: undefined,\n\t\t\t\t\tmodelRegistry: undefined,\n\t\t\t\t\tsignal: undefined,\n\t\t\t\t\tisProjectTrusted: () => false,\n\t\t\t\t} as unknown as ExtensionContext,\n\t\t\t\towner,\n\t\t\t\toauthRuntime,\n\t\t\t\tgeneration,\n\t\t\t\t\"stale_load_time_initialization\",\n\t\t\t);\n\t\t});\n\t}\n\n\tnexus.on(\"session_start\", async (_event, ctx) => {\n\t\tcurrentModel = ctx.model;\n\t\tdirectToolsFrozen = false;\n\t\tconst generation = ++lifecycleGeneration;\n\t\tconst previousState = state;\n\t\tconst previousOwner = currentOwner;\n\t\tconst previousOAuthRuntime = currentOAuthRuntime;\n\t\tconst owner = createMcpRuntimeOwner();\n\t\tconst oauthRuntime = createOAuthRuntime(owner.signal);\n\t\tcurrentOwner = owner;\n\t\tcurrentOAuthRuntime = oauthRuntime;\n\t\tstate = null;\n\t\tinitPromise = null;\n\n\t\t// Abort synchronously before awaiting cleanup so old callbacks and startup\n\t\t// work cannot resume into a stale ExtensionContext.\n\t\tconst stopPrevious = previousOwner?.stop(\"MCP extension session restarted\") ?? Promise.resolve();\n\t\ttry {\n\t\t\tawait Promise.all([\n\t\t\t\tstopPrevious,\n\t\t\t\tshutdownState(previousState, \"session_restart\"),\n\t\t\t\tpreviousOAuthRuntime ? shutdownOAuth(previousOAuthRuntime) : Promise.resolve(),\n\t\t\t]);\n\t\t} catch (error) {\n\t\t\tconsole.error(`MCP: failed to shut down previous session state: ${formatTerminalError(error)}`);\n\t\t}\n\n\t\tif (generation !== lifecycleGeneration || !owner.isActive()) return;\n\n\t\tconst initialization = startInitialization(ctx, owner, oauthRuntime, generation, \"stale_session_start\");\n\t\tif (envRaw !== undefined && envRaw !== \"__none__\") {\n\t\t\tconst missingEnvDirectTools = getMissingConfiguredDirectToolServers(\n\t\t\t\tearlyConfig,\n\t\t\t\tloadMetadataCache(),\n\t\t\t\tenvDirectToolOverride,\n\t\t\t);\n\t\t\tif (missingEnvDirectTools.length > 0) {\n\t\t\t\tawait initialization;\n\t\t\t}\n\t\t}\n\t});\n\n\tnexus.on(\"model_select\", (event) => {\n\t\tcurrentModel = event.model;\n\t});\n\n\tnexus.on(\"input\", async () => {\n\t\tconst inputOwner = currentOwner;\n\t\tif (!inputOwner?.isActive()) return;\n\n\t\tif (!state && initPromise) {\n\t\t\ttry {\n\t\t\t\tawait awaitWithTimeout(initPromise, INIT_WAIT_TIMEOUT_MS);\n\t\t\t} catch {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tconst inputState = state;\n\t\tif (!inputState || !inputOwner.isActive()) return;\n\t\ttry {\n\t\t\tawait inputState.lifecycle.ensureConverged(inputOwner.signal);\n\t\t} catch (error) {\n\t\t\tif (!isAbortError(error, inputOwner.signal)) {\n\t\t\t\tlogger.debug(`MCP: keep-alive convergence failed before input: ${formatTerminalError(error)}`);\n\t\t\t}\n\t\t}\n\t});\n\n\tnexus.on(\"session_shutdown\", async () => {\n\t\t++lifecycleGeneration;\n\t\tconst currentState = state;\n\t\tconst owner = currentOwner;\n\t\tconst oauthRuntime = currentOAuthRuntime;\n\t\tcurrentOwner = null;\n\t\tcurrentOAuthRuntime = null;\n\t\tcurrentModel = undefined;\n\t\tstate = null;\n\t\tinitPromise = null;\n\n\t\t// Abort before awaiting cleanup so delayed initialization cannot touch stale\n\t\t// Nexus context after session shutdown.\n\t\tconst stopOwner = owner?.stop(\"MCP extension session shutdown\") ?? Promise.resolve();\n\t\ttry {\n\t\t\tawait Promise.all([\n\t\t\t\tstopOwner,\n\t\t\t\tshutdownState(currentState, \"session_shutdown\"),\n\t\t\t\toauthRuntime ? shutdownOAuth(oauthRuntime) : Promise.resolve(),\n\t\t\t]);\n\t\t} catch (error) {\n\t\t\tconsole.error(`MCP: session shutdown cleanup failed: ${formatTerminalError(error)}`);\n\t\t}\n\t});\n\n\t// Re-flag returned MCP tool failures so nexus registers them as errors (see toolErrorOverride).\n\tnexus.on(\"tool_result\", (event) => toolErrorOverride(event.details));\n\n\tconst registerMcpCommand = (commandName: string) =>\n\t\tnexus.registerCommand(commandName, {\n\t\t\tdescription: \"Configure and manage MCP servers\",\n\t\t\tgetArgumentCompletions: (prefix: string) => {\n\t\t\t\tconst normalized = prefix.trimStart();\n\t\t\t\tconst argumentMatch = normalized.match(/^(\\S+)\\s+(.*)$/);\n\t\t\t\tif (!argumentMatch) {\n\t\t\t\t\tconst subcommands = [\n\t\t\t\t\t\t{ value: \"reconnect\", label: \"reconnect — Reconnect servers\" },\n\t\t\t\t\t\t{ value: \"tools\", label: \"tools — List all tools\" },\n\t\t\t\t\t\t{ value: \"prompts\", label: \"prompts — List all MCP prompts\" },\n\t\t\t\t\t\t{ value: \"setup\", label: \"setup — Configure MCP servers\" },\n\t\t\t\t\t\t{ value: \"add\", label: \"add — Add a custom server\" },\n\t\t\t\t\t\t{ value: \"logout\", label: \"logout — Clear server credentials\" },\n\t\t\t\t\t\t{ value: \"token\", label: \"token — Manage stored bearer tokens\" },\n\t\t\t\t\t\t{ value: \"disable\", label: \"disable — Disable a server\" },\n\t\t\t\t\t\t{ value: \"enable\", label: \"enable — Enable a server\" },\n\t\t\t\t\t\t{ value: \"status\", label: \"status — Live connections, reconnect, per-tool toggles\" },\n\t\t\t\t\t].filter(({ value }) => value.startsWith(normalized));\n\t\t\t\t\treturn subcommands.length > 0 ? subcommands : null;\n\t\t\t\t}\n\n\t\t\t\tconst [, subcommand, argumentPrefix] = argumentMatch;\n\t\t\t\tif (\n\t\t\t\t\t(subcommand !== \"reconnect\" &&\n\t\t\t\t\t\tsubcommand !== \"logout\" &&\n\t\t\t\t\t\tsubcommand !== \"disable\" &&\n\t\t\t\t\t\tsubcommand !== \"enable\" &&\n\t\t\t\t\t\tsubcommand !== \"token\") ||\n\t\t\t\t\targumentPrefix === undefined ||\n\t\t\t\t\t!state\n\t\t\t\t)\n\t\t\t\t\treturn null;\n\n\t\t\t\tif (subcommand === \"token\") {\n\t\t\t\t\tconst tokenMatch = argumentPrefix.trimStart().match(/^(set|remove|status)\\s+(.*)$/);\n\t\t\t\t\tif (!tokenMatch) {\n\t\t\t\t\t\tconst actions = [\"set\", \"remove\", \"status\"]\n\t\t\t\t\t\t\t.filter((action) => action.startsWith(argumentPrefix.trimStart()))\n\t\t\t\t\t\t\t.map((action) => ({ value: `token ${action} `, label: `${action} — Bearer token ${action}` }));\n\t\t\t\t\t\treturn actions.length > 0 ? actions : null;\n\t\t\t\t\t}\n\t\t\t\t\tconst action = tokenMatch[1] ?? \"\";\n\t\t\t\t\tconst serverPrefix = tokenMatch[2] ?? \"\";\n\t\t\t\t\tconst servers = Object.keys(state.config.mcpServers)\n\t\t\t\t\t\t.filter((serverName) => serverName.startsWith(serverPrefix.trimStart()))\n\t\t\t\t\t\t.map((serverName) => ({ value: `token ${action} ${serverName}`, label: serverName }));\n\t\t\t\t\treturn servers.length > 0 ? servers : null;\n\t\t\t\t}\n\n\t\t\t\tconst servers = Object.keys(state.config.mcpServers)\n\t\t\t\t\t.filter((serverName) => serverName.startsWith(argumentPrefix.trimStart()))\n\t\t\t\t\t.map((serverName) => ({ value: `${subcommand} ${serverName}`, label: serverName }));\n\t\t\t\treturn servers.length > 0 ? servers : null;\n\t\t\t},\n\t\t\thandler: async (args, ctx) => {\n\t\t\t\tconst commandOwner = currentOwner;\n\t\t\t\tconst commandReload = typeof ctx.reload === \"function\" ? ctx.reload.bind(ctx) : async () => {};\n\t\t\t\tconst commandHasUI = ctx.hasUI;\n\t\t\t\tconst commandCtx = {\n\t\t\t\t\thasUI: commandHasUI,\n\t\t\t\t\tui: commandHasUI ? (commandOwner ? createOwnedUi(ctx.ui, commandOwner) : ctx.ui) : undefined,\n\t\t\t\t\tcwd: ctx.cwd,\n\t\t\t\t\tmode: ctx.mode,\n\t\t\t\t\tsignal: commandOwner?.signal ?? ctx.signal,\n\t\t\t\t\tisProjectTrusted: () => ctx.isProjectTrusted(),\n\t\t\t\t} as unknown as ExtensionContext;\n\t\t\t\tif (!state && initPromise) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst initialized = await initPromise;\n\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\tstate = initialized;\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\tif (commandCtx.hasUI) commandCtx.ui?.notify(`MCP initialization failed: ${message}`, \"error\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!state) {\n\t\t\t\t\tif (commandCtx.hasUI) commandCtx.ui?.notify(\"MCP not initialized\", \"error\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst parts = args?.trim()?.split(/\\s+/) ?? [];\n\t\t\t\tconst subcommand = parts[0] ?? \"\";\n\t\t\t\tconst targetServer = parts[1];\n\t\t\t\tconst rest = parts.slice(1).join(\" \");\n\n\t\t\t\tswitch (subcommand) {\n\t\t\t\t\tcase \"reconnect\":\n\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\tawait reconnectServers(state, commandCtx, targetServer);\n\t\t\t\t\t\tif (directToolsFrozen) syncToolSurface(commandCtx);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"tools\":\n\t\t\t\t\t\tawait showTools(state, commandCtx);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"prompts\":\n\t\t\t\t\t\tawait showPrompts(state, commandCtx);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"setup\": {\n\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\tif (!ctx.isProjectTrusted()) {\n\t\t\t\t\t\t\tcommandCtx.ui?.notify(\"Trust this project before opening MCP setup.\", \"warning\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (programmaticConfig) {\n\t\t\t\t\t\t\tcommandCtx.ui?.notify(\n\t\t\t\t\t\t\t\t\"MCP setup is unavailable when config is supplied by createMcpAdapter().\",\n\t\t\t\t\t\t\t\t\"info\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst result = await openMcpSetup(state, nexus, commandCtx, earlyConfigPath, \"setup\");\n\t\t\t\t\t\tif (result?.configChanged) {\n\t\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\t\tawait commandReload();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"add\": {\n\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\tif (!ctx.isProjectTrusted()) {\n\t\t\t\t\t\t\tcommandCtx.ui?.notify(\"Trust this project before running /mcp add.\", \"warning\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (programmaticConfig) {\n\t\t\t\t\t\t\tcommandCtx.ui?.notify(\n\t\t\t\t\t\t\t\t\"/mcp add is unavailable when config is supplied by createMcpAdapter().\",\n\t\t\t\t\t\t\t\t\"info\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst addArgv = parts.slice(1);\n\t\t\t\t\t\tif (addArgv.length === 0) {\n\t\t\t\t\t\t\tcommandCtx.ui?.notify(ADD_SERVER_USAGE, \"info\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst parsed = parseAddServerArgs(addArgv);\n\t\t\t\t\t\tif (!parsed.ok) {\n\t\t\t\t\t\t\tcommandCtx.ui?.notify(`${parsed.error}\\n\\n${ADD_SERVER_USAGE}`, \"error\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst { path } = addCustomServer(commandCtx.cwd, parsed.name, parsed.entry);\n\t\t\t\t\t\tcommandCtx.ui?.notify(`Added MCP server \"${parsed.name}\" to ${path} — run /reload to apply`, \"info\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"logout\": {\n\t\t\t\t\t\tconst serverName = rest;\n\t\t\t\t\t\tif (!serverName) {\n\t\t\t\t\t\t\tif (commandCtx.hasUI) commandCtx.ui?.notify(\"Usage: /mcp logout <server>\", \"error\");\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\tawait logoutServer(serverName, state, commandCtx);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"token\": {\n\t\t\t\t\t\tconst action = parts[1];\n\t\t\t\t\t\tconst serverName = parts.slice(2).join(\" \");\n\t\t\t\t\t\tif (action !== \"set\" && action !== \"remove\" && action !== \"status\") {\n\t\t\t\t\t\t\tif (commandCtx.hasUI)\n\t\t\t\t\t\t\t\tcommandCtx.ui?.notify(\"Usage: /mcp token set|remove|status <server>\", \"error\");\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!serverName) {\n\t\t\t\t\t\t\tif (commandCtx.hasUI)\n\t\t\t\t\t\t\t\tcommandCtx.ui?.notify(\"Usage: /mcp token set|remove|status <server>\", \"error\");\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\tawait manageBearerToken(action, serverName, state, commandCtx);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"disable\":\n\t\t\t\t\tcase \"enable\": {\n\t\t\t\t\t\tconst serverName = rest;\n\t\t\t\t\t\tif (!ctx.isProjectTrusted()) {\n\t\t\t\t\t\t\tcommandCtx.ui?.notify(`Trust this project before running /mcp ${subcommand}.`, \"warning\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (programmaticConfig) {\n\t\t\t\t\t\t\tcommandCtx.ui?.notify(\n\t\t\t\t\t\t\t\t`/mcp ${subcommand} is unavailable when config is supplied by createMcpAdapter().`,\n\t\t\t\t\t\t\t\t\"info\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!serverName) {\n\t\t\t\t\t\t\tcommandCtx.ui?.notify(`Usage: /mcp ${subcommand} <server>`, \"error\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!state.config.mcpServers[serverName]) {\n\t\t\t\t\t\t\tcommandCtx.ui?.notify(`Server \"${serverName}\" not found in effective config`, \"error\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\tconst result = writeProjectServerDisabledOverride(\n\t\t\t\t\t\t\tearlyConfigPath,\n\t\t\t\t\t\t\tcommandCtx.cwd,\n\t\t\t\t\t\t\tserverName,\n\t\t\t\t\t\t\tsubcommand === \"disable\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (result.changed) {\n\t\t\t\t\t\t\tcommandCtx.ui?.notify(\n\t\t\t\t\t\t\t\t`${subcommand === \"disable\" ? \"Disabled\" : \"Enabled\"} server \"${serverName}\" in ${result.path} — run /reload to apply`,\n\t\t\t\t\t\t\t\t\"info\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcommandCtx.ui?.notify(\n\t\t\t\t\t\t\t\t`Server \"${serverName}\" is already ${subcommand === \"disable\" ? \"disabled\" : \"enabled\"}`,\n\t\t\t\t\t\t\t\t\"info\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"status\": {\n\t\t\t\t\t\t// The live connection/reconnect/per-tool-toggle view. Kept reachable by\n\t\t\t\t\t\t// explicit name; bare /mcp now always opens the setup+manage panel below.\n\t\t\t\t\t\tif (commandCtx.hasUI) {\n\t\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\t\tif (programmaticConfig || !ctx.isProjectTrusted()) {\n\t\t\t\t\t\t\t\tif (programmaticConfig) {\n\t\t\t\t\t\t\t\t\tcommandCtx.ui?.notify(\n\t\t\t\t\t\t\t\t\t\t\"MCP status is shown from the in-memory SDK config; configuration discovery is unavailable.\",\n\t\t\t\t\t\t\t\t\t\t\"info\",\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tawait showStatus(state, commandCtx);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst result = await openMcpPanel(state, nexus, commandCtx, earlyConfigPath, (changes) => {\n\t\t\t\t\t\t\t\tapplyDirectToolConfigChanges(changes);\n\t\t\t\t\t\t\t\tsyncToolSurface(commandCtx);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (result?.configChanged) {\n\t\t\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\t\t\tawait commandReload();\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tawait showStatus(state, commandCtx);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tif (commandCtx.hasUI) {\n\t\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\t\tif (programmaticConfig || !ctx.isProjectTrusted()) {\n\t\t\t\t\t\t\t\tif (programmaticConfig) {\n\t\t\t\t\t\t\t\t\tcommandCtx.ui?.notify(\n\t\t\t\t\t\t\t\t\t\t\"MCP status is shown from the in-memory SDK config; configuration discovery is unavailable.\",\n\t\t\t\t\t\t\t\t\t\t\"info\",\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tawait showStatus(state, commandCtx);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst result = await openMcpSetup(state, nexus, commandCtx, earlyConfigPath, \"setup\");\n\t\t\t\t\t\t\tif (result?.configChanged) {\n\t\t\t\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\t\t\t\tawait commandReload();\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tawait showStatus(state, commandCtx);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\tregisterMcpCommand(\"mcp\");\n\n\tnexus.registerCommand(\"mcp-auth\", {\n\t\tdescription: \"Authenticate with an MCP server (OAuth)\",\n\t\thandler: async (args, ctx) => {\n\t\t\tconst commandOwner = currentOwner;\n\t\t\tconst commandHasUI = ctx.hasUI;\n\t\t\tconst commandCtx = {\n\t\t\t\thasUI: commandHasUI,\n\t\t\t\tui: commandHasUI ? (commandOwner ? createOwnedUi(ctx.ui, commandOwner) : ctx.ui) : undefined,\n\t\t\t\tcwd: ctx.cwd,\n\t\t\t\tmode: ctx.mode,\n\t\t\t\tsignal: commandOwner?.signal ?? ctx.signal,\n\t\t\t\tisProjectTrusted: () => ctx.isProjectTrusted(),\n\t\t\t} as unknown as ExtensionContext;\n\t\t\tconst serverName = args?.trim();\n\t\t\tif (!serverName && !commandCtx.hasUI) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!state && initPromise) {\n\t\t\t\ttry {\n\t\t\t\t\tconst initialized = await initPromise;\n\t\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\t\tstate = initialized;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\tif (commandCtx.hasUI) commandCtx.ui?.notify(`MCP initialization failed: ${message}`, \"error\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!state) {\n\t\t\t\tif (commandCtx.hasUI) commandCtx.ui?.notify(\"MCP not initialized\", \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!serverName) {\n\t\t\t\tif (!ctx.isProjectTrusted()) {\n\t\t\t\t\tcommandCtx.ui?.notify(\n\t\t\t\t\t\t\"Trust this project or specify a global MCP server with /mcp-auth <server>.\",\n\t\t\t\t\t\t\"warning\",\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (programmaticConfig) {\n\t\t\t\t\tcommandCtx.ui?.notify(\n\t\t\t\t\t\t\"Use /mcp-auth <server> to authenticate a server from the in-memory SDK config.\",\n\t\t\t\t\t\t\"info\",\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait openMcpAuthPanel(state, nexus, commandCtx, earlyConfigPath);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst result = await authenticateServer(\n\t\t\t\tserverName,\n\t\t\t\tstate.config,\n\t\t\t\tcommandCtx,\n\t\t\t\tcommandCtx.signal,\n\t\t\t\tstate.oauthRuntime,\n\t\t\t\tnexus,\n\t\t\t);\n\t\t\tif (result.ok) {\n\t\t\t\tcommandOwner?.throwIfInactive();\n\t\t\t\tawait reconnectServer(state, commandCtx, serverName);\n\t\t\t}\n\t\t},\n\t});\n\n\tif (earlyConfig.settings?.scriptMode !== false) {\n\t\t(nexus.registerTool as (tool: unknown) => unknown)({\n\t\t\tname: \"mcpScript\",\n\t\t\tlabel: \"MCP Script\",\n\t\t\tdescription:\n\t\t\t\t\"Run trusted JavaScript that makes multiple MCP tool calls in one request — loop, filter, chain, or fan out between calls. For a single MCP call, search, describe, status check, or auth action, use the mcp tool instead. Discover with await tools.search({ query }) — resolves to { items: [{ path, name, server, description? }], total, hasMore, nextOffset }, not an { ok, data } envelope. Inspect with await tools.describe({ path }) — resolves to the tool descriptor with inputTypeScript, or { path, error: { code, message, suggestions } }. Then call tools.call(path, args) — resolves to { ok: true, data } or { ok: false, error: { code, message } } — or use direct flat calls when the name is already known; use emit(value) for user-visible output. Load the mcp-scripting skill for the full workflow guide.\",\n\t\t\tpromptSnippet: \"Batch multiple MCP tool calls in one JavaScript request (loop, filter, chain)\",\n\t\t\tparameters: Type.Object({\n\t\t\t\tcode: Type.String({\n\t\t\t\t\tdescription: \"Trusted JavaScript MCP script. Use tools.<prefixedToolName>(args) and emit(value).\",\n\t\t\t\t}),\n\t\t\t\ttimeoutMs: optionalNumber({\n\t\t\t\t\tminimum: 1,\n\t\t\t\t\tdescription: \"Execution timeout in milliseconds (default: 30000)\",\n\t\t\t\t}),\n\t\t\t}),\n\t\t\trenderResult: renderMcpToolResult,\n\t\t\tasync execute(\n\t\t\t\t_toolCallId: string,\n\t\t\t\tparams: { code: string; timeoutMs?: number },\n\t\t\t\tsignal: AbortSignal | undefined,\n\t\t\t) {\n\t\t\t\tconst executeOwner = currentOwner;\n\t\t\t\tif (!state && initPromise) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst initialized = await awaitWithTimeout(initPromise, INIT_WAIT_TIMEOUT_MS);\n\t\t\t\t\t\tif (initialized === INIT_WAIT_TIMED_OUT) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\t\t\t\ttext: \"MCP initialization is still in progress. Try again shortly.\",\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\tdetails: { mode: \"script\", error: \"init_timeout\", timeoutMs: INIT_WAIT_TIMEOUT_MS },\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\texecuteOwner?.throwIfInactive();\n\t\t\t\t\t\tstate = initialized;\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (executeOwner && isAbortError(error, executeOwner.signal)) throw error;\n\t\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: `MCP initialization failed: ${message}` }],\n\t\t\t\t\t\t\tdetails: { mode: \"script\", error: \"init_failed\", message },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!state) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: \"MCP not initialized\" }],\n\t\t\t\t\t\tdetails: { mode: \"script\", error: \"not_initialized\" },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\texecuteOwner?.throwIfInactive();\n\t\t\t\treturn runMcpScript(state, params.code, params.timeoutMs, getNexusTools, signal);\n\t\t\t},\n\t\t});\n\t}\n\n\tfunction registerProxyTool(description: string): void {\n\t\t(nexus.registerTool as (tool: unknown) => unknown)({\n\t\t\tname: \"mcp\",\n\t\t\tlabel: \"MCP\",\n\t\t\tdescription,\n\t\t\tpromptSnippet: \"MCP gateway — status, search, describe, auth, and single MCP tool calls\",\n\t\t\trenderShell: toolRenderShell,\n\t\t\trenderCall: createMcpProxyToolCallRenderer(toolRenderOptions),\n\t\t\tparameters: Type.Object({\n\t\t\t\ttool: Type.Optional(Type.String({ description: \"Tool name to call (e.g., 'xcodebuild_list_sims')\" })),\n\t\t\t\targs: Type.Optional(\n\t\t\t\t\tType.Union(\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\tType.String({ description: 'Arguments as a JSON string (e.g., \\'{\"key\": \"value\"}\\')' }),\n\t\t\t\t\t\t\tType.Object(\n\t\t\t\t\t\t\t\t{},\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tadditionalProperties: true,\n\t\t\t\t\t\t\t\t\tdescription: 'Arguments as a JSON object (e.g., { \"key\": \"value\" })',\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t],\n\t\t\t\t\t\t{ description: \"Tool arguments as a JSON object, or as a JSON string encoding one\" },\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tconnect: Type.Optional(\n\t\t\t\t\tType.String({ description: \"Server name to connect (lazy connect + metadata refresh)\" }),\n\t\t\t\t),\n\t\t\t\tdescribe: Type.Optional(Type.String({ description: \"Tool name to describe (shows parameters)\" })),\n\t\t\t\tinstructions: Type.Optional(\n\t\t\t\t\tType.String({ description: \"Server name to show that server's usage instructions\" }),\n\t\t\t\t),\n\t\t\t\tsearch: Type.Optional(Type.String({ description: \"Search tools by name/description\" })),\n\t\t\t\tregex: Type.Optional(Type.Boolean({ description: \"Treat search as regex (default: substring match)\" })),\n\t\t\t\tincludeSchemas: Type.Optional(\n\t\t\t\t\tType.Boolean({ description: \"Include parameter schemas in search results (default: true)\" }),\n\t\t\t\t),\n\t\t\t\tlimit: optionalNumber({ minimum: 1, description: \"Maximum search results to return (default: 12)\" }),\n\t\t\t\toffset: optionalNumber({ minimum: 0, description: \"Search result offset (default: 0)\" }),\n\t\t\t\tserver: Type.Optional(\n\t\t\t\t\tType.String({ description: \"Filter to specific server (also disambiguates tool calls)\" }),\n\t\t\t\t),\n\t\t\t\taction: Type.Optional(\n\t\t\t\t\tType.String({ description: \"Action: 'ui-messages', 'auth-start', or 'auth-complete'\" }),\n\t\t\t\t),\n\t\t\t}),\n\t\t\trenderResult: renderMcpToolResult,\n\t\t\tasync execute(\n\t\t\t\t_toolCallId: string,\n\t\t\t\tparams: {\n\t\t\t\t\ttool?: string;\n\t\t\t\t\targs?: string | Record<string, unknown>;\n\t\t\t\t\tconnect?: string;\n\t\t\t\t\tdescribe?: string;\n\t\t\t\t\tinstructions?: string;\n\t\t\t\t\tsearch?: string;\n\t\t\t\t\tregex?: boolean;\n\t\t\t\t\tincludeSchemas?: boolean;\n\t\t\t\t\tlimit?: number;\n\t\t\t\t\toffset?: number;\n\t\t\t\t\tserver?: string;\n\t\t\t\t\taction?: string;\n\t\t\t\t},\n\t\t\t\tsignal: AbortSignal | undefined,\n\t\t\t\t_onUpdate: AgentToolUpdateCallback<Record<string, unknown>> | undefined,\n\t\t\t\t_ctx: ExtensionContext,\n\t\t\t) {\n\t\t\t\tconst executeOwner = currentOwner;\n\t\t\t\tconst parseArgs = (\n\t\t\t\t\tvalue: string | Record<string, unknown> | undefined,\n\t\t\t\t): Record<string, unknown> | undefined => {\n\t\t\t\t\tif (value === undefined || value === \"\") return undefined;\n\t\t\t\t\tlet args: unknown;\n\t\t\t\t\tif (typeof value === \"string\") {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\targs = JSON.parse(value);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif (error instanceof SyntaxError) {\n\t\t\t\t\t\t\t\tthrow new Error(`Invalid args JSON: ${error.message}`, { cause: error });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\targs = value;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (typeof args !== \"object\" || args === null || Array.isArray(args)) {\n\t\t\t\t\t\tconst gotType = Array.isArray(args) ? \"array\" : args === null ? \"null\" : typeof args;\n\t\t\t\t\t\tthrow new Error(`Invalid args: expected a JSON object, got ${gotType}`);\n\t\t\t\t\t}\n\t\t\t\t\treturn args as Record<string, unknown>;\n\t\t\t\t};\n\t\t\t\tconst validateNestedGatewayParams = (value: Record<string, unknown>): typeof params => {\n\t\t\t\t\tfor (const key of [\n\t\t\t\t\t\t\"tool\",\n\t\t\t\t\t\t\"connect\",\n\t\t\t\t\t\t\"describe\",\n\t\t\t\t\t\t\"instructions\",\n\t\t\t\t\t\t\"search\",\n\t\t\t\t\t\t\"server\",\n\t\t\t\t\t\t\"action\",\n\t\t\t\t\t] as const) {\n\t\t\t\t\t\tif (value[key] !== undefined && typeof value[key] !== \"string\") {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`Invalid nested gateway param \\`${key}\\`: expected string, got ${Array.isArray(value[key]) ? \"array\" : typeof value[key]}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor (const key of [\"regex\", \"includeSchemas\"] as const) {\n\t\t\t\t\t\tif (value[key] !== undefined && typeof value[key] !== \"boolean\") {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`Invalid nested gateway param \\`${key}\\`: expected boolean, got ${Array.isArray(value[key]) ? \"array\" : typeof value[key]}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor (const key of [\"limit\", \"offset\"] as const) {\n\t\t\t\t\t\tif (value[key] !== undefined && typeof value[key] !== \"number\") {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`Invalid nested gateway param \\`${key}\\`: expected number, got ${Array.isArray(value[key]) ? \"array\" : typeof value[key]}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst args = value.args;\n\t\t\t\t\tif (\n\t\t\t\t\t\targs !== undefined &&\n\t\t\t\t\t\ttypeof args !== \"string\" &&\n\t\t\t\t\t\t(typeof args !== \"object\" || args === null || Array.isArray(args))\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Invalid nested gateway param \\`args\\`: expected JSON object or JSON string, got ${Array.isArray(args) ? \"array\" : args === null ? \"null\" : typeof args}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn value as typeof params;\n\t\t\t\t};\n\t\t\t\tlet parsedArgs = parseArgs(params.args);\n\t\t\t\tlet dispatchParams = params;\n\t\t\t\tconst hasGatewayMode = (value: typeof params): boolean =>\n\t\t\t\t\tvalue.tool !== undefined ||\n\t\t\t\t\tvalue.connect !== undefined ||\n\t\t\t\t\tvalue.describe !== undefined ||\n\t\t\t\t\tvalue.instructions !== undefined ||\n\t\t\t\t\tvalue.search !== undefined ||\n\t\t\t\t\tvalue.server !== undefined ||\n\t\t\t\t\tvalue.action !== undefined;\n\t\t\t\tif (!hasGatewayMode(params) && parsedArgs) {\n\t\t\t\t\tconst nestedParams = validateNestedGatewayParams(parsedArgs);\n\t\t\t\t\tif (hasGatewayMode(nestedParams)) {\n\t\t\t\t\t\tdispatchParams = nestedParams;\n\t\t\t\t\t\tparsedArgs = parseArgs(nestedParams.args);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'Gateway params were nested inside `args`; pass them top-level (for example, mcp({ search: \"...\" }) or mcp({ tool: \"...\", args: {} })).',\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else if (!hasGatewayMode(params) && params.args !== undefined) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'Gateway params were nested inside `args`; pass them top-level (for example, mcp({ search: \"...\" }) or mcp({ tool: \"...\", args: {} })).',\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (!state && initPromise) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst initialized = await awaitWithTimeout(initPromise, INIT_WAIT_TIMEOUT_MS);\n\t\t\t\t\t\tif (initialized === INIT_WAIT_TIMED_OUT) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\t\t\t\ttext: \"MCP initialization is still in progress. Try again shortly.\",\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\tdetails: { error: \"init_timeout\", timeoutMs: INIT_WAIT_TIMEOUT_MS },\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\texecuteOwner?.throwIfInactive();\n\t\t\t\t\t\tstate = initialized;\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (executeOwner && isAbortError(error, executeOwner.signal)) throw error;\n\t\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: `MCP initialization failed: ${message}` }],\n\t\t\t\t\t\t\tdetails: { error: \"init_failed\", message },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!state) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: \"MCP not initialized\" }],\n\t\t\t\t\t\tdetails: { error: \"not_initialized\" },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\texecuteOwner?.throwIfInactive();\n\n\t\t\t\tif (dispatchParams.action === \"ui-messages\") {\n\t\t\t\t\treturn executeUiMessages(state);\n\t\t\t\t}\n\t\t\t\tif (dispatchParams.action === \"auth-start\") {\n\t\t\t\t\tif (!dispatchParams.server) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\t\t\ttext: 'auth-start requires `server`. Example: mcp({ action: \"auth-start\", server: \"linear-server\" })',\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tdetails: { mode: \"auth-start\", error: \"missing_server\" },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\treturn signal\n\t\t\t\t\t\t? executeAuthStart(state, dispatchParams.server, signal)\n\t\t\t\t\t\t: executeAuthStart(state, dispatchParams.server);\n\t\t\t\t}\n\t\t\t\tif (dispatchParams.action === \"auth-complete\") {\n\t\t\t\t\tif (!dispatchParams.server) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: \"auth-complete requires `server`.\" }],\n\t\t\t\t\t\t\tdetails: { mode: \"auth-complete\", error: \"missing_server\" },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tconst input = parsedArgs?.redirectUrl ?? parsedArgs?.code ?? parsedArgs?.input;\n\t\t\t\t\tif (typeof input !== \"string\" || input.trim().length === 0) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\t\t\ttext: \"auth-complete requires args with `redirectUrl`, `code`, or `input`.\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tdetails: { mode: \"auth-complete\", error: \"missing_input\" },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\treturn signal\n\t\t\t\t\t\t? executeAuthComplete(state, dispatchParams.server, input, signal)\n\t\t\t\t\t\t: executeAuthComplete(state, dispatchParams.server, input);\n\t\t\t\t}\n\t\t\t\tif (dispatchParams.tool) {\n\t\t\t\t\treturn executeCall(state, dispatchParams.tool, parsedArgs, dispatchParams.server, getNexusTools, signal);\n\t\t\t\t}\n\t\t\t\tif (dispatchParams.connect) {\n\t\t\t\t\tconst result = await executeConnect(state, dispatchParams.connect, signal);\n\t\t\t\t\tsyncToolSurface(_ctx as ExtensionContext);\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t\tif (dispatchParams.describe) {\n\t\t\t\t\treturn executeDescribe(state, dispatchParams.describe);\n\t\t\t\t}\n\t\t\t\tif (dispatchParams.instructions) {\n\t\t\t\t\treturn executeInstructions(state, dispatchParams.instructions);\n\t\t\t\t}\n\t\t\t\tif (dispatchParams.search !== undefined) {\n\t\t\t\t\treturn executeSearch(\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\tdispatchParams.search,\n\t\t\t\t\t\tdispatchParams.regex,\n\t\t\t\t\t\tdispatchParams.server,\n\t\t\t\t\t\tdispatchParams.includeSchemas,\n\t\t\t\t\t\tdispatchParams.limit,\n\t\t\t\t\t\tdispatchParams.offset,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (dispatchParams.server) {\n\t\t\t\t\treturn executeList(state, dispatchParams.server);\n\t\t\t\t}\n\t\t\t\treturn executeStatus(state);\n\t\t\t},\n\t\t});\n\t\tproxyToolRegistered = true;\n\t\tproxyToolDescription = description;\n\t}\n\n\tfunction syncProxyTool(config: McpConfig, cache: MetadataCache | null, directSpecs: DirectToolSpec[]): void {\n\t\tconst missingConfiguredDirectToolServers = getMissingConfiguredDirectToolServers(\n\t\t\tconfig,\n\t\t\tcache,\n\t\t\tenvRaw === undefined || envRaw === \"__none__\" ? undefined : envDirectToolOverride,\n\t\t);\n\t\tconst shouldRegisterProxyTool =\n\t\t\tconfig.settings?.disableProxyTool !== true ||\n\t\t\tdirectSpecs.length === 0 ||\n\t\t\tmissingConfiguredDirectToolServers.length > 0;\n\n\t\tif (shouldRegisterProxyTool) {\n\t\t\tconst description = buildProxyDescription(config, cache, directSpecs);\n\t\t\tif (!proxyToolRegistered || proxyToolDescription !== description) {\n\t\t\t\tregisterProxyTool(description);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst activeTools = getActiveToolsIfReady();\n\t\t\tif (activeTools && !activeTools.includes(\"mcp\")) {\n\t\t\t\tnexus.setActiveTools([...activeTools, \"mcp\"]);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (proxyToolRegistered) {\n\t\t\tconst unregistered = deactivateTools([\"mcp\"]);\n\t\t\tif (unregistered.includes(\"mcp\")) {\n\t\t\t\tproxyToolRegistered = false;\n\t\t\t\tproxyToolDescription = null;\n\t\t\t}\n\t\t}\n\t}\n\n\tnexus.on(\"resources_discover\", () => {\n\t\tconst skillsPath = join(import.meta.dirname, \"skills\");\n\t\tif (existsSync(skillsPath)) return { skillPaths: [skillsPath] };\n\t});\n\n\tconst initialDirectTools = syncDirectTools(earlyConfig, earlyCache).specs;\n\tsyncProxyTool(earlyConfig, earlyCache, initialDirectTools);\n\tstartLoadTimeInitialization();\n}\n\nexport function createMcpAdapter(options: McpAdapterOptions = {}) {\n\tconst factoryConfig = options.config !== undefined ? cloneMcpConfig(options.config) : undefined;\n\treturn function mcpAdapter(nexus: ExtensionAPI) {\n\t\tinstallMcpAdapter(nexus, {\n\t\t\t...(options.configPath !== undefined ? { configPath: options.configPath } : {}),\n\t\t\t...(factoryConfig !== undefined ? { config: cloneMcpConfig(factoryConfig) } : {}),\n\t\t});\n\t};\n}\n\n/**\n * Register an MCP server with the adapter installed for this Nexus instance.\n * Registrations are session/runtime scoped and never persisted. Duplicate\n * names fail closed. Registered servers are proxy-tool-only; their tools\n * become visible at the next tool sync. To change a definition, dispose the\n * registration and register again.\n */\nexport function registerMcpServer(options: {\n\tnexus: ExtensionAPI;\n\tname: string;\n\tdefinition: ServerEntry;\n}): McpServerRegistration {\n\tconst { nexus, name, definition } = options;\n\tconst register = runtimeRegistrars.get(nexus);\n\tif (!register) {\n\t\tthrow new Error(\"The native Nexus MCP runtime is not installed for this instance\");\n\t}\n\treturn register(name, definition);\n}\n\nexport default createMcpAdapter();\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { existsSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { Type } from "typebox";
|
|
4
|
-
import { authenticateServer, logoutServer, manageBearerToken, openMcpAuthPanel, openMcpPanel, openMcpSetup, reconnectServer, reconnectServers, showPrompts, showStatus, showTools, } from "./commands.js";
|
|
4
|
+
import { ADD_SERVER_USAGE, addCustomServer, authenticateServer, logoutServer, manageBearerToken, openMcpAuthPanel, openMcpPanel, openMcpSetup, parseAddServerArgs, reconnectServer, reconnectServers, showPrompts, showStatus, showTools, } from "./commands.js";
|
|
5
5
|
import { cloneMcpConfig, loadMcpConfig, writeProjectServerDisabledOverride } from "./config.js";
|
|
6
6
|
import { buildProxyDescription, createDirectToolExecutor, getMissingConfiguredDirectToolServers, resolveDirectTools, } from "./direct-tools.js";
|
|
7
7
|
import { toolErrorOverride } from "./error-signal.js";
|
|
@@ -497,7 +497,7 @@ function installMcpAdapter(nexus, options) {
|
|
|
497
497
|
// Re-flag returned MCP tool failures so nexus registers them as errors (see toolErrorOverride).
|
|
498
498
|
nexus.on("tool_result", (event) => toolErrorOverride(event.details));
|
|
499
499
|
const registerMcpCommand = (commandName) => nexus.registerCommand(commandName, {
|
|
500
|
-
description: "
|
|
500
|
+
description: "Configure and manage MCP servers",
|
|
501
501
|
getArgumentCompletions: (prefix) => {
|
|
502
502
|
const normalized = prefix.trimStart();
|
|
503
503
|
const argumentMatch = normalized.match(/^(\S+)\s+(.*)$/);
|
|
@@ -507,11 +507,12 @@ function installMcpAdapter(nexus, options) {
|
|
|
507
507
|
{ value: "tools", label: "tools — List all tools" },
|
|
508
508
|
{ value: "prompts", label: "prompts — List all MCP prompts" },
|
|
509
509
|
{ value: "setup", label: "setup — Configure MCP servers" },
|
|
510
|
+
{ value: "add", label: "add — Add a custom server" },
|
|
510
511
|
{ value: "logout", label: "logout — Clear server credentials" },
|
|
511
512
|
{ value: "token", label: "token — Manage stored bearer tokens" },
|
|
512
513
|
{ value: "disable", label: "disable — Disable a server" },
|
|
513
514
|
{ value: "enable", label: "enable — Enable a server" },
|
|
514
|
-
{ value: "status", label: "status —
|
|
515
|
+
{ value: "status", label: "status — Live connections, reconnect, per-tool toggles" },
|
|
515
516
|
].filter(({ value }) => value.startsWith(normalized));
|
|
516
517
|
return subcommands.length > 0 ? subcommands : null;
|
|
517
518
|
}
|
|
@@ -609,6 +610,30 @@ function installMcpAdapter(nexus, options) {
|
|
|
609
610
|
}
|
|
610
611
|
break;
|
|
611
612
|
}
|
|
613
|
+
case "add": {
|
|
614
|
+
commandOwner?.throwIfInactive();
|
|
615
|
+
if (!ctx.isProjectTrusted()) {
|
|
616
|
+
commandCtx.ui?.notify("Trust this project before running /mcp add.", "warning");
|
|
617
|
+
break;
|
|
618
|
+
}
|
|
619
|
+
if (programmaticConfig) {
|
|
620
|
+
commandCtx.ui?.notify("/mcp add is unavailable when config is supplied by createMcpAdapter().", "info");
|
|
621
|
+
break;
|
|
622
|
+
}
|
|
623
|
+
const addArgv = parts.slice(1);
|
|
624
|
+
if (addArgv.length === 0) {
|
|
625
|
+
commandCtx.ui?.notify(ADD_SERVER_USAGE, "info");
|
|
626
|
+
break;
|
|
627
|
+
}
|
|
628
|
+
const parsed = parseAddServerArgs(addArgv);
|
|
629
|
+
if (!parsed.ok) {
|
|
630
|
+
commandCtx.ui?.notify(`${parsed.error}\n\n${ADD_SERVER_USAGE}`, "error");
|
|
631
|
+
break;
|
|
632
|
+
}
|
|
633
|
+
const { path } = addCustomServer(commandCtx.cwd, parsed.name, parsed.entry);
|
|
634
|
+
commandCtx.ui?.notify(`Added MCP server "${parsed.name}" to ${path} — run /reload to apply`, "info");
|
|
635
|
+
break;
|
|
636
|
+
}
|
|
612
637
|
case "logout": {
|
|
613
638
|
const serverName = rest;
|
|
614
639
|
if (!serverName) {
|
|
@@ -666,7 +691,9 @@ function installMcpAdapter(nexus, options) {
|
|
|
666
691
|
}
|
|
667
692
|
break;
|
|
668
693
|
}
|
|
669
|
-
|
|
694
|
+
case "status": {
|
|
695
|
+
// The live connection/reconnect/per-tool-toggle view. Kept reachable by
|
|
696
|
+
// explicit name; bare /mcp now always opens the setup+manage panel below.
|
|
670
697
|
if (commandCtx.hasUI) {
|
|
671
698
|
commandOwner?.throwIfInactive();
|
|
672
699
|
if (programmaticConfig || !ctx.isProjectTrusted()) {
|
|
@@ -690,6 +717,28 @@ function installMcpAdapter(nexus, options) {
|
|
|
690
717
|
await showStatus(state, commandCtx);
|
|
691
718
|
}
|
|
692
719
|
break;
|
|
720
|
+
}
|
|
721
|
+
default:
|
|
722
|
+
if (commandCtx.hasUI) {
|
|
723
|
+
commandOwner?.throwIfInactive();
|
|
724
|
+
if (programmaticConfig || !ctx.isProjectTrusted()) {
|
|
725
|
+
if (programmaticConfig) {
|
|
726
|
+
commandCtx.ui?.notify("MCP status is shown from the in-memory SDK config; configuration discovery is unavailable.", "info");
|
|
727
|
+
}
|
|
728
|
+
await showStatus(state, commandCtx);
|
|
729
|
+
break;
|
|
730
|
+
}
|
|
731
|
+
const result = await openMcpSetup(state, nexus, commandCtx, earlyConfigPath, "setup");
|
|
732
|
+
if (result?.configChanged) {
|
|
733
|
+
commandOwner?.throwIfInactive();
|
|
734
|
+
await commandReload();
|
|
735
|
+
return;
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
else {
|
|
739
|
+
await showStatus(state, commandCtx);
|
|
740
|
+
}
|
|
741
|
+
break;
|
|
693
742
|
}
|
|
694
743
|
},
|
|
695
744
|
});
|
|
@@ -741,7 +790,7 @@ function installMcpAdapter(nexus, options) {
|
|
|
741
790
|
await openMcpAuthPanel(state, nexus, commandCtx, earlyConfigPath);
|
|
742
791
|
return;
|
|
743
792
|
}
|
|
744
|
-
const result = await authenticateServer(serverName, state.config, commandCtx, commandCtx.signal, state.oauthRuntime);
|
|
793
|
+
const result = await authenticateServer(serverName, state.config, commandCtx, commandCtx.signal, state.oauthRuntime, nexus);
|
|
745
794
|
if (result.ok) {
|
|
746
795
|
commandOwner?.throwIfInactive();
|
|
747
796
|
await reconnectServer(state, commandCtx, serverName);
|