@phren/agent 0.1.15 → 0.3.5
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 +86 -0
- package/dist/agent-loop/index.js +239 -65
- package/dist/agent-loop/stream.js +212 -29
- package/dist/agent-loop/types.js +15 -2
- package/dist/checkpoint.js +103 -22
- package/dist/commands/info.js +30 -15
- package/dist/commands/model.js +6 -2
- package/dist/commands/review.js +183 -0
- package/dist/commands/session.js +70 -7
- package/dist/commands.js +168 -12
- package/dist/config.js +87 -10
- package/dist/context/compactor.js +239 -0
- package/dist/context/pruner.js +39 -13
- package/dist/context/token-counter.js +33 -1
- package/dist/custom-commands.js +69 -0
- package/dist/guards/repeat-tool-reminder.js +75 -0
- package/dist/headless.js +115 -0
- package/dist/herdr-hooks.js +71 -0
- package/dist/index.js +351 -48
- package/dist/mcp-client.js +434 -73
- package/dist/mcp-oauth.js +121 -0
- package/dist/memory/anti-patterns.js +7 -3
- package/dist/memory/auto-capture.js +7 -3
- package/dist/memory/context.js +92 -73
- package/dist/memory/project-context.js +24 -5
- package/dist/memory/provenance.js +15 -0
- package/dist/memory/review-triage.js +166 -0
- package/dist/memory/session.js +36 -1
- package/dist/models.js +152 -19
- package/dist/multi/child-entry.js +65 -10
- package/dist/multi/diff-renderer.js +3 -3
- package/dist/multi/markdown.js +125 -27
- package/dist/multi/provider-manager.js +8 -0
- package/dist/multi/publish.js +72 -0
- package/dist/multi/spawner.js +45 -4
- package/dist/multi/syntax-highlight.js +25 -4
- package/dist/multi/types.js +1 -1
- package/dist/permissions/allowlist.js +86 -13
- package/dist/permissions/checker.js +42 -7
- package/dist/permissions/kernel-sandbox.js +197 -0
- package/dist/permissions/prompt.js +10 -1
- package/dist/permissions/sandbox.js +40 -17
- package/dist/providers/anthropic.js +154 -7
- package/dist/providers/codex-auth.js +28 -0
- package/dist/providers/codex.js +134 -23
- package/dist/providers/history.js +35 -0
- package/dist/providers/ollama.js +37 -6
- package/dist/providers/openai-compat.js +171 -74
- package/dist/providers/openrouter.js +47 -17
- package/dist/providers/replay.js +62 -0
- package/dist/providers/resolve.js +41 -7
- package/dist/providers/retry.js +38 -5
- package/dist/providers/types.js +9 -1
- package/dist/repl.js +47 -5
- package/dist/session/log.js +217 -0
- package/dist/session/persist.js +190 -0
- package/dist/settings.js +42 -26
- package/dist/system-prompt.js +18 -2
- package/dist/tools/apply-patch.js +355 -0
- package/dist/tools/edit-engine.js +287 -0
- package/dist/tools/edit-file.js +86 -27
- package/dist/tools/grep.js +25 -10
- package/dist/tools/lint-test.js +0 -22
- package/dist/tools/mcp-resources.js +51 -6
- package/dist/tools/phren-finding.js +12 -4
- package/dist/tools/phren-search.js +7 -2
- package/dist/tools/read-file.js +37 -9
- package/dist/tools/read-image.js +76 -0
- package/dist/tools/registry.js +27 -5
- package/dist/tools/shell.js +134 -71
- package/dist/tools/skill.js +20 -20
- package/dist/tools/spawn-agent.js +77 -13
- package/dist/tools/update-plan.js +48 -0
- package/dist/tools/web-fetch.js +110 -12
- package/dist/tools/web-search.js +4 -4
- package/dist/tui/components/App.js +98 -26
- package/dist/tui/components/ApprovalPanel.js +8 -0
- package/dist/tui/components/InputArea.js +5 -5
- package/dist/tui/components/ModelPicker.js +43 -0
- package/dist/tui/components/PhrenInput.js +10 -5
- package/dist/tui/components/PlanReview.js +7 -0
- package/dist/tui/components/ShortcutHelp.js +5 -0
- package/dist/tui/components/StatusBar.js +46 -20
- package/dist/tui/components/SteerQueue.js +1 -1
- package/dist/tui/components/ThinkingIndicator.js +6 -4
- package/dist/tui/components/ToolCall.js +10 -4
- package/dist/tui/components/ToolDetail.js +21 -0
- package/dist/tui/help.js +6 -0
- package/dist/tui/hooks/useKeyboardShortcuts.js +15 -1
- package/dist/tui/index.js +0 -1
- package/dist/tui/ink-entry.js +317 -33
- package/dist/tui/tool-render.js +1 -1
- package/dist/user-hooks.js +171 -0
- package/package.json +14 -8
- package/dist/multi/multi-commands.js +0 -170
- package/dist/multi/multi-events.js +0 -98
- package/dist/multi/multi-render.js +0 -147
- package/dist/multi/pane.js +0 -28
- package/dist/multi/tui-multi.js +0 -200
- package/dist/permissions/privacy.js +0 -248
- package/dist/tui/components/AgentMessage.js +0 -5
- package/dist/tui/components/ChatMessage.js +0 -23
- package/dist/tui/components/CodeBlock.js +0 -8
- package/dist/tui/components/Separator.js +0 -7
- package/dist/tui/components/StreamingText.js +0 -5
- package/dist/tui/components/UserMessage.js +0 -5
- package/dist/tui/menu-mode.js +0 -86
- package/dist/tui/mouse.js +0 -71
- package/dist/tui/terminal-control.js +0 -62
- package/dist/tui.js +0 -781
package/dist/mcp-client.js
CHANGED
|
@@ -1,110 +1,399 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* MCP client — connects to MCP servers, discovers tools, wraps them as AgentTools.
|
|
3
|
-
*
|
|
3
|
+
* Supports stdio, streamable HTTP, and legacy HTTP+SSE transports.
|
|
4
4
|
*/
|
|
5
|
+
import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js";
|
|
6
|
+
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
7
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
5
8
|
import { spawn } from "child_process";
|
|
6
9
|
import * as fs from "fs";
|
|
7
10
|
import * as readline from "readline";
|
|
11
|
+
import { McpOAuthProvider } from "./mcp-oauth.js";
|
|
8
12
|
import { VERSION } from "./package-metadata.js";
|
|
9
13
|
import { scrubEnv } from "./permissions/shell-safety.js";
|
|
10
|
-
|
|
11
|
-
|
|
14
|
+
const STDERR_BUFFER_LINES = 200;
|
|
15
|
+
const REQUEST_TIMEOUT_MS = 30_000;
|
|
16
|
+
function isPlainObject(value) {
|
|
17
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
18
|
+
}
|
|
19
|
+
function parseServerType(value) {
|
|
20
|
+
if (value === "stdio" || value === "http" || value === "sse")
|
|
21
|
+
return value;
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
|
24
|
+
function asStringRecord(value) {
|
|
25
|
+
if (!isPlainObject(value))
|
|
26
|
+
return undefined;
|
|
27
|
+
const out = {};
|
|
28
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
29
|
+
if (typeof entry === "string")
|
|
30
|
+
out[key] = entry;
|
|
31
|
+
}
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
class StdioTransport {
|
|
12
35
|
proc;
|
|
13
|
-
nextId = 1;
|
|
14
|
-
pending = new Map();
|
|
15
36
|
rl;
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
37
|
+
stderrRl;
|
|
38
|
+
stderrLines = [];
|
|
39
|
+
closed = false;
|
|
40
|
+
constructor(config, onMessage, onError) {
|
|
19
41
|
const env = { ...scrubEnv(), ...config.env };
|
|
20
42
|
this.proc = spawn(config.command, config.args ?? [], {
|
|
21
43
|
stdio: ["pipe", "pipe", "pipe"],
|
|
22
44
|
env,
|
|
23
45
|
});
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
const { resolve, reject, timer } = this.pending.get(msg.id);
|
|
30
|
-
clearTimeout(timer);
|
|
31
|
-
this.pending.delete(msg.id);
|
|
32
|
-
if (msg.error)
|
|
33
|
-
reject(new Error(`MCP error: ${msg.error.message}`));
|
|
34
|
-
else
|
|
35
|
-
resolve(msg.result);
|
|
46
|
+
if (this.proc.stdout) {
|
|
47
|
+
this.rl = readline.createInterface({ input: this.proc.stdout });
|
|
48
|
+
this.rl.on("line", (line) => {
|
|
49
|
+
try {
|
|
50
|
+
onMessage(JSON.parse(line));
|
|
36
51
|
}
|
|
52
|
+
catch {
|
|
53
|
+
/* ignore non-JSON lines */
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
if (this.proc.stderr) {
|
|
58
|
+
this.stderrRl = readline.createInterface({ input: this.proc.stderr });
|
|
59
|
+
this.stderrRl.on("line", (line) => {
|
|
60
|
+
this.stderrLines.push(line);
|
|
61
|
+
if (this.stderrLines.length > STDERR_BUFFER_LINES)
|
|
62
|
+
this.stderrLines.shift();
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
this.proc.on("error", (err) => {
|
|
66
|
+
if (!this.closed)
|
|
67
|
+
onError(err);
|
|
68
|
+
});
|
|
69
|
+
this.proc.on("exit", (code, signal) => {
|
|
70
|
+
if (!this.closed) {
|
|
71
|
+
onError(new Error(`MCP server exited (code ${code ?? "null"}, signal ${signal ?? "none"})`));
|
|
37
72
|
}
|
|
38
|
-
catch { /* ignore non-JSON lines */ }
|
|
39
73
|
});
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
74
|
+
}
|
|
75
|
+
async post(message) {
|
|
76
|
+
if (this.closed)
|
|
77
|
+
throw new Error("MCP connection closed");
|
|
78
|
+
const stdin = this.proc.stdin;
|
|
79
|
+
if (!stdin || stdin.destroyed)
|
|
80
|
+
throw new Error("MCP server stdin unavailable");
|
|
81
|
+
await new Promise((resolve, reject) => {
|
|
82
|
+
try {
|
|
83
|
+
stdin.write(JSON.stringify(message) + "\n", (err) => (err ? reject(err) : resolve()));
|
|
84
|
+
}
|
|
85
|
+
catch (err) {
|
|
86
|
+
reject(err instanceof Error ? err : new Error(String(err)));
|
|
44
87
|
}
|
|
45
|
-
this.pending.clear();
|
|
46
88
|
});
|
|
47
89
|
}
|
|
48
|
-
|
|
90
|
+
getStderr() {
|
|
91
|
+
return this.stderrLines;
|
|
92
|
+
}
|
|
93
|
+
close() {
|
|
94
|
+
if (this.closed)
|
|
95
|
+
return;
|
|
96
|
+
this.closed = true;
|
|
97
|
+
try {
|
|
98
|
+
this.proc.stdin?.end();
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
/* ignore */
|
|
102
|
+
}
|
|
103
|
+
try {
|
|
104
|
+
this.proc.kill();
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
/* ignore */
|
|
108
|
+
}
|
|
109
|
+
this.rl?.close();
|
|
110
|
+
this.stderrRl?.close();
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
class RemoteTransport {
|
|
114
|
+
transport;
|
|
115
|
+
oauth;
|
|
116
|
+
ready;
|
|
117
|
+
closed = false;
|
|
118
|
+
accepted = new Set();
|
|
119
|
+
constructor(config, onMessage, onError) {
|
|
120
|
+
const url = new URL(config.url);
|
|
121
|
+
if (!["https:", "http:"].includes(url.protocol) || url.username || url.password)
|
|
122
|
+
throw new Error("Invalid MCP server URL");
|
|
123
|
+
if (config.oauth) {
|
|
124
|
+
if (url.protocol !== "https:" && !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))
|
|
125
|
+
throw new Error("MCP OAuth requires HTTPS except on loopback");
|
|
126
|
+
this.oauth = new McpOAuthProvider(url.href, typeof config.oauth === "object" ? config.oauth : {});
|
|
127
|
+
}
|
|
128
|
+
const options = { authProvider: this.oauth, requestInit: { headers: config.headers },
|
|
129
|
+
fetch: async (input, init) => {
|
|
130
|
+
const response = await fetch(input, { ...init, redirect: "error" });
|
|
131
|
+
if (response.status === 202 && init?.method === "POST" && typeof init.body === "string") {
|
|
132
|
+
const message = JSON.parse(init.body);
|
|
133
|
+
if (typeof message.id === "number")
|
|
134
|
+
this.accepted.add(message.id);
|
|
135
|
+
}
|
|
136
|
+
return response;
|
|
137
|
+
} };
|
|
138
|
+
this.transport = config.type === "sse" ? new SSEClientTransport(url, options) : new StreamableHTTPClientTransport(url, options);
|
|
139
|
+
this.transport.onmessage = message => onMessage(message);
|
|
140
|
+
this.transport.onerror = error => { if (!(error instanceof UnauthorizedError) && !this.closed)
|
|
141
|
+
onError(error); };
|
|
142
|
+
this.transport.onclose = () => { if (!this.closed)
|
|
143
|
+
onError(new Error("MCP stream closed")); };
|
|
144
|
+
this.ready = this.withAuth(() => this.transport.start());
|
|
145
|
+
this.ready.catch(() => { });
|
|
146
|
+
}
|
|
147
|
+
async withAuth(operation) {
|
|
148
|
+
try {
|
|
149
|
+
await operation();
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
if (!(error instanceof UnauthorizedError) || !this.oauth || this.closed)
|
|
153
|
+
throw error;
|
|
154
|
+
const code = await this.oauth.authorizationCode();
|
|
155
|
+
if (this.closed)
|
|
156
|
+
throw new Error("MCP connection closed");
|
|
157
|
+
await this.transport.finishAuth(code);
|
|
158
|
+
await operation();
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
async post(message, signal) {
|
|
162
|
+
await this.ready;
|
|
163
|
+
if (this.closed || signal?.aborted)
|
|
164
|
+
throw new Error("MCP call aborted");
|
|
165
|
+
await this.withAuth(() => this.transport.send(message));
|
|
166
|
+
if (typeof message.id === "number" && this.accepted.delete(message.id) && message.method === "initialize"
|
|
167
|
+
&& this.transport instanceof StreamableHTTPClientTransport) {
|
|
168
|
+
// Some older servers accept initialization itself and answer on GET SSE.
|
|
169
|
+
await this.transport.resumeStream("");
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
setProtocolVersion(version) { this.transport.setProtocolVersion?.(version); }
|
|
173
|
+
close() {
|
|
174
|
+
if (this.closed)
|
|
175
|
+
return;
|
|
176
|
+
this.closed = true;
|
|
177
|
+
this.oauth?.close();
|
|
178
|
+
void this.transport.close().catch(() => { });
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
/** Active MCP server connection. */
|
|
182
|
+
class McpConnection {
|
|
183
|
+
name;
|
|
184
|
+
transport;
|
|
185
|
+
nextId = 1;
|
|
186
|
+
pending = new Map();
|
|
187
|
+
tools = [];
|
|
188
|
+
notificationHandlers = new Set();
|
|
189
|
+
closed = false;
|
|
190
|
+
constructor(name, config) {
|
|
191
|
+
this.name = name;
|
|
192
|
+
const onMessage = (msg) => this.handleMessage(msg);
|
|
193
|
+
const onError = (err) => this.failAll(err);
|
|
194
|
+
const type = config.type ?? (config.url ? "http" : "stdio");
|
|
195
|
+
if (type === "http" || type === "sse") {
|
|
196
|
+
if (!config.url)
|
|
197
|
+
throw new Error(`MCP server "${name}" has type ${type} but no url`);
|
|
198
|
+
this.transport = new RemoteTransport({ ...config, type }, onMessage, onError);
|
|
199
|
+
}
|
|
200
|
+
else {
|
|
201
|
+
if (!config.command)
|
|
202
|
+
throw new Error(`MCP server "${name}" has type stdio but no command`);
|
|
203
|
+
this.transport = new StdioTransport(config, onMessage, onError);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
handleMessage(msg) {
|
|
207
|
+
if ("id" in msg && msg.id !== undefined && msg.id !== null) {
|
|
208
|
+
const pending = this.pending.get(msg.id);
|
|
209
|
+
if (!pending)
|
|
210
|
+
return;
|
|
211
|
+
clearTimeout(pending.timer);
|
|
212
|
+
this.pending.delete(msg.id);
|
|
213
|
+
if ("error" in msg && msg.error)
|
|
214
|
+
pending.reject(new Error(`MCP error: ${msg.error.message}`));
|
|
215
|
+
else
|
|
216
|
+
pending.resolve(msg.result);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
const method = msg.method;
|
|
220
|
+
if (!method)
|
|
221
|
+
return;
|
|
222
|
+
if (method === "notifications/tools/list_changed") {
|
|
223
|
+
void this.refreshTools();
|
|
224
|
+
}
|
|
225
|
+
for (const handler of this.notificationHandlers) {
|
|
226
|
+
handler(method, msg.params);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
failAll(err) {
|
|
230
|
+
for (const { reject, timer } of this.pending.values()) {
|
|
231
|
+
clearTimeout(timer);
|
|
232
|
+
reject(err);
|
|
233
|
+
}
|
|
234
|
+
this.pending.clear();
|
|
235
|
+
}
|
|
236
|
+
send(method, params, signal) {
|
|
237
|
+
if (this.closed)
|
|
238
|
+
return Promise.reject(new Error("MCP connection closed"));
|
|
49
239
|
return new Promise((resolve, reject) => {
|
|
50
240
|
const id = this.nextId++;
|
|
51
|
-
|
|
241
|
+
let settled = false;
|
|
52
242
|
const timer = setTimeout(() => {
|
|
53
|
-
if (
|
|
54
|
-
|
|
55
|
-
|
|
243
|
+
if (settled)
|
|
244
|
+
return;
|
|
245
|
+
settled = true;
|
|
246
|
+
this.pending.delete(id);
|
|
247
|
+
signal?.removeEventListener("abort", onAbort);
|
|
248
|
+
reject(new Error(`MCP call ${method} timed out`));
|
|
249
|
+
}, method === "initialize" ? 330_000 : REQUEST_TIMEOUT_MS);
|
|
250
|
+
const onAbort = () => {
|
|
251
|
+
if (settled)
|
|
252
|
+
return;
|
|
253
|
+
settled = true;
|
|
254
|
+
clearTimeout(timer);
|
|
255
|
+
this.pending.delete(id);
|
|
256
|
+
reject(new Error(`MCP call ${method} aborted`));
|
|
257
|
+
};
|
|
258
|
+
if (signal) {
|
|
259
|
+
if (signal.aborted) {
|
|
260
|
+
settled = true;
|
|
261
|
+
clearTimeout(timer);
|
|
262
|
+
reject(new Error(`MCP call ${method} aborted`));
|
|
263
|
+
return;
|
|
56
264
|
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
this.
|
|
265
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
266
|
+
}
|
|
267
|
+
this.pending.set(id, {
|
|
268
|
+
resolve: (value) => {
|
|
269
|
+
if (settled)
|
|
270
|
+
return;
|
|
271
|
+
settled = true;
|
|
272
|
+
signal?.removeEventListener("abort", onAbort);
|
|
273
|
+
resolve(value);
|
|
274
|
+
},
|
|
275
|
+
reject: (err) => {
|
|
276
|
+
if (settled)
|
|
277
|
+
return;
|
|
278
|
+
settled = true;
|
|
279
|
+
signal?.removeEventListener("abort", onAbort);
|
|
280
|
+
reject(err);
|
|
281
|
+
},
|
|
282
|
+
timer,
|
|
283
|
+
});
|
|
284
|
+
this.transport
|
|
285
|
+
.post({ jsonrpc: "2.0", id, method, params }, signal, id)
|
|
286
|
+
.catch((err) => {
|
|
287
|
+
if (settled)
|
|
288
|
+
return;
|
|
289
|
+
settled = true;
|
|
290
|
+
clearTimeout(timer);
|
|
291
|
+
this.pending.delete(id);
|
|
292
|
+
signal?.removeEventListener("abort", onAbort);
|
|
293
|
+
reject(err instanceof Error ? err : new Error(String(err)));
|
|
294
|
+
});
|
|
60
295
|
});
|
|
61
296
|
}
|
|
297
|
+
async notify(method, params) {
|
|
298
|
+
if (this.closed)
|
|
299
|
+
return;
|
|
300
|
+
await this.transport.post({ jsonrpc: "2.0", method, params });
|
|
301
|
+
}
|
|
62
302
|
async initialize() {
|
|
63
|
-
await this.send("initialize", {
|
|
64
|
-
protocolVersion: "
|
|
303
|
+
const result = await this.send("initialize", {
|
|
304
|
+
protocolVersion: "2025-11-25",
|
|
65
305
|
capabilities: {},
|
|
66
306
|
clientInfo: { name: "phren-agent", version: VERSION },
|
|
67
307
|
});
|
|
68
|
-
|
|
69
|
-
|
|
308
|
+
if (this.transport instanceof RemoteTransport && isPlainObject(result) && typeof result.protocolVersion === "string")
|
|
309
|
+
this.transport.setProtocolVersion(result.protocolVersion);
|
|
310
|
+
await this.notify("notifications/initialized");
|
|
70
311
|
}
|
|
71
312
|
async listTools() {
|
|
72
|
-
const result = await this.send("tools/list");
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
async callTool(name, args) {
|
|
76
|
-
return await this.send("tools/call", { name, arguments: args });
|
|
313
|
+
const result = (await this.send("tools/list"));
|
|
314
|
+
this.tools = result?.tools ?? [];
|
|
315
|
+
return this.tools;
|
|
77
316
|
}
|
|
78
|
-
|
|
317
|
+
async refreshTools() {
|
|
79
318
|
try {
|
|
80
|
-
this.
|
|
319
|
+
const result = (await this.send("tools/list"));
|
|
320
|
+
this.tools = result?.tools ?? [];
|
|
81
321
|
}
|
|
82
|
-
catch {
|
|
83
|
-
|
|
84
|
-
this.proc.kill();
|
|
85
|
-
}
|
|
86
|
-
catch { /* ignore */ }
|
|
87
|
-
this.rl.close();
|
|
88
|
-
for (const { reject, timer } of this.pending.values()) {
|
|
89
|
-
clearTimeout(timer);
|
|
90
|
-
reject(new Error("Connection closed"));
|
|
322
|
+
catch {
|
|
323
|
+
return;
|
|
91
324
|
}
|
|
92
|
-
this.pending.clear();
|
|
93
325
|
}
|
|
326
|
+
getTools() {
|
|
327
|
+
return this.tools;
|
|
328
|
+
}
|
|
329
|
+
async callTool(name, args, signal) {
|
|
330
|
+
return (await this.send("tools/call", { name, arguments: args }, signal));
|
|
331
|
+
}
|
|
332
|
+
async listResources() {
|
|
333
|
+
const result = (await this.send("resources/list"));
|
|
334
|
+
return result?.resources ?? [];
|
|
335
|
+
}
|
|
336
|
+
async readResource(uri) {
|
|
337
|
+
const result = (await this.send("resources/read", { uri }));
|
|
338
|
+
return result?.contents ?? [];
|
|
339
|
+
}
|
|
340
|
+
async listPrompts() {
|
|
341
|
+
const result = (await this.send("prompts/list"));
|
|
342
|
+
return result?.prompts ?? [];
|
|
343
|
+
}
|
|
344
|
+
async getPrompt(name, args) {
|
|
345
|
+
return (await this.send("prompts/get", { name, arguments: args }));
|
|
346
|
+
}
|
|
347
|
+
onNotification(handler) {
|
|
348
|
+
this.notificationHandlers.add(handler);
|
|
349
|
+
return () => {
|
|
350
|
+
this.notificationHandlers.delete(handler);
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
getStderr() {
|
|
354
|
+
return this.transport instanceof StdioTransport ? this.transport.getStderr() : [];
|
|
355
|
+
}
|
|
356
|
+
close() {
|
|
357
|
+
if (this.closed)
|
|
358
|
+
return;
|
|
359
|
+
this.closed = true;
|
|
360
|
+
this.transport.close();
|
|
361
|
+
this.failAll(new Error("Connection closed"));
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
function normalizeInputSchema(schema) {
|
|
365
|
+
if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
|
|
366
|
+
return { type: "object", properties: {} };
|
|
367
|
+
}
|
|
368
|
+
return schema;
|
|
369
|
+
}
|
|
370
|
+
function formatToolResult(result) {
|
|
371
|
+
const content = result?.content;
|
|
372
|
+
if (!content || content.length === 0)
|
|
373
|
+
return result?.isError ? "MCP tool reported an error" : "OK";
|
|
374
|
+
return content
|
|
375
|
+
.map((block) => {
|
|
376
|
+
if (typeof block.text === "string")
|
|
377
|
+
return block.text;
|
|
378
|
+
if (block.type === "image" && block.data)
|
|
379
|
+
return `[image ${block.mimeType ?? "image"}]`;
|
|
380
|
+
if (block.type === "resource" && block.uri)
|
|
381
|
+
return `[resource ${block.uri}]`;
|
|
382
|
+
return JSON.stringify(block);
|
|
383
|
+
})
|
|
384
|
+
.join("\n");
|
|
94
385
|
}
|
|
95
386
|
/** Wrap an MCP tool as an AgentTool. */
|
|
96
387
|
function wrapMcpTool(conn, def) {
|
|
97
388
|
return {
|
|
98
389
|
name: `mcp_${conn.name}_${def.name}`,
|
|
99
390
|
description: `[${conn.name}] ${def.description ?? def.name}`,
|
|
100
|
-
input_schema: def.inputSchema
|
|
101
|
-
async execute(input) {
|
|
391
|
+
input_schema: normalizeInputSchema(def.inputSchema),
|
|
392
|
+
async execute(input, signal) {
|
|
102
393
|
try {
|
|
103
|
-
const result = await conn.callTool(def.name, input);
|
|
104
|
-
const text = result
|
|
105
|
-
|
|
106
|
-
.join("\n") ?? "OK";
|
|
107
|
-
return { output: text };
|
|
394
|
+
const result = await conn.callTool(def.name, input, signal);
|
|
395
|
+
const text = formatToolResult(result);
|
|
396
|
+
return result?.isError ? { output: text, is_error: true } : { output: text };
|
|
108
397
|
}
|
|
109
398
|
catch (err) {
|
|
110
399
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -113,33 +402,87 @@ function wrapMcpTool(conn, def) {
|
|
|
113
402
|
},
|
|
114
403
|
};
|
|
115
404
|
}
|
|
405
|
+
const mcpConnections = new Map();
|
|
406
|
+
export const mcpRegistry = {
|
|
407
|
+
listServers() {
|
|
408
|
+
return [...mcpConnections.keys()];
|
|
409
|
+
},
|
|
410
|
+
getConnection(name) {
|
|
411
|
+
return mcpConnections.get(name);
|
|
412
|
+
},
|
|
413
|
+
async listResources(server) {
|
|
414
|
+
const names = server ? [server] : [...mcpConnections.keys()];
|
|
415
|
+
const out = [];
|
|
416
|
+
for (const name of names) {
|
|
417
|
+
const conn = mcpConnections.get(name);
|
|
418
|
+
if (!conn)
|
|
419
|
+
continue;
|
|
420
|
+
const resources = await conn.listResources();
|
|
421
|
+
for (const resource of resources)
|
|
422
|
+
out.push({ server: name, ...resource });
|
|
423
|
+
}
|
|
424
|
+
return out;
|
|
425
|
+
},
|
|
426
|
+
async readResource(server, uri) {
|
|
427
|
+
const conn = mcpConnections.get(server);
|
|
428
|
+
if (!conn)
|
|
429
|
+
throw new Error(`MCP server not connected: ${server}`);
|
|
430
|
+
return conn.readResource(uri);
|
|
431
|
+
},
|
|
432
|
+
async listPrompts(server) {
|
|
433
|
+
const names = server ? [server] : [...mcpConnections.keys()];
|
|
434
|
+
const out = [];
|
|
435
|
+
for (const name of names) {
|
|
436
|
+
const conn = mcpConnections.get(name);
|
|
437
|
+
if (!conn)
|
|
438
|
+
continue;
|
|
439
|
+
const prompts = await conn.listPrompts();
|
|
440
|
+
for (const prompt of prompts)
|
|
441
|
+
out.push({ server: name, ...prompt });
|
|
442
|
+
}
|
|
443
|
+
return out;
|
|
444
|
+
},
|
|
445
|
+
async getPrompt(server, name, args) {
|
|
446
|
+
const conn = mcpConnections.get(server);
|
|
447
|
+
if (!conn)
|
|
448
|
+
throw new Error(`MCP server not connected: ${server}`);
|
|
449
|
+
return conn.getPrompt(name, args);
|
|
450
|
+
},
|
|
451
|
+
};
|
|
116
452
|
/** Connect to MCP servers and return their tools as AgentTools. */
|
|
117
453
|
export async function connectMcpServers(servers, verbose = false) {
|
|
118
454
|
const connections = [];
|
|
119
455
|
const tools = [];
|
|
120
456
|
for (const [name, config] of Object.entries(servers)) {
|
|
457
|
+
let conn;
|
|
121
458
|
try {
|
|
122
459
|
if (verbose)
|
|
123
460
|
process.stderr.write(`Connecting to MCP server: ${name}...\n`);
|
|
124
|
-
|
|
461
|
+
conn = new McpConnection(name, config);
|
|
125
462
|
await conn.initialize();
|
|
126
463
|
const mcpTools = await conn.listTools();
|
|
127
464
|
for (const def of mcpTools) {
|
|
128
465
|
tools.push(wrapMcpTool(conn, def));
|
|
129
466
|
}
|
|
130
467
|
connections.push(conn);
|
|
468
|
+
mcpConnections.set(name, conn);
|
|
131
469
|
if (verbose)
|
|
132
470
|
process.stderr.write(` ${name}: ${mcpTools.length} tools\n`);
|
|
133
471
|
}
|
|
134
472
|
catch (err) {
|
|
473
|
+
conn?.close();
|
|
135
474
|
const msg = err instanceof Error ? err.message : String(err);
|
|
136
475
|
process.stderr.write(`Failed to connect to MCP server "${name}": ${msg}\n`);
|
|
137
476
|
}
|
|
138
477
|
}
|
|
139
478
|
return {
|
|
140
479
|
tools,
|
|
141
|
-
cleanup: () => {
|
|
142
|
-
conn
|
|
480
|
+
cleanup: () => {
|
|
481
|
+
for (const conn of connections) {
|
|
482
|
+
conn.close();
|
|
483
|
+
mcpConnections.delete(conn.name);
|
|
484
|
+
}
|
|
485
|
+
},
|
|
143
486
|
};
|
|
144
487
|
}
|
|
145
488
|
/** Load MCP server config from a JSON file (same format as Claude Code's mcpServers). */
|
|
@@ -148,17 +491,35 @@ export function loadMcpConfig(configPath) {
|
|
|
148
491
|
return {};
|
|
149
492
|
try {
|
|
150
493
|
const raw = JSON.parse(fs.readFileSync(configPath, "utf-8"));
|
|
151
|
-
// Support both { mcpServers: {...} } and direct { serverName: {...} } formats
|
|
152
494
|
const servers = raw.mcpServers ?? raw;
|
|
495
|
+
if (!isPlainObject(servers))
|
|
496
|
+
return {};
|
|
153
497
|
const result = {};
|
|
154
498
|
for (const [name, entry] of Object.entries(servers)) {
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
499
|
+
if (!isPlainObject(entry))
|
|
500
|
+
continue;
|
|
501
|
+
const explicitType = parseServerType(entry.type);
|
|
502
|
+
const url = typeof entry.url === "string" ? entry.url : undefined;
|
|
503
|
+
const command = typeof entry.command === "string" ? entry.command : undefined;
|
|
504
|
+
const args = Array.isArray(entry.args) ? entry.args.map(String) : undefined;
|
|
505
|
+
const env = asStringRecord(entry.env);
|
|
506
|
+
const headers = asStringRecord(entry.headers);
|
|
507
|
+
const type = explicitType ?? (command ? "stdio" : url ? "http" : undefined);
|
|
508
|
+
if (type === "stdio") {
|
|
509
|
+
if (!command)
|
|
510
|
+
continue;
|
|
511
|
+
result[name] = { command, args, env };
|
|
512
|
+
}
|
|
513
|
+
else if (type === "http" || type === "sse") {
|
|
514
|
+
if (!url)
|
|
515
|
+
continue;
|
|
516
|
+
const oauth = entry.oauth === true ? true : isPlainObject(entry.oauth) ? {
|
|
517
|
+
clientId: typeof entry.oauth.clientId === "string" ? entry.oauth.clientId : undefined,
|
|
518
|
+
clientSecret: typeof entry.oauth.clientSecret === "string" ? entry.oauth.clientSecret : undefined,
|
|
519
|
+
scope: typeof entry.oauth.scope === "string" ? entry.oauth.scope : undefined,
|
|
520
|
+
callbackPort: typeof entry.oauth.callbackPort === "number" ? entry.oauth.callbackPort : undefined,
|
|
521
|
+
} : undefined;
|
|
522
|
+
result[name] = { type, url, headers, ...(oauth ? { oauth } : {}) };
|
|
162
523
|
}
|
|
163
524
|
}
|
|
164
525
|
return result;
|