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