@slashfi/agents-sdk 0.62.0 → 0.63.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/dist/cjs/index.js +1 -29
- package/dist/cjs/index.js.map +1 -1
- package/dist/index.d.ts +1 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -18
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +14 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +1 -44
- package/src/types.ts +8 -0
- package/dist/cjs/client.js +0 -193
- package/dist/cjs/client.js.map +0 -1
- package/dist/cjs/codegen.js +0 -1071
- package/dist/cjs/codegen.js.map +0 -1
- package/dist/cjs/introspect.js +0 -136
- package/dist/cjs/introspect.js.map +0 -1
- package/dist/cjs/jsonc.js +0 -74
- package/dist/cjs/jsonc.js.map +0 -1
- package/dist/cjs/pack.js +0 -256
- package/dist/cjs/pack.js.map +0 -1
- package/dist/client.d.ts +0 -49
- package/dist/client.d.ts.map +0 -1
- package/dist/client.js +0 -190
- package/dist/client.js.map +0 -1
- package/dist/codegen.d.ts +0 -163
- package/dist/codegen.d.ts.map +0 -1
- package/dist/codegen.js +0 -1059
- package/dist/codegen.js.map +0 -1
- package/dist/introspect.d.ts +0 -16
- package/dist/introspect.d.ts.map +0 -1
- package/dist/introspect.js +0 -133
- package/dist/introspect.js.map +0 -1
- package/dist/jsonc.d.ts +0 -15
- package/dist/jsonc.d.ts.map +0 -1
- package/dist/jsonc.js +0 -70
- package/dist/jsonc.js.map +0 -1
- package/dist/pack.d.ts +0 -59
- package/dist/pack.d.ts.map +0 -1
- package/dist/pack.js +0 -252
- package/dist/pack.js.map +0 -1
- package/src/client.ts +0 -273
- package/src/codegen.test.ts +0 -537
- package/src/codegen.ts +0 -1423
- package/src/introspect.ts +0 -171
- package/src/jsonc.ts +0 -83
- package/src/pack.ts +0 -394
package/dist/codegen.js
DELETED
|
@@ -1,1059 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* MCP Codegen
|
|
3
|
-
*
|
|
4
|
-
* Connects to any MCP server, introspects its tools via `tools/list`,
|
|
5
|
-
* and generates readable agent-definition source files.
|
|
6
|
-
*
|
|
7
|
-
* Supports three transport modes:
|
|
8
|
-
* - stdio: spawn a process (e.g., `npx @modelcontextprotocol/server-notion`)
|
|
9
|
-
* - sse: connect to an SSE endpoint
|
|
10
|
-
* - http: connect to an HTTP JSON-RPC endpoint
|
|
11
|
-
*
|
|
12
|
-
* @example
|
|
13
|
-
* ```typescript
|
|
14
|
-
* import { codegen } from '@slashfi/agents-sdk';
|
|
15
|
-
*
|
|
16
|
-
* await codegen({
|
|
17
|
-
* server: 'npx @modelcontextprotocol/server-notion',
|
|
18
|
-
* outDir: './generated/notion',
|
|
19
|
-
* agentPath: '@notion',
|
|
20
|
-
* });
|
|
21
|
-
* ```
|
|
22
|
-
*
|
|
23
|
-
* @example CLI
|
|
24
|
-
* ```bash
|
|
25
|
-
* agents-sdk codegen --server 'npx @mcp/notion' --name notion
|
|
26
|
-
* agents-sdk use notion search_pages '{"query": "hello"}'
|
|
27
|
-
* agents-sdk use notion --list
|
|
28
|
-
* ```
|
|
29
|
-
*/
|
|
30
|
-
import { mkdirSync, writeFileSync, existsSync, readFileSync } from "node:fs";
|
|
31
|
-
import { join, resolve } from "node:path";
|
|
32
|
-
import { discoverOAuthMetadata } from "./mcp-client.js";
|
|
33
|
-
// ============================================
|
|
34
|
-
// Protocol Constants
|
|
35
|
-
// ============================================
|
|
36
|
-
const LATEST_PROTOCOL_VERSION = "2025-03-26";
|
|
37
|
-
const SUPPORTED_PROTOCOL_VERSIONS = [
|
|
38
|
-
"2025-03-26",
|
|
39
|
-
"2024-11-05",
|
|
40
|
-
"2024-10-07",
|
|
41
|
-
];
|
|
42
|
-
// ============================================
|
|
43
|
-
// Safe Environment (security)
|
|
44
|
-
// ============================================
|
|
45
|
-
/** Only inherit safe env vars when spawning MCP servers (prevents secret leakage). */
|
|
46
|
-
const DEFAULT_INHERITED_ENV_VARS = process.platform === "win32"
|
|
47
|
-
? [
|
|
48
|
-
"APPDATA",
|
|
49
|
-
"HOMEDRIVE",
|
|
50
|
-
"HOMEPATH",
|
|
51
|
-
"LOCALAPPDATA",
|
|
52
|
-
"PATH",
|
|
53
|
-
"PROCESSOR_ARCHITECTURE",
|
|
54
|
-
"SYSTEMDRIVE",
|
|
55
|
-
"SYSTEMROOT",
|
|
56
|
-
"TEMP",
|
|
57
|
-
"USERNAME",
|
|
58
|
-
"USERPROFILE",
|
|
59
|
-
"PROGRAMFILES",
|
|
60
|
-
]
|
|
61
|
-
: ["HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER"];
|
|
62
|
-
function getDefaultEnvironment() {
|
|
63
|
-
const env = {};
|
|
64
|
-
for (const key of DEFAULT_INHERITED_ENV_VARS) {
|
|
65
|
-
const value = process.env[key];
|
|
66
|
-
if (value === undefined || value.startsWith("()"))
|
|
67
|
-
continue;
|
|
68
|
-
env[key] = value;
|
|
69
|
-
}
|
|
70
|
-
return env;
|
|
71
|
-
}
|
|
72
|
-
// ============================================
|
|
73
|
-
// Transport: stdio
|
|
74
|
-
// ============================================
|
|
75
|
-
import spawn from "cross-spawn";
|
|
76
|
-
function createStdioTransport(source) {
|
|
77
|
-
// Use cross-spawn for Windows compatibility (.cmd/.bat wrappers, spaces in paths)
|
|
78
|
-
// Env: if explicit env provided, use safe defaults + explicit. Otherwise inherit process.env.
|
|
79
|
-
const env = source.env
|
|
80
|
-
? { ...getDefaultEnvironment(), ...source.env }
|
|
81
|
-
: { ...process.env };
|
|
82
|
-
const proc = spawn(source.command, source.args ?? [], {
|
|
83
|
-
stdio: ["pipe", "pipe", "pipe"],
|
|
84
|
-
env,
|
|
85
|
-
});
|
|
86
|
-
let requestId = 0;
|
|
87
|
-
const pending = new Map();
|
|
88
|
-
// Error handlers for pipes (prevent unhandled errors)
|
|
89
|
-
proc.on("error", (err) => {
|
|
90
|
-
for (const [id, p] of pending) {
|
|
91
|
-
p.reject(new Error(`Process error: ${err.message}`));
|
|
92
|
-
pending.delete(id);
|
|
93
|
-
}
|
|
94
|
-
});
|
|
95
|
-
proc.stdin?.on("error", () => { });
|
|
96
|
-
proc.stdout?.on("error", () => { });
|
|
97
|
-
proc.stderr?.on("error", () => { });
|
|
98
|
-
// Read stdout with Content-Length framing (MCP spec) or newline-delimited fallback
|
|
99
|
-
let buffer = "";
|
|
100
|
-
proc.stdout.on("data", (chunk) => {
|
|
101
|
-
buffer += chunk.toString();
|
|
102
|
-
// Try to parse messages from buffer
|
|
103
|
-
while (buffer.length > 0) {
|
|
104
|
-
// Check for Content-Length framing (MCP standard)
|
|
105
|
-
const clMatch = buffer.match(/^Content-Length:\s*(\d+)\r?\n(?:[^\r\n]+\r?\n)*\r?\n/);
|
|
106
|
-
if (clMatch) {
|
|
107
|
-
const contentLength = parseInt(clMatch[1], 10);
|
|
108
|
-
const headerEnd = clMatch[0].length;
|
|
109
|
-
if (buffer.length >= headerEnd + contentLength) {
|
|
110
|
-
const body = buffer.slice(headerEnd, headerEnd + contentLength);
|
|
111
|
-
buffer = buffer.slice(headerEnd + contentLength);
|
|
112
|
-
try {
|
|
113
|
-
const msg = JSON.parse(body);
|
|
114
|
-
if (msg.id !== undefined && pending.has(msg.id)) {
|
|
115
|
-
const p = pending.get(msg.id);
|
|
116
|
-
pending.delete(msg.id);
|
|
117
|
-
if (msg.error) {
|
|
118
|
-
p.reject(new Error(`MCP error ${msg.error.code}: ${msg.error.message}`));
|
|
119
|
-
}
|
|
120
|
-
else {
|
|
121
|
-
p.resolve(msg.result);
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
catch {
|
|
126
|
-
// malformed JSON, skip
|
|
127
|
-
}
|
|
128
|
-
continue;
|
|
129
|
-
}
|
|
130
|
-
// Not enough data yet, wait for more
|
|
131
|
-
break;
|
|
132
|
-
}
|
|
133
|
-
// Fallback: newline-delimited JSON
|
|
134
|
-
const newlineIdx = buffer.indexOf("\n");
|
|
135
|
-
if (newlineIdx === -1)
|
|
136
|
-
break;
|
|
137
|
-
const line = buffer.slice(0, newlineIdx).trim();
|
|
138
|
-
buffer = buffer.slice(newlineIdx + 1);
|
|
139
|
-
if (!line)
|
|
140
|
-
continue;
|
|
141
|
-
try {
|
|
142
|
-
const msg = JSON.parse(line);
|
|
143
|
-
if (msg.id !== undefined && pending.has(msg.id)) {
|
|
144
|
-
const p = pending.get(msg.id);
|
|
145
|
-
pending.delete(msg.id);
|
|
146
|
-
if (msg.error) {
|
|
147
|
-
p.reject(new Error(`MCP error ${msg.error.code}: ${msg.error.message}`));
|
|
148
|
-
}
|
|
149
|
-
else {
|
|
150
|
-
p.resolve(msg.result);
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
catch {
|
|
155
|
-
// ignore non-JSON lines (e.g., server logs)
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
});
|
|
159
|
-
return {
|
|
160
|
-
async send(method, params) {
|
|
161
|
-
const id = ++requestId;
|
|
162
|
-
const message = JSON.stringify({
|
|
163
|
-
jsonrpc: "2.0",
|
|
164
|
-
id,
|
|
165
|
-
method,
|
|
166
|
-
params: params ?? {},
|
|
167
|
-
});
|
|
168
|
-
// Send as newline-delimited JSON (compatible with all MCP SDK versions)
|
|
169
|
-
proc.stdin.write(message + "\n");
|
|
170
|
-
return new Promise((resolve, reject) => {
|
|
171
|
-
const timeout = setTimeout(() => {
|
|
172
|
-
pending.delete(id);
|
|
173
|
-
reject(new Error(`MCP request timed out: ${method}`));
|
|
174
|
-
}, 30_000);
|
|
175
|
-
pending.set(id, {
|
|
176
|
-
resolve: (v) => {
|
|
177
|
-
clearTimeout(timeout);
|
|
178
|
-
resolve(v);
|
|
179
|
-
},
|
|
180
|
-
reject: (e) => {
|
|
181
|
-
clearTimeout(timeout);
|
|
182
|
-
reject(e);
|
|
183
|
-
},
|
|
184
|
-
});
|
|
185
|
-
});
|
|
186
|
-
},
|
|
187
|
-
async notify(method, params) {
|
|
188
|
-
// Notification = no id field, no response expected
|
|
189
|
-
const message = JSON.stringify({
|
|
190
|
-
jsonrpc: "2.0",
|
|
191
|
-
method,
|
|
192
|
-
...(params ? { params } : {}),
|
|
193
|
-
});
|
|
194
|
-
proc.stdin.write(message + "\n");
|
|
195
|
-
},
|
|
196
|
-
async close() {
|
|
197
|
-
// Graceful shutdown: stdin.end → wait → SIGTERM → wait → SIGKILL
|
|
198
|
-
const closePromise = new Promise((resolve) => {
|
|
199
|
-
proc.once("close", () => resolve());
|
|
200
|
-
});
|
|
201
|
-
try {
|
|
202
|
-
proc.stdin?.end();
|
|
203
|
-
}
|
|
204
|
-
catch { /* ignore */ }
|
|
205
|
-
await Promise.race([closePromise, new Promise((r) => setTimeout(r, 2000))]);
|
|
206
|
-
if (proc.exitCode === null) {
|
|
207
|
-
try {
|
|
208
|
-
proc.kill("SIGTERM");
|
|
209
|
-
}
|
|
210
|
-
catch { /* ignore */ }
|
|
211
|
-
await Promise.race([closePromise, new Promise((r) => setTimeout(r, 2000))]);
|
|
212
|
-
}
|
|
213
|
-
if (proc.exitCode === null) {
|
|
214
|
-
try {
|
|
215
|
-
proc.kill("SIGKILL");
|
|
216
|
-
}
|
|
217
|
-
catch { /* ignore */ }
|
|
218
|
-
}
|
|
219
|
-
},
|
|
220
|
-
};
|
|
221
|
-
}
|
|
222
|
-
// ============================================
|
|
223
|
-
// Transport: HTTP JSON-RPC (Streamable HTTP)
|
|
224
|
-
// ============================================
|
|
225
|
-
function createHttpTransport(source) {
|
|
226
|
-
let requestId = 0;
|
|
227
|
-
let sessionId = null;
|
|
228
|
-
return {
|
|
229
|
-
async send(method, params) {
|
|
230
|
-
const id = ++requestId;
|
|
231
|
-
const res = await fetch(source.url, {
|
|
232
|
-
method: "POST",
|
|
233
|
-
headers: {
|
|
234
|
-
"Content-Type": "application/json",
|
|
235
|
-
"Accept": "application/json, text/event-stream",
|
|
236
|
-
...source.headers,
|
|
237
|
-
...(sessionId ? { "mcp-session-id": sessionId } : {}),
|
|
238
|
-
},
|
|
239
|
-
body: JSON.stringify({
|
|
240
|
-
jsonrpc: "2.0",
|
|
241
|
-
id,
|
|
242
|
-
method,
|
|
243
|
-
params: params ?? {},
|
|
244
|
-
}),
|
|
245
|
-
});
|
|
246
|
-
if (!res.ok) {
|
|
247
|
-
throw new Error(`HTTP ${res.status}: ${await res.text()}`);
|
|
248
|
-
}
|
|
249
|
-
// Capture session ID if returned
|
|
250
|
-
const newSessionId = res.headers.get("mcp-session-id");
|
|
251
|
-
if (newSessionId)
|
|
252
|
-
sessionId = newSessionId;
|
|
253
|
-
const contentType = res.headers.get("content-type") ?? "";
|
|
254
|
-
// Handle SSE-wrapped responses (Streamable HTTP)
|
|
255
|
-
if (contentType.includes("text/event-stream")) {
|
|
256
|
-
const text = await res.text();
|
|
257
|
-
// Parse SSE: look for "data: {...}" lines
|
|
258
|
-
for (const line of text.split("\n")) {
|
|
259
|
-
if (line.startsWith("data: ")) {
|
|
260
|
-
try {
|
|
261
|
-
const msg = JSON.parse(line.slice(6));
|
|
262
|
-
if (msg.error) {
|
|
263
|
-
throw new Error(`MCP error ${msg.error.code}: ${msg.error.message}`);
|
|
264
|
-
}
|
|
265
|
-
return msg.result;
|
|
266
|
-
}
|
|
267
|
-
catch (e) {
|
|
268
|
-
if (e instanceof SyntaxError)
|
|
269
|
-
continue;
|
|
270
|
-
throw e;
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
throw new Error("No JSON-RPC response found in SSE stream");
|
|
275
|
-
}
|
|
276
|
-
// Standard JSON response
|
|
277
|
-
const msg = (await res.json());
|
|
278
|
-
if (msg.error) {
|
|
279
|
-
throw new Error(`MCP error ${msg.error.code}: ${msg.error.message}`);
|
|
280
|
-
}
|
|
281
|
-
return msg.result;
|
|
282
|
-
},
|
|
283
|
-
async notify(method, params) {
|
|
284
|
-
// Send notification (no id, accept 202 Accepted)
|
|
285
|
-
const res = await fetch(source.url, {
|
|
286
|
-
method: "POST",
|
|
287
|
-
headers: {
|
|
288
|
-
"Content-Type": "application/json",
|
|
289
|
-
"Accept": "application/json, text/event-stream",
|
|
290
|
-
...source.headers,
|
|
291
|
-
...(sessionId ? { "mcp-session-id": sessionId } : {}),
|
|
292
|
-
},
|
|
293
|
-
body: JSON.stringify({
|
|
294
|
-
jsonrpc: "2.0",
|
|
295
|
-
method,
|
|
296
|
-
...(params ? { params } : {}),
|
|
297
|
-
}),
|
|
298
|
-
});
|
|
299
|
-
// 202 Accepted is expected for notifications
|
|
300
|
-
if (!res.ok && res.status !== 202) {
|
|
301
|
-
await res.text().catch(() => { });
|
|
302
|
-
}
|
|
303
|
-
},
|
|
304
|
-
async close() {
|
|
305
|
-
// nothing to close for HTTP
|
|
306
|
-
},
|
|
307
|
-
};
|
|
308
|
-
}
|
|
309
|
-
// ============================================
|
|
310
|
-
// Transport: SSE (legacy MCP SSE protocol)
|
|
311
|
-
// ============================================
|
|
312
|
-
function createSseTransport(source) {
|
|
313
|
-
let postEndpoint = null;
|
|
314
|
-
let requestId = 0;
|
|
315
|
-
const pending = new Map();
|
|
316
|
-
let sseController = null;
|
|
317
|
-
// Connect to SSE and discover the POST endpoint
|
|
318
|
-
const connectPromise = (async () => {
|
|
319
|
-
const res = await fetch(source.url, {
|
|
320
|
-
headers: {
|
|
321
|
-
Accept: "text/event-stream",
|
|
322
|
-
...source.headers,
|
|
323
|
-
},
|
|
324
|
-
});
|
|
325
|
-
if (!res.ok) {
|
|
326
|
-
throw new Error(`SSE connect failed: ${res.status} ${await res.text()}`);
|
|
327
|
-
}
|
|
328
|
-
const reader = res.body.getReader();
|
|
329
|
-
sseController = reader;
|
|
330
|
-
const decoder = new TextDecoder();
|
|
331
|
-
let buffer = "";
|
|
332
|
-
// Read SSE events in background
|
|
333
|
-
(async () => {
|
|
334
|
-
try {
|
|
335
|
-
while (true) {
|
|
336
|
-
const { done, value } = await reader.read();
|
|
337
|
-
if (done)
|
|
338
|
-
break;
|
|
339
|
-
buffer += decoder.decode(value, { stream: true });
|
|
340
|
-
// Process complete SSE events
|
|
341
|
-
while (buffer.includes("\n\n")) {
|
|
342
|
-
const eventEnd = buffer.indexOf("\n\n");
|
|
343
|
-
const eventText = buffer.slice(0, eventEnd);
|
|
344
|
-
buffer = buffer.slice(eventEnd + 2);
|
|
345
|
-
let eventType = "message";
|
|
346
|
-
let eventData = "";
|
|
347
|
-
for (const line of eventText.split("\n")) {
|
|
348
|
-
if (line.startsWith("event: ")) {
|
|
349
|
-
eventType = line.slice(7).trim();
|
|
350
|
-
}
|
|
351
|
-
else if (line.startsWith("data: ")) {
|
|
352
|
-
eventData += line.slice(6);
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
if (eventType === "endpoint" && eventData) {
|
|
356
|
-
// Resolve relative URLs
|
|
357
|
-
const base = new URL(source.url);
|
|
358
|
-
postEndpoint = eventData.startsWith("http")
|
|
359
|
-
? eventData
|
|
360
|
-
: `${base.origin}${eventData}`;
|
|
361
|
-
}
|
|
362
|
-
else if (eventType === "message" && eventData) {
|
|
363
|
-
try {
|
|
364
|
-
const msg = JSON.parse(eventData);
|
|
365
|
-
if (msg.id !== undefined && pending.has(msg.id)) {
|
|
366
|
-
const p = pending.get(msg.id);
|
|
367
|
-
pending.delete(msg.id);
|
|
368
|
-
if (msg.error) {
|
|
369
|
-
p.reject(new Error(`MCP error ${msg.error.code}: ${msg.error.message}`));
|
|
370
|
-
}
|
|
371
|
-
else {
|
|
372
|
-
p.resolve(msg.result);
|
|
373
|
-
}
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
catch {
|
|
377
|
-
// ignore malformed JSON
|
|
378
|
-
}
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
catch {
|
|
384
|
-
// stream closed
|
|
385
|
-
}
|
|
386
|
-
})();
|
|
387
|
-
// Wait for endpoint to be discovered
|
|
388
|
-
const deadline = Date.now() + 10_000;
|
|
389
|
-
while (!postEndpoint && Date.now() < deadline) {
|
|
390
|
-
await new Promise((r) => setTimeout(r, 100));
|
|
391
|
-
}
|
|
392
|
-
if (!postEndpoint) {
|
|
393
|
-
throw new Error("SSE endpoint not discovered within timeout");
|
|
394
|
-
}
|
|
395
|
-
})();
|
|
396
|
-
return {
|
|
397
|
-
async send(method, params) {
|
|
398
|
-
await connectPromise;
|
|
399
|
-
const id = ++requestId;
|
|
400
|
-
const res = await fetch(postEndpoint, {
|
|
401
|
-
method: "POST",
|
|
402
|
-
headers: {
|
|
403
|
-
"Content-Type": "application/json",
|
|
404
|
-
...source.headers,
|
|
405
|
-
},
|
|
406
|
-
body: JSON.stringify({
|
|
407
|
-
jsonrpc: "2.0",
|
|
408
|
-
id,
|
|
409
|
-
method,
|
|
410
|
-
params: params ?? {},
|
|
411
|
-
}),
|
|
412
|
-
});
|
|
413
|
-
if (!res.ok) {
|
|
414
|
-
const body = await res.text();
|
|
415
|
-
throw new Error(`HTTP ${res.status}: ${body}`);
|
|
416
|
-
}
|
|
417
|
-
// Response may come via SSE stream or directly
|
|
418
|
-
const contentType = res.headers.get("content-type") ?? "";
|
|
419
|
-
if (contentType.includes("application/json")) {
|
|
420
|
-
const msg = (await res.json());
|
|
421
|
-
if (msg.error) {
|
|
422
|
-
throw new Error(`MCP error ${msg.error.code}: ${msg.error.message}`);
|
|
423
|
-
}
|
|
424
|
-
return msg.result;
|
|
425
|
-
}
|
|
426
|
-
// Otherwise wait for response via SSE stream
|
|
427
|
-
return new Promise((resolve, reject) => {
|
|
428
|
-
const timeout = setTimeout(() => {
|
|
429
|
-
pending.delete(id);
|
|
430
|
-
reject(new Error(`MCP SSE request timed out: ${method}`));
|
|
431
|
-
}, 30_000);
|
|
432
|
-
pending.set(id, {
|
|
433
|
-
resolve: (v) => {
|
|
434
|
-
clearTimeout(timeout);
|
|
435
|
-
resolve(v);
|
|
436
|
-
},
|
|
437
|
-
reject: (e) => {
|
|
438
|
-
clearTimeout(timeout);
|
|
439
|
-
reject(e);
|
|
440
|
-
},
|
|
441
|
-
});
|
|
442
|
-
});
|
|
443
|
-
},
|
|
444
|
-
async close() {
|
|
445
|
-
if (sseController) {
|
|
446
|
-
await sseController.cancel().catch(() => { });
|
|
447
|
-
}
|
|
448
|
-
},
|
|
449
|
-
async notify(method, params) {
|
|
450
|
-
await connectPromise;
|
|
451
|
-
await fetch(postEndpoint, {
|
|
452
|
-
method: "POST",
|
|
453
|
-
headers: {
|
|
454
|
-
"Content-Type": "application/json",
|
|
455
|
-
...source.headers,
|
|
456
|
-
},
|
|
457
|
-
body: JSON.stringify({
|
|
458
|
-
jsonrpc: "2.0",
|
|
459
|
-
method,
|
|
460
|
-
...(params ? { params } : {}),
|
|
461
|
-
}),
|
|
462
|
-
}).catch(() => { });
|
|
463
|
-
},
|
|
464
|
-
};
|
|
465
|
-
}
|
|
466
|
-
// ============================================
|
|
467
|
-
// Source Parsing
|
|
468
|
-
// ============================================
|
|
469
|
-
/**
|
|
470
|
-
* Extract the base URL from a server source (for OAuth discovery).
|
|
471
|
-
* Returns null for stdio/command-based sources.
|
|
472
|
-
*/
|
|
473
|
-
function resolveServerUrl(source) {
|
|
474
|
-
if (typeof source === "string") {
|
|
475
|
-
if (source.startsWith("http://") || source.startsWith("https://")) {
|
|
476
|
-
return source.replace(/\/sse$/, "");
|
|
477
|
-
}
|
|
478
|
-
return null;
|
|
479
|
-
}
|
|
480
|
-
if ("url" in source) {
|
|
481
|
-
return source.url.replace(/\/sse$/, "");
|
|
482
|
-
}
|
|
483
|
-
return null;
|
|
484
|
-
}
|
|
485
|
-
function parseServerSource(source) {
|
|
486
|
-
if (typeof source === "string") {
|
|
487
|
-
// URL -> HTTP or SSE transport
|
|
488
|
-
if (source.startsWith("http://") || source.startsWith("https://")) {
|
|
489
|
-
// URLs ending in /sse use SSE transport
|
|
490
|
-
if (source.endsWith("/sse")) {
|
|
491
|
-
return createSseTransport({ url: source });
|
|
492
|
-
}
|
|
493
|
-
return createHttpTransport({ url: source });
|
|
494
|
-
}
|
|
495
|
-
// Command string -> stdio transport
|
|
496
|
-
const parts = source.split(/\s+/);
|
|
497
|
-
return createStdioTransport({
|
|
498
|
-
command: parts[0],
|
|
499
|
-
args: parts.slice(1),
|
|
500
|
-
});
|
|
501
|
-
}
|
|
502
|
-
if ("url" in source) {
|
|
503
|
-
// URLs ending in /sse use SSE transport
|
|
504
|
-
if (source.url.endsWith("/sse")) {
|
|
505
|
-
return createSseTransport(source);
|
|
506
|
-
}
|
|
507
|
-
return createHttpTransport(source);
|
|
508
|
-
}
|
|
509
|
-
if ("spawn" in source) {
|
|
510
|
-
return createSpawnHttpTransport(source);
|
|
511
|
-
}
|
|
512
|
-
return createStdioTransport(source);
|
|
513
|
-
}
|
|
514
|
-
// ============================================
|
|
515
|
-
// Transport: Spawn + HTTP (for servers needing a port)
|
|
516
|
-
// ============================================
|
|
517
|
-
function createSpawnHttpTransport(source) {
|
|
518
|
-
const port = source.port ?? Math.floor(40000 + Math.random() * 10000);
|
|
519
|
-
const endpoint = source.endpoint ?? "/mcp";
|
|
520
|
-
const args = [...(source.args ?? []), "--port", String(port)];
|
|
521
|
-
const spawnEnv = source.env
|
|
522
|
-
? { ...getDefaultEnvironment(), ...source.env }
|
|
523
|
-
: { ...process.env };
|
|
524
|
-
const proc = Bun.spawn([source.spawn, ...args], {
|
|
525
|
-
stdin: "pipe",
|
|
526
|
-
stdout: "pipe",
|
|
527
|
-
stderr: "pipe",
|
|
528
|
-
env: spawnEnv,
|
|
529
|
-
});
|
|
530
|
-
// Create inner HTTP transport
|
|
531
|
-
const inner = createHttpTransport({ url: `http://127.0.0.1:${port}${endpoint}` });
|
|
532
|
-
// Wait for server to be ready
|
|
533
|
-
const readyPromise = (async () => {
|
|
534
|
-
const deadline = Date.now() + 15_000;
|
|
535
|
-
while (Date.now() < deadline) {
|
|
536
|
-
try {
|
|
537
|
-
await fetch(`http://127.0.0.1:${port}${endpoint}`, {
|
|
538
|
-
method: "POST",
|
|
539
|
-
headers: { "Content-Type": "application/json" },
|
|
540
|
-
body: "{}",
|
|
541
|
-
signal: AbortSignal.timeout(1000),
|
|
542
|
-
});
|
|
543
|
-
// Any response (even 400) means server is up
|
|
544
|
-
return;
|
|
545
|
-
}
|
|
546
|
-
catch {
|
|
547
|
-
await new Promise((r) => setTimeout(r, 500));
|
|
548
|
-
}
|
|
549
|
-
}
|
|
550
|
-
throw new Error(`Server failed to start on port ${port} within 15s`);
|
|
551
|
-
})();
|
|
552
|
-
return {
|
|
553
|
-
async send(method, params) {
|
|
554
|
-
await readyPromise;
|
|
555
|
-
return inner.send(method, params);
|
|
556
|
-
},
|
|
557
|
-
async notify(method, params) {
|
|
558
|
-
await readyPromise;
|
|
559
|
-
return inner.notify(method, params);
|
|
560
|
-
},
|
|
561
|
-
async close() {
|
|
562
|
-
await inner.close();
|
|
563
|
-
proc.kill();
|
|
564
|
-
},
|
|
565
|
-
};
|
|
566
|
-
}
|
|
567
|
-
// ============================================
|
|
568
|
-
// Code Generation Helpers
|
|
569
|
-
// ============================================
|
|
570
|
-
/** Convert tool name to a valid TypeScript identifier (camelCase) */
|
|
571
|
-
export function toIdentifier(name) {
|
|
572
|
-
return name
|
|
573
|
-
.replace(/[^a-zA-Z0-9_]/g, "_")
|
|
574
|
-
.split("_")
|
|
575
|
-
.filter(Boolean)
|
|
576
|
-
.map((part, i) => i === 0
|
|
577
|
-
? part.toLowerCase()
|
|
578
|
-
: part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
|
|
579
|
-
.join("");
|
|
580
|
-
}
|
|
581
|
-
/** Convert tool name to PascalCase for type names */
|
|
582
|
-
export function toPascalCase(name) {
|
|
583
|
-
return name
|
|
584
|
-
.replace(/[^a-zA-Z0-9_]/g, "_")
|
|
585
|
-
.split("_")
|
|
586
|
-
.filter(Boolean)
|
|
587
|
-
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
|
|
588
|
-
.join("");
|
|
589
|
-
}
|
|
590
|
-
/** Convert tool name to kebab-case for file names */
|
|
591
|
-
function toKebabCase(name) {
|
|
592
|
-
return name
|
|
593
|
-
.replace(/[^a-zA-Z0-9]/g, "-")
|
|
594
|
-
.replace(/-+/g, "-")
|
|
595
|
-
.replace(/^-|-$/g, "")
|
|
596
|
-
.toLowerCase();
|
|
597
|
-
}
|
|
598
|
-
/** Serialize a JSON schema to a readable TypeScript literal string */
|
|
599
|
-
export function schemaToString(schema, indent = 4) {
|
|
600
|
-
const pad = " ".repeat(indent);
|
|
601
|
-
const lines = [];
|
|
602
|
-
lines.push("{");
|
|
603
|
-
lines.push(`${pad}type: '${schema.type}' as const,`);
|
|
604
|
-
if (schema.description) {
|
|
605
|
-
lines.push(`${pad}description: ${JSON.stringify(schema.description)},`);
|
|
606
|
-
}
|
|
607
|
-
if (schema.enum) {
|
|
608
|
-
lines.push(`${pad}enum: ${JSON.stringify(schema.enum)},`);
|
|
609
|
-
}
|
|
610
|
-
if (schema.properties) {
|
|
611
|
-
lines.push(`${pad}properties: {`);
|
|
612
|
-
for (const [key, prop] of Object.entries(schema.properties)) {
|
|
613
|
-
const safeKey = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : JSON.stringify(key);
|
|
614
|
-
lines.push(`${pad} ${safeKey}: ${schemaToString(prop, indent + 4)},`);
|
|
615
|
-
}
|
|
616
|
-
lines.push(`${pad}},`);
|
|
617
|
-
}
|
|
618
|
-
if (schema.items) {
|
|
619
|
-
lines.push(`${pad}items: ${schemaToString(schema.items, indent + 2)},`);
|
|
620
|
-
}
|
|
621
|
-
if (schema.required && schema.required.length > 0) {
|
|
622
|
-
lines.push(`${pad}required: [${schema.required.map((r) => `'${r}'`).join(", ")}] as const,`);
|
|
623
|
-
}
|
|
624
|
-
if (schema.additionalProperties !== undefined) {
|
|
625
|
-
if (typeof schema.additionalProperties === "boolean") {
|
|
626
|
-
lines.push(`${pad}additionalProperties: ${schema.additionalProperties},`);
|
|
627
|
-
}
|
|
628
|
-
else {
|
|
629
|
-
lines.push(`${pad}additionalProperties: ${schemaToString(schema.additionalProperties, indent + 2)},`);
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
if (schema.default !== undefined) {
|
|
633
|
-
lines.push(`${pad}default: ${JSON.stringify(schema.default)},`);
|
|
634
|
-
}
|
|
635
|
-
lines.push(`${" ".repeat(indent - 2)}}`);
|
|
636
|
-
return lines.join("\n");
|
|
637
|
-
}
|
|
638
|
-
/** Generate a TypeScript interface from a JSON Schema */
|
|
639
|
-
export function schemaToInterface(name, schema) {
|
|
640
|
-
if (schema.type !== "object" || !schema.properties) {
|
|
641
|
-
return `export type ${name} = unknown;`;
|
|
642
|
-
}
|
|
643
|
-
const required = new Set(schema.required ?? []);
|
|
644
|
-
const lines = [`export interface ${name} {`];
|
|
645
|
-
for (const [key, prop] of Object.entries(schema.properties)) {
|
|
646
|
-
const p = prop;
|
|
647
|
-
const optional = required.has(key) ? "" : "?";
|
|
648
|
-
const tsType = jsonSchemaToTsType(p);
|
|
649
|
-
if (p.description) {
|
|
650
|
-
lines.push(` /** ${p.description} */`);
|
|
651
|
-
}
|
|
652
|
-
lines.push(` ${/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : JSON.stringify(key)}${optional}: ${tsType};`);
|
|
653
|
-
}
|
|
654
|
-
lines.push("}");
|
|
655
|
-
return lines.join("\n");
|
|
656
|
-
}
|
|
657
|
-
/** Convert a JSON Schema type to a TypeScript type string */
|
|
658
|
-
function jsonSchemaToTsType(schema) {
|
|
659
|
-
// const literal
|
|
660
|
-
if (schema.const !== undefined) {
|
|
661
|
-
return JSON.stringify(schema.const);
|
|
662
|
-
}
|
|
663
|
-
// enum
|
|
664
|
-
if (schema.enum) {
|
|
665
|
-
return schema.enum.map((v) => JSON.stringify(v)).join(" | ");
|
|
666
|
-
}
|
|
667
|
-
// oneOf / anyOf → union
|
|
668
|
-
if (schema.oneOf) {
|
|
669
|
-
return schema.oneOf.map(jsonSchemaToTsType).join(" | ");
|
|
670
|
-
}
|
|
671
|
-
if (schema.anyOf) {
|
|
672
|
-
return schema.anyOf.map(jsonSchemaToTsType).join(" | ");
|
|
673
|
-
}
|
|
674
|
-
// allOf → intersection
|
|
675
|
-
if (schema.allOf) {
|
|
676
|
-
return schema.allOf.map(jsonSchemaToTsType).join(" & ");
|
|
677
|
-
}
|
|
678
|
-
// not → exclude
|
|
679
|
-
if (schema.not) {
|
|
680
|
-
return `Exclude<unknown, ${jsonSchemaToTsType(schema.not)}>`;
|
|
681
|
-
}
|
|
682
|
-
// $ref
|
|
683
|
-
if (schema.$ref) {
|
|
684
|
-
const ref = schema.$ref;
|
|
685
|
-
// Extract name from #/$defs/Foo or #/definitions/Foo
|
|
686
|
-
const match = ref.match(/\/([^/]+)$/);
|
|
687
|
-
return match ? match[1] : "unknown";
|
|
688
|
-
}
|
|
689
|
-
switch (schema.type) {
|
|
690
|
-
case "string":
|
|
691
|
-
// Include format hint if present
|
|
692
|
-
if (schema.format)
|
|
693
|
-
return `string /* ${schema.format} */`;
|
|
694
|
-
return "string";
|
|
695
|
-
case "integer":
|
|
696
|
-
return "number /* integer */";
|
|
697
|
-
case "number":
|
|
698
|
-
return "number";
|
|
699
|
-
case "boolean":
|
|
700
|
-
return "boolean";
|
|
701
|
-
case "null":
|
|
702
|
-
return "null";
|
|
703
|
-
case "array":
|
|
704
|
-
if (schema.items) {
|
|
705
|
-
return `${jsonSchemaToTsType(schema.items)}[]`;
|
|
706
|
-
}
|
|
707
|
-
// Tuple arrays (prefixItems)
|
|
708
|
-
if (schema.prefixItems) {
|
|
709
|
-
const items = schema.prefixItems.map(jsonSchemaToTsType);
|
|
710
|
-
return `[${items.join(", ")}]`;
|
|
711
|
-
}
|
|
712
|
-
return "unknown[]";
|
|
713
|
-
case "object":
|
|
714
|
-
if (schema.properties) {
|
|
715
|
-
const required = new Set(schema.required ?? []);
|
|
716
|
-
const props = Object.entries(schema.properties)
|
|
717
|
-
.map(([k, v]) => {
|
|
718
|
-
const opt = required.has(k) ? "" : "?";
|
|
719
|
-
return `${k}${opt}: ${jsonSchemaToTsType(v)}`;
|
|
720
|
-
})
|
|
721
|
-
.join("; ");
|
|
722
|
-
// additionalProperties
|
|
723
|
-
if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
|
|
724
|
-
const addlType = jsonSchemaToTsType(schema.additionalProperties);
|
|
725
|
-
return props
|
|
726
|
-
? `{ ${props}; [key: string]: ${addlType} }`
|
|
727
|
-
: `Record<string, ${addlType}>`;
|
|
728
|
-
}
|
|
729
|
-
return `{ ${props} }`;
|
|
730
|
-
}
|
|
731
|
-
if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
|
|
732
|
-
return `Record<string, ${jsonSchemaToTsType(schema.additionalProperties)}>`;
|
|
733
|
-
}
|
|
734
|
-
return "Record<string, unknown>";
|
|
735
|
-
default:
|
|
736
|
-
// type as array (e.g., ["string", "null"])
|
|
737
|
-
if (Array.isArray(schema.type)) {
|
|
738
|
-
return schema.type.map((t) => (t === "null" ? "null" : t === "integer" ? "number" : t)).join(" | ");
|
|
739
|
-
}
|
|
740
|
-
return "unknown";
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
// ============================================
|
|
744
|
-
// File Generators
|
|
745
|
-
// ============================================
|
|
746
|
-
function generateToolFile(tool, _sdkImport, _generateTypes) {
|
|
747
|
-
const schema = tool.inputSchema ?? {
|
|
748
|
-
type: "object",
|
|
749
|
-
properties: {},
|
|
750
|
-
};
|
|
751
|
-
const lines = [];
|
|
752
|
-
// Title
|
|
753
|
-
lines.push(`# ${tool.name}`);
|
|
754
|
-
lines.push("");
|
|
755
|
-
if (tool.description) {
|
|
756
|
-
lines.push(tool.description);
|
|
757
|
-
lines.push("");
|
|
758
|
-
}
|
|
759
|
-
// Parameters table
|
|
760
|
-
const props = (schema.properties ?? {});
|
|
761
|
-
const required = new Set(schema.required ?? []);
|
|
762
|
-
const paramNames = Object.keys(props);
|
|
763
|
-
if (paramNames.length > 0) {
|
|
764
|
-
lines.push("## Parameters");
|
|
765
|
-
lines.push("");
|
|
766
|
-
lines.push("| Name | Type | Required | Description |");
|
|
767
|
-
lines.push("|------|------|----------|-------------|");
|
|
768
|
-
for (const name of paramNames) {
|
|
769
|
-
const prop = props[name];
|
|
770
|
-
const type = jsonSchemaToTsType(prop);
|
|
771
|
-
const req = required.has(name) ? "\u2713" : "";
|
|
772
|
-
const desc = (prop.description ?? "").replace(/\|/g, "\\|");
|
|
773
|
-
lines.push(`| ${name} | \`${type}\` | ${req} | ${desc} |`);
|
|
774
|
-
}
|
|
775
|
-
lines.push("");
|
|
776
|
-
}
|
|
777
|
-
return lines.join("\n");
|
|
778
|
-
}
|
|
779
|
-
function generateAgentConfig(serverInfo, _tools, agentPath, sdkImport, visibility) {
|
|
780
|
-
const lines = [];
|
|
781
|
-
lines.push(`/**`);
|
|
782
|
-
lines.push(` * Agent: ${agentPath}`);
|
|
783
|
-
if (serverInfo.name) {
|
|
784
|
-
lines.push(` * MCP Server: ${serverInfo.name} v${serverInfo.version ?? "unknown"}`);
|
|
785
|
-
}
|
|
786
|
-
lines.push(` *`);
|
|
787
|
-
lines.push(` * Auto-generated by agents-sdk codegen.`);
|
|
788
|
-
lines.push(` */`);
|
|
789
|
-
lines.push("");
|
|
790
|
-
lines.push(`import { defineAgent } from '${sdkImport}';`);
|
|
791
|
-
lines.push("");
|
|
792
|
-
lines.push(`export default defineAgent({`);
|
|
793
|
-
lines.push(` path: '${agentPath}',`);
|
|
794
|
-
lines.push(` entrypoint: './entrypoint.md',`);
|
|
795
|
-
lines.push(` visibility: '${visibility}' as const,`);
|
|
796
|
-
lines.push(`});`);
|
|
797
|
-
lines.push("");
|
|
798
|
-
return lines.join("\n");
|
|
799
|
-
}
|
|
800
|
-
function generateEntrypoint(serverInfo, tools, agentPath) {
|
|
801
|
-
const lines = [];
|
|
802
|
-
const name = serverInfo.name ?? agentPath;
|
|
803
|
-
lines.push(`# ${name}`);
|
|
804
|
-
lines.push("");
|
|
805
|
-
if (serverInfo.version) {
|
|
806
|
-
lines.push(`> MCP Server v${serverInfo.version}`);
|
|
807
|
-
lines.push("");
|
|
808
|
-
}
|
|
809
|
-
lines.push(`You are an agent wrapping the ${name} MCP server.`);
|
|
810
|
-
lines.push("");
|
|
811
|
-
lines.push(`## Available Tools`);
|
|
812
|
-
lines.push("");
|
|
813
|
-
for (const tool of tools) {
|
|
814
|
-
lines.push(`- **${tool.name}**: ${tool.description ?? "No description"}`);
|
|
815
|
-
}
|
|
816
|
-
lines.push("");
|
|
817
|
-
return lines.join("\n");
|
|
818
|
-
}
|
|
819
|
-
function generateIndex(_tools) {
|
|
820
|
-
const lines = [];
|
|
821
|
-
lines.push(`/**`);
|
|
822
|
-
lines.push(` * Auto-generated index.`);
|
|
823
|
-
lines.push(` */`);
|
|
824
|
-
lines.push("");
|
|
825
|
-
lines.push(`export { default as agent } from './agent.config.js';`);
|
|
826
|
-
lines.push("");
|
|
827
|
-
return lines.join("\n");
|
|
828
|
-
}
|
|
829
|
-
function generateCli(serverInfo, tools, agentPath) {
|
|
830
|
-
const name = serverInfo.name ?? agentPath;
|
|
831
|
-
const lines = [];
|
|
832
|
-
lines.push(`#!/usr/bin/env bun`);
|
|
833
|
-
lines.push(`/**`);
|
|
834
|
-
lines.push(` * CLI for ${name}`);
|
|
835
|
-
lines.push(` *`);
|
|
836
|
-
lines.push(` * Usage:`);
|
|
837
|
-
lines.push(` * bun cli.ts <tool_name> [json_params]`);
|
|
838
|
-
lines.push(` * bun cli.ts --list`);
|
|
839
|
-
lines.push(` *`);
|
|
840
|
-
lines.push(` * Auto-generated by agents-sdk codegen.`);
|
|
841
|
-
lines.push(` */`);
|
|
842
|
-
lines.push("");
|
|
843
|
-
lines.push(`const tools = ${JSON.stringify(tools.map(t => ({ name: t.name, description: t.description ?? '' })), null, 2)};`);
|
|
844
|
-
lines.push("");
|
|
845
|
-
lines.push(`const args = process.argv.slice(2);`);
|
|
846
|
-
lines.push("");
|
|
847
|
-
lines.push(`if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {`);
|
|
848
|
-
lines.push(` console.log('${name} CLI\\n');`);
|
|
849
|
-
lines.push(` console.log('Usage: bun cli.ts <tool> [params_json]\\n');`);
|
|
850
|
-
lines.push(` console.log('Available tools:');`);
|
|
851
|
-
lines.push(` for (const t of tools) {`);
|
|
852
|
-
lines.push(` console.log(\` \${t.name.padEnd(30)} \${t.description}\`);`);
|
|
853
|
-
lines.push(` }`);
|
|
854
|
-
lines.push(` process.exit(0);`);
|
|
855
|
-
lines.push(`}`);
|
|
856
|
-
lines.push("");
|
|
857
|
-
lines.push(`if (args[0] === '--list') {`);
|
|
858
|
-
lines.push(` for (const t of tools) {`);
|
|
859
|
-
lines.push(` console.log(\`\${t.name}\\t\${t.description}\`);`);
|
|
860
|
-
lines.push(` }`);
|
|
861
|
-
lines.push(` process.exit(0);`);
|
|
862
|
-
lines.push(`}`);
|
|
863
|
-
lines.push("");
|
|
864
|
-
lines.push(`const toolName = args[0];`);
|
|
865
|
-
lines.push(`const params = args[1] ? JSON.parse(args[1]) : {};`);
|
|
866
|
-
lines.push("");
|
|
867
|
-
lines.push(`if (!tools.find(t => t.name === toolName)) {`);
|
|
868
|
-
lines.push(` console.error(\`Unknown tool: \${toolName}\`);`);
|
|
869
|
-
lines.push(` console.error(\`Available: \${tools.map(t => t.name).join(', ')}\`);`);
|
|
870
|
-
lines.push(` process.exit(1);`);
|
|
871
|
-
lines.push(`}`);
|
|
872
|
-
lines.push("");
|
|
873
|
-
lines.push(`// TODO: Connect to MCP server and execute the tool`);
|
|
874
|
-
lines.push(`console.log(JSON.stringify({ tool: toolName, params, status: 'not_connected' }, null, 2));`);
|
|
875
|
-
lines.push("");
|
|
876
|
-
return lines.join("\n");
|
|
877
|
-
}
|
|
878
|
-
function generateManifest(serverSource, serverInfo, tools, agentPath, oauth) {
|
|
879
|
-
// Build connection spec from server source + OAuth discovery
|
|
880
|
-
const serverUrl = resolveServerUrl(serverSource);
|
|
881
|
-
const connection = serverUrl
|
|
882
|
-
? {
|
|
883
|
-
url: serverUrl,
|
|
884
|
-
transport: (typeof serverSource === 'string' && serverSource.endsWith('/sse')) ||
|
|
885
|
-
(typeof serverSource === 'object' && 'url' in serverSource && serverSource.url.endsWith('/sse'))
|
|
886
|
-
? 'sse'
|
|
887
|
-
: 'http',
|
|
888
|
-
auth: oauth
|
|
889
|
-
? {
|
|
890
|
-
type: 'oauth',
|
|
891
|
-
discovery: `${serverUrl.replace(/\/mcp$/, '')}/.well-known/oauth-authorization-server`,
|
|
892
|
-
dynamic_registration: !!oauth.registration_endpoint,
|
|
893
|
-
}
|
|
894
|
-
: { type: 'none' },
|
|
895
|
-
}
|
|
896
|
-
: undefined;
|
|
897
|
-
const manifest = {
|
|
898
|
-
agentPath,
|
|
899
|
-
serverSource,
|
|
900
|
-
serverInfo,
|
|
901
|
-
tools: tools.map((t) => ({ name: t.name, description: t.description, ...(t.inputSchema ? { inputSchema: t.inputSchema } : {}) })),
|
|
902
|
-
...(connection ? { connection } : {}),
|
|
903
|
-
...(oauth ? { oauth } : {}),
|
|
904
|
-
generatedAt: new Date().toISOString(),
|
|
905
|
-
};
|
|
906
|
-
return JSON.stringify(manifest, null, 2) + "\n";
|
|
907
|
-
}
|
|
908
|
-
// ============================================
|
|
909
|
-
// Main: codegen()
|
|
910
|
-
// ============================================
|
|
911
|
-
/**
|
|
912
|
-
* Connect to an MCP server, introspect its tools, and generate
|
|
913
|
-
* agent-definition source files.
|
|
914
|
-
*/
|
|
915
|
-
export async function codegen(options) {
|
|
916
|
-
const sdkImport = options.sdkImport ?? "@slashfi/agents-sdk";
|
|
917
|
-
const generateTypes = options.types !== false;
|
|
918
|
-
const generateCliFile = options.cli !== false;
|
|
919
|
-
const visibility = options.visibility ?? "public";
|
|
920
|
-
const outDir = resolve(options.outDir);
|
|
921
|
-
// 1. Connect to MCP server
|
|
922
|
-
const transport = parseServerSource(options.server);
|
|
923
|
-
let serverInfo = {};
|
|
924
|
-
let tools = [];
|
|
925
|
-
try {
|
|
926
|
-
// 2. Initialize handshake
|
|
927
|
-
const initResult = (await transport.send("initialize", {
|
|
928
|
-
protocolVersion: LATEST_PROTOCOL_VERSION,
|
|
929
|
-
capabilities: {},
|
|
930
|
-
clientInfo: { name: "agents-sdk-codegen", version: "1.0.0" },
|
|
931
|
-
}));
|
|
932
|
-
// Validate protocol version
|
|
933
|
-
if (initResult?.protocolVersion &&
|
|
934
|
-
!SUPPORTED_PROTOCOL_VERSIONS.includes(initResult.protocolVersion)) {
|
|
935
|
-
throw new Error(`Server protocol version ${initResult.protocolVersion} is not supported. Supported: ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")}`);
|
|
936
|
-
}
|
|
937
|
-
serverInfo = initResult?.serverInfo ?? {};
|
|
938
|
-
// Send initialized notification (no id — this is a notification, not a request)
|
|
939
|
-
await transport.notify("notifications/initialized");
|
|
940
|
-
// 3. List tools (with pagination)
|
|
941
|
-
const allTools = [];
|
|
942
|
-
let cursor;
|
|
943
|
-
do {
|
|
944
|
-
const toolsResult = (await transport.send("tools/list", {
|
|
945
|
-
...(cursor ? { cursor } : {}),
|
|
946
|
-
}));
|
|
947
|
-
allTools.push(...(toolsResult?.tools ?? []));
|
|
948
|
-
cursor = toolsResult?.nextCursor;
|
|
949
|
-
} while (cursor);
|
|
950
|
-
tools = allTools;
|
|
951
|
-
}
|
|
952
|
-
finally {
|
|
953
|
-
await transport.close();
|
|
954
|
-
}
|
|
955
|
-
if (tools.length === 0) {
|
|
956
|
-
throw new Error("MCP server returned no tools. Is the server running and configured correctly?");
|
|
957
|
-
}
|
|
958
|
-
// 3.5. Discover OAuth metadata (for URL-based servers)
|
|
959
|
-
let oauth = null;
|
|
960
|
-
const serverUrl = resolveServerUrl(options.server);
|
|
961
|
-
if (serverUrl) {
|
|
962
|
-
oauth = await discoverOAuthMetadata(serverUrl);
|
|
963
|
-
}
|
|
964
|
-
// 4. Derive agent path
|
|
965
|
-
const agentPath = options.agentPath ??
|
|
966
|
-
`@${(options.name ?? serverInfo.name ?? "mcp-agent").toLowerCase().replace(/[^a-z0-9-]/g, "-")}`;
|
|
967
|
-
// 5. Create output directory
|
|
968
|
-
mkdirSync(outDir, { recursive: true });
|
|
969
|
-
const files = [];
|
|
970
|
-
// 6. Generate tool files
|
|
971
|
-
const toolFiles = [];
|
|
972
|
-
for (const tool of tools) {
|
|
973
|
-
const fileName = `${toKebabCase(tool.name)}.tool.md`;
|
|
974
|
-
const content = generateToolFile(tool, sdkImport, generateTypes);
|
|
975
|
-
writeFileSync(join(outDir, fileName), content);
|
|
976
|
-
toolFiles.push(fileName);
|
|
977
|
-
files.push(fileName);
|
|
978
|
-
}
|
|
979
|
-
// 7. Generate entrypoint.md
|
|
980
|
-
const entrypoint = generateEntrypoint(serverInfo, tools, agentPath);
|
|
981
|
-
writeFileSync(join(outDir, "entrypoint.md"), entrypoint);
|
|
982
|
-
files.push("entrypoint.md");
|
|
983
|
-
// 8. Generate agent.config.ts
|
|
984
|
-
const agentConfig = generateAgentConfig(serverInfo, tools, agentPath, sdkImport, visibility);
|
|
985
|
-
writeFileSync(join(outDir, "agent.config.ts"), agentConfig);
|
|
986
|
-
files.push("agent.config.ts");
|
|
987
|
-
// 9. Generate index.ts
|
|
988
|
-
const index = generateIndex(tools);
|
|
989
|
-
writeFileSync(join(outDir, "index.ts"), index);
|
|
990
|
-
files.push("index.ts");
|
|
991
|
-
// 10. Generate CLI
|
|
992
|
-
if (generateCliFile) {
|
|
993
|
-
const cli = generateCli(serverInfo, tools, agentPath);
|
|
994
|
-
writeFileSync(join(outDir, "cli.ts"), cli);
|
|
995
|
-
files.push("cli.ts");
|
|
996
|
-
}
|
|
997
|
-
// 11. Generate manifest (for `agents-sdk use`)
|
|
998
|
-
const manifest = generateManifest(options.server, serverInfo, tools, agentPath, oauth);
|
|
999
|
-
writeFileSync(join(outDir, ".codegen-manifest.json"), manifest);
|
|
1000
|
-
files.push(".codegen-manifest.json");
|
|
1001
|
-
return {
|
|
1002
|
-
outDir,
|
|
1003
|
-
serverInfo,
|
|
1004
|
-
toolCount: tools.length,
|
|
1005
|
-
toolFiles,
|
|
1006
|
-
files,
|
|
1007
|
-
...(oauth ? { oauth } : {}),
|
|
1008
|
-
};
|
|
1009
|
-
}
|
|
1010
|
-
// ============================================
|
|
1011
|
-
// Use: execute a tool on a codegenned agent
|
|
1012
|
-
// ============================================
|
|
1013
|
-
/**
|
|
1014
|
-
* Execute a tool on a previously codegenned agent by reconnecting
|
|
1015
|
-
* to the MCP server and calling the tool.
|
|
1016
|
-
*/
|
|
1017
|
-
export async function useAgent(options) {
|
|
1018
|
-
const manifestPath = join(resolve(options.agentDir), ".codegen-manifest.json");
|
|
1019
|
-
if (!existsSync(manifestPath)) {
|
|
1020
|
-
throw new Error(`No codegen manifest found at ${manifestPath}. Run codegen first.`);
|
|
1021
|
-
}
|
|
1022
|
-
const manifest = JSON.parse(readFileSync(manifestPath, "utf-8"));
|
|
1023
|
-
// Verify tool exists
|
|
1024
|
-
const toolDef = manifest.tools.find((t) => t.name === options.tool);
|
|
1025
|
-
if (!toolDef) {
|
|
1026
|
-
const available = manifest.tools.map((t) => t.name).join(", ");
|
|
1027
|
-
throw new Error(`Unknown tool '${options.tool}'. Available: ${available}`);
|
|
1028
|
-
}
|
|
1029
|
-
// Connect to server and call tool
|
|
1030
|
-
const transport = parseServerSource(manifest.serverSource);
|
|
1031
|
-
try {
|
|
1032
|
-
await transport.send("initialize", {
|
|
1033
|
-
protocolVersion: LATEST_PROTOCOL_VERSION,
|
|
1034
|
-
capabilities: {},
|
|
1035
|
-
clientInfo: { name: "agents-sdk-use", version: "1.0.0" },
|
|
1036
|
-
});
|
|
1037
|
-
await transport.notify("notifications/initialized");
|
|
1038
|
-
const result = await transport.send("tools/call", {
|
|
1039
|
-
name: options.tool,
|
|
1040
|
-
arguments: options.params ?? {},
|
|
1041
|
-
});
|
|
1042
|
-
return result;
|
|
1043
|
-
}
|
|
1044
|
-
finally {
|
|
1045
|
-
await transport.close();
|
|
1046
|
-
}
|
|
1047
|
-
}
|
|
1048
|
-
/**
|
|
1049
|
-
* List tools available on a codegenned agent.
|
|
1050
|
-
*/
|
|
1051
|
-
export function listAgentTools(agentDir) {
|
|
1052
|
-
const manifestPath = join(resolve(agentDir), ".codegen-manifest.json");
|
|
1053
|
-
if (!existsSync(manifestPath)) {
|
|
1054
|
-
throw new Error(`No codegen manifest found at ${manifestPath}. Run codegen first.`);
|
|
1055
|
-
}
|
|
1056
|
-
const manifest = JSON.parse(readFileSync(manifestPath, "utf-8"));
|
|
1057
|
-
return manifest.tools;
|
|
1058
|
-
}
|
|
1059
|
-
//# sourceMappingURL=codegen.js.map
|