@jangmanj/mcp-client 0.1.1 → 0.2.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/README.md +29 -0
- package/dist/ext-events/push.js +1 -1
- package/extensions/bridge.ts +486 -0
- package/extensions/config.ts +298 -0
- package/extensions/content.ts +78 -0
- package/extensions/index.ts +154 -0
- package/extensions/pi-api.ts +129 -0
- package/package.json +16 -2
package/README.md
CHANGED
|
@@ -27,6 +27,35 @@ npm install @jangmanj/mcp-client
|
|
|
27
27
|
- Use `"moduleResolution": "NodeNext"` (or `"Bundler"`) in your consumer `tsconfig.json` so subpath exports resolve cleanly.
|
|
28
28
|
- If your consumer `tsconfig.json` overrides `"lib"` without `"DOM"` (for example `"lib": ["ES2023"]`), install `@types/node` and include `"types": ["node"]` so standard Web/Node globals (`AbortSignal`, `URL`, `Response`, `CryptoKey`) are typed.
|
|
29
29
|
|
|
30
|
+
## Pi extension
|
|
31
|
+
|
|
32
|
+
This package doubles as a [Pi](https://pi.dev) package: installing it registers an
|
|
33
|
+
extension that replaces Pi's built-in MCP session support with a bridge built on
|
|
34
|
+
this library (transports, lifecycle, ops, MRTR) and exposes each server's tools to
|
|
35
|
+
Pi as `mcp__<server>__<tool>`.
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
pi install npm:@jangmanj/mcp-client
|
|
39
|
+
# or from a checkout / git ref:
|
|
40
|
+
pi install ./path/to/mcp-client
|
|
41
|
+
pi install git:github.com/JangMan-J/mcp-client@v0.1.1
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
The extension reads the same `mcp.json` files as built-in MCP
|
|
45
|
+
(`$PI_CODING_AGENT_DIR/mcp.json` or `~/.pi/agent/mcp.json`, plus `.pi/mcp.json` in
|
|
46
|
+
trusted projects) with the same merge, interpolation (`${VAR}`, `!command`), and
|
|
47
|
+
exposure rules (`codemode` default, `direct`/`deferred`/`hidden`, `toolExposure`
|
|
48
|
+
patterns). `/mcp` lists server states; `/mcp reconnect <name>` restarts one.
|
|
49
|
+
Servers registered by other extensions via `pi.registerMcpServer()` are connected
|
|
50
|
+
too, with file configuration taking precedence.
|
|
51
|
+
|
|
52
|
+
Not supported yet: OAuth flows (`oauth` entries connect unauthenticated and will
|
|
53
|
+
fail on servers that require it — use `headers` with a token instead), MCP
|
|
54
|
+
prompts/resources, elicitations, and task-based tool calls.
|
|
55
|
+
|
|
56
|
+
A running Pi session picks the extension up on `/reload`; fresh starts load it
|
|
57
|
+
automatically.
|
|
58
|
+
|
|
30
59
|
## Development
|
|
31
60
|
|
|
32
61
|
```sh
|
package/dist/ext-events/push.js
CHANGED
|
@@ -34,7 +34,7 @@ export function watchStream(open, clock, jitter, advance, accept, deliver) {
|
|
|
34
34
|
let heartbeat = 0;
|
|
35
35
|
const arm = () => {
|
|
36
36
|
timer?.();
|
|
37
|
-
timer = clock.setTimeout(reconnect, heartbeat);
|
|
37
|
+
timer = clock.setTimeout(reconnect, heartbeat * 2);
|
|
38
38
|
};
|
|
39
39
|
void stream.done.then(reconnect, reconnect);
|
|
40
40
|
void (async () => {
|
|
@@ -0,0 +1,486 @@
|
|
|
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 "../dist/index.js";
|
|
9
|
+
import {
|
|
10
|
+
createOps,
|
|
11
|
+
normalizeContent,
|
|
12
|
+
type Ops,
|
|
13
|
+
type ToolCallResult,
|
|
14
|
+
type ToolEntry,
|
|
15
|
+
} from "../dist/ops/index.js";
|
|
16
|
+
import { HttpTransport } from "../dist/transport-http/index.js";
|
|
17
|
+
import { StdioTransport } from "../dist/transport-stdio/index.js";
|
|
18
|
+
import type { Outcome } from "../dist/index.js";
|
|
19
|
+
import type { Exposure, ResolvedServerConfig } from "./config.ts";
|
|
20
|
+
import { convertBlocks } from "./content.ts";
|
|
21
|
+
import type { ExtensionAPI, ToolAnnotations, ToolResult } from "./pi-api.ts";
|
|
22
|
+
|
|
23
|
+
export type ServerStatus = "connecting" | "connected" | "error" | "disabled";
|
|
24
|
+
|
|
25
|
+
export interface ServerState {
|
|
26
|
+
readonly name: string;
|
|
27
|
+
config: ResolvedServerConfig;
|
|
28
|
+
status: ServerStatus;
|
|
29
|
+
toolCount: number;
|
|
30
|
+
error?: string | undefined;
|
|
31
|
+
description?: string | undefined;
|
|
32
|
+
/** Full server instructions from server/discover, when offered. */
|
|
33
|
+
instructions?: string | undefined;
|
|
34
|
+
client?: McpClient | undefined;
|
|
35
|
+
ops?: Ops | undefined;
|
|
36
|
+
/** Pi tool names registered for this server (persist across reconnects). */
|
|
37
|
+
readonly registeredTools: Set<string>;
|
|
38
|
+
/** Exposures this server's tools were registered with. */
|
|
39
|
+
readonly exposures: Set<Exposure>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function sanitizeNamePart(s: string): string {
|
|
43
|
+
return s.replace(/[^A-Za-z0-9_]/g, "_");
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function shortHash(s: string): string {
|
|
47
|
+
return createHash("sha1").update(s).digest("hex").slice(0, 8);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Map server tool names to Pi tool names: mcp__<server>__<tool>, with a hash
|
|
52
|
+
* suffix for every tool in a collision group (same rule as built-in MCP).
|
|
53
|
+
*/
|
|
54
|
+
export function assignToolNames(server: string, toolNames: readonly string[]): Map<string, string> {
|
|
55
|
+
const prefix = `mcp__${sanitizeNamePart(server)}__`;
|
|
56
|
+
const byBase = new Map<string, string[]>();
|
|
57
|
+
for (const t of toolNames) {
|
|
58
|
+
const base = prefix + sanitizeNamePart(t);
|
|
59
|
+
const group = byBase.get(base);
|
|
60
|
+
if (group) group.push(t);
|
|
61
|
+
else byBase.set(base, [t]);
|
|
62
|
+
}
|
|
63
|
+
const out = new Map<string, string>();
|
|
64
|
+
for (const [base, group] of byBase) {
|
|
65
|
+
if (group.length === 1) {
|
|
66
|
+
out.set(group[0] as string, base);
|
|
67
|
+
} else {
|
|
68
|
+
for (const t of group) out.set(t, `${base}_h${shortHash(t)}`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Per-tool exposure: exact toolExposure key, then first matching `*` pattern, else the server's. */
|
|
75
|
+
export function toolExposureFor(config: ResolvedServerConfig, toolName: string): Exposure {
|
|
76
|
+
const overrides = config.toolExposure;
|
|
77
|
+
if (overrides) {
|
|
78
|
+
const exact = overrides[toolName];
|
|
79
|
+
if (exact !== undefined) return normalizeOverride(exact);
|
|
80
|
+
for (const [pattern, value] of Object.entries(overrides)) {
|
|
81
|
+
if (!pattern.includes("*")) continue;
|
|
82
|
+
const re = new RegExp(`^${pattern.split("*").map(escapeRe).join(".*")}$`);
|
|
83
|
+
if (re.test(toolName)) return normalizeOverride(value);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return config.exposure;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function normalizeOverride(value: string): Exposure {
|
|
90
|
+
return value === "direct" || value === "deferred" || value === "hidden" ? value : "codemode";
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function escapeRe(s: string): string {
|
|
94
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function annotationsOf(entry: ToolEntry): ToolAnnotations | undefined {
|
|
98
|
+
const v = entry.annotations?.value;
|
|
99
|
+
if (typeof v !== "object" || v === null) return undefined;
|
|
100
|
+
const rec = v as Record<string, unknown>;
|
|
101
|
+
const out: ToolAnnotations = {};
|
|
102
|
+
if (typeof rec.readOnlyHint === "boolean") out.readOnlyHint = rec.readOnlyHint;
|
|
103
|
+
if (typeof rec.destructiveHint === "boolean") out.destructiveHint = rec.destructiveHint;
|
|
104
|
+
if (typeof rec.idempotentHint === "boolean") out.idempotentHint = rec.idempotentHint;
|
|
105
|
+
if (typeof rec.openWorldHint === "boolean") out.openWorldHint = rec.openWorldHint;
|
|
106
|
+
return Object.keys(out).length > 0 ? out : undefined;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function inputSchemaOf(entry: ToolEntry): Record<string, unknown> {
|
|
110
|
+
const schema = entry.tool.inputSchema;
|
|
111
|
+
if (typeof schema === "object" && schema !== null && !Array.isArray(schema)) {
|
|
112
|
+
return schema as Record<string, unknown>;
|
|
113
|
+
}
|
|
114
|
+
return { type: "object", properties: {} };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Transport-failure kinds worth one reconnect + retry. */
|
|
118
|
+
const RETRY_KINDS = new Set(["connect", "closed", "stream-broken", "process-exit"]);
|
|
119
|
+
|
|
120
|
+
export function describeOutcome(outcome: Exclude<Outcome<unknown>, { kind: "ok" }>): string {
|
|
121
|
+
switch (outcome.kind) {
|
|
122
|
+
case "jsonrpc-error":
|
|
123
|
+
return `JSON-RPC error ${outcome.code}: ${outcome.message}`;
|
|
124
|
+
case "transport-failure":
|
|
125
|
+
return `${outcome.failure.kind}: ${outcome.failure.message}`;
|
|
126
|
+
case "tool-isError":
|
|
127
|
+
return "tool reported an error";
|
|
128
|
+
case "cancelled":
|
|
129
|
+
return "cancelled";
|
|
130
|
+
case "uncertain-write":
|
|
131
|
+
return `uncertain write (${outcome.uncertain.evidence}); not retried`;
|
|
132
|
+
case "mrtr-interim":
|
|
133
|
+
return "server requested mid-request input (elicitations are not supported yet)";
|
|
134
|
+
case "task-handle":
|
|
135
|
+
return "server returned a task handle (task-based calls are not supported yet)";
|
|
136
|
+
default:
|
|
137
|
+
return `${outcome.kind}: ${JSON.stringify("detail" in outcome ? outcome.detail : undefined)?.slice(0, 300)}`;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export interface BridgeOptions {
|
|
142
|
+
readonly pi: ExtensionAPI;
|
|
143
|
+
readonly notify: (message: string, level: "info" | "warning" | "error") => void;
|
|
144
|
+
/** Bound for connection waits from tool_call / before_agent_start. */
|
|
145
|
+
readonly waitMs?: number;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export class McpBridge {
|
|
149
|
+
private readonly pi: ExtensionAPI;
|
|
150
|
+
private readonly notify: BridgeOptions["notify"];
|
|
151
|
+
private readonly waitMs: number;
|
|
152
|
+
private readonly states = new Map<string, ServerState>();
|
|
153
|
+
private readonly pending = new Map<string, Promise<void>>();
|
|
154
|
+
|
|
155
|
+
constructor(opts: BridgeOptions) {
|
|
156
|
+
this.pi = opts.pi;
|
|
157
|
+
this.notify = opts.notify;
|
|
158
|
+
this.waitMs = opts.waitMs ?? 10_000;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
get(name: string): ServerState | undefined {
|
|
162
|
+
return this.states.get(name);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
list(): ServerState[] {
|
|
166
|
+
return [...this.states.values()];
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Start connecting every enabled server in the background; mark the rest. */
|
|
170
|
+
sync(configs: ReadonlyMap<string, ResolvedServerConfig>): void {
|
|
171
|
+
for (const [name, cfg] of configs) {
|
|
172
|
+
const existing = this.states.get(name);
|
|
173
|
+
if (existing) {
|
|
174
|
+
const changed = JSON.stringify(existing.config) !== JSON.stringify(cfg);
|
|
175
|
+
existing.config = cfg;
|
|
176
|
+
if (!cfg.enabled) {
|
|
177
|
+
void this.teardown(existing);
|
|
178
|
+
existing.status = "disabled";
|
|
179
|
+
existing.error = undefined;
|
|
180
|
+
} else if (changed || existing.status === "disabled" || existing.status === "error") {
|
|
181
|
+
this.connectInBackground(existing);
|
|
182
|
+
}
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
const state: ServerState = {
|
|
186
|
+
name,
|
|
187
|
+
config: cfg,
|
|
188
|
+
status: cfg.enabled ? "connecting" : "disabled",
|
|
189
|
+
toolCount: 0,
|
|
190
|
+
registeredTools: new Set(),
|
|
191
|
+
exposures: new Set(),
|
|
192
|
+
};
|
|
193
|
+
this.states.set(name, state);
|
|
194
|
+
if (cfg.enabled) this.connectInBackground(state);
|
|
195
|
+
}
|
|
196
|
+
// Servers removed from configuration: tear down, keep registrations inert.
|
|
197
|
+
for (const [name, state] of this.states) {
|
|
198
|
+
if (!configs.has(name) && state.status !== "disabled") {
|
|
199
|
+
void this.teardown(state);
|
|
200
|
+
state.status = "disabled";
|
|
201
|
+
state.error = "removed from configuration";
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
private connectInBackground(state: ServerState): void {
|
|
207
|
+
state.status = "connecting";
|
|
208
|
+
state.error = undefined;
|
|
209
|
+
const p = this.connect(state)
|
|
210
|
+
.then(() => this.ensureReachTools())
|
|
211
|
+
.catch(() => {});
|
|
212
|
+
this.pending.set(state.name, p);
|
|
213
|
+
void p.finally(() => {
|
|
214
|
+
if (this.pending.get(state.name) === p) this.pending.delete(state.name);
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Wait for pending connections, bounded by waitMs. */
|
|
219
|
+
async waitForPending(predicate?: (state: ServerState) => boolean): Promise<void> {
|
|
220
|
+
const names = [...this.states.values()]
|
|
221
|
+
.filter((s) => (predicate ? predicate(s) : true))
|
|
222
|
+
.map((s) => s.name);
|
|
223
|
+
const pending = names
|
|
224
|
+
.map((n) => this.pending.get(n))
|
|
225
|
+
.filter((p): p is Promise<void> => p !== undefined);
|
|
226
|
+
if (pending.length === 0) return;
|
|
227
|
+
await Promise.race([
|
|
228
|
+
Promise.allSettled(pending),
|
|
229
|
+
new Promise((resolve) => setTimeout(resolve, this.waitMs)),
|
|
230
|
+
]);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async reconnect(name: string): Promise<ServerState> {
|
|
234
|
+
const state = this.states.get(name);
|
|
235
|
+
if (!state) throw new Error(`unknown server: ${name}`);
|
|
236
|
+
await this.teardown(state);
|
|
237
|
+
state.status = "connecting";
|
|
238
|
+
state.error = undefined;
|
|
239
|
+
state.toolCount = 0;
|
|
240
|
+
await this.connect(state);
|
|
241
|
+
this.ensureReachTools();
|
|
242
|
+
return state;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async closeAll(): Promise<void> {
|
|
246
|
+
await Promise.allSettled([...this.pending.values()]);
|
|
247
|
+
await Promise.allSettled([...this.states.values()].map((s) => this.teardown(s)));
|
|
248
|
+
this.states.clear();
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
private async teardown(state: ServerState): Promise<void> {
|
|
252
|
+
const client = state.client;
|
|
253
|
+
state.client = undefined;
|
|
254
|
+
state.ops = undefined;
|
|
255
|
+
if (client) {
|
|
256
|
+
try {
|
|
257
|
+
await client.close({ graceMs: 500 });
|
|
258
|
+
} catch {
|
|
259
|
+
// close is best-effort
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
private buildClient(config: ResolvedServerConfig): McpClient {
|
|
265
|
+
const transport =
|
|
266
|
+
config.kind === "stdio"
|
|
267
|
+
? new StdioTransport({
|
|
268
|
+
command: config.command as string,
|
|
269
|
+
args: config.args ?? [],
|
|
270
|
+
...(config.cwd !== undefined ? { cwd: config.cwd } : {}),
|
|
271
|
+
...(config.env !== undefined ? { env: config.env } : {}),
|
|
272
|
+
})
|
|
273
|
+
: new HttpTransport({
|
|
274
|
+
url: config.url as string,
|
|
275
|
+
...(config.headers !== undefined ? { extraHeaders: config.headers } : {}),
|
|
276
|
+
});
|
|
277
|
+
return new McpClient({
|
|
278
|
+
transport,
|
|
279
|
+
server: { key: config.name, label: config.name },
|
|
280
|
+
clientInfo: { name: "pi", version: "mcp-client-bridge" },
|
|
281
|
+
defaults: { timeoutMs: config.timeoutMs },
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
private async connect(state: ServerState): Promise<void> {
|
|
286
|
+
const { config } = state;
|
|
287
|
+
try {
|
|
288
|
+
if (config.wantsOAuth) {
|
|
289
|
+
this.notify(
|
|
290
|
+
`mcp "${state.name}": oauth config is not supported by this bridge yet; connect may fail with 401`,
|
|
291
|
+
"warning",
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
const client = this.buildClient(config);
|
|
295
|
+
const ops = createOps(client);
|
|
296
|
+
state.client = client;
|
|
297
|
+
state.ops = ops;
|
|
298
|
+
|
|
299
|
+
// Best-effort server/discover for instructions used as namespace text.
|
|
300
|
+
try {
|
|
301
|
+
const discovered = await client.discover({ timeoutMs: 10_000 });
|
|
302
|
+
if (discovered.kind === "ok") {
|
|
303
|
+
const instructions = discovered.value.instructions;
|
|
304
|
+
if (typeof instructions === "string" && instructions.trim() !== "") {
|
|
305
|
+
state.description = config.description ?? instructions.split("\n")[0];
|
|
306
|
+
state.instructions = instructions;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
} catch {
|
|
310
|
+
// discover is optional metadata
|
|
311
|
+
}
|
|
312
|
+
if (state.description === undefined && config.description !== undefined) {
|
|
313
|
+
state.description = config.description;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const listed = await ops.tools.listAll({ maxItems: 10_000 });
|
|
317
|
+
if (listed.kind === "ok") {
|
|
318
|
+
this.registerTools(state, listed.value.items);
|
|
319
|
+
for (const warning of listed.value.warnings) {
|
|
320
|
+
this.notify(`mcp "${state.name}": ${warning}`, "warning");
|
|
321
|
+
}
|
|
322
|
+
} else if (
|
|
323
|
+
listed.kind === "capability-absent" ||
|
|
324
|
+
(listed.kind === "jsonrpc-error" && listed.code === -32601)
|
|
325
|
+
) {
|
|
326
|
+
// Server without a tools capability: valid, just nothing to register.
|
|
327
|
+
} else {
|
|
328
|
+
throw new Error(describeOutcome(listed));
|
|
329
|
+
}
|
|
330
|
+
state.status = "connected";
|
|
331
|
+
state.error = undefined;
|
|
332
|
+
} catch (err) {
|
|
333
|
+
state.status = "error";
|
|
334
|
+
state.error = err instanceof Error ? err.message : String(err);
|
|
335
|
+
await this.teardown(state);
|
|
336
|
+
this.notify(`mcp "${state.name}": ${state.error}`, "error");
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
private registerTools(state: ServerState, entries: readonly ToolEntry[]): void {
|
|
341
|
+
const usable = entries.filter((e) => typeof e.name === "string" && e.name !== "");
|
|
342
|
+
const names = assignToolNames(state.name, usable.map((e) => e.name));
|
|
343
|
+
for (const entry of usable) {
|
|
344
|
+
const piName = names.get(entry.name) as string;
|
|
345
|
+
if (state.registeredTools.has(piName)) continue;
|
|
346
|
+
const exposure = toolExposureFor(state.config, entry.name);
|
|
347
|
+
const toolDescription =
|
|
348
|
+
typeof entry.tool.description === "string" ? entry.tool.description : "";
|
|
349
|
+
const annotations = annotationsOf(entry);
|
|
350
|
+
this.pi.registerTool({
|
|
351
|
+
name: piName,
|
|
352
|
+
label: `${state.name}: ${entry.name}`,
|
|
353
|
+
description: toolDescription || `MCP tool ${entry.name} on ${state.name}`,
|
|
354
|
+
parameters: inputSchemaOf(entry),
|
|
355
|
+
exposure,
|
|
356
|
+
namespace: {
|
|
357
|
+
name: `mcp__${sanitizeNamePart(state.name)}`,
|
|
358
|
+
aliases: [state.name, state.name.replace(/-/g, "_")],
|
|
359
|
+
...(state.description !== undefined ? { description: state.description } : {}),
|
|
360
|
+
...(state.instructions !== undefined ? { instructions: state.instructions } : {}),
|
|
361
|
+
},
|
|
362
|
+
...(annotations !== undefined ? { annotations } : {}),
|
|
363
|
+
promptSnippet: toolDescription.split("\n")[0] ?? "",
|
|
364
|
+
execute: (_id, params, signal, onUpdate) =>
|
|
365
|
+
this.callTool(state.name, entry.name, params, signal, onUpdate),
|
|
366
|
+
});
|
|
367
|
+
state.registeredTools.add(piName);
|
|
368
|
+
state.exposures.add(exposure);
|
|
369
|
+
}
|
|
370
|
+
state.toolCount = state.registeredTools.size;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
private async callTool(
|
|
374
|
+
serverName: string,
|
|
375
|
+
toolName: string,
|
|
376
|
+
params: Record<string, unknown>,
|
|
377
|
+
signal: AbortSignal | undefined,
|
|
378
|
+
onUpdate: ((partial: ToolResult) => void) | undefined,
|
|
379
|
+
): Promise<ToolResult> {
|
|
380
|
+
let state = this.states.get(serverName);
|
|
381
|
+
if (!state?.ops || state.status !== "connected") {
|
|
382
|
+
throw new Error(
|
|
383
|
+
`MCP server "${serverName}" is not connected (status: ${state?.status ?? "unknown"}${
|
|
384
|
+
state?.error ? `, ${state.error}` : ""
|
|
385
|
+
}). Run /mcp reconnect ${serverName}.`,
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
const progress = (p: unknown) => {
|
|
389
|
+
const msg = (p as { message?: unknown })?.message;
|
|
390
|
+
if (typeof msg === "string" && onUpdate) {
|
|
391
|
+
onUpdate({
|
|
392
|
+
content: [{ type: "text", text: `${serverName}/${toolName}: ${msg}` }],
|
|
393
|
+
details: { server: serverName, tool: toolName },
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
let outcome = await state.ops.tools.call(toolName, params, {
|
|
398
|
+
validateInput: false, // Pi already validated against the same schema
|
|
399
|
+
allowUnvalidated: true,
|
|
400
|
+
...(signal !== undefined ? { signal } : {}),
|
|
401
|
+
onProgress: progress,
|
|
402
|
+
});
|
|
403
|
+
if (
|
|
404
|
+
outcome.kind === "transport-failure" &&
|
|
405
|
+
RETRY_KINDS.has(outcome.failure.kind) &&
|
|
406
|
+
!(signal?.aborted ?? false)
|
|
407
|
+
) {
|
|
408
|
+
// Dropped connection: reconnect once and retry, like built-in MCP does.
|
|
409
|
+
try {
|
|
410
|
+
state = await this.reconnect(serverName);
|
|
411
|
+
} catch {
|
|
412
|
+
// fall through to reporting the original outcome
|
|
413
|
+
}
|
|
414
|
+
if (state.ops && state.status === "connected") {
|
|
415
|
+
outcome = await state.ops.tools.call(toolName, params, {
|
|
416
|
+
validateInput: false,
|
|
417
|
+
allowUnvalidated: true,
|
|
418
|
+
...(signal !== undefined ? { signal } : {}),
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
return this.outcomeToResult(serverName, toolName, outcome);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
private outcomeToResult(
|
|
426
|
+
serverName: string,
|
|
427
|
+
toolName: string,
|
|
428
|
+
outcome: Outcome<ToolCallResult>,
|
|
429
|
+
): ToolResult {
|
|
430
|
+
const details = { server: serverName, tool: toolName };
|
|
431
|
+
if (outcome.kind === "ok") {
|
|
432
|
+
const { value } = outcome;
|
|
433
|
+
return {
|
|
434
|
+
content: convertBlocks(value.content),
|
|
435
|
+
details: { ...details, validation: value.validation.status },
|
|
436
|
+
...(value.structuredContent !== undefined ? { structuredContent: value.structuredContent } : {}),
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
if (outcome.kind === "tool-isError") {
|
|
440
|
+
const raw = outcome.result;
|
|
441
|
+
return {
|
|
442
|
+
content: convertBlocks(normalizeContent(raw.content)),
|
|
443
|
+
details,
|
|
444
|
+
isError: true,
|
|
445
|
+
...(raw.structuredContent !== undefined ? { structuredContent: raw.structuredContent } : {}),
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
throw new Error(`mcp ${serverName}/${toolName}: ${describeOutcome(outcome)}`);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* Mirror of built-in behavior: once a codemode-exposure server connects,
|
|
453
|
+
* activate codemode; for deferred, activate tool_search.
|
|
454
|
+
*/
|
|
455
|
+
ensureReachTools(): void {
|
|
456
|
+
const exposures = new Set<Exposure>();
|
|
457
|
+
for (const s of this.states.values()) {
|
|
458
|
+
if (s.status === "connected") for (const e of s.exposures) exposures.add(e);
|
|
459
|
+
}
|
|
460
|
+
const autoEnable = this.pi.getSettings?.()?.autoEnableCodemode;
|
|
461
|
+
const all = this.pi.getAllTools();
|
|
462
|
+
const active = new Set(this.pi.getActiveTools());
|
|
463
|
+
const wanted: string[] = [];
|
|
464
|
+
if (exposures.has("codemode") && autoEnable !== false) wanted.push("codemode");
|
|
465
|
+
if (exposures.has("deferred")) wanted.push("tool_search");
|
|
466
|
+
const toAdd = wanted.filter((n) => all.some((t) => t.name === n) && !active.has(n));
|
|
467
|
+
if (toAdd.length > 0) this.pi.setActiveTools([...active, ...toAdd]);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
statusLines(): string[] {
|
|
471
|
+
if (this.states.size === 0) return ["No MCP servers configured."];
|
|
472
|
+
return [...this.states.values()].map((s) => {
|
|
473
|
+
const base = `${s.name} (${s.config.kind}, ${s.config.source})`;
|
|
474
|
+
switch (s.status) {
|
|
475
|
+
case "connected":
|
|
476
|
+
return `${base}: connected, ${s.toolCount} tool${s.toolCount === 1 ? "" : "s"}`;
|
|
477
|
+
case "connecting":
|
|
478
|
+
return `${base}: connecting…`;
|
|
479
|
+
case "disabled":
|
|
480
|
+
return `${base}: disabled${s.error ? ` (${s.error})` : ""}`;
|
|
481
|
+
case "error":
|
|
482
|
+
return `${base}: error: ${s.error ?? "unknown"}`;
|
|
483
|
+
}
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
}
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mcp.json discovery, validation, and merging.
|
|
3
|
+
*
|
|
4
|
+
* Mirrors Pi's built-in rules (docs/mcp.md): user-level servers live in
|
|
5
|
+
* ~/.pi/agent/mcp.json, project servers in .pi/mcp.json (trusted projects
|
|
6
|
+
* only), a project entry replaces a user entry, and a project entry without
|
|
7
|
+
* command/url/type overlays only enabled/exposure/toolExposure.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { execSync } from "node:child_process";
|
|
11
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import type { McpServerEntry } from "./pi-api.ts";
|
|
14
|
+
|
|
15
|
+
export type Exposure = "direct" | "codemode" | "deferred" | "hidden";
|
|
16
|
+
|
|
17
|
+
export interface ResolvedServerConfig {
|
|
18
|
+
readonly name: string;
|
|
19
|
+
readonly source: "user" | "project" | "extension";
|
|
20
|
+
readonly kind: "stdio" | "http";
|
|
21
|
+
readonly command?: string;
|
|
22
|
+
readonly args?: readonly string[];
|
|
23
|
+
readonly env?: Record<string, string>;
|
|
24
|
+
readonly cwd?: string;
|
|
25
|
+
readonly url?: string;
|
|
26
|
+
readonly headers?: Record<string, string>;
|
|
27
|
+
readonly enabled: boolean;
|
|
28
|
+
readonly exposure: Exposure;
|
|
29
|
+
readonly toolExposure?: Record<string, string>;
|
|
30
|
+
readonly description?: string;
|
|
31
|
+
readonly timeoutMs: number;
|
|
32
|
+
/** Present when the entry sets `oauth`: not supported by this bridge yet. */
|
|
33
|
+
readonly wantsOAuth: boolean;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface LoadedConfigs {
|
|
37
|
+
readonly servers: Map<string, ResolvedServerConfig>;
|
|
38
|
+
readonly warnings: string[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface LoadOptions {
|
|
42
|
+
readonly homeDir: string;
|
|
43
|
+
readonly cwd: string;
|
|
44
|
+
readonly projectTrusted: boolean;
|
|
45
|
+
/** Environment for `${VAR}` interpolation; defaults to process.env. */
|
|
46
|
+
readonly env?: Record<string, string | undefined>;
|
|
47
|
+
/** Runner for `!command` values; injectable for tests. */
|
|
48
|
+
readonly exec?: (command: string) => string;
|
|
49
|
+
/** Registered (extension) servers; file entries win on name collision. */
|
|
50
|
+
readonly registered?: ReadonlyMap<string, McpServerEntry>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const NAME_RE = /^[A-Za-z0-9_-]+$/;
|
|
54
|
+
const EXPOSURES = new Set(["direct", "codemode", "codemode-deferred", "deferred", "hidden"]);
|
|
55
|
+
const DEFAULT_TIMEOUT_MS = 60_000;
|
|
56
|
+
|
|
57
|
+
export function normalizeExposure(value: string | undefined): Exposure {
|
|
58
|
+
switch (value) {
|
|
59
|
+
case "direct":
|
|
60
|
+
case "deferred":
|
|
61
|
+
case "hidden":
|
|
62
|
+
return value;
|
|
63
|
+
default:
|
|
64
|
+
return "codemode"; // codemode-deferred and unknown values land here
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Normalized identity: names differing only in `-` vs `_` are the same server. */
|
|
69
|
+
export function serverKey(name: string): string {
|
|
70
|
+
return name.replace(/-/g, "_");
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function defaultExec(command: string): string {
|
|
74
|
+
return execSync(command, { encoding: "utf8", timeout: 10_000 }).trim();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Interpolate one config value: `!command` (whole value) runs a command,
|
|
79
|
+
* `${VAR}` reads from env. Returns undefined warnings-free value or the value
|
|
80
|
+
* with failures replaced by "".
|
|
81
|
+
*/
|
|
82
|
+
export function interpolate(
|
|
83
|
+
value: string,
|
|
84
|
+
env: Record<string, string | undefined>,
|
|
85
|
+
exec: (command: string) => string,
|
|
86
|
+
warnings: string[],
|
|
87
|
+
where: string,
|
|
88
|
+
): string {
|
|
89
|
+
if (value.startsWith("!")) {
|
|
90
|
+
try {
|
|
91
|
+
return exec(value.slice(1));
|
|
92
|
+
} catch (err) {
|
|
93
|
+
warnings.push(`${where}: command failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
94
|
+
return "";
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_m, name: string) => {
|
|
98
|
+
const v = env[name];
|
|
99
|
+
if (v === undefined) warnings.push(`${where}: environment variable ${name} is not set`);
|
|
100
|
+
return v ?? "";
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function expandTilde(path: string, homeDir: string): string {
|
|
105
|
+
if (path === "~") return homeDir;
|
|
106
|
+
if (path.startsWith("~/")) return join(homeDir, path.slice(2));
|
|
107
|
+
return path;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function interpolateRecord(
|
|
111
|
+
record: Record<string, string>,
|
|
112
|
+
env: Record<string, string | undefined>,
|
|
113
|
+
exec: (command: string) => string,
|
|
114
|
+
warnings: string[],
|
|
115
|
+
where: string,
|
|
116
|
+
): Record<string, string> {
|
|
117
|
+
const out: Record<string, string> = {};
|
|
118
|
+
for (const [k, v] of Object.entries(record)) {
|
|
119
|
+
out[k] = interpolate(v, env, exec, warnings, `${where}.${k}`);
|
|
120
|
+
}
|
|
121
|
+
return out;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
interface RawEntry {
|
|
125
|
+
readonly name: string;
|
|
126
|
+
readonly raw: McpServerEntry;
|
|
127
|
+
readonly source: "user" | "project" | "extension";
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function readFileEntries(path: string, source: "user" | "project", warnings: string[]): RawEntry[] {
|
|
131
|
+
if (!existsSync(path)) return [];
|
|
132
|
+
let parsed: unknown;
|
|
133
|
+
try {
|
|
134
|
+
parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
135
|
+
} catch (err) {
|
|
136
|
+
warnings.push(`${path}: ${err instanceof Error ? err.message : String(err)}`);
|
|
137
|
+
return [];
|
|
138
|
+
}
|
|
139
|
+
const servers = (parsed as { mcpServers?: unknown })?.mcpServers;
|
|
140
|
+
if (servers === undefined || servers === null) return [];
|
|
141
|
+
if (typeof servers !== "object" || Array.isArray(servers)) {
|
|
142
|
+
warnings.push(`${path}: "mcpServers" must be an object`);
|
|
143
|
+
return [];
|
|
144
|
+
}
|
|
145
|
+
return Object.entries(servers as Record<string, unknown>).map(([name, raw]) => ({
|
|
146
|
+
name,
|
|
147
|
+
raw: (raw ?? {}) as McpServerEntry,
|
|
148
|
+
source,
|
|
149
|
+
}));
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function isPartialOverride(raw: McpServerEntry): boolean {
|
|
153
|
+
return raw.command === undefined && raw.url === undefined && raw.type === undefined;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function resolveEntry(
|
|
157
|
+
entry: RawEntry,
|
|
158
|
+
opts: LoadOptions,
|
|
159
|
+
warnings: string[],
|
|
160
|
+
): ResolvedServerConfig | undefined {
|
|
161
|
+
const { name, raw, source } = entry;
|
|
162
|
+
const where = `${source} server "${name}"`;
|
|
163
|
+
if (!NAME_RE.test(name)) {
|
|
164
|
+
warnings.push(`${where}: invalid name (allowed: letters, digits, _, -)`);
|
|
165
|
+
return undefined;
|
|
166
|
+
}
|
|
167
|
+
if (raw.type !== undefined && raw.type !== "stdio" && raw.type !== "http" && raw.type !== "streamable-http") {
|
|
168
|
+
warnings.push(`${where}: unsupported type ${JSON.stringify(raw.type)} (sse is not supported)`);
|
|
169
|
+
return undefined;
|
|
170
|
+
}
|
|
171
|
+
if (raw.exposure !== undefined && !EXPOSURES.has(raw.exposure)) {
|
|
172
|
+
warnings.push(`${where}: unknown exposure ${JSON.stringify(raw.exposure)}, using "codemode"`);
|
|
173
|
+
}
|
|
174
|
+
for (const [pattern, value] of Object.entries(raw.toolExposure ?? {})) {
|
|
175
|
+
if (!EXPOSURES.has(value)) {
|
|
176
|
+
warnings.push(`${where}: unknown toolExposure ${JSON.stringify(value)} for ${pattern}`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const env = opts.env ?? process.env;
|
|
181
|
+
const exec = opts.exec ?? defaultExec;
|
|
182
|
+
|
|
183
|
+
const base = {
|
|
184
|
+
name,
|
|
185
|
+
source,
|
|
186
|
+
enabled: raw.enabled !== false,
|
|
187
|
+
exposure: normalizeExposure(raw.exposure),
|
|
188
|
+
timeoutMs: raw.timeout !== undefined && raw.timeout > 0 ? raw.timeout * 1000 : DEFAULT_TIMEOUT_MS,
|
|
189
|
+
wantsOAuth: raw.oauth !== undefined,
|
|
190
|
+
...(raw.toolExposure !== undefined ? { toolExposure: raw.toolExposure } : {}),
|
|
191
|
+
...(raw.description !== undefined ? { description: raw.description } : {}),
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
if (raw.command !== undefined) {
|
|
195
|
+
return {
|
|
196
|
+
...base,
|
|
197
|
+
kind: "stdio",
|
|
198
|
+
command: expandTilde(raw.command, opts.homeDir),
|
|
199
|
+
args: (raw.args ?? []).map((a) => expandTilde(a, opts.homeDir)),
|
|
200
|
+
...(raw.env !== undefined
|
|
201
|
+
? { env: interpolateRecord(raw.env, env, exec, warnings, where) }
|
|
202
|
+
: {}),
|
|
203
|
+
...(raw.cwd !== undefined ? { cwd: expandTilde(raw.cwd, opts.homeDir) } : {}),
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
if (raw.url !== undefined) {
|
|
207
|
+
return {
|
|
208
|
+
...base,
|
|
209
|
+
kind: "http",
|
|
210
|
+
url: raw.url,
|
|
211
|
+
...(raw.headers !== undefined
|
|
212
|
+
? { headers: interpolateRecord(raw.headers, env, exec, warnings, where) }
|
|
213
|
+
: {}),
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
warnings.push(`${where}: needs "command" (stdio) or "url" (http)`);
|
|
217
|
+
return undefined;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Directory holding mcp.json: PI_CODING_AGENT_DIR when set, else
|
|
222
|
+
* ~/.pi/agent. Mirrors Pi's own resolution (docs/environment-variables.md).
|
|
223
|
+
*/
|
|
224
|
+
export function agentDir(env: Record<string, string | undefined>, homeDir: string): string {
|
|
225
|
+
const override = env.PI_CODING_AGENT_DIR;
|
|
226
|
+
if (typeof override === "string" && override !== "") return override;
|
|
227
|
+
return join(homeDir, ".pi", "agent");
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Load and merge user-level and project-level mcp.json, plus servers
|
|
232
|
+
* registered by other extensions. File entries take precedence over
|
|
233
|
+
* registered ones; project entries take precedence over user entries.
|
|
234
|
+
*/
|
|
235
|
+
export function loadServerConfigs(opts: LoadOptions): LoadedConfigs {
|
|
236
|
+
const warnings: string[] = [];
|
|
237
|
+
const merged = new Map<string, ResolvedServerConfig>();
|
|
238
|
+
const seenKeys = new Map<string, string>(); // normalized key -> first name
|
|
239
|
+
|
|
240
|
+
const userEntries = readFileEntries(
|
|
241
|
+
join(agentDir(opts.env ?? (process.env as Record<string, string | undefined>), opts.homeDir), "mcp.json"),
|
|
242
|
+
"user",
|
|
243
|
+
warnings,
|
|
244
|
+
);
|
|
245
|
+
const projectEntries = opts.projectTrusted
|
|
246
|
+
? readFileEntries(join(opts.cwd, ".pi", "mcp.json"), "project", warnings)
|
|
247
|
+
: [];
|
|
248
|
+
|
|
249
|
+
// Extension-registered servers first: file config overrides them by name.
|
|
250
|
+
if (opts.registered) {
|
|
251
|
+
for (const [name, raw] of opts.registered) {
|
|
252
|
+
const cfg = resolveEntry({ name, raw, source: "extension" }, opts, warnings);
|
|
253
|
+
if (cfg) {
|
|
254
|
+
merged.set(name, cfg);
|
|
255
|
+
seenKeys.set(serverKey(name), name);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const applyFile = (entries: RawEntry[], overlayOnly: boolean) => {
|
|
261
|
+
for (const entry of entries) {
|
|
262
|
+
const key = serverKey(entry.name);
|
|
263
|
+
const priorName = seenKeys.get(key);
|
|
264
|
+
if (priorName !== undefined && priorName !== entry.name) {
|
|
265
|
+
warnings.push(
|
|
266
|
+
`${entry.source} server "${entry.name}": conflicts with "${priorName}" (names differ only in -/_), skipping`,
|
|
267
|
+
);
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
if (overlayOnly && isPartialOverride(entry.raw)) {
|
|
271
|
+
const base = merged.get(entry.name);
|
|
272
|
+
if (!base) {
|
|
273
|
+
warnings.push(
|
|
274
|
+
`project server "${entry.name}": partial override without a matching user-level server`,
|
|
275
|
+
);
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
merged.set(entry.name, {
|
|
279
|
+
...base,
|
|
280
|
+
enabled: entry.raw.enabled !== undefined ? entry.raw.enabled !== false : base.enabled,
|
|
281
|
+
exposure: entry.raw.exposure !== undefined ? normalizeExposure(entry.raw.exposure) : base.exposure,
|
|
282
|
+
...(entry.raw.toolExposure !== undefined ? { toolExposure: entry.raw.toolExposure } : {}),
|
|
283
|
+
});
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
const cfg = resolveEntry(entry, opts, warnings);
|
|
287
|
+
if (cfg) {
|
|
288
|
+
merged.set(entry.name, cfg);
|
|
289
|
+
seenKeys.set(key, entry.name);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
|
|
294
|
+
applyFile(userEntries, false);
|
|
295
|
+
applyFile(projectEntries, true);
|
|
296
|
+
|
|
297
|
+
return { servers: merged, warnings };
|
|
298
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Convert MCP content blocks to Pi tool-result content.
|
|
3
|
+
*
|
|
4
|
+
* Pi's built-in MCP support truncates long text and offloads binary to temp
|
|
5
|
+
* files. This bridge truncates text inline at the same order of magnitude and
|
|
6
|
+
* passes images through as Pi image blocks; everything else degrades to a
|
|
7
|
+
* text description so the model always sees something.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { ContentBlock } from "../dist/ops/index.js";
|
|
11
|
+
import type { PiContent } from "./pi-api.ts";
|
|
12
|
+
|
|
13
|
+
/** Per-text-block cap, matching Pi's generic tool-output limit of ~50 KB. */
|
|
14
|
+
export const MAX_TEXT_CHARS = 50_000;
|
|
15
|
+
|
|
16
|
+
export function truncateText(text: string): string {
|
|
17
|
+
if (text.length <= MAX_TEXT_CHARS) return text;
|
|
18
|
+
return `${text.slice(0, MAX_TEXT_CHARS)}\n…${text.length - MAX_TEXT_CHARS} chars truncated…`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function asRecord(v: unknown): Record<string, unknown> | undefined {
|
|
22
|
+
return typeof v === "object" && v !== null ? (v as Record<string, unknown>) : undefined;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function textBlock(text: unknown): PiContent {
|
|
26
|
+
return { type: "text", text: truncateText(typeof text === "string" ? text : JSON.stringify(text)) };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function convertBlocks(blocks: readonly ContentBlock[]): PiContent[] {
|
|
30
|
+
const out: PiContent[] = [];
|
|
31
|
+
for (const block of blocks) {
|
|
32
|
+
const raw = asRecord(block.raw) ?? {};
|
|
33
|
+
switch (block.type) {
|
|
34
|
+
case "text":
|
|
35
|
+
out.push(textBlock(raw.text));
|
|
36
|
+
break;
|
|
37
|
+
case "image": {
|
|
38
|
+
const data = raw.data;
|
|
39
|
+
const mimeType = raw.mimeType;
|
|
40
|
+
if (typeof data === "string" && typeof mimeType === "string") {
|
|
41
|
+
out.push({ type: "image", data, mimeType });
|
|
42
|
+
} else {
|
|
43
|
+
out.push(textBlock("[image block with invalid data omitted]"));
|
|
44
|
+
}
|
|
45
|
+
break;
|
|
46
|
+
}
|
|
47
|
+
case "audio":
|
|
48
|
+
out.push(textBlock(`[audio${typeof raw.mimeType === "string" ? ` ${raw.mimeType}` : ""} omitted]`));
|
|
49
|
+
break;
|
|
50
|
+
case "resource_link": {
|
|
51
|
+
const name = typeof raw.name === "string" ? raw.name : undefined;
|
|
52
|
+
const uri = typeof raw.uri === "string" ? raw.uri : "(no uri)";
|
|
53
|
+
out.push(textBlock(`Resource${name ? ` "${name}"` : ""}: ${uri}`));
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
case "resource": {
|
|
57
|
+
const resource = asRecord(raw.resource) ?? raw;
|
|
58
|
+
const uri = typeof resource.uri === "string" ? resource.uri : undefined;
|
|
59
|
+
if (typeof resource.text === "string") {
|
|
60
|
+
out.push(textBlock(resource.text));
|
|
61
|
+
} else if (
|
|
62
|
+
typeof resource.blob === "string" &&
|
|
63
|
+
typeof resource.mimeType === "string" &&
|
|
64
|
+
resource.mimeType.startsWith("image/")
|
|
65
|
+
) {
|
|
66
|
+
out.push({ type: "image", data: resource.blob, mimeType: resource.mimeType });
|
|
67
|
+
} else {
|
|
68
|
+
out.push(textBlock(`[binary resource${uri ? ` ${uri}` : ""} omitted]`));
|
|
69
|
+
}
|
|
70
|
+
break;
|
|
71
|
+
}
|
|
72
|
+
default:
|
|
73
|
+
out.push(textBlock(block.raw));
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (out.length === 0) out.push(textBlock("(no content)"));
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pi extension entry: replaces Pi's built-in MCP session support with a
|
|
3
|
+
* bridge implemented on this library (@jangmanj/mcp-client).
|
|
4
|
+
*
|
|
5
|
+
* Registering the /mcp command is what makes Pi stand down its built-in MCP
|
|
6
|
+
* extension for sessions (docs/mcp.md#replace-the-built-in-mcp-support), so
|
|
7
|
+
* this extension reads mcp.json itself and owns all connections.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { McpBridge } from "./bridge.ts";
|
|
12
|
+
import { loadServerConfigs, type ResolvedServerConfig } from "./config.ts";
|
|
13
|
+
import type { ExtensionAPI, McpServerEntry, SessionContext, Ui } from "./pi-api.ts";
|
|
14
|
+
|
|
15
|
+
/** Tolerantly unwrap pi.getMcpServers() / mcp_servers_change event shapes. */
|
|
16
|
+
export function registeredServersOf(x: unknown): Map<string, McpServerEntry> {
|
|
17
|
+
const out = new Map<string, McpServerEntry>();
|
|
18
|
+
const put = (name: unknown, value: unknown) => {
|
|
19
|
+
if (typeof name !== "string" || name === "") return;
|
|
20
|
+
const rec = (typeof value === "object" && value !== null ? value : {}) as Record<string, unknown>;
|
|
21
|
+
const config = (typeof rec.config === "object" && rec.config !== null ? rec.config : rec) as McpServerEntry;
|
|
22
|
+
out.set(name, config);
|
|
23
|
+
};
|
|
24
|
+
if (x instanceof Map) {
|
|
25
|
+
for (const [k, v] of x) put(k, v);
|
|
26
|
+
} else if (Array.isArray(x)) {
|
|
27
|
+
for (const item of x) {
|
|
28
|
+
if (Array.isArray(item)) put(item[0], item[1]);
|
|
29
|
+
else if (typeof item === "object" && item !== null) {
|
|
30
|
+
const rec = item as Record<string, unknown>;
|
|
31
|
+
put(rec.name, rec.config ?? rec);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
} else if (typeof x === "object" && x !== null) {
|
|
35
|
+
for (const [k, v] of Object.entries(x)) put(k, v);
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export default function (pi: ExtensionAPI) {
|
|
41
|
+
// Bridge notifications go to the most recent session context's UI.
|
|
42
|
+
let currentUi: Ui | undefined;
|
|
43
|
+
const bridge = new McpBridge({
|
|
44
|
+
pi,
|
|
45
|
+
notify: (message, level) => currentUi?.notify(message, level),
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
// Registering /mcp replaces built-in MCP support for sessions.
|
|
49
|
+
pi.registerCommand("mcp", {
|
|
50
|
+
description: "MCP servers (mcp-client bridge): /mcp [list] | /mcp reconnect <name>",
|
|
51
|
+
handler: async (args, ctx) => {
|
|
52
|
+
const [sub, ...rest] = args.trim().split(/\s+/).filter(Boolean);
|
|
53
|
+
if (sub === undefined || sub === "list") {
|
|
54
|
+
ctx.ui.notify(bridge.statusLines().join("\n"), "info");
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (sub === "reconnect" && rest[0] !== undefined) {
|
|
58
|
+
try {
|
|
59
|
+
const state = await bridge.reconnect(rest[0]);
|
|
60
|
+
ctx.ui.notify(
|
|
61
|
+
state.status === "connected"
|
|
62
|
+
? `mcp "${state.name}": connected, ${state.toolCount} tools`
|
|
63
|
+
: `mcp "${state.name}": ${state.error ?? "failed"}`,
|
|
64
|
+
state.status === "connected" ? "info" : "error",
|
|
65
|
+
);
|
|
66
|
+
} catch (err) {
|
|
67
|
+
ctx.ui.notify(err instanceof Error ? err.message : String(err), "error");
|
|
68
|
+
}
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
ctx.ui.notify("Usage: /mcp [list] | /mcp reconnect <name>", "info");
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
let fileConfigs = new Map<string, ResolvedServerConfig>();
|
|
76
|
+
|
|
77
|
+
const loadAndSync = (ctx: SessionContext) => {
|
|
78
|
+
const { servers, warnings } = loadServerConfigs({
|
|
79
|
+
homeDir: homedir(),
|
|
80
|
+
cwd: ctx.cwd,
|
|
81
|
+
projectTrusted: safeTrusted(ctx),
|
|
82
|
+
registered: registeredServersOf(pi.getMcpServers()),
|
|
83
|
+
});
|
|
84
|
+
fileConfigs = servers;
|
|
85
|
+
for (const warning of warnings) ctx.ui.notify(`mcp: ${warning}`, "warning");
|
|
86
|
+
bridge.sync(servers);
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
90
|
+
currentUi = ctx.ui;
|
|
91
|
+
loadAndSync(ctx);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
pi.on("mcp_servers_change", async (event, ctx) => {
|
|
95
|
+
currentUi = ctx.ui; const merged = new Map(fileConfigs);
|
|
96
|
+
for (const [name, raw] of registeredServersOf(event.servers)) {
|
|
97
|
+
if (!merged.has(name)) {
|
|
98
|
+
const { servers } = loadServerConfigs({
|
|
99
|
+
homeDir: homedir(),
|
|
100
|
+
cwd: ctx.cwd,
|
|
101
|
+
projectTrusted: false,
|
|
102
|
+
registered: new Map([[name, raw]]),
|
|
103
|
+
});
|
|
104
|
+
const cfg = servers.get(name);
|
|
105
|
+
if (cfg) merged.set(name, cfg);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
bridge.sync(merged);
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
pi.on("session_shutdown", async (_event, ctx) => {
|
|
112
|
+
currentUi = ctx.ui;
|
|
113
|
+
await bridge.closeAll();
|
|
114
|
+
fileConfigs = new Map();
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
pi.on("before_agent_start", async (event, _ctx) => {
|
|
118
|
+
// Direct-exposure tools must be declared in the first request: wait for
|
|
119
|
+
// those servers, bounded, like built-in MCP does.
|
|
120
|
+
await bridge.waitForPending((s) => s.config.exposure === "direct");
|
|
121
|
+
|
|
122
|
+
const sections = event.systemPromptOptions?.sections;
|
|
123
|
+
if (!sections) return;
|
|
124
|
+
const lines = bridge
|
|
125
|
+
.list()
|
|
126
|
+
.filter((s) => s.config.enabled && s.config.exposure !== "direct" && s.config.exposure !== "hidden")
|
|
127
|
+
.map((s) => {
|
|
128
|
+
const reach = s.config.exposure === "deferred" ? "tool_search" : "codemode";
|
|
129
|
+
const desc = s.description ?? "MCP server";
|
|
130
|
+
return `- mcp__${s.name.replace(/-/g, "_")}: ${desc} (tools reachable via ${reach})`;
|
|
131
|
+
});
|
|
132
|
+
if (lines.length > 0) sections.mcp_servers = lines.join("\n");
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
pi.on("tool_call", async (event, _ctx) => {
|
|
136
|
+
// Late registration: finish connecting servers before codemode /
|
|
137
|
+
// tool_search / direct mcp__* calls run.
|
|
138
|
+
if (
|
|
139
|
+
event.toolName === "codemode" ||
|
|
140
|
+
event.toolName === "tool_search" ||
|
|
141
|
+
event.toolName.startsWith("mcp__")
|
|
142
|
+
) {
|
|
143
|
+
await bridge.waitForPending();
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function safeTrusted(ctx: SessionContext): boolean {
|
|
149
|
+
try {
|
|
150
|
+
return ctx.isProjectTrusted();
|
|
151
|
+
} catch {
|
|
152
|
+
return false;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal structural types for the Pi extension API surface this bridge uses.
|
|
3
|
+
*
|
|
4
|
+
* This package deliberately does not depend on @earendil-works/pi-coding-agent
|
|
5
|
+
* (see scripts/check-forbidden.mjs): Pi injects its own copies of host packages
|
|
6
|
+
* at runtime, and the factory receives everything through the `pi` argument.
|
|
7
|
+
* The declarations below cover only what the bridge touches. If Pi widens its
|
|
8
|
+
* API, these stay valid; if Pi narrows it, jiti will fail loudly at load.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export type PiContent =
|
|
12
|
+
| { type: "text"; text: string }
|
|
13
|
+
| { type: "image"; data: string; mimeType: string };
|
|
14
|
+
|
|
15
|
+
export interface ToolResult {
|
|
16
|
+
content: PiContent[];
|
|
17
|
+
details?: unknown;
|
|
18
|
+
isError?: boolean;
|
|
19
|
+
structuredContent?: unknown;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type ToolExposure = "direct" | "model-only" | "codemode" | "deferred" | "hidden";
|
|
23
|
+
|
|
24
|
+
export interface ToolAnnotations {
|
|
25
|
+
readOnlyHint?: boolean;
|
|
26
|
+
destructiveHint?: boolean;
|
|
27
|
+
idempotentHint?: boolean;
|
|
28
|
+
openWorldHint?: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface ToolNamespace {
|
|
32
|
+
name: string;
|
|
33
|
+
aliases?: string[];
|
|
34
|
+
description?: string;
|
|
35
|
+
instructions?: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export type OnUpdate = (partial: ToolResult) => void;
|
|
39
|
+
|
|
40
|
+
export interface ToolDefinition {
|
|
41
|
+
name: string;
|
|
42
|
+
label: string;
|
|
43
|
+
description: string;
|
|
44
|
+
parameters: Record<string, unknown>;
|
|
45
|
+
exposure?: ToolExposure;
|
|
46
|
+
namespace?: ToolNamespace;
|
|
47
|
+
annotations?: ToolAnnotations;
|
|
48
|
+
promptSnippet?: string;
|
|
49
|
+
execute(
|
|
50
|
+
toolCallId: string,
|
|
51
|
+
params: Record<string, unknown>,
|
|
52
|
+
signal: AbortSignal | undefined,
|
|
53
|
+
onUpdate: OnUpdate | undefined,
|
|
54
|
+
ctx: unknown,
|
|
55
|
+
): Promise<ToolResult>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Shape of one `mcpServers` entry in mcp.json / pi.registerMcpServer(). */
|
|
59
|
+
export interface McpServerEntry {
|
|
60
|
+
type?: string;
|
|
61
|
+
command?: string;
|
|
62
|
+
args?: string[];
|
|
63
|
+
env?: Record<string, string>;
|
|
64
|
+
cwd?: string;
|
|
65
|
+
url?: string;
|
|
66
|
+
headers?: Record<string, string>;
|
|
67
|
+
oauth?: Record<string, unknown>;
|
|
68
|
+
enabled?: boolean;
|
|
69
|
+
exposure?: string;
|
|
70
|
+
toolExposure?: Record<string, string>;
|
|
71
|
+
description?: string;
|
|
72
|
+
timeout?: number;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface Ui {
|
|
76
|
+
notify(message: string, level?: "info" | "warning" | "error"): void;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface SessionContext {
|
|
80
|
+
cwd: string;
|
|
81
|
+
hasUI: boolean;
|
|
82
|
+
isProjectTrusted(): boolean;
|
|
83
|
+
ui: Ui;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface CommandContext {
|
|
87
|
+
ui: Ui;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export interface ToolInfo {
|
|
91
|
+
name: string;
|
|
92
|
+
exposure?: string;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface SystemPromptOptions {
|
|
96
|
+
sections?: Record<string, string>;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface BeforeAgentStartEvent {
|
|
100
|
+
systemPromptOptions?: SystemPromptOptions;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export interface ToolCallEvent {
|
|
104
|
+
toolName: string;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export interface McpServersChangeEvent {
|
|
108
|
+
servers: unknown;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export interface CommandDefinition {
|
|
112
|
+
description: string;
|
|
113
|
+
handler(args: string, ctx: CommandContext): Promise<void> | void;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export interface ExtensionAPI {
|
|
117
|
+
on(event: "session_start", handler: (event: { reason?: string }, ctx: SessionContext) => unknown): void;
|
|
118
|
+
on(event: "session_shutdown", handler: (event: { reason?: string }, ctx: SessionContext) => unknown): void;
|
|
119
|
+
on(event: "before_agent_start", handler: (event: BeforeAgentStartEvent, ctx: SessionContext) => unknown): void;
|
|
120
|
+
on(event: "tool_call", handler: (event: ToolCallEvent, ctx: SessionContext) => unknown): void;
|
|
121
|
+
on(event: "mcp_servers_change", handler: (event: McpServersChangeEvent, ctx: SessionContext) => unknown): void;
|
|
122
|
+
registerTool(definition: ToolDefinition): void;
|
|
123
|
+
registerCommand(name: string, definition: CommandDefinition): void;
|
|
124
|
+
getActiveTools(): string[];
|
|
125
|
+
setActiveTools(names: string[]): void;
|
|
126
|
+
getAllTools(): ToolInfo[];
|
|
127
|
+
getMcpServers(): unknown;
|
|
128
|
+
getSettings?(): Record<string, unknown>;
|
|
129
|
+
}
|
package/package.json
CHANGED
|
@@ -1,9 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jangmanj/mcp-client",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "MCP 2026-07-28 client library: core, transports, auth, ops, MRTR/cache, OTEL telemetry, and extensions.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "JangMan-J",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"mcp",
|
|
9
|
+
"model-context-protocol",
|
|
10
|
+
"pi-package",
|
|
11
|
+
"pi-extension"
|
|
12
|
+
],
|
|
13
|
+
"pi": {
|
|
14
|
+
"extensions": [
|
|
15
|
+
"./extensions/index.ts"
|
|
16
|
+
]
|
|
17
|
+
},
|
|
7
18
|
"repository": {
|
|
8
19
|
"type": "git",
|
|
9
20
|
"url": "git+https://github.com/JangMan-J/mcp-client.git"
|
|
@@ -19,6 +30,8 @@
|
|
|
19
30
|
],
|
|
20
31
|
"files": [
|
|
21
32
|
"dist",
|
|
33
|
+
"extensions",
|
|
34
|
+
"!extensions/test",
|
|
22
35
|
"README.md",
|
|
23
36
|
"LICENSE"
|
|
24
37
|
],
|
|
@@ -70,7 +83,8 @@
|
|
|
70
83
|
},
|
|
71
84
|
"scripts": {
|
|
72
85
|
"build": "node scripts/build-workspaces.mjs",
|
|
73
|
-
"
|
|
86
|
+
"prepare": "npm run build",
|
|
87
|
+
"typecheck": "tsc -b tsconfig.json && tsc --noEmit -p tsconfig.test.json && tsc --noEmit -p tsconfig.extensions.json",
|
|
74
88
|
"test": "vitest run",
|
|
75
89
|
"gen:schema": "node scripts/gen-schema-types.mjs",
|
|
76
90
|
"check:deps": "node scripts/check-deps.mjs",
|