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