@slashfi/agents-sdk 0.17.0 → 0.19.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.
@@ -0,0 +1,1016 @@
1
+ // @ts-nocheck — WIP codegen module, type errors will be fixed in a dedicated PR
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
+ import { mkdirSync, writeFileSync, existsSync, readFileSync } from "node:fs";
32
+ import { join, resolve } from "node:path";
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
+ function parseServerSource(source) {
470
+ if (typeof source === "string") {
471
+ // URL -> HTTP or SSE transport
472
+ if (source.startsWith("http://") || source.startsWith("https://")) {
473
+ // URLs ending in /sse use SSE transport
474
+ if (source.endsWith("/sse")) {
475
+ return createSseTransport({ url: source });
476
+ }
477
+ return createHttpTransport({ url: source });
478
+ }
479
+ // Command string -> stdio transport
480
+ const parts = source.split(/\s+/);
481
+ return createStdioTransport({
482
+ command: parts[0],
483
+ args: parts.slice(1),
484
+ });
485
+ }
486
+ if ("url" in source) {
487
+ // URLs ending in /sse use SSE transport
488
+ if (source.url.endsWith("/sse")) {
489
+ return createSseTransport(source);
490
+ }
491
+ return createHttpTransport(source);
492
+ }
493
+ if ("spawn" in source) {
494
+ return createSpawnHttpTransport(source);
495
+ }
496
+ return createStdioTransport(source);
497
+ }
498
+ // ============================================
499
+ // Transport: Spawn + HTTP (for servers needing a port)
500
+ // ============================================
501
+ function createSpawnHttpTransport(source) {
502
+ const port = source.port ?? Math.floor(40000 + Math.random() * 10000);
503
+ const endpoint = source.endpoint ?? "/mcp";
504
+ const args = [...(source.args ?? []), "--port", String(port)];
505
+ const spawnEnv = source.env
506
+ ? { ...getDefaultEnvironment(), ...source.env }
507
+ : { ...process.env };
508
+ const proc = Bun.spawn([source.spawn, ...args], {
509
+ stdin: "pipe",
510
+ stdout: "pipe",
511
+ stderr: "pipe",
512
+ env: spawnEnv,
513
+ });
514
+ // Create inner HTTP transport
515
+ const inner = createHttpTransport({ url: `http://127.0.0.1:${port}${endpoint}` });
516
+ // Wait for server to be ready
517
+ const readyPromise = (async () => {
518
+ const deadline = Date.now() + 15_000;
519
+ while (Date.now() < deadline) {
520
+ try {
521
+ const _res = await fetch(`http://127.0.0.1:${port}${endpoint}`, {
522
+ method: "POST",
523
+ headers: { "Content-Type": "application/json" },
524
+ body: "{}",
525
+ signal: AbortSignal.timeout(1000),
526
+ });
527
+ // Any response (even 400) means server is up
528
+ return;
529
+ }
530
+ catch {
531
+ await new Promise((r) => setTimeout(r, 500));
532
+ }
533
+ }
534
+ throw new Error(`Server failed to start on port ${port} within 15s`);
535
+ })();
536
+ return {
537
+ async send(method, params) {
538
+ await readyPromise;
539
+ return inner.send(method, params);
540
+ },
541
+ async notify(method, params) {
542
+ await readyPromise;
543
+ return inner.notify(method, params);
544
+ },
545
+ async close() {
546
+ await inner.close();
547
+ proc.kill();
548
+ },
549
+ };
550
+ }
551
+ // ============================================
552
+ // Code Generation Helpers
553
+ // ============================================
554
+ /** Convert tool name to a valid TypeScript identifier (camelCase) */
555
+ function toIdentifier(name) {
556
+ return name
557
+ .replace(/[^a-zA-Z0-9_]/g, "_")
558
+ .split("_")
559
+ .filter(Boolean)
560
+ .map((part, i) => i === 0
561
+ ? part.toLowerCase()
562
+ : part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
563
+ .join("");
564
+ }
565
+ /** Convert tool name to PascalCase for type names */
566
+ function toPascalCase(name) {
567
+ return name
568
+ .replace(/[^a-zA-Z0-9_]/g, "_")
569
+ .split("_")
570
+ .filter(Boolean)
571
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
572
+ .join("");
573
+ }
574
+ /** Convert tool name to kebab-case for file names */
575
+ function toKebabCase(name) {
576
+ return name
577
+ .replace(/[^a-zA-Z0-9]/g, "-")
578
+ .replace(/-+/g, "-")
579
+ .replace(/^-|-$/g, "")
580
+ .toLowerCase();
581
+ }
582
+ /** Serialize a JSON schema to a readable TypeScript literal string */
583
+ function schemaToString(schema, indent = 4) {
584
+ const pad = " ".repeat(indent);
585
+ const lines = [];
586
+ lines.push("{");
587
+ lines.push(`${pad}type: '${schema.type}' as const,`);
588
+ if (schema.description) {
589
+ lines.push(`${pad}description: ${JSON.stringify(schema.description)},`);
590
+ }
591
+ if (schema.enum) {
592
+ lines.push(`${pad}enum: ${JSON.stringify(schema.enum)},`);
593
+ }
594
+ if (schema.properties) {
595
+ lines.push(`${pad}properties: {`);
596
+ for (const [key, prop] of Object.entries(schema.properties)) {
597
+ const safeKey = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : JSON.stringify(key);
598
+ lines.push(`${pad} ${safeKey}: ${schemaToString(prop, indent + 4)},`);
599
+ }
600
+ lines.push(`${pad}},`);
601
+ }
602
+ if (schema.items) {
603
+ lines.push(`${pad}items: ${schemaToString(schema.items, indent + 2)},`);
604
+ }
605
+ if (schema.required && schema.required.length > 0) {
606
+ lines.push(`${pad}required: [${schema.required.map((r) => `'${r}'`).join(", ")}] as const,`);
607
+ }
608
+ if (schema.additionalProperties !== undefined) {
609
+ if (typeof schema.additionalProperties === "boolean") {
610
+ lines.push(`${pad}additionalProperties: ${schema.additionalProperties},`);
611
+ }
612
+ else {
613
+ lines.push(`${pad}additionalProperties: ${schemaToString(schema.additionalProperties, indent + 2)},`);
614
+ }
615
+ }
616
+ if (schema.default !== undefined) {
617
+ lines.push(`${pad}default: ${JSON.stringify(schema.default)},`);
618
+ }
619
+ lines.push(`${" ".repeat(indent - 2)}}`);
620
+ return lines.join("\n");
621
+ }
622
+ /** Generate a TypeScript interface from a JSON Schema */
623
+ function schemaToInterface(name, schema) {
624
+ if (schema.type !== "object" || !schema.properties) {
625
+ return `export type ${name} = unknown;`;
626
+ }
627
+ const required = new Set(schema.required ?? []);
628
+ const lines = [`export interface ${name} {`];
629
+ for (const [key, prop] of Object.entries(schema.properties)) {
630
+ const p = prop;
631
+ const optional = required.has(key) ? "" : "?";
632
+ const tsType = jsonSchemaToTsType(p);
633
+ if (p.description) {
634
+ lines.push(` /** ${p.description} */`);
635
+ }
636
+ lines.push(` ${/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : JSON.stringify(key)}${optional}: ${tsType};`);
637
+ }
638
+ lines.push("}");
639
+ return lines.join("\n");
640
+ }
641
+ /** Convert a JSON Schema type to a TypeScript type string */
642
+ function jsonSchemaToTsType(schema) {
643
+ // const literal
644
+ if (schema.const !== undefined) {
645
+ return JSON.stringify(schema.const);
646
+ }
647
+ // enum
648
+ if (schema.enum) {
649
+ return schema.enum.map((v) => JSON.stringify(v)).join(" | ");
650
+ }
651
+ // oneOf / anyOf → union
652
+ if (schema.oneOf) {
653
+ return schema.oneOf.map(jsonSchemaToTsType).join(" | ");
654
+ }
655
+ if (schema.anyOf) {
656
+ return schema.anyOf.map(jsonSchemaToTsType).join(" | ");
657
+ }
658
+ // allOf → intersection
659
+ if (schema.allOf) {
660
+ return schema.allOf.map(jsonSchemaToTsType).join(" & ");
661
+ }
662
+ // not → exclude
663
+ if (schema.not) {
664
+ return `Exclude<unknown, ${jsonSchemaToTsType(schema.not)}>`;
665
+ }
666
+ // $ref
667
+ if (schema.$ref) {
668
+ const ref = schema.$ref;
669
+ // Extract name from #/$defs/Foo or #/definitions/Foo
670
+ const match = ref.match(/\/([^/]+)$/);
671
+ return match ? match[1] : "unknown";
672
+ }
673
+ switch (schema.type) {
674
+ case "string":
675
+ // Include format hint if present
676
+ if (schema.format)
677
+ return `string /* ${schema.format} */`;
678
+ return "string";
679
+ case "integer":
680
+ return "number /* integer */";
681
+ case "number":
682
+ return "number";
683
+ case "boolean":
684
+ return "boolean";
685
+ case "null":
686
+ return "null";
687
+ case "array":
688
+ if (schema.items) {
689
+ return `${jsonSchemaToTsType(schema.items)}[]`;
690
+ }
691
+ // Tuple arrays (prefixItems)
692
+ if (schema.prefixItems) {
693
+ const items = schema.prefixItems.map(jsonSchemaToTsType);
694
+ return `[${items.join(", ")}]`;
695
+ }
696
+ return "unknown[]";
697
+ case "object":
698
+ if (schema.properties) {
699
+ const required = new Set(schema.required ?? []);
700
+ const props = Object.entries(schema.properties)
701
+ .map(([k, v]) => {
702
+ const opt = required.has(k) ? "" : "?";
703
+ return `${k}${opt}: ${jsonSchemaToTsType(v)}`;
704
+ })
705
+ .join("; ");
706
+ // additionalProperties
707
+ if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
708
+ const addlType = jsonSchemaToTsType(schema.additionalProperties);
709
+ return props
710
+ ? `{ ${props}; [key: string]: ${addlType} }`
711
+ : `Record<string, ${addlType}>`;
712
+ }
713
+ return `{ ${props} }`;
714
+ }
715
+ if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
716
+ return `Record<string, ${jsonSchemaToTsType(schema.additionalProperties)}>`;
717
+ }
718
+ return "Record<string, unknown>";
719
+ default:
720
+ // type as array (e.g., ["string", "null"])
721
+ if (Array.isArray(schema.type)) {
722
+ return schema.type.map((t) => (t === "null" ? "null" : t === "integer" ? "number" : t)).join(" | ");
723
+ }
724
+ return "unknown";
725
+ }
726
+ }
727
+ // ============================================
728
+ // File Generators
729
+ // ============================================
730
+ function generateToolFile(tool, _sdkImport, _generateTypes) {
731
+ const schema = tool.inputSchema ?? {
732
+ type: "object",
733
+ properties: {},
734
+ };
735
+ const lines = [];
736
+ // Title
737
+ lines.push(`# ${tool.name}`);
738
+ lines.push("");
739
+ if (tool.description) {
740
+ lines.push(tool.description);
741
+ lines.push("");
742
+ }
743
+ // Parameters table
744
+ const props = (schema.properties ?? {});
745
+ const required = new Set(schema.required ?? []);
746
+ const paramNames = Object.keys(props);
747
+ if (paramNames.length > 0) {
748
+ lines.push("## Parameters");
749
+ lines.push("");
750
+ lines.push("| Name | Type | Required | Description |");
751
+ lines.push("|------|------|----------|-------------|");
752
+ for (const name of paramNames) {
753
+ const prop = props[name];
754
+ const type = jsonSchemaToTsType(prop);
755
+ const req = required.has(name) ? "\u2713" : "";
756
+ const desc = (prop.description ?? "").replace(/\|/g, "\\|");
757
+ lines.push(`| ${name} | \`${type}\` | ${req} | ${desc} |`);
758
+ }
759
+ lines.push("");
760
+ }
761
+ return lines.join("\n");
762
+ }
763
+ function generateAgentConfig(serverInfo, _tools, agentPath, sdkImport, visibility) {
764
+ const lines = [];
765
+ lines.push(`/**`);
766
+ lines.push(` * Agent: ${agentPath}`);
767
+ if (serverInfo.name) {
768
+ lines.push(` * MCP Server: ${serverInfo.name} v${serverInfo.version ?? "unknown"}`);
769
+ }
770
+ lines.push(` *`);
771
+ lines.push(` * Auto-generated by agents-sdk codegen.`);
772
+ lines.push(` */`);
773
+ lines.push("");
774
+ lines.push(`import { defineAgent } from '${sdkImport}';`);
775
+ lines.push("");
776
+ lines.push(`export default defineAgent({`);
777
+ lines.push(` path: '${agentPath}',`);
778
+ lines.push(` entrypoint: './entrypoint.md',`);
779
+ lines.push(` visibility: '${visibility}' as const,`);
780
+ lines.push(`});`);
781
+ lines.push("");
782
+ return lines.join("\n");
783
+ }
784
+ function generateEntrypoint(serverInfo, tools, agentPath) {
785
+ const lines = [];
786
+ const name = serverInfo.name ?? agentPath;
787
+ lines.push(`# ${name}`);
788
+ lines.push("");
789
+ if (serverInfo.version) {
790
+ lines.push(`> MCP Server v${serverInfo.version}`);
791
+ lines.push("");
792
+ }
793
+ lines.push(`You are an agent wrapping the ${name} MCP server.`);
794
+ lines.push("");
795
+ lines.push(`## Available Tools`);
796
+ lines.push("");
797
+ for (const tool of tools) {
798
+ lines.push(`- **${tool.name}**: ${tool.description ?? "No description"}`);
799
+ }
800
+ lines.push("");
801
+ return lines.join("\n");
802
+ }
803
+ function generateIndex(_tools) {
804
+ const lines = [];
805
+ lines.push(`/**`);
806
+ lines.push(` * Auto-generated index.`);
807
+ lines.push(` */`);
808
+ lines.push("");
809
+ lines.push(`export { default as agent } from './agent.config.js';`);
810
+ lines.push("");
811
+ return lines.join("\n");
812
+ }
813
+ function generateCli(serverInfo, tools, agentPath) {
814
+ const name = serverInfo.name ?? agentPath;
815
+ const lines = [];
816
+ lines.push(`#!/usr/bin/env bun`);
817
+ lines.push(`/**`);
818
+ lines.push(` * CLI for ${name}`);
819
+ lines.push(` *`);
820
+ lines.push(` * Usage:`);
821
+ lines.push(` * bun cli.ts <tool_name> [json_params]`);
822
+ lines.push(` * bun cli.ts --list`);
823
+ lines.push(` *`);
824
+ lines.push(` * Auto-generated by agents-sdk codegen.`);
825
+ lines.push(` */`);
826
+ lines.push("");
827
+ lines.push(`const tools = ${JSON.stringify(tools.map(t => ({ name: t.name, description: t.description ?? '' })), null, 2)};`);
828
+ lines.push("");
829
+ lines.push(`const args = process.argv.slice(2);`);
830
+ lines.push("");
831
+ lines.push(`if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {`);
832
+ lines.push(` console.log('${name} CLI\\n');`);
833
+ lines.push(` console.log('Usage: bun cli.ts <tool> [params_json]\\n');`);
834
+ lines.push(` console.log('Available tools:');`);
835
+ lines.push(` for (const t of tools) {`);
836
+ lines.push(` console.log(\` \${t.name.padEnd(30)} \${t.description}\`);`);
837
+ lines.push(` }`);
838
+ lines.push(` process.exit(0);`);
839
+ lines.push(`}`);
840
+ lines.push("");
841
+ lines.push(`if (args[0] === '--list') {`);
842
+ lines.push(` for (const t of tools) {`);
843
+ lines.push(` console.log(\`\${t.name}\\t\${t.description}\`);`);
844
+ lines.push(` }`);
845
+ lines.push(` process.exit(0);`);
846
+ lines.push(`}`);
847
+ lines.push("");
848
+ lines.push(`const toolName = args[0];`);
849
+ lines.push(`const params = args[1] ? JSON.parse(args[1]) : {};`);
850
+ lines.push("");
851
+ lines.push(`if (!tools.find(t => t.name === toolName)) {`);
852
+ lines.push(` console.error(\`Unknown tool: \${toolName}\`);`);
853
+ lines.push(` console.error(\`Available: \${tools.map(t => t.name).join(', ')}\`);`);
854
+ lines.push(` process.exit(1);`);
855
+ lines.push(`}`);
856
+ lines.push("");
857
+ lines.push(`// TODO: Connect to MCP server and execute the tool`);
858
+ lines.push(`console.log(JSON.stringify({ tool: toolName, params, status: 'not_connected' }, null, 2));`);
859
+ lines.push("");
860
+ return lines.join("\n");
861
+ }
862
+ function generateManifest(serverSource, serverInfo, tools, agentPath) {
863
+ const manifest = {
864
+ agentPath,
865
+ serverSource,
866
+ serverInfo,
867
+ tools: tools.map((t) => ({ name: t.name, description: t.description })),
868
+ generatedAt: new Date().toISOString(),
869
+ };
870
+ return JSON.stringify(manifest, null, 2) + "\n";
871
+ }
872
+ // ============================================
873
+ // Main: codegen()
874
+ // ============================================
875
+ /**
876
+ * Connect to an MCP server, introspect its tools, and generate
877
+ * agent-definition source files.
878
+ */
879
+ export async function codegen(options) {
880
+ const sdkImport = options.sdkImport ?? "@slashfi/agents-sdk";
881
+ const generateTypes = options.types !== false;
882
+ const generateCliFile = options.cli !== false;
883
+ const visibility = options.visibility ?? "public";
884
+ const outDir = resolve(options.outDir);
885
+ // 1. Connect to MCP server
886
+ const transport = parseServerSource(options.server);
887
+ let serverInfo = {};
888
+ let tools = [];
889
+ try {
890
+ // 2. Initialize handshake
891
+ const initResult = (await transport.send("initialize", {
892
+ protocolVersion: LATEST_PROTOCOL_VERSION,
893
+ capabilities: {},
894
+ clientInfo: { name: "agents-sdk-codegen", version: "1.0.0" },
895
+ }));
896
+ // Validate protocol version
897
+ if (initResult?.protocolVersion &&
898
+ !SUPPORTED_PROTOCOL_VERSIONS.includes(initResult.protocolVersion)) {
899
+ throw new Error(`Server protocol version ${initResult.protocolVersion} is not supported. Supported: ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")}`);
900
+ }
901
+ serverInfo = initResult?.serverInfo ?? {};
902
+ // Send initialized notification (no id — this is a notification, not a request)
903
+ await transport.notify("notifications/initialized");
904
+ // 3. List tools (with pagination)
905
+ const allTools = [];
906
+ let cursor;
907
+ do {
908
+ const toolsResult = (await transport.send("tools/list", {
909
+ ...(cursor ? { cursor } : {}),
910
+ }));
911
+ allTools.push(...(toolsResult?.tools ?? []));
912
+ cursor = toolsResult?.nextCursor;
913
+ } while (cursor);
914
+ tools = allTools;
915
+ }
916
+ finally {
917
+ await transport.close();
918
+ }
919
+ if (tools.length === 0) {
920
+ throw new Error("MCP server returned no tools. Is the server running and configured correctly?");
921
+ }
922
+ // 4. Derive agent path
923
+ const agentPath = options.agentPath ??
924
+ `@${(options.name ?? serverInfo.name ?? "mcp-agent").toLowerCase().replace(/[^a-z0-9-]/g, "-")}`;
925
+ // 5. Create output directory
926
+ mkdirSync(outDir, { recursive: true });
927
+ const files = [];
928
+ // 6. Generate tool files
929
+ const toolFiles = [];
930
+ for (const tool of tools) {
931
+ const fileName = `${toKebabCase(tool.name)}.tool.md`;
932
+ const content = generateToolFile(tool, sdkImport, generateTypes);
933
+ writeFileSync(join(outDir, fileName), content);
934
+ toolFiles.push(fileName);
935
+ files.push(fileName);
936
+ }
937
+ // 7. Generate entrypoint.md
938
+ const entrypoint = generateEntrypoint(serverInfo, tools, agentPath);
939
+ writeFileSync(join(outDir, "entrypoint.md"), entrypoint);
940
+ files.push("entrypoint.md");
941
+ // 8. Generate agent.config.ts
942
+ const agentConfig = generateAgentConfig(serverInfo, tools, agentPath, sdkImport, visibility);
943
+ writeFileSync(join(outDir, "agent.config.ts"), agentConfig);
944
+ files.push("agent.config.ts");
945
+ // 9. Generate index.ts
946
+ const index = generateIndex(tools);
947
+ writeFileSync(join(outDir, "index.ts"), index);
948
+ files.push("index.ts");
949
+ // 10. Generate CLI
950
+ if (generateCliFile) {
951
+ const cli = generateCli(serverInfo, tools, agentPath);
952
+ writeFileSync(join(outDir, "cli.ts"), cli);
953
+ files.push("cli.ts");
954
+ }
955
+ // 11. Generate manifest (for `agents-sdk use`)
956
+ const manifest = generateManifest(options.server, serverInfo, tools, agentPath);
957
+ writeFileSync(join(outDir, ".codegen-manifest.json"), manifest);
958
+ files.push(".codegen-manifest.json");
959
+ return {
960
+ outDir,
961
+ serverInfo,
962
+ toolCount: tools.length,
963
+ toolFiles,
964
+ files,
965
+ };
966
+ }
967
+ // ============================================
968
+ // Use: execute a tool on a codegenned agent
969
+ // ============================================
970
+ /**
971
+ * Execute a tool on a previously codegenned agent by reconnecting
972
+ * to the MCP server and calling the tool.
973
+ */
974
+ export async function useAgent(options) {
975
+ const manifestPath = join(resolve(options.agentDir), ".codegen-manifest.json");
976
+ if (!existsSync(manifestPath)) {
977
+ throw new Error(`No codegen manifest found at ${manifestPath}. Run codegen first.`);
978
+ }
979
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf-8"));
980
+ // Verify tool exists
981
+ const toolDef = manifest.tools.find((t) => t.name === options.tool);
982
+ if (!toolDef) {
983
+ const available = manifest.tools.map((t) => t.name).join(", ");
984
+ throw new Error(`Unknown tool '${options.tool}'. Available: ${available}`);
985
+ }
986
+ // Connect to server and call tool
987
+ const transport = parseServerSource(manifest.serverSource);
988
+ try {
989
+ await transport.send("initialize", {
990
+ protocolVersion: LATEST_PROTOCOL_VERSION,
991
+ capabilities: {},
992
+ clientInfo: { name: "agents-sdk-use", version: "1.0.0" },
993
+ });
994
+ await transport.notify("notifications/initialized");
995
+ const result = await transport.send("tools/call", {
996
+ name: options.tool,
997
+ arguments: options.params ?? {},
998
+ });
999
+ return result;
1000
+ }
1001
+ finally {
1002
+ await transport.close();
1003
+ }
1004
+ }
1005
+ /**
1006
+ * List tools available on a codegenned agent.
1007
+ */
1008
+ export function listAgentTools(agentDir) {
1009
+ const manifestPath = join(resolve(agentDir), ".codegen-manifest.json");
1010
+ if (!existsSync(manifestPath)) {
1011
+ throw new Error(`No codegen manifest found at ${manifestPath}. Run codegen first.`);
1012
+ }
1013
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf-8"));
1014
+ return manifest.tools;
1015
+ }
1016
+ //# sourceMappingURL=codegen.js.map