@jangmanj/mcp 0.0.0-stage → 0.13.0
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/LICENSE +21 -0
- package/README.md +337 -2
- package/adapters/pi/bridge.ts +721 -0
- package/adapters/pi/config.ts +364 -0
- package/adapters/pi/content-offloaded.ts +53 -0
- package/adapters/pi/content.ts +78 -0
- package/adapters/pi/diagnostics.ts +26 -0
- package/adapters/pi/elicitation.ts +133 -0
- package/adapters/pi/index.ts +210 -0
- package/adapters/pi/oauth.ts +219 -0
- package/adapters/pi/pi-api.ts +133 -0
- package/adapters/pi/resources.ts +177 -0
- package/adapters/pi/result-files.ts +32 -0
- package/adapters/pi/tasks.ts +49 -0
- package/dist/auth/client-credentials.d.ts +65 -0
- package/dist/auth/client-credentials.js +388 -0
- package/dist/auth/discovery.d.ts +28 -0
- package/dist/auth/discovery.js +125 -0
- package/dist/auth/index.d.ts +9 -0
- package/dist/auth/index.js +5 -0
- package/dist/auth/node-ports.d.ts +8 -0
- package/dist/auth/node-ports.js +67 -0
- package/dist/auth/protocol.d.ts +12 -0
- package/dist/auth/protocol.js +39 -0
- package/dist/auth/provider.d.ts +114 -0
- package/dist/auth/provider.js +407 -0
- package/dist/auth/safe-fetch.d.ts +14 -0
- package/dist/auth/safe-fetch.js +130 -0
- package/dist/client/events.d.ts +33 -0
- package/dist/client/events.js +84 -0
- package/dist/client/index.d.ts +65 -0
- package/dist/client/index.js +128 -0
- package/dist/core/auth-types.d.ts +36 -0
- package/dist/core/auth-types.js +11 -0
- package/dist/core/bearer-challenge.d.ts +3 -0
- package/dist/core/bearer-challenge.js +63 -0
- package/dist/core/cancel.d.ts +70 -0
- package/dist/core/cancel.js +177 -0
- package/dist/core/extension.d.ts +33 -0
- package/dist/core/extension.js +145 -0
- package/dist/core/index.d.ts +73 -0
- package/dist/core/index.js +129 -0
- package/dist/core/jsonrpc.d.ts +49 -0
- package/dist/core/jsonrpc.js +80 -0
- package/dist/core/lifecycle.d.ts +128 -0
- package/dist/core/lifecycle.js +251 -0
- package/dist/core/outcome.d.ts +98 -0
- package/dist/core/outcome.js +32 -0
- package/dist/core/ports.d.ts +144 -0
- package/dist/core/ports.js +67 -0
- package/dist/core/progress.d.ts +81 -0
- package/dist/core/progress.js +205 -0
- package/dist/core/request.d.ts +108 -0
- package/dist/core/request.js +578 -0
- package/dist/core/schema/index.d.ts +1 -0
- package/dist/core/schema/index.js +1 -0
- package/dist/core/schema/types.d.ts +4154 -0
- package/dist/core/schema/types.js +6 -0
- package/dist/core/telemetry.d.ts +25 -0
- package/dist/core/telemetry.js +37 -0
- package/dist/ext-events/index.d.ts +79 -0
- package/dist/ext-events/index.js +218 -0
- package/dist/ext-events/model.d.ts +10 -0
- package/dist/ext-events/model.js +6 -0
- package/dist/ext-events/push.d.ts +18 -0
- package/dist/ext-events/push.js +101 -0
- package/dist/ext-events/stream.d.ts +6 -0
- package/dist/ext-events/stream.js +60 -0
- package/dist/ext-server-cards/index.d.ts +107 -0
- package/dist/ext-server-cards/index.js +249 -0
- package/dist/ext-skills/cache.d.ts +20 -0
- package/dist/ext-skills/cache.js +101 -0
- package/dist/ext-skills/client.d.ts +82 -0
- package/dist/ext-skills/client.js +292 -0
- package/dist/ext-skills/extension.d.ts +16 -0
- package/dist/ext-skills/extension.js +29 -0
- package/dist/ext-skills/index.d.ts +4 -0
- package/dist/ext-skills/index.js +4 -0
- package/dist/ext-skills/verify.d.ts +57 -0
- package/dist/ext-skills/verify.js +168 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/mrtr-cache/cache.d.ts +51 -0
- package/dist/mrtr-cache/cache.js +295 -0
- package/dist/mrtr-cache/client.d.ts +24 -0
- package/dist/mrtr-cache/client.js +44 -0
- package/dist/mrtr-cache/common.d.ts +10 -0
- package/dist/mrtr-cache/common.js +9 -0
- package/dist/mrtr-cache/elicitation.d.ts +42 -0
- package/dist/mrtr-cache/elicitation.js +221 -0
- package/dist/mrtr-cache/index.d.ts +9 -0
- package/dist/mrtr-cache/index.js +8 -0
- package/dist/mrtr-cache/mrtr.d.ts +37 -0
- package/dist/mrtr-cache/mrtr.js +250 -0
- package/dist/mrtr-cache/refresh.d.ts +8 -0
- package/dist/mrtr-cache/refresh.js +30 -0
- package/dist/mrtr-cache/stream.d.ts +5 -0
- package/dist/mrtr-cache/stream.js +18 -0
- package/dist/mrtr-cache/subscriptions.d.ts +96 -0
- package/dist/mrtr-cache/subscriptions.js +288 -0
- package/dist/mrtr-cache/tasks.d.ts +103 -0
- package/dist/mrtr-cache/tasks.js +444 -0
- package/dist/ops/common.d.ts +18 -0
- package/dist/ops/common.js +39 -0
- package/dist/ops/completion.d.ts +44 -0
- package/dist/ops/completion.js +65 -0
- package/dist/ops/content.d.ts +40 -0
- package/dist/ops/content.js +117 -0
- package/dist/ops/icons.d.ts +29 -0
- package/dist/ops/icons.js +82 -0
- package/dist/ops/index.d.ts +30 -0
- package/dist/ops/index.js +28 -0
- package/dist/ops/pagination.d.ts +32 -0
- package/dist/ops/pagination.js +65 -0
- package/dist/ops/prompts.d.ts +32 -0
- package/dist/ops/prompts.js +68 -0
- package/dist/ops/resources.d.ts +42 -0
- package/dist/ops/resources.js +104 -0
- package/dist/ops/schema.d.ts +39 -0
- package/dist/ops/schema.js +163 -0
- package/dist/ops/tools.d.ts +88 -0
- package/dist/ops/tools.js +169 -0
- package/dist/ops/uri-template.d.ts +3 -0
- package/dist/ops/uri-template.js +101 -0
- package/dist/server/index.d.ts +5 -0
- package/dist/server/index.js +5 -0
- package/dist/server/mrtr.d.ts +38 -0
- package/dist/server/mrtr.js +99 -0
- package/dist/server/protocol.d.ts +21 -0
- package/dist/server/protocol.js +49 -0
- package/dist/server/server.d.ts +105 -0
- package/dist/server/server.js +383 -0
- package/dist/server/skills.d.ts +45 -0
- package/dist/server/skills.js +73 -0
- package/dist/server/uri.d.ts +2 -0
- package/dist/server/uri.js +27 -0
- package/dist/server-events/bus.d.ts +40 -0
- package/dist/server-events/bus.js +84 -0
- package/dist/server-events/events.d.ts +36 -0
- package/dist/server-events/events.js +108 -0
- package/dist/server-events/index.d.ts +6 -0
- package/dist/server-events/index.js +6 -0
- package/dist/server-events/notices.d.ts +24 -0
- package/dist/server-events/notices.js +31 -0
- package/dist/server-events/subscriptions.d.ts +33 -0
- package/dist/server-events/subscriptions.js +77 -0
- package/dist/server-events/tasks.d.ts +43 -0
- package/dist/server-events/tasks.js +101 -0
- package/dist/server-events/types.d.ts +25 -0
- package/dist/server-events/types.js +34 -0
- package/dist/server-transport/auth.d.ts +20 -0
- package/dist/server-transport/auth.js +29 -0
- package/dist/server-transport/channel.d.ts +17 -0
- package/dist/server-transport/channel.js +47 -0
- package/dist/server-transport/http.d.ts +19 -0
- package/dist/server-transport/http.js +209 -0
- package/dist/server-transport/index.d.ts +4 -0
- package/dist/server-transport/index.js +4 -0
- package/dist/server-transport/stdio.d.ts +16 -0
- package/dist/server-transport/stdio.js +83 -0
- package/dist/telemetry-otel/index.d.ts +64 -0
- package/dist/telemetry-otel/index.js +196 -0
- package/dist/testing/index.d.ts +36 -0
- package/dist/testing/index.js +140 -0
- package/dist/transport-http/headers.d.ts +24 -0
- package/dist/transport-http/headers.js +140 -0
- package/dist/transport-http/index.d.ts +3 -0
- package/dist/transport-http/index.js +3 -0
- package/dist/transport-http/sse.d.ts +33 -0
- package/dist/transport-http/sse.js +152 -0
- package/dist/transport-http/transport.d.ts +66 -0
- package/dist/transport-http/transport.js +854 -0
- package/dist/transport-stdio/framing.d.ts +50 -0
- package/dist/transport-stdio/framing.js +154 -0
- package/dist/transport-stdio/index.d.ts +4 -0
- package/dist/transport-stdio/index.js +4 -0
- package/dist/transport-stdio/stderr-ring.d.ts +27 -0
- package/dist/transport-stdio/stderr-ring.js +105 -0
- package/dist/transport-stdio/transport.d.ts +142 -0
- package/dist/transport-stdio/transport.js +743 -0
- package/dist/transport-stdio/write-queue.d.ts +48 -0
- package/dist/transport-stdio/write-queue.js +147 -0
- package/package.json +134 -4
|
@@ -0,0 +1,721 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Connection bridge: owns McpClient instances built from this library and
|
|
3
|
+
* registers their tools with Pi, mirroring the built-in MCP exposure model
|
|
4
|
+
* (codemode default; direct/deferred/hidden; per-tool toolExposure overrides).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
8
|
+
import { McpClient } from "@jangmanj/mcp/core";
|
|
9
|
+
import {
|
|
10
|
+
createOps,
|
|
11
|
+
normalizeContent,
|
|
12
|
+
type Ops,
|
|
13
|
+
type ToolCallResult,
|
|
14
|
+
type ToolEntry,
|
|
15
|
+
} from "@jangmanj/mcp/ops";
|
|
16
|
+
import { HttpTransport } from "@jangmanj/mcp/transport-http";
|
|
17
|
+
import { StdioTransport } from "@jangmanj/mcp/transport-stdio";
|
|
18
|
+
import { createTasksExtension } from "@jangmanj/mcp/mrtr-cache";
|
|
19
|
+
import type { Outcome } from "@jangmanj/mcp/core";
|
|
20
|
+
import type { Exposure, ResolvedServerConfig } from "./config.ts";
|
|
21
|
+
import { convertBlocksOffloaded } from "./content-offloaded.ts";
|
|
22
|
+
import { DiagnosticsLog } from "./diagnostics.ts";
|
|
23
|
+
import { callWithElicitation } from "./elicitation.ts";
|
|
24
|
+
import { consentPort } from "./elicitation.ts";
|
|
25
|
+
import {
|
|
26
|
+
canonicalResource,
|
|
27
|
+
createOAuthProvider,
|
|
28
|
+
FileCredentialStore,
|
|
29
|
+
} from "./oauth.ts";
|
|
30
|
+
import { ResourceTools } from "./resources.ts";
|
|
31
|
+
import { getTask, cancelTask, taskHandleResult } from "./tasks.ts";
|
|
32
|
+
import type { ExtensionAPI, ToolAnnotations, ToolDefinition, ToolResult, Ui } from "./pi-api.ts";
|
|
33
|
+
|
|
34
|
+
export type ServerStatus = "connecting" | "connected" | "error" | "disabled";
|
|
35
|
+
|
|
36
|
+
export interface ServerState {
|
|
37
|
+
readonly name: string;
|
|
38
|
+
config: ResolvedServerConfig;
|
|
39
|
+
status: ServerStatus;
|
|
40
|
+
toolCount: number;
|
|
41
|
+
error?: string | undefined;
|
|
42
|
+
description?: string | undefined;
|
|
43
|
+
/** Full server instructions from server/discover, when offered. */
|
|
44
|
+
instructions?: string | undefined;
|
|
45
|
+
client?: McpClient | undefined;
|
|
46
|
+
ops?: Ops | undefined;
|
|
47
|
+
/** Set when the server rejected unauthenticated requests. */
|
|
48
|
+
authRequired?: boolean | undefined;
|
|
49
|
+
/** Closes the loopback redirect listener of an OAuth provider, if any. */
|
|
50
|
+
closeRedirect?: (() => void) | undefined;
|
|
51
|
+
/** Capabilities from server/discover, when available. */
|
|
52
|
+
capabilities?: Record<string, unknown> | undefined;
|
|
53
|
+
/** Closes the subscriptions/listen stream, if any. */
|
|
54
|
+
listenClose?: (() => void) | undefined;
|
|
55
|
+
/** Registered definitions by Pi tool name (for updates/withdrawal). */
|
|
56
|
+
readonly definitions: Map<string, ToolDefinition>;
|
|
57
|
+
/** Pi tool name -> server tool name. */
|
|
58
|
+
readonly toolNames: Map<string, string>;
|
|
59
|
+
/** Pi tool names registered for this server (persist across reconnects). */
|
|
60
|
+
readonly registeredTools: Set<string>;
|
|
61
|
+
/** Exposures this server's tools were registered with. */
|
|
62
|
+
readonly exposures: Set<Exposure>;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function sanitizeNamePart(s: string): string {
|
|
66
|
+
return s.replace(/[^A-Za-z0-9_]/g, "_");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function shortHash(s: string): string {
|
|
70
|
+
return createHash("sha1").update(s).digest("hex").slice(0, 8);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Map server tool names to Pi tool names: mcp__<server>__<tool>, with a hash
|
|
75
|
+
* suffix for every tool in a collision group (same rule as built-in MCP).
|
|
76
|
+
*/
|
|
77
|
+
export function assignToolNames(server: string, toolNames: readonly string[]): Map<string, string> {
|
|
78
|
+
const prefix = `mcp__${sanitizeNamePart(server)}__`;
|
|
79
|
+
const byBase = new Map<string, string[]>();
|
|
80
|
+
for (const t of toolNames) {
|
|
81
|
+
const base = prefix + sanitizeNamePart(t);
|
|
82
|
+
const group = byBase.get(base);
|
|
83
|
+
if (group) group.push(t);
|
|
84
|
+
else byBase.set(base, [t]);
|
|
85
|
+
}
|
|
86
|
+
const out = new Map<string, string>();
|
|
87
|
+
for (const [base, group] of byBase) {
|
|
88
|
+
if (group.length === 1) {
|
|
89
|
+
out.set(group[0] as string, base);
|
|
90
|
+
} else {
|
|
91
|
+
for (const t of group) out.set(t, `${base}_h${shortHash(t)}`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return out;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Per-tool exposure: exact toolExposure key, then first matching `*` pattern, else the server's. */
|
|
98
|
+
export function toolExposureFor(config: ResolvedServerConfig, toolName: string): Exposure {
|
|
99
|
+
const overrides = config.toolExposure;
|
|
100
|
+
if (overrides) {
|
|
101
|
+
const exact = overrides[toolName];
|
|
102
|
+
if (exact !== undefined) return normalizeOverride(exact);
|
|
103
|
+
for (const [pattern, value] of Object.entries(overrides)) {
|
|
104
|
+
if (!pattern.includes("*")) continue;
|
|
105
|
+
const re = new RegExp(`^${pattern.split("*").map(escapeRe).join(".*")}$`);
|
|
106
|
+
if (re.test(toolName)) return normalizeOverride(value);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return config.exposure;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function normalizeOverride(value: string): Exposure {
|
|
113
|
+
return value === "direct" || value === "deferred" || value === "hidden" ? value : "codemode";
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function escapeRe(s: string): string {
|
|
117
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function annotationsOf(entry: ToolEntry): ToolAnnotations | undefined {
|
|
121
|
+
const v = entry.annotations?.value;
|
|
122
|
+
if (typeof v !== "object" || v === null) return undefined;
|
|
123
|
+
const rec = v as Record<string, unknown>;
|
|
124
|
+
const out: ToolAnnotations = {};
|
|
125
|
+
if (typeof rec.readOnlyHint === "boolean") out.readOnlyHint = rec.readOnlyHint;
|
|
126
|
+
if (typeof rec.destructiveHint === "boolean") out.destructiveHint = rec.destructiveHint;
|
|
127
|
+
if (typeof rec.idempotentHint === "boolean") out.idempotentHint = rec.idempotentHint;
|
|
128
|
+
if (typeof rec.openWorldHint === "boolean") out.openWorldHint = rec.openWorldHint;
|
|
129
|
+
return Object.keys(out).length > 0 ? out : undefined;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function inputSchemaOf(entry: ToolEntry): Record<string, unknown> {
|
|
133
|
+
const schema = entry.tool.inputSchema;
|
|
134
|
+
if (typeof schema === "object" && schema !== null && !Array.isArray(schema)) {
|
|
135
|
+
return schema as Record<string, unknown>;
|
|
136
|
+
}
|
|
137
|
+
return { type: "object", properties: {} };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Transport-failure kinds worth one reconnect + retry. */
|
|
141
|
+
const RETRY_KINDS = new Set(["connect", "closed", "stream-broken", "process-exit"]);
|
|
142
|
+
|
|
143
|
+
function isAuthOutcome(outcome: Outcome<unknown>): boolean {
|
|
144
|
+
if (outcome.kind === "auth-failure" || outcome.kind === "auth-unavailable") return true;
|
|
145
|
+
return (
|
|
146
|
+
outcome.kind === "transport-failure" &&
|
|
147
|
+
(outcome.failure.kind === "auth-failure" || outcome.failure.kind === "auth-unavailable")
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function describeOutcome(outcome: Exclude<Outcome<unknown>, { kind: "ok" }>): string {
|
|
152
|
+
switch (outcome.kind) {
|
|
153
|
+
case "jsonrpc-error":
|
|
154
|
+
return `JSON-RPC error ${outcome.code}: ${outcome.message}`;
|
|
155
|
+
case "transport-failure":
|
|
156
|
+
return `${outcome.failure.kind}: ${outcome.failure.message}`;
|
|
157
|
+
case "tool-isError":
|
|
158
|
+
return "tool reported an error";
|
|
159
|
+
case "cancelled":
|
|
160
|
+
return "cancelled";
|
|
161
|
+
case "uncertain-write":
|
|
162
|
+
return `uncertain write (${outcome.uncertain.evidence}); not retried`;
|
|
163
|
+
case "mrtr-interim":
|
|
164
|
+
return "server requested mid-request input (elicitations are not supported yet)";
|
|
165
|
+
case "task-handle":
|
|
166
|
+
return "server returned a task handle (task-based calls are not supported yet)";
|
|
167
|
+
default:
|
|
168
|
+
return `${outcome.kind}: ${JSON.stringify("detail" in outcome ? outcome.detail : undefined)?.slice(0, 300)}`;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export interface BridgeOptions {
|
|
173
|
+
readonly pi: ExtensionAPI;
|
|
174
|
+
readonly notify: (message: string, level: "info" | "warning" | "error") => void;
|
|
175
|
+
/** Bound for connection waits from tool_call / before_agent_start. */
|
|
176
|
+
readonly waitMs?: number;
|
|
177
|
+
/** Path of the OAuth credential store file; enables OAuth for HTTP servers. */
|
|
178
|
+
readonly credentialStorePath?: string;
|
|
179
|
+
/** Host confirm dialog for OAuth consent prompts. */
|
|
180
|
+
readonly confirm?: (title: string, message: string) => Promise<boolean>;
|
|
181
|
+
/** Browser opener override (tests); defaults to the system browser. */
|
|
182
|
+
readonly browserOpen?: (url: string, signal: AbortSignal) => Promise<void>;
|
|
183
|
+
/** Allow OAuth against insecure loopback HTTP (local dev servers, tests). */
|
|
184
|
+
readonly allowInsecureAuth?: boolean;
|
|
185
|
+
/** Host UI for elicitation prompts; without it elicitations decline. */
|
|
186
|
+
readonly ui?: Ui;
|
|
187
|
+
/** Diagnostics log path (mcp-client.log). */
|
|
188
|
+
readonly diagnosticsLogPath?: string;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export class McpBridge {
|
|
192
|
+
private readonly pi: ExtensionAPI;
|
|
193
|
+
private readonly notify: BridgeOptions["notify"];
|
|
194
|
+
private readonly waitMs: number;
|
|
195
|
+
private readonly states = new Map<string, ServerState>();
|
|
196
|
+
private readonly pending = new Map<string, Promise<void>>();
|
|
197
|
+
private readonly credentials: FileCredentialStore | undefined;
|
|
198
|
+
private readonly confirm: BridgeOptions["confirm"];
|
|
199
|
+
private readonly browserOpen: BridgeOptions["browserOpen"];
|
|
200
|
+
private readonly allowInsecureAuth: boolean;
|
|
201
|
+
private readonly resourceTools: ResourceTools;
|
|
202
|
+
private readonly exposureByServer = new Map<string, Exposure>();
|
|
203
|
+
private readonly ui: Ui;
|
|
204
|
+
private readonly log: DiagnosticsLog | undefined;
|
|
205
|
+
/** Server name for which an interactive login (/mcp login) is armed. */
|
|
206
|
+
private loginArmed: string | undefined;
|
|
207
|
+
|
|
208
|
+
constructor(opts: BridgeOptions) {
|
|
209
|
+
this.pi = opts.pi;
|
|
210
|
+
this.notify = opts.notify;
|
|
211
|
+
this.waitMs = opts.waitMs ?? 10_000;
|
|
212
|
+
this.credentials = opts.credentialStorePath !== undefined
|
|
213
|
+
? new FileCredentialStore(opts.credentialStorePath)
|
|
214
|
+
: undefined;
|
|
215
|
+
this.confirm = opts.confirm;
|
|
216
|
+
this.browserOpen = opts.browserOpen;
|
|
217
|
+
this.allowInsecureAuth = opts.allowInsecureAuth ?? false;
|
|
218
|
+
this.ui = opts.ui ?? { notify: () => {} };
|
|
219
|
+
this.log = opts.diagnosticsLogPath !== undefined ? new DiagnosticsLog(opts.diagnosticsLogPath) : undefined;
|
|
220
|
+
this.resourceTools = new ResourceTools(this.pi, () => this.list(), this.exposureByServer);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
get(name: string): ServerState | undefined {
|
|
224
|
+
return this.states.get(name);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
list(): ServerState[] {
|
|
228
|
+
return [...this.states.values()];
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Start connecting every enabled server in the background; mark the rest. */
|
|
232
|
+
sync(configs: ReadonlyMap<string, ResolvedServerConfig>): void {
|
|
233
|
+
for (const [name, cfg] of configs) {
|
|
234
|
+
const existing = this.states.get(name);
|
|
235
|
+
if (existing) {
|
|
236
|
+
const changed = JSON.stringify(existing.config) !== JSON.stringify(cfg);
|
|
237
|
+
existing.config = cfg;
|
|
238
|
+
if (!cfg.enabled) {
|
|
239
|
+
void this.teardown(existing);
|
|
240
|
+
existing.status = "disabled";
|
|
241
|
+
existing.error = undefined;
|
|
242
|
+
} else if (changed || existing.status === "disabled" || existing.status === "error") {
|
|
243
|
+
this.connectInBackground(existing);
|
|
244
|
+
}
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
const state: ServerState = {
|
|
248
|
+
name,
|
|
249
|
+
config: cfg,
|
|
250
|
+
status: cfg.enabled ? "connecting" : "disabled",
|
|
251
|
+
toolCount: 0,
|
|
252
|
+
registeredTools: new Set(),
|
|
253
|
+
exposures: new Set(),
|
|
254
|
+
definitions: new Map(),
|
|
255
|
+
toolNames: new Map(),
|
|
256
|
+
};
|
|
257
|
+
this.states.set(name, state);
|
|
258
|
+
if (cfg.enabled) this.connectInBackground(state);
|
|
259
|
+
}
|
|
260
|
+
// Servers removed from configuration: tear down, keep registrations inert.
|
|
261
|
+
for (const [name, state] of this.states) {
|
|
262
|
+
if (!configs.has(name) && state.status !== "disabled") {
|
|
263
|
+
void this.teardown(state);
|
|
264
|
+
state.status = "disabled";
|
|
265
|
+
state.error = "removed from configuration";
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
private connectInBackground(state: ServerState): void {
|
|
271
|
+
state.status = "connecting";
|
|
272
|
+
state.error = undefined;
|
|
273
|
+
const p = this.connect(state)
|
|
274
|
+
.then(() => this.ensureReachTools())
|
|
275
|
+
.catch(() => {});
|
|
276
|
+
this.pending.set(state.name, p);
|
|
277
|
+
void p.finally(() => {
|
|
278
|
+
if (this.pending.get(state.name) === p) this.pending.delete(state.name);
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Wait for pending connections, bounded by waitMs. */
|
|
283
|
+
async waitForPending(predicate?: (state: ServerState) => boolean): Promise<void> {
|
|
284
|
+
const names = [...this.states.values()]
|
|
285
|
+
.filter((s) => (predicate ? predicate(s) : true))
|
|
286
|
+
.map((s) => s.name);
|
|
287
|
+
const pending = names
|
|
288
|
+
.map((n) => this.pending.get(n))
|
|
289
|
+
.filter((p): p is Promise<void> => p !== undefined);
|
|
290
|
+
if (pending.length === 0) return;
|
|
291
|
+
await Promise.race([
|
|
292
|
+
Promise.allSettled(pending),
|
|
293
|
+
new Promise((resolve) => setTimeout(resolve, this.waitMs)),
|
|
294
|
+
]);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
async reconnect(name: string): Promise<ServerState> {
|
|
298
|
+
const state = this.states.get(name);
|
|
299
|
+
if (!state) throw new Error(`unknown server: ${name}`);
|
|
300
|
+
await this.teardown(state);
|
|
301
|
+
state.status = "connecting";
|
|
302
|
+
state.error = undefined;
|
|
303
|
+
state.toolCount = 0;
|
|
304
|
+
await this.connect(state);
|
|
305
|
+
this.ensureReachTools();
|
|
306
|
+
return state;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Interactive OAuth sign-in: arms the consent gate and reconnects. */
|
|
310
|
+
async login(name: string): Promise<ServerState> {
|
|
311
|
+
const state = this.states.get(name);
|
|
312
|
+
if (!state) throw new Error(`unknown server: ${name}`);
|
|
313
|
+
if (state.config.kind !== "http") {
|
|
314
|
+
throw new Error(`mcp "${name}": OAuth applies to HTTP servers only`);
|
|
315
|
+
}
|
|
316
|
+
if (!this.credentials) throw new Error("OAuth is not available (no credential store)");
|
|
317
|
+
this.loginArmed = name;
|
|
318
|
+
try {
|
|
319
|
+
await this.reconnect(name);
|
|
320
|
+
} finally {
|
|
321
|
+
this.loginArmed = undefined;
|
|
322
|
+
}
|
|
323
|
+
return state;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** Delete stored credentials for the server's resource and reconnect. */
|
|
327
|
+
async logout(name: string): Promise<ServerState> {
|
|
328
|
+
const state = this.states.get(name);
|
|
329
|
+
if (!state) throw new Error(`unknown server: ${name}`);
|
|
330
|
+
if (this.credentials && state.config.url !== undefined) {
|
|
331
|
+
await this.credentials.deleteResource(canonicalResource(state.config.url));
|
|
332
|
+
}
|
|
333
|
+
await this.reconnect(name);
|
|
334
|
+
return state;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
async closeAll(): Promise<void> {
|
|
338
|
+
await Promise.allSettled([...this.pending.values()]);
|
|
339
|
+
await Promise.allSettled([...this.states.values()].map((s) => this.teardown(s)));
|
|
340
|
+
this.states.clear();
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
private async teardown(state: ServerState): Promise<void> {
|
|
344
|
+
const client = state.client;
|
|
345
|
+
state.client = undefined;
|
|
346
|
+
state.ops = undefined;
|
|
347
|
+
state.listenClose?.();
|
|
348
|
+
state.listenClose = undefined;
|
|
349
|
+
state.closeRedirect?.();
|
|
350
|
+
state.closeRedirect = undefined;
|
|
351
|
+
if (client) {
|
|
352
|
+
try {
|
|
353
|
+
await client.close({ graceMs: 500 });
|
|
354
|
+
} catch {
|
|
355
|
+
// close is best-effort
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
private async buildClient(config: ResolvedServerConfig, state: ServerState): Promise<McpClient> {
|
|
361
|
+
let transport: StdioTransport | HttpTransport;
|
|
362
|
+
if (config.kind === "stdio") {
|
|
363
|
+
transport = new StdioTransport({
|
|
364
|
+
command: config.command as string,
|
|
365
|
+
args: config.args ?? [],
|
|
366
|
+
...(config.cwd !== undefined ? { cwd: config.cwd } : {}),
|
|
367
|
+
...(config.env !== undefined ? { env: config.env } : {}),
|
|
368
|
+
});
|
|
369
|
+
} else {
|
|
370
|
+
// OAuth attaches when no static Authorization header is configured
|
|
371
|
+
// (mirrors Pi's rule); the flow itself runs on the first 401.
|
|
372
|
+
const hasStaticAuth = Object.keys(config.headers ?? {}).some(
|
|
373
|
+
(k) => k.toLowerCase() === "authorization",
|
|
374
|
+
);
|
|
375
|
+
let authProvider;
|
|
376
|
+
if (!hasStaticAuth && this.credentials) {
|
|
377
|
+
const handle = await createOAuthProvider({
|
|
378
|
+
config,
|
|
379
|
+
store: this.credentials,
|
|
380
|
+
interactive: () => this.loginArmed === config.name,
|
|
381
|
+
...(this.confirm !== undefined ? { confirm: this.confirm } : {}),
|
|
382
|
+
...(this.browserOpen !== undefined ? { browserOpen: this.browserOpen } : {}),
|
|
383
|
+
allowInsecureAuth: this.allowInsecureAuth,
|
|
384
|
+
});
|
|
385
|
+
authProvider = handle.provider;
|
|
386
|
+
state.closeRedirect = handle.closeRedirect;
|
|
387
|
+
}
|
|
388
|
+
transport = new HttpTransport({
|
|
389
|
+
url: config.url as string,
|
|
390
|
+
...(config.headers !== undefined ? { extraHeaders: config.headers } : {}),
|
|
391
|
+
...(authProvider !== undefined ? { authProvider } : {}),
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
const client = new McpClient({
|
|
395
|
+
transport,
|
|
396
|
+
server: { key: config.name, label: config.name },
|
|
397
|
+
clientInfo: { name: "pi", version: "mcp-client-bridge" },
|
|
398
|
+
defaults: { timeoutMs: config.timeoutMs },
|
|
399
|
+
ports: { consent: consentPort(this.ui, config.name) },
|
|
400
|
+
});
|
|
401
|
+
client.use(createTasksExtension({
|
|
402
|
+
serverKey: config.name,
|
|
403
|
+
request: (method, params, opts) => client.request(method, params, opts),
|
|
404
|
+
peerCapabilities: () => (state.capabilities ?? {}) as Record<string, unknown>,
|
|
405
|
+
}));
|
|
406
|
+
return client;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
private async connect(state: ServerState): Promise<void> {
|
|
410
|
+
const { config } = state;
|
|
411
|
+
try {
|
|
412
|
+
const client = await this.buildClient(config, state);
|
|
413
|
+
const ops = createOps(client);
|
|
414
|
+
state.client = client;
|
|
415
|
+
state.ops = ops;
|
|
416
|
+
|
|
417
|
+
// Best-effort server/discover for instructions used as namespace text.
|
|
418
|
+
try {
|
|
419
|
+
const discovered = await client.discover({ timeoutMs: 10_000 });
|
|
420
|
+
if (discovered.kind === "ok") {
|
|
421
|
+
state.capabilities = discovered.value.capabilities as Record<string, unknown>;
|
|
422
|
+
const instructions = discovered.value.instructions;
|
|
423
|
+
if (typeof instructions === "string" && instructions.trim() !== "") {
|
|
424
|
+
state.description = config.description ?? instructions.split("\n")[0];
|
|
425
|
+
state.instructions = instructions;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
} catch {
|
|
429
|
+
// discover is optional metadata
|
|
430
|
+
}
|
|
431
|
+
if (state.description === undefined && config.description !== undefined) {
|
|
432
|
+
state.description = config.description;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
const listed = await ops.tools.listAll({ maxItems: 10_000 });
|
|
436
|
+
if (listed.kind === "ok") {
|
|
437
|
+
this.registerTools(state, listed.value.items);
|
|
438
|
+
for (const warning of listed.value.warnings) {
|
|
439
|
+
this.notify(`mcp "${state.name}": ${warning}`, "warning");
|
|
440
|
+
}
|
|
441
|
+
} else if (
|
|
442
|
+
listed.kind === "capability-absent" ||
|
|
443
|
+
(listed.kind === "jsonrpc-error" && listed.code === -32601)
|
|
444
|
+
) {
|
|
445
|
+
// Server without a tools capability: valid, just nothing to register.
|
|
446
|
+
} else if (isAuthOutcome(listed)) {
|
|
447
|
+
state.authRequired = true;
|
|
448
|
+
throw new Error(`authentication required — sign in with /mcp login ${state.name}`);
|
|
449
|
+
} else {
|
|
450
|
+
throw new Error(describeOutcome(listed));
|
|
451
|
+
}
|
|
452
|
+
state.status = "connected";
|
|
453
|
+
state.error = undefined;
|
|
454
|
+
state.authRequired = undefined;
|
|
455
|
+
this.exposureByServer.set(state.name, config.exposure);
|
|
456
|
+
this.resourceTools.ensure();
|
|
457
|
+
this.startListen(state);
|
|
458
|
+
this.log?.line(state.name, `connected (${state.toolCount} tools)`);
|
|
459
|
+
} catch (err) {
|
|
460
|
+
state.status = "error";
|
|
461
|
+
state.error = err instanceof Error ? err.message : String(err);
|
|
462
|
+
this.log?.line(state.name, `error: ${state.error}`);
|
|
463
|
+
await this.teardown(state);
|
|
464
|
+
this.notify(`mcp "${state.name}": ${state.error}`, "error");
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
private registerTools(state: ServerState, entries: readonly ToolEntry[]): void {
|
|
469
|
+
const usable = entries.filter((e) => typeof e.name === "string" && e.name !== "");
|
|
470
|
+
const names = assignToolNames(state.name, usable.map((e) => e.name));
|
|
471
|
+
const seen = new Set<string>();
|
|
472
|
+
for (const entry of usable) {
|
|
473
|
+
const piName = names.get(entry.name) as string;
|
|
474
|
+
seen.add(piName);
|
|
475
|
+
const exposure = toolExposureFor(state.config, entry.name);
|
|
476
|
+
const toolDescription =
|
|
477
|
+
typeof entry.tool.description === "string" ? entry.tool.description : "";
|
|
478
|
+
const annotations = annotationsOf(entry);
|
|
479
|
+
const definition: ToolDefinition = {
|
|
480
|
+
name: piName,
|
|
481
|
+
label: `${state.name}: ${entry.name}`,
|
|
482
|
+
description: toolDescription || `MCP tool ${entry.name} on ${state.name}`,
|
|
483
|
+
parameters: inputSchemaOf(entry),
|
|
484
|
+
exposure,
|
|
485
|
+
namespace: {
|
|
486
|
+
name: `mcp__${sanitizeNamePart(state.name)}`,
|
|
487
|
+
aliases: [state.name, state.name.replace(/-/g, "_")],
|
|
488
|
+
...(state.description !== undefined ? { description: state.description } : {}),
|
|
489
|
+
...(state.instructions !== undefined ? { instructions: state.instructions } : {}),
|
|
490
|
+
},
|
|
491
|
+
...(annotations !== undefined ? { annotations } : {}),
|
|
492
|
+
promptSnippet: toolDescription.split("\n")[0] ?? "",
|
|
493
|
+
execute: (_id, params, signal, onUpdate) =>
|
|
494
|
+
this.callTool(state.name, entry.name, params, signal, onUpdate),
|
|
495
|
+
};
|
|
496
|
+
const previous = state.definitions.get(piName);
|
|
497
|
+
if (!previous || JSON.stringify(previous.parameters) !== JSON.stringify(definition.parameters) || previous.exposure !== exposure) {
|
|
498
|
+
this.pi.registerTool(definition);
|
|
499
|
+
}
|
|
500
|
+
state.definitions.set(piName, definition);
|
|
501
|
+
state.toolNames.set(piName, entry.name);
|
|
502
|
+
state.registeredTools.add(piName);
|
|
503
|
+
state.exposures.add(exposure);
|
|
504
|
+
}
|
|
505
|
+
// Withdrawn tools become unreachable but stay registered (Pi has no unregister).
|
|
506
|
+
for (const [piName, definition] of state.definitions) {
|
|
507
|
+
if (!seen.has(piName) && definition.exposure !== "hidden") {
|
|
508
|
+
this.pi.registerTool({ ...definition, exposure: "hidden" });
|
|
509
|
+
state.definitions.set(piName, { ...definition, exposure: "hidden" });
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
state.toolCount = seen.size;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
private startListen(state: ServerState): void {
|
|
516
|
+
if (state.listenClose || !state.client) return;
|
|
517
|
+
const toolsCap = state.capabilities?.tools as { listChanged?: boolean } | undefined;
|
|
518
|
+
if (toolsCap?.listChanged !== true) return;
|
|
519
|
+
const stream = state.client.openStream("subscriptions/listen", {
|
|
520
|
+
notifications: { toolsListChanged: true, promptsListChanged: true, resourcesListChanged: true },
|
|
521
|
+
});
|
|
522
|
+
state.listenClose = () => stream.close();
|
|
523
|
+
void (async () => {
|
|
524
|
+
try {
|
|
525
|
+
for await (const notification of stream) {
|
|
526
|
+
if (notification.method === "notifications/tools/list_changed") {
|
|
527
|
+
await this.refreshTools(state);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
} catch {
|
|
531
|
+
// listen stream ended; reconnect re-establishes it
|
|
532
|
+
}
|
|
533
|
+
})();
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
private async refreshTools(state: ServerState): Promise<void> {
|
|
537
|
+
if (!state.ops) return;
|
|
538
|
+
const listed = await state.ops.tools.listAll({ maxItems: 10_000 });
|
|
539
|
+
if (listed.kind !== "ok") return;
|
|
540
|
+
this.registerTools(state, listed.value.items);
|
|
541
|
+
this.ensureReachTools();
|
|
542
|
+
this.log?.line(state.name, `tools/list_changed (${state.toolCount} tools)`);
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
private async callTool(
|
|
546
|
+
serverName: string,
|
|
547
|
+
toolName: string,
|
|
548
|
+
params: Record<string, unknown>,
|
|
549
|
+
signal: AbortSignal | undefined,
|
|
550
|
+
onUpdate: ((partial: ToolResult) => void) | undefined,
|
|
551
|
+
): Promise<ToolResult> {
|
|
552
|
+
let state = this.states.get(serverName);
|
|
553
|
+
if (!state?.ops || state.status !== "connected") {
|
|
554
|
+
throw new Error(
|
|
555
|
+
`MCP server "${serverName}" is not connected (status: ${state?.status ?? "unknown"}${
|
|
556
|
+
state?.error ? `, ${state.error}` : ""
|
|
557
|
+
}). Run /mcp reconnect ${serverName}.`,
|
|
558
|
+
);
|
|
559
|
+
}
|
|
560
|
+
const progress = (p: unknown) => {
|
|
561
|
+
const msg = (p as { message?: unknown })?.message;
|
|
562
|
+
if (typeof msg === "string" && onUpdate) {
|
|
563
|
+
onUpdate({
|
|
564
|
+
content: [{ type: "text", text: `${serverName}/${toolName}: ${msg}` }],
|
|
565
|
+
details: { server: serverName, tool: toolName },
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
};
|
|
569
|
+
let outcome = await callWithElicitation(state, toolName, params, {
|
|
570
|
+
...(signal !== undefined ? { signal } : {}),
|
|
571
|
+
onProgress: progress,
|
|
572
|
+
}, this.ui);
|
|
573
|
+
if (
|
|
574
|
+
outcome.kind === "transport-failure" &&
|
|
575
|
+
RETRY_KINDS.has(outcome.failure.kind) &&
|
|
576
|
+
!(signal?.aborted ?? false)
|
|
577
|
+
) {
|
|
578
|
+
// Dropped connection: reconnect once and retry, like built-in MCP does.
|
|
579
|
+
try {
|
|
580
|
+
state = await this.reconnect(serverName);
|
|
581
|
+
} catch {
|
|
582
|
+
// fall through to reporting the original outcome
|
|
583
|
+
}
|
|
584
|
+
if (state.ops && state.status === "connected") {
|
|
585
|
+
outcome = await callWithElicitation(state, toolName, params, {
|
|
586
|
+
...(signal !== undefined ? { signal } : {}),
|
|
587
|
+
}, this.ui);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
if (outcome.kind === "task-handle") return taskHandleResult(state, toolName, outcome);
|
|
591
|
+
return this.outcomeToResult(serverName, toolName, outcome);
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
private async outcomeToResult(
|
|
595
|
+
serverName: string,
|
|
596
|
+
toolName: string,
|
|
597
|
+
outcome: Outcome<ToolCallResult>,
|
|
598
|
+
): Promise<ToolResult> {
|
|
599
|
+
const details = { server: serverName, tool: toolName };
|
|
600
|
+
if (outcome.kind === "ok") {
|
|
601
|
+
const { value } = outcome;
|
|
602
|
+
return {
|
|
603
|
+
content: await convertBlocksOffloaded(value.content),
|
|
604
|
+
details: { ...details, validation: value.validation.status },
|
|
605
|
+
...(value.structuredContent !== undefined ? { structuredContent: value.structuredContent } : {}),
|
|
606
|
+
};
|
|
607
|
+
}
|
|
608
|
+
if (outcome.kind === "tool-isError") {
|
|
609
|
+
const raw = outcome.result;
|
|
610
|
+
return {
|
|
611
|
+
content: await convertBlocksOffloaded(normalizeContent(raw.content)),
|
|
612
|
+
details,
|
|
613
|
+
isError: true,
|
|
614
|
+
...(raw.structuredContent !== undefined ? { structuredContent: raw.structuredContent } : {}),
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
throw new Error(`mcp ${serverName}/${toolName}: ${describeOutcome(outcome)}`);
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/** Prompt list for /mcp prompts. */
|
|
621
|
+
async promptsList(name: string): Promise<unknown[]> {
|
|
622
|
+
const state = this.states.get(name);
|
|
623
|
+
if (!state?.ops) throw new Error(`MCP server "${name}" is not connected`);
|
|
624
|
+
const outcome = await state.ops.prompts.listAll();
|
|
625
|
+
if (outcome.kind !== "ok") throw new Error(`prompts/list failed: ${outcome.kind}`);
|
|
626
|
+
return outcome.value.items;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/** Prompt get for /mcp prompt. */
|
|
630
|
+
async promptGet(name: string, prompt: string, args: Record<string, string>): Promise<unknown> {
|
|
631
|
+
const state = this.states.get(name);
|
|
632
|
+
if (!state?.ops) throw new Error(`MCP server "${name}" is not connected`);
|
|
633
|
+
const outcome = await state.ops.prompts.get(prompt, args);
|
|
634
|
+
if (outcome.kind !== "ok") throw new Error(`prompts/get failed: ${outcome.kind}`);
|
|
635
|
+
return outcome.value;
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
async resourcesList(name: string): Promise<unknown[]> {
|
|
639
|
+
const state = this.states.get(name);
|
|
640
|
+
if (!state?.ops) throw new Error(`MCP server "${name}" is not connected`);
|
|
641
|
+
const outcome = await state.ops.resources.listAll();
|
|
642
|
+
if (outcome.kind !== "ok") throw new Error(`resources/list failed: ${outcome.kind}`);
|
|
643
|
+
return outcome.value.items.map((item: { raw: Record<string, unknown> }) => item.raw);
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
async taskState(name: string, taskId: string, cancel = false): Promise<unknown> {
|
|
647
|
+
const state = this.states.get(name);
|
|
648
|
+
if (!state?.ops) throw new Error(`MCP server "${name}" is not connected`);
|
|
649
|
+
return cancel ? cancelTask(state, taskId) : getTask(state, taskId);
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
/** Session-only enable/disable; persistence is handled by the command layer. */
|
|
653
|
+
setEnabled(name: string, enabled: boolean): void {
|
|
654
|
+
const state = this.states.get(name);
|
|
655
|
+
if (!state) throw new Error(`unknown server: ${name}`);
|
|
656
|
+
state.config = { ...state.config, enabled };
|
|
657
|
+
if (!enabled) {
|
|
658
|
+
void this.teardown(state);
|
|
659
|
+
state.status = "disabled";
|
|
660
|
+
} else {
|
|
661
|
+
this.connectInBackground(state);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/** Session-only exposure change; re-registers affected tools. */
|
|
666
|
+
setExposure(name: string, exposure: Exposure, toolPattern?: string): void {
|
|
667
|
+
const state = this.states.get(name);
|
|
668
|
+
if (!state) throw new Error(`unknown server: ${name}`);
|
|
669
|
+
state.config = toolPattern
|
|
670
|
+
? { ...state.config, toolExposure: { ...state.config.toolExposure, [toolPattern]: exposure } }
|
|
671
|
+
: { ...state.config, exposure };
|
|
672
|
+
this.exposureByServer.set(name, state.config.exposure);
|
|
673
|
+
for (const [piName, definition] of state.definitions) {
|
|
674
|
+
const serverTool = state.toolNames.get(piName) as string;
|
|
675
|
+
const next = toolExposureFor(state.config, serverTool);
|
|
676
|
+
if (definition.exposure !== next) {
|
|
677
|
+
this.pi.registerTool({ ...definition, exposure: next });
|
|
678
|
+
state.definitions.set(piName, { ...definition, exposure: next });
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
this.ensureReachTools();
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/**
|
|
685
|
+
* Mirror of built-in behavior: once a codemode-exposure server connects,
|
|
686
|
+
* activate codemode; for deferred, activate tool_search.
|
|
687
|
+
*/
|
|
688
|
+
ensureReachTools(): void {
|
|
689
|
+
const exposures = new Set<Exposure>();
|
|
690
|
+
for (const s of this.states.values()) {
|
|
691
|
+
if (s.status === "connected") for (const e of s.exposures) exposures.add(e);
|
|
692
|
+
}
|
|
693
|
+
const autoEnable = this.pi.getSettings?.()?.autoEnableCodemode;
|
|
694
|
+
const all = this.pi.getAllTools();
|
|
695
|
+
const active = new Set(this.pi.getActiveTools());
|
|
696
|
+
const wanted: string[] = [];
|
|
697
|
+
if (exposures.has("codemode") && autoEnable !== false) wanted.push("codemode");
|
|
698
|
+
if (exposures.has("deferred")) wanted.push("tool_search");
|
|
699
|
+
const toAdd = wanted.filter((n) => all.some((t) => t.name === n) && !active.has(n));
|
|
700
|
+
if (toAdd.length > 0) this.pi.setActiveTools([...active, ...toAdd]);
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
statusLines(): string[] {
|
|
704
|
+
if (this.states.size === 0) return ["No MCP servers configured."];
|
|
705
|
+
return [...this.states.values()].map((s) => {
|
|
706
|
+
const base = `${s.name} (${s.config.kind}, ${s.config.source})`;
|
|
707
|
+
switch (s.status) {
|
|
708
|
+
case "connected":
|
|
709
|
+
return `${base}: connected, ${s.toolCount} tool${s.toolCount === 1 ? "" : "s"}`;
|
|
710
|
+
case "connecting":
|
|
711
|
+
return `${base}: connecting…`;
|
|
712
|
+
case "disabled":
|
|
713
|
+
return `${base}: disabled${s.error ? ` (${s.error})` : ""}`;
|
|
714
|
+
case "error":
|
|
715
|
+
return s.authRequired
|
|
716
|
+
? `${base}: needs sign-in — /mcp login ${s.name}`
|
|
717
|
+
: `${base}: error: ${s.error ?? "unknown"}`;
|
|
718
|
+
}
|
|
719
|
+
});
|
|
720
|
+
}
|
|
721
|
+
}
|