@slashfi/agents-sdk 0.24.2 → 0.24.4

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