sdk/index.js
// AgentRove Native Agent SDK (MIT). Zero dependencies, Node.js >= 20, ES modules.
// Copied verbatim into every downloadable native Agent Pack, so each pack is self-contained.
//
// Concepts
// - manifest (agent.json): identity, tools with JSON-Schema-like input/output schemas, typed IO
// for composition, permissions (filesystem / network hosts / credential env vars), costs.
// - defineAgent(manifest, handlers): validates the manifest and binds one handler per tool.
// - agent.call(tool, input, ctx): validates input, enforces permissions and confirmation, runs the
// handler, validates output. Handlers receive ctx = { fetch, env, now, log } — never raw globals.
// - runCli(agent, argv): `node bin/cli.js <tool> --json '{...}'` or `--input file.json`; prints JSON.
// - runMcpStdio(agent): minimal Model Context Protocol server over stdio (initialize, tools/list,
// tools/call) so MCP clients such as Claude Code can call the tools.
import { readFileSync } from "node:fs";
import { createInterface } from "node:readline";
export const SDK_VERSION = "0.1.0";
export class AgentError extends Error {
constructor(code, message, details) {
super(message);
this.code = code;
this.details = details;
}
}
// ---------------------------------------------------------------------------------------------
// Minimal JSON-schema validator (subset: type, required, properties, additionalProperties,
// enum, items, minItems, maxItems, minLength, maxLength, minimum, maximum, pattern, format:date-time)
// ---------------------------------------------------------------------------------------------
export function validate(schema, value, path = "$") {
const errors = [];
const t = schema?.type;
const typeOf = (v) => (Array.isArray(v) ? "array" : v === null ? "null" : Number.isInteger(v) ? "integer" : typeof v);
if (t) {
const actual = typeOf(value);
const ok = Array.isArray(t) ? t.some((x) => x === actual || (x === "number" && actual === "integer")) : t === actual || (t === "number" && actual === "integer");
if (!ok) return [`${path}: expected ${Array.isArray(t) ? t.join("|") : t}, got ${actual}`];
}
if (schema.enum && !schema.enum.includes(value)) errors.push(`${path}: must be one of ${schema.enum.join(", ")}`);
if (typeof value === "string") {
if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(`${path}: shorter than ${schema.minLength}`);
if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(`${path}: longer than ${schema.maxLength}`);
if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(`${path}: does not match ${schema.pattern}`);
if (schema.format === "date-time" && (!/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2}))?$/.test(value) || Number.isNaN(Date.parse(value)))) errors.push(`${path}: not an ISO 8601 date (YYYY-MM-DD) or date-time with Z or an offset`);
}
if (typeof value === "number") {
if (schema.minimum !== undefined && value < schema.minimum) errors.push(`${path}: below ${schema.minimum}`);
if (schema.maximum !== undefined && value > schema.maximum) errors.push(`${path}: above ${schema.maximum}`);
}
if (Array.isArray(value)) {
if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(`${path}: fewer than ${schema.minItems} items`);
if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(`${path}: more than ${schema.maxItems} items`);
if (schema.items) value.forEach((v, i) => errors.push(...validate(schema.items, v, `${path}[${i}]`)));
}
if (value && typeof value === "object" && !Array.isArray(value)) {
for (const r of schema.required ?? []) if (!Object.hasOwn(value, r) || value[r] === undefined) errors.push(`${path}.${r}: required`);
for (const [k, v] of Object.entries(value)) {
if (v === undefined) continue; // treated as absent
const sub = schema.properties?.[k];
if (sub) errors.push(...validate(sub, v, `${path}.${k}`));
else if (schema.additionalProperties === false) errors.push(`${path}.${k}: not allowed`);
}
}
return errors;
}
const MANIFEST_SCHEMA = {
type: "object",
required: ["id", "name", "version", "license", "summary", "tools", "permissions", "io", "runtimes", "external_costs"],
properties: {
id: { type: "string", pattern: "^agentrove\\.[a-z0-9-]+$" },
name: { type: "string", minLength: 2 },
version: { type: "string", pattern: "^\\d+\\.\\d+\\.\\d+$" },
license: { type: "string" },
summary: { type: "string", minLength: 10, maxLength: 300 },
tools: { type: "array", minItems: 1 },
permissions: {
type: "object",
required: ["filesystem", "network", "credentials"],
properties: {
filesystem: { enum: ["none", "read", "read_write"] },
network: { type: "array", items: { type: "string" } },
credentials: { type: "array", items: { type: "string", pattern: "^[A-Z][A-Z0-9_]*$" } },
},
},
io: { type: "object", required: ["inputs", "outputs"] },
runtimes: { type: "array", minItems: 1 },
external_costs: { type: "string" },
},
};
export function validateManifest(manifest) {
const errors = validate(MANIFEST_SCHEMA, manifest);
const names = new Set();
for (const [i, t] of (manifest.tools ?? []).entries()) {
if (!t.name || !/^[a-z][a-z0-9_]{1,40}$/.test(t.name)) errors.push(`$.tools[${i}].name invalid`);
if (names.has(t.name)) errors.push(`$.tools[${i}].name duplicated`);
names.add(t.name);
if (!t.input_schema || !t.output_schema) errors.push(`$.tools[${i}]: input_schema and output_schema required`);
if (!["none", "writes_local_files", "external_read", "external_write"].includes(t.side_effects)) errors.push(`$.tools[${i}].side_effects invalid`);
if (t.side_effects === "external_write" && t.requires_confirmation !== true) errors.push(`$.tools[${i}]: external_write tools must require confirmation`);
}
return errors;
}
// ---------------------------------------------------------------------------------------------
// Permission-guarded context
// ---------------------------------------------------------------------------------------------
export function hostAllowed(url, allowlist) {
let u;
try { u = new URL(url); } catch { return false; }
if (u.protocol !== "https:" || u.username || u.password) return false;
// Non-default ports must be listed explicitly as "host:port".
if (u.port && u.port !== "443") return allowlist.some((a) => a.toLowerCase() === `${u.hostname.toLowerCase()}:${u.port}`);
const h = u.hostname.toLowerCase();
return allowlist.some((a) => (a.startsWith("*.") ? h.endsWith(a.slice(1)) : h === a.toLowerCase()));
}
export function makeContext(manifest, overrides = {}) {
const allow = manifest.permissions.network ?? [];
const extra = overrides.extraHosts ?? [];
const baseFetch = overrides.fetch ?? globalThis.fetch;
const env = {};
for (const k of manifest.permissions.credentials ?? []) if (overrides.env?.[k] ?? process.env[k]) env[k] = overrides.env?.[k] ?? process.env[k];
return {
env,
now: overrides.now ?? (() => new Date()),
log: overrides.log ?? (() => {}),
async fetch(url, init) {
// Callers that pass redirect "manual"/"error" handle redirects themselves (each new ctx.fetch call is
// re-checked). Otherwise redirects are followed here, max 3 hops, each hop checked against the allowlist.
if (init?.redirect === "manual" || init?.redirect === "error") {
if (!hostAllowed(String(url), [...allow, ...extra])) throw new AgentError("network_denied", `Host not in this agent's network allowlist: ${String(url)}`);
return baseFetch(url, { ...init, signal: init?.signal ?? AbortSignal.timeout(overrides.timeoutMs ?? 15000) });
}
let current = String(url);
for (let hop = 0; hop <= 3; hop++) {
if (!hostAllowed(current, [...allow, ...extra])) throw new AgentError("network_denied", `Host not in this agent's network allowlist: ${current}`);
const res = await baseFetch(current, { ...init, redirect: "manual", signal: init?.signal ?? AbortSignal.timeout(overrides.timeoutMs ?? 15000) });
if (res.status < 300 || res.status > 399 || !res.headers?.get?.("location")) return res;
current = new URL(res.headers.get("location"), current).toString();
}
throw new AgentError("network_denied", "Too many redirects");
},
};
}
// ---------------------------------------------------------------------------------------------
// Agent definition
// ---------------------------------------------------------------------------------------------
export function defineAgent(manifest, handlers) {
const errs = validateManifest(manifest);
if (errs.length) throw new AgentError("invalid_manifest", `Invalid manifest: ${errs.join("; ")}`, errs);
for (const t of manifest.tools) if (typeof handlers[t.name] !== "function") throw new AgentError("invalid_manifest", `No handler for tool ${t.name}`);
return {
manifest,
tool(name) {
return manifest.tools.find((t) => t.name === name) ?? null;
},
async call(name, input, ctxOverrides = {}) {
const tool = this.tool(name);
if (!tool) throw new AgentError("unknown_tool", `Unknown tool: ${name}`);
const inErr = validate(tool.input_schema, input);
if (inErr.length) throw new AgentError("invalid_input", `Invalid input: ${inErr.join("; ")}`, inErr);
if (tool.requires_confirmation && input.confirm !== true) {
throw new AgentError("confirmation_required", `Tool ${name} has side effects (${tool.side_effects}). Re-run with "confirm": true after reviewing the preview.`);
}
const ctx = makeContext(manifest, ctxOverrides);
const out = await handlers[name](input, ctx);
const outErr = validate(tool.output_schema, out);
if (outErr.length) throw new AgentError("invalid_output", `Tool produced invalid output: ${outErr.join("; ")}`, outErr);
return out;
},
};
}
// ---------------------------------------------------------------------------------------------
// CLI runner
// ---------------------------------------------------------------------------------------------
export async function runCli(agent, argv = process.argv.slice(2), io = { stdout: process.stdout, stderr: process.stderr }) {
const [tool, ...rest] = argv;
if (!tool || tool === "--help" || tool === "help") {
io.stdout.write(`${agent.manifest.name} ${agent.manifest.version}\nTools:\n${agent.manifest.tools.map((t) => ` ${t.name} ${t.description}`).join("\n")}\nUsage: <tool> --json '<input>' | --input <file.json> | --input - (read JSON from stdin)\n`);
return 0;
}
let input = {};
const ji = rest.indexOf("--json");
const fi = rest.indexOf("--input");
try {
if (ji >= 0) input = JSON.parse(rest[ji + 1] ?? "{}");
else if (fi >= 0) input = JSON.parse(rest[fi + 1] === "-" ? readFileSync(0, "utf8") : readFileSync(rest[fi + 1], "utf8"));
const out = await agent.call(tool, input);
io.stdout.write(JSON.stringify(out, null, 2) + "\n");
return 0;
} catch (e) {
io.stderr.write(JSON.stringify({ error: e.code ?? "error", message: e.message }) + "\n");
return 1;
}
}
// ---------------------------------------------------------------------------------------------
// Minimal MCP server over stdio (JSON-RPC 2.0, newline-delimited)
// ---------------------------------------------------------------------------------------------
export function handleMcpMessage(agent, msg) {
if (!msg || typeof msg !== "object" || Array.isArray(msg)) {
return Promise.resolve({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "Invalid Request" } });
}
const reply = (result) => ({ jsonrpc: "2.0", id: msg.id, result });
const fail = (code, message) => ({ jsonrpc: "2.0", id: msg.id, error: { code, message } });
switch (msg.method) {
case "initialize":
return Promise.resolve(reply({
protocolVersion: msg.params?.protocolVersion ?? "2025-06-18",
capabilities: { tools: {} },
serverInfo: { name: agent.manifest.id, version: agent.manifest.version },
}));
case "notifications/initialized":
return Promise.resolve(null);
case "ping":
return Promise.resolve(reply({}));
case "tools/list":
return Promise.resolve(reply({ tools: agent.manifest.tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.input_schema })) }));
case "tools/call":
return agent
.call(msg.params?.name, msg.params?.arguments ?? {})
.then((out) => reply({ content: [{ type: "text", text: JSON.stringify(out, null, 2) }], structuredContent: out, isError: false }))
.catch((e) => reply({ content: [{ type: "text", text: `${e.code ?? "error"}: ${e.message}` }], isError: true }));
default:
return Promise.resolve(msg.id === undefined ? null : fail(-32601, `Method not found: ${msg.method}`));
}
}
export function runMcpStdio(agent) {
const rl = createInterface({ input: process.stdin });
rl.on("line", async (line) => {
let msg;
try { msg = JSON.parse(line); } catch { return; }
const res = await handleMcpMessage(agent, msg);
if (res) process.stdout.write(JSON.stringify(res) + "\n");
});
}