@slashfi/agents-sdk 0.21.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/adk.ts ADDED
@@ -0,0 +1,398 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * ADK CLI — Agent Development Kit
4
+ *
5
+ * Unified CLI for building, testing, and publishing agent definitions.
6
+ *
7
+ * Commands:
8
+ * codegen Generate agent definitions from an MCP server (full codegen)
9
+ * introspect Introspect an MCP server → agent.json (lightweight)
10
+ * pack Generate publishable @agentdef/* package from agent.json
11
+ * publish Pack + npm publish to @agentdef/*
12
+ * use Execute a tool on a generated agent
13
+ * list List all generated agents
14
+ *
15
+ * @example
16
+ * ```bash
17
+ * # Full codegen from MCP server
18
+ * adk codegen --server 'npx @mcp/notion' --name notion --out ./agents/@notion
19
+ *
20
+ * # Lightweight introspect → agent.json
21
+ * adk introspect --server 'npx @notionhq/notion-mcp-server' --name notion
22
+ *
23
+ * # Build + publish
24
+ * adk pack
25
+ * adk publish
26
+ *
27
+ * # Use a tool
28
+ * adk use notion search_pages '{"query": "hello"}'
29
+ * adk use notion --list
30
+ * ```
31
+ */
32
+
33
+ import { existsSync, readdirSync } from "node:fs";
34
+ import { join, resolve } from "node:path";
35
+ import { codegen, listAgentTools, useAgent } from "./codegen.js";
36
+ import type { CodegenManifest } from "./codegen.js";
37
+ import { pack, publish } from "./pack.js";
38
+
39
+ const args = process.argv.slice(2);
40
+ const command = args[0];
41
+
42
+ // ============================================
43
+ // Helpers
44
+ // ============================================
45
+
46
+ function getArg(flag: string): string | undefined {
47
+ const idx = args.indexOf(flag);
48
+ if (idx === -1 || idx + 1 >= args.length) return undefined;
49
+ return args[idx + 1];
50
+ }
51
+
52
+ function hasFlag(flag: string): boolean {
53
+ return args.includes(flag);
54
+ }
55
+
56
+ function getAgentsDir(): string {
57
+ return resolve(process.env.AGENTS_SDK_DIR ?? "./agents");
58
+ }
59
+
60
+ function findAgentDir(name: string): string | null {
61
+ const agentsDir = getAgentsDir();
62
+
63
+ const exactPath = resolve(name);
64
+ if (existsSync(join(exactPath, ".codegen-manifest.json"))) return exactPath;
65
+
66
+ const withAt = join(agentsDir, `@${name}`);
67
+ if (existsSync(join(withAt, ".codegen-manifest.json"))) return withAt;
68
+
69
+ const withoutAt = join(agentsDir, name);
70
+ if (existsSync(join(withoutAt, ".codegen-manifest.json"))) return withoutAt;
71
+
72
+ return null;
73
+ }
74
+
75
+ function printUsage() {
76
+ console.log(`
77
+ adk — Agent Development Kit
78
+
79
+ Usage:
80
+ adk codegen [options] Generate agent from MCP server (full codegen)
81
+ adk introspect [options] Introspect MCP server → agent.json
82
+ adk pack [options] Generate publishable package from agent.json
83
+ adk publish [options] Pack + npm publish to @agentdef/*
84
+ adk use <agent> [options] Execute a tool on a generated agent
85
+ adk list List all generated agents
86
+
87
+ Codegen options:
88
+ --server <source> MCP server (command string or URL)
89
+ --name <name> Agent name (default: derived from server)
90
+ --out <dir> Output directory (default: ./agents/@<name>)
91
+ --path <path> Agent path override
92
+ --no-cli Skip CLI generation
93
+ --no-types Skip TypeScript interface generation
94
+ --visibility <level> Agent visibility (public|internal|private)
95
+
96
+ Introspect options:
97
+ --server <cmd> MCP server command to introspect
98
+ --name <name> Agent name for output
99
+ --out <path> Output path (default: ./<name>.json)
100
+
101
+ Pack / Publish options:
102
+ --agent <path> Path to agent.json (default: ./agent.json)
103
+ --out <dir> Output directory (default: ./dist)
104
+ --scope <scope> npm scope (default: @agentdef)
105
+ --previous <path> Previous agent.json for diff
106
+ --dry-run Don't actually publish (publish only)
107
+ --tag <tag> npm dist-tag (default: latest)
108
+ --access <level> npm access: public | restricted (default: public)
109
+
110
+ Use options:
111
+ adk use <agent> <tool> [params_json]
112
+ adk use <agent> --list List tools on the agent
113
+
114
+ Examples:
115
+ adk codegen --server 'npx @mcp/notion' --name notion
116
+ adk introspect --server 'npx @notionhq/notion-mcp-server' --name notion
117
+ adk pack --agent ./agent.json
118
+ adk publish --dry-run
119
+ adk use notion search_pages '{"query": "hello"}'
120
+ `);
121
+ }
122
+
123
+ // ============================================
124
+ // Commands
125
+ // ============================================
126
+
127
+ async function runCodegen() {
128
+ const server = getArg("--server");
129
+ const name = getArg("--name");
130
+ const outDir = getArg("--out");
131
+ const agentPath = getArg("--path");
132
+ const visibility = getArg("--visibility") as
133
+ | "public"
134
+ | "internal"
135
+ | "private"
136
+ | undefined;
137
+ const noCli = hasFlag("--no-cli");
138
+ const noTypes = hasFlag("--no-types");
139
+
140
+ if (!server) {
141
+ console.error(
142
+ "Error: --server is required.\n" +
143
+ " Example: adk codegen --server 'npx @mcp/notion' --name notion",
144
+ );
145
+ process.exit(1);
146
+ }
147
+
148
+ const resolvedOutDir =
149
+ outDir ??
150
+ join(
151
+ getAgentsDir(),
152
+ `@${(name ?? "mcp-agent").toLowerCase().replace(/[^a-z0-9-]/g, "-")}`,
153
+ );
154
+
155
+ console.log(`Connecting to MCP server: ${server}`);
156
+ console.log(`Output: ${resolvedOutDir}\n`);
157
+
158
+ try {
159
+ const result = await codegen({
160
+ server,
161
+ outDir: resolvedOutDir,
162
+ agentPath,
163
+ name,
164
+ cli: !noCli,
165
+ types: !noTypes,
166
+ visibility,
167
+ });
168
+
169
+ console.log(
170
+ `\x1b[32m\u2713\x1b[0m Generated ${result.toolCount} tools from ${result.serverInfo.name ?? "MCP server"}`,
171
+ );
172
+ console.log("\nFiles:");
173
+ for (const f of result.files) {
174
+ console.log(` ${f}`);
175
+ }
176
+ console.log(
177
+ `\nUse: adk use ${name ?? result.serverInfo.name ?? "<agent>"} --list`,
178
+ );
179
+ } catch (err) {
180
+ console.error(
181
+ `\x1b[31mError:\x1b[0m ${err instanceof Error ? err.message : String(err)}`,
182
+ );
183
+ process.exit(1);
184
+ }
185
+ }
186
+
187
+ async function runIntrospect() {
188
+ const server = getArg("--server");
189
+ const name = getArg("--name");
190
+ const out = getArg("--out") || (name ? `./${name}.json` : undefined);
191
+
192
+ if (!server || !name) {
193
+ console.error(
194
+ "Usage: adk introspect --server <cmd> --name <name> [--out <path>]",
195
+ );
196
+ process.exit(1);
197
+ }
198
+
199
+ const { introspectMcp } = await import("./introspect.js");
200
+ await introspectMcp({ server, name, out });
201
+ }
202
+
203
+ function runPack() {
204
+ const agentFile = getArg("--agent") || "./agent.json";
205
+ const outDir = getArg("--out") || "./dist";
206
+ const scope = getArg("--scope") || "@agentdef";
207
+ const previousAgentFile = getArg("--previous");
208
+
209
+ if (!existsSync(resolve(agentFile))) {
210
+ console.error(`agent.json not found at ${resolve(agentFile)}`);
211
+ console.error("Run 'adk introspect' first, or specify --agent <path>");
212
+ process.exit(1);
213
+ }
214
+
215
+ const result = pack({ agentFile, outDir, scope, previousAgentFile });
216
+ console.log(`\n\u2705 Packed ${result.packageName}@${result.version}`);
217
+ console.log(` Hash: ${result.hash}`);
218
+ console.log(` Tools: ${result.meta.toolCount}`);
219
+ console.log(` Size: ${(result.meta.sizeBytes / 1024).toFixed(1)}KB`);
220
+ console.log(` Output: ${result.packageDir}`);
221
+ if (result.meta.changes) {
222
+ const c = result.meta.changes;
223
+ if (c.toolsAdded.length > 0)
224
+ console.log(` Added: ${c.toolsAdded.join(", ")}`);
225
+ if (c.toolsRemoved.length > 0)
226
+ console.log(` Removed: ${c.toolsRemoved.join(", ")}`);
227
+ if (c.toolsModified.length > 0)
228
+ console.log(` Modified: ${c.toolsModified.join(", ")}`);
229
+ }
230
+ }
231
+
232
+ function runPublish() {
233
+ const agentFile = getArg("--agent") || "./agent.json";
234
+ const outDir = getArg("--out") || "./dist";
235
+ const scope = getArg("--scope") || "@agentdef";
236
+ const previousAgentFile = getArg("--previous");
237
+ const dryRun = hasFlag("--dry-run");
238
+ const tag = getArg("--tag");
239
+ const access = getArg("--access") as "public" | "restricted" | undefined;
240
+ const registry = getArg("--registry");
241
+
242
+ if (!existsSync(resolve(agentFile))) {
243
+ console.error(`agent.json not found at ${resolve(agentFile)}`);
244
+ console.error("Run 'adk introspect' first, or specify --agent <path>");
245
+ process.exit(1);
246
+ }
247
+
248
+ try {
249
+ const result = publish({
250
+ agentFile,
251
+ outDir,
252
+ scope,
253
+ previousAgentFile,
254
+ dryRun,
255
+ tag,
256
+ access,
257
+ registry,
258
+ });
259
+ console.log(
260
+ `\n\u2705 Published ${result.packageName}@${result.version} (hash: ${result.hash})`,
261
+ );
262
+ } catch (err) {
263
+ console.error(err instanceof Error ? err.message : String(err));
264
+ process.exit(1);
265
+ }
266
+ }
267
+
268
+ async function runUse() {
269
+ const agentName = args[1];
270
+
271
+ if (!agentName) {
272
+ console.error(
273
+ "Error: agent name required.\n" +
274
+ " Example: adk use notion search_pages '{...}'",
275
+ );
276
+ process.exit(1);
277
+ }
278
+
279
+ const agentDir = findAgentDir(agentName);
280
+ if (!agentDir) {
281
+ console.error(
282
+ `Error: agent '${agentName}' not found.\n` +
283
+ ` Looked in: ${getAgentsDir()}\n` +
284
+ ` Generate first: adk codegen --server '...' --name ${agentName}`,
285
+ );
286
+ process.exit(1);
287
+ }
288
+
289
+ if (hasFlag("--list")) {
290
+ const tools = listAgentTools(agentDir);
291
+ console.log(`Tools for ${agentName}:\n`);
292
+ for (const t of tools) {
293
+ console.log(` ${t.name.padEnd(30)} ${t.description ?? ""}`);
294
+ }
295
+ return;
296
+ }
297
+
298
+ const toolName = args[2];
299
+ if (!toolName) {
300
+ console.error(
301
+ `Error: tool name required.\n Example: adk use ${agentName} <tool> [params]\n List tools: adk use ${agentName} --list`,
302
+ );
303
+ process.exit(1);
304
+ }
305
+
306
+ const paramsStr = args[3];
307
+ const params = paramsStr ? JSON.parse(paramsStr) : {};
308
+
309
+ try {
310
+ const result = await useAgent({
311
+ agentDir,
312
+ tool: toolName,
313
+ params,
314
+ });
315
+ console.log(JSON.stringify(result, null, 2));
316
+ } catch (err) {
317
+ console.error(
318
+ `\x1b[31mError:\x1b[0m ${err instanceof Error ? err.message : String(err)}`,
319
+ );
320
+ process.exit(1);
321
+ }
322
+ }
323
+
324
+ function runList() {
325
+ const agentsDir = getAgentsDir();
326
+
327
+ if (!existsSync(agentsDir)) {
328
+ console.log("No generated agents found.");
329
+ return;
330
+ }
331
+
332
+ const entries = readdirSync(agentsDir);
333
+ const agents: { name: string; tools: number; server?: string }[] = [];
334
+
335
+ for (const entry of entries) {
336
+ const manifestPath = join(agentsDir, entry, ".codegen-manifest.json");
337
+ if (existsSync(manifestPath)) {
338
+ try {
339
+ const manifest: CodegenManifest = JSON.parse(
340
+ require("node:fs").readFileSync(manifestPath, "utf-8"),
341
+ );
342
+ agents.push({
343
+ name: manifest.agentPath,
344
+ tools: manifest.tools.length,
345
+ server: manifest.serverInfo.name,
346
+ });
347
+ } catch {
348
+ agents.push({ name: entry, tools: 0 });
349
+ }
350
+ }
351
+ }
352
+
353
+ if (agents.length === 0) {
354
+ console.log("No generated agents found.");
355
+ return;
356
+ }
357
+
358
+ console.log("Generated agents:\n");
359
+ for (const a of agents) {
360
+ console.log(
361
+ ` ${a.name.padEnd(25)} ${String(a.tools).padEnd(5)} tools${a.server ? ` (${a.server})` : ""}`,
362
+ );
363
+ }
364
+ }
365
+
366
+ // ============================================
367
+ // Main
368
+ // ============================================
369
+
370
+ switch (command) {
371
+ case "codegen":
372
+ await runCodegen();
373
+ break;
374
+ case "introspect":
375
+ await runIntrospect();
376
+ break;
377
+ case "pack":
378
+ runPack();
379
+ break;
380
+ case "publish":
381
+ runPublish();
382
+ break;
383
+ case "use":
384
+ await runUse();
385
+ break;
386
+ case "list":
387
+ runList();
388
+ break;
389
+ case "--help":
390
+ case "-h":
391
+ case undefined:
392
+ printUsage();
393
+ break;
394
+ default:
395
+ console.error(`Unknown command: ${command}`);
396
+ printUsage();
397
+ process.exit(1);
398
+ }
package/src/index.ts CHANGED
@@ -314,3 +314,29 @@ export type {
314
314
  AgentClient,
315
315
  CreateClientOptions,
316
316
  } from "./client.js";
317
+
318
+ // ============================================
319
+ // JSONC Parser
320
+ // ============================================
321
+
322
+ export { parseJsonc, readJsoncFile } from "./jsonc.js";
323
+
324
+ // ============================================
325
+ // Pack & Publish
326
+ // ============================================
327
+
328
+ export { pack, publish } from "./pack.js";
329
+ export type {
330
+ PackOptions,
331
+ PackResult,
332
+ PublishOptions,
333
+ VersionMeta,
334
+ VersionChanges,
335
+ } from "./pack.js";
336
+
337
+ // ============================================
338
+ // Introspect
339
+ // ============================================
340
+
341
+ export { introspectMcp } from "./introspect.js";
342
+ export type { IntrospectOptions } from "./introspect.js";
@@ -0,0 +1,171 @@
1
+ /**
2
+ * MCP Introspection
3
+ *
4
+ * Connects to an MCP server, introspects its tools,
5
+ * and outputs a SerializedAgentDefinition (agent.json).
6
+ *
7
+ * Deduplicates shared $defs across tools.
8
+ */
9
+
10
+ import { spawn } from "node:child_process";
11
+ import { mkdirSync, writeFileSync } from "node:fs";
12
+ import { dirname, resolve } from "node:path";
13
+
14
+ export interface IntrospectOptions {
15
+ server: string;
16
+ name: string;
17
+ out?: string;
18
+ env?: Record<string, string>;
19
+ }
20
+
21
+ function deduplicateDefs(tools: Record<string, unknown>[]): {
22
+ tools: Record<string, unknown>[];
23
+ sharedDefs: Record<string, unknown>;
24
+ } {
25
+ const defsByContent = new Map<string, { name: string; schema: unknown }>();
26
+
27
+ for (const tool of tools) {
28
+ const schema = tool.inputSchema as Record<string, unknown> | undefined;
29
+ const defs = schema?.$defs;
30
+ if (!defs || typeof defs !== "object") continue;
31
+ for (const [defName, defSchema] of Object.entries(
32
+ defs as Record<string, unknown>,
33
+ )) {
34
+ const key = JSON.stringify(defSchema);
35
+ if (!defsByContent.has(key)) {
36
+ defsByContent.set(key, { name: defName, schema: defSchema });
37
+ }
38
+ }
39
+ }
40
+
41
+ const sharedDefs: Record<string, unknown> = {};
42
+ for (const { name, schema } of Array.from(defsByContent.values())) {
43
+ sharedDefs[name] = schema;
44
+ }
45
+
46
+ const cleanedTools = tools.map((t) => {
47
+ const schema = { ...(t.inputSchema as Record<string, unknown>) };
48
+ schema.$defs = undefined;
49
+ return { ...t, inputSchema: schema };
50
+ });
51
+
52
+ return { tools: cleanedTools, sharedDefs };
53
+ }
54
+
55
+ export async function introspectMcp(options: IntrospectOptions): Promise<void> {
56
+ const { server, name, out } = options;
57
+
58
+ const parts = server.split(/\s+/);
59
+ const proc = spawn(parts[0], parts.slice(1), {
60
+ stdio: ["pipe", "pipe", "pipe"],
61
+ env: { ...process.env, ...options.env },
62
+ });
63
+
64
+ let buffer = "";
65
+ let messageId = 0;
66
+
67
+ function sendJsonRpc(
68
+ method: string,
69
+ params: Record<string, unknown> = {},
70
+ ): number {
71
+ const id = ++messageId;
72
+ const msg = JSON.stringify({ jsonrpc: "2.0", id, method, params });
73
+ proc.stdin?.write(`${msg}\n`);
74
+ return id;
75
+ }
76
+
77
+ function waitForResponse(targetId: number): Promise<Record<string, unknown>> {
78
+ return new Promise((res, reject) => {
79
+ const timeout = setTimeout(() => reject(new Error("Timeout")), 30000);
80
+ const handler = (chunk: Buffer) => {
81
+ buffer += chunk.toString();
82
+ const lines = buffer.split("\n");
83
+ buffer = lines.pop() || "";
84
+ for (const line of lines) {
85
+ const trimmed = line.trim();
86
+ if (!trimmed) continue;
87
+ try {
88
+ const parsed = JSON.parse(trimmed);
89
+ if (parsed.id === targetId) {
90
+ clearTimeout(timeout);
91
+ proc.stdout?.removeListener("data", handler);
92
+ if (parsed.error) reject(new Error(JSON.stringify(parsed.error)));
93
+ else res(parsed.result);
94
+ }
95
+ } catch {
96
+ /* ignore non-JSON */
97
+ }
98
+ }
99
+ };
100
+ proc.stdout?.on("data", handler);
101
+ });
102
+ }
103
+
104
+ try {
105
+ console.log(`Connecting to MCP server: ${server}`);
106
+
107
+ const initId = sendJsonRpc("initialize", {
108
+ protocolVersion: "2024-11-05",
109
+ capabilities: {},
110
+ clientInfo: { name: "adk-introspect", version: "1.0.0" },
111
+ });
112
+ const initResult = (await waitForResponse(initId)) as Record<
113
+ string,
114
+ unknown
115
+ >;
116
+ const serverInfo = initResult.serverInfo as
117
+ | Record<string, string>
118
+ | undefined;
119
+ console.log(`Server: ${serverInfo?.name} v${serverInfo?.version}`);
120
+
121
+ proc.stdin?.write(
122
+ `${JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })}\n`,
123
+ );
124
+
125
+ const toolsId = sendJsonRpc("tools/list", {});
126
+ const toolsResult = (await waitForResponse(toolsId)) as Record<
127
+ string,
128
+ unknown
129
+ >;
130
+ const rawTools = (
131
+ (toolsResult.tools || []) as Record<string, unknown>[]
132
+ ).map((t) => ({
133
+ name: t.name as string,
134
+ description: (t.description as string) || "",
135
+ inputSchema: (t.inputSchema as Record<string, unknown>) || {
136
+ type: "object",
137
+ properties: {},
138
+ },
139
+ }));
140
+ console.log(`Discovered ${rawTools.length} tools`);
141
+
142
+ const { tools, sharedDefs } = deduplicateDefs(rawTools);
143
+ const defsCount = Object.keys(sharedDefs).length;
144
+ if (defsCount > 0) {
145
+ console.log(`Hoisted ${defsCount} shared $defs`);
146
+ }
147
+
148
+ const definition: Record<string, unknown> = {
149
+ path: name,
150
+ name: serverInfo?.name || name,
151
+ description: `Agent for ${serverInfo?.name || name}`,
152
+ version: serverInfo?.version || "1.0.0",
153
+ visibility: "public",
154
+ serverSource: server,
155
+ serverInfo,
156
+ ...(defsCount > 0 ? { $defs: sharedDefs } : {}),
157
+ tools,
158
+ generatedAt: new Date().toISOString(),
159
+ sdkVersion: "0.22.0",
160
+ };
161
+
162
+ const outPath = out || `./${name}.json`;
163
+ const resolved = resolve(outPath);
164
+ mkdirSync(dirname(resolved), { recursive: true });
165
+ writeFileSync(resolved, `${JSON.stringify(definition, null, 2)}\n`);
166
+ const sizeKB = (JSON.stringify(definition).length / 1024).toFixed(1);
167
+ console.log(`\nWrote ${resolved} (${sizeKB}KB, ${tools.length} tools)`);
168
+ } finally {
169
+ proc.kill();
170
+ }
171
+ }
package/src/jsonc.ts ADDED
@@ -0,0 +1,83 @@
1
+ /**
2
+ * JSONC Parser
3
+ *
4
+ * Parses JSON with comments (single-line and multi-line)
5
+ * so agent.json files can be annotated.
6
+ */
7
+
8
+ import { readFileSync } from "node:fs";
9
+
10
+ /**
11
+ * Strip comments from JSONC content and parse as JSON.
12
+ */
13
+ export function parseJsonc(content: string): unknown {
14
+ let result = "";
15
+ let i = 0;
16
+ let inString = false;
17
+ let stringChar = "";
18
+
19
+ while (i < content.length) {
20
+ if (inString) {
21
+ if (content[i] === "\\" && i + 1 < content.length) {
22
+ result += content[i] + content[i + 1];
23
+ i += 2;
24
+ continue;
25
+ }
26
+ if (content[i] === stringChar) {
27
+ inString = false;
28
+ }
29
+ result += content[i];
30
+ i++;
31
+ continue;
32
+ }
33
+
34
+ if (content[i] === '"') {
35
+ inString = true;
36
+ stringChar = content[i];
37
+ result += content[i];
38
+ i++;
39
+ continue;
40
+ }
41
+
42
+ // Single-line comment
43
+ if (
44
+ content[i] === "/" &&
45
+ i + 1 < content.length &&
46
+ content[i + 1] === "/"
47
+ ) {
48
+ while (i < content.length && content[i] !== "\n") i++;
49
+ continue;
50
+ }
51
+
52
+ // Multi-line comment
53
+ if (
54
+ content[i] === "/" &&
55
+ i + 1 < content.length &&
56
+ content[i + 1] === "*"
57
+ ) {
58
+ i += 2;
59
+ while (
60
+ i + 1 < content.length &&
61
+ !(content[i] === "*" && content[i + 1] === "/")
62
+ )
63
+ i++;
64
+ i += 2;
65
+ continue;
66
+ }
67
+
68
+ result += content[i];
69
+ i++;
70
+ }
71
+
72
+ // Handle trailing commas
73
+ const cleaned = result.replace(/,\s*([}\]])/g, "$1");
74
+ return JSON.parse(cleaned);
75
+ }
76
+
77
+ /**
78
+ * Read and parse a JSONC file.
79
+ */
80
+ export function readJsoncFile(path: string): unknown {
81
+ const content = readFileSync(path, "utf-8");
82
+ return parseJsonc(content);
83
+ }