@backendkit-labs/agent-core 0.37.0 → 0.37.2

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 (52) hide show
  1. package/README.md +87 -0
  2. package/dist/agent-discovery/RemoteAgentRegistry.d.ts.map +1 -1
  3. package/dist/agent-discovery/RemoteAgentRegistry.js +4 -1
  4. package/dist/agent-discovery/RemoteAgentRegistry.js.map +1 -1
  5. package/dist/agent-discovery/download-guard.d.ts +20 -0
  6. package/dist/agent-discovery/download-guard.d.ts.map +1 -0
  7. package/dist/agent-discovery/download-guard.js +84 -0
  8. package/dist/agent-discovery/download-guard.js.map +1 -0
  9. package/dist/context/pipeline.d.ts +9 -0
  10. package/dist/context/pipeline.d.ts.map +1 -1
  11. package/dist/context/pipeline.js +20 -4
  12. package/dist/context/pipeline.js.map +1 -1
  13. package/dist/index.d.ts +10 -2
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +23 -3
  16. package/dist/index.js.map +1 -1
  17. package/dist/mcp/MCPClientManager.d.ts.map +1 -1
  18. package/dist/mcp/MCPClientManager.js +20 -1
  19. package/dist/mcp/MCPClientManager.js.map +1 -1
  20. package/dist/mcp/index.d.ts +6 -0
  21. package/dist/mcp/index.d.ts.map +1 -1
  22. package/dist/mcp/index.js +15 -1
  23. package/dist/mcp/index.js.map +1 -1
  24. package/dist/mcp/tool-server-cli.d.ts +48 -0
  25. package/dist/mcp/tool-server-cli.d.ts.map +1 -0
  26. package/dist/mcp/tool-server-cli.js +106 -0
  27. package/dist/mcp/tool-server-cli.js.map +1 -0
  28. package/dist/mcp/tool-server-http.d.ts +41 -0
  29. package/dist/mcp/tool-server-http.d.ts.map +1 -0
  30. package/dist/mcp/tool-server-http.js +133 -0
  31. package/dist/mcp/tool-server-http.js.map +1 -0
  32. package/dist/mcp/tool-server.d.ts +90 -0
  33. package/dist/mcp/tool-server.d.ts.map +1 -0
  34. package/dist/mcp/tool-server.js +224 -0
  35. package/dist/mcp/tool-server.js.map +1 -0
  36. package/dist/shared/utils/atomic-write.d.ts.map +1 -1
  37. package/dist/shared/utils/atomic-write.js +5 -2
  38. package/dist/shared/utils/atomic-write.js.map +1 -1
  39. package/dist/shared/utils/project-key.d.ts.map +1 -1
  40. package/dist/shared/utils/project-key.js +8 -1
  41. package/dist/shared/utils/project-key.js.map +1 -1
  42. package/dist/tools/createToolContext.d.ts +15 -0
  43. package/dist/tools/createToolContext.d.ts.map +1 -0
  44. package/dist/tools/createToolContext.js +34 -0
  45. package/dist/tools/createToolContext.js.map +1 -0
  46. package/dist/tools/defineTool.d.ts +43 -7
  47. package/dist/tools/defineTool.d.ts.map +1 -1
  48. package/dist/tools/defineTool.js +68 -10
  49. package/dist/tools/defineTool.js.map +1 -1
  50. package/dist/types/index.d.ts +22 -0
  51. package/dist/types/index.d.ts.map +1 -1
  52. package/package.json +1 -1
@@ -0,0 +1,224 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createToolRegistrar = createToolRegistrar;
4
+ exports.createToolServerFactory = createToolServerFactory;
5
+ exports.createToolServer = createToolServer;
6
+ exports.hashArgs = hashArgs;
7
+ const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
8
+ const node_crypto_1 = require("node:crypto");
9
+ const zod_1 = require("zod");
10
+ const createToolContext_1 = require("../tools/createToolContext");
11
+ const defineTool_1 = require("../tools/defineTool");
12
+ const DEFAULT_MAX_OUTPUT_CHARS = 1_048_576;
13
+ /**
14
+ * Validates the tools once (names, declared facts, schemas) and returns a function that registers them, with
15
+ * the per-call guarantees above, on any `McpServer`: one that also serves prompt tools, resources or prompts
16
+ * of its own. `createToolServerFactory` is this plus a fresh `McpServer` per call.
17
+ */
18
+ function createToolRegistrar(opts) {
19
+ const prepared = prepareTools(opts);
20
+ const maxOutputChars = opts.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
21
+ return server => registerTools(server, opts, prepared, maxOutputChars);
22
+ }
23
+ /**
24
+ * Validates the tools once and returns a factory that builds a connected-ready `McpServer` per call. The
25
+ * stateless HTTP transport needs a fresh server per request; stdio needs one.
26
+ */
27
+ function createToolServerFactory(opts) {
28
+ const register = createToolRegistrar(opts);
29
+ return () => {
30
+ const server = new mcp_js_1.McpServer({ name: opts.name, version: opts.version ?? '1.0.0' });
31
+ register(server);
32
+ return server;
33
+ };
34
+ }
35
+ /** One `McpServer` with every tool registered. Connect it to any MCP server transport. */
36
+ function createToolServer(opts) {
37
+ return createToolServerFactory(opts)();
38
+ }
39
+ // ── Preparation ───────────────────────────────────────────────────────────────
40
+ function prepareTools(opts) {
41
+ if (!opts.name)
42
+ throw new Error('createToolServer: name is required');
43
+ const seen = new Set();
44
+ const prepared = [];
45
+ for (const tool of opts.tools) {
46
+ (0, defineTool_1.validateToolDefinition)(tool);
47
+ if (seen.has(tool.name))
48
+ throw new Error(`createToolServer(${opts.name}): duplicate tool name "${tool.name}"`);
49
+ seen.add(tool.name);
50
+ if (tool.destructive && !opts.authorize) {
51
+ throw new Error(`createToolServer(${opts.name}): tool "${tool.name}" is destructive and no authorize hook was given. ` +
52
+ 'A direct tool skips the engine\'s allowedTools, gates and budget; the server must gate it itself.');
53
+ }
54
+ prepared.push({ tool, schema: inputSchemaOf(opts.name, tool), annotations: annotationsOf(tool) });
55
+ }
56
+ return prepared;
57
+ }
58
+ /**
59
+ * The schema a tool is registered with. Tools from `defineTool` carry their Zod schema, which is used as is:
60
+ * no conversion, so what the client validates against is exactly what `execute` validates against. A
61
+ * hand-written `ToolDefinition` only has JSON Schema; it goes through `z.fromJSONSchema`, which rejects
62
+ * constructs it cannot express (`if/then/else`, `not`, external `$ref`) instead of degrading silently.
63
+ */
64
+ function inputSchemaOf(serverName, tool) {
65
+ const own = (0, defineTool_1.getToolInputSchema)(tool);
66
+ if (own)
67
+ return own;
68
+ try {
69
+ return zod_1.z.fromJSONSchema(tool.parameters, { defaultTarget: 'openapi-3.0' });
70
+ }
71
+ catch (err) {
72
+ throw new Error(`createToolServer(${serverName}): cannot derive an input schema for tool "${tool.name}" from its JSON Schema: ` +
73
+ `${err.message}. Define it with defineTool, or simplify the schema.`);
74
+ }
75
+ }
76
+ function annotationsOf(tool) {
77
+ const a = {};
78
+ if (tool.readOnly !== undefined)
79
+ a.readOnlyHint = tool.readOnly;
80
+ if (tool.destructive !== undefined)
81
+ a.destructiveHint = tool.destructive;
82
+ if (tool.idempotent !== undefined)
83
+ a.idempotentHint = tool.idempotent;
84
+ if (tool.openWorld !== undefined)
85
+ a.openWorldHint = tool.openWorld;
86
+ return Object.keys(a).length > 0 ? a : undefined;
87
+ }
88
+ // ── Server ────────────────────────────────────────────────────────────────────
89
+ function registerTools(server, opts, prepared, maxOutputChars) {
90
+ for (const { tool, schema, annotations } of prepared) {
91
+ server.registerTool(tool.name, {
92
+ description: tool.description,
93
+ ...(tool.title !== undefined ? { title: tool.title } : {}),
94
+ // The SDK accepts a whole Zod object schema here, not only a raw shape.
95
+ inputSchema: schema,
96
+ ...(annotations ? { annotations } : {}),
97
+ ...(tool.meta ? { _meta: tool.meta } : {}),
98
+ },
99
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
100
+ (async (args, extra) => runCall(opts, tool, maxOutputChars, args, extra)));
101
+ }
102
+ }
103
+ async function runCall(opts, tool, maxOutputChars, rawArgs, extra) {
104
+ const started = Date.now();
105
+ const args = (rawArgs && typeof rawArgs === 'object' ? rawArgs : {});
106
+ const info = { tool, args, requestId: extra.requestId, ...(extra.sessionId ? { sessionId: extra.sessionId } : {}) };
107
+ const finish = async (outcome, text, error) => {
108
+ await audit(opts, {
109
+ at: new Date(started).toISOString(),
110
+ server: opts.name,
111
+ tool: tool.name,
112
+ ...(info.sessionId ? { sessionId: info.sessionId } : {}),
113
+ requestId: extra.requestId,
114
+ argsHash: hashArgs(args),
115
+ outcome,
116
+ durationMs: Date.now() - started,
117
+ outputChars: outcome === 'ok' ? text.length : 0,
118
+ ...(error !== undefined ? { error } : {}),
119
+ });
120
+ return outcome === 'ok'
121
+ ? { content: [{ type: 'text', text }] }
122
+ : { content: [{ type: 'text', text }], isError: true };
123
+ };
124
+ // 1. Authorization — before anything else runs.
125
+ if (opts.authorize) {
126
+ let allowed = false;
127
+ let reason = 'denied by authorize';
128
+ try {
129
+ allowed = await opts.authorize(info);
130
+ }
131
+ catch (err) {
132
+ reason = `authorize threw: ${messageOf(err)}`;
133
+ }
134
+ if (!allowed)
135
+ return finish('denied', `Tool "${tool.name}" denied: ${reason}`, reason);
136
+ }
137
+ // 2. Cancellation: client abort or time limit, whichever comes first.
138
+ const timeoutMs = tool.timeoutMs ?? opts.toolTimeoutMs;
139
+ const controller = new AbortController();
140
+ const onClientAbort = () => controller.abort(extra.signal.reason);
141
+ if (extra.signal.aborted)
142
+ onClientAbort();
143
+ else
144
+ extra.signal.addEventListener('abort', onClientAbort, { once: true });
145
+ let timer;
146
+ const timedOut = new Promise((_, reject) => {
147
+ if (timeoutMs === undefined)
148
+ return;
149
+ timer = setTimeout(() => {
150
+ controller.abort(new Error(`TOOL_TIMEOUT after ${timeoutMs}ms`));
151
+ reject(new ToolTimeout(timeoutMs));
152
+ }, timeoutMs);
153
+ });
154
+ // 3. Context and execution.
155
+ try {
156
+ const ctx = contextFor(opts, info, controller.signal);
157
+ const output = await Promise.race([tool.execute(args, ctx), timedOut]);
158
+ const text = typeof output === 'string' ? output : JSON.stringify(output);
159
+ if (text.length > maxOutputChars) {
160
+ const msg = `Tool "${tool.name}" returned ${text.length} characters; the limit is ${maxOutputChars}`;
161
+ return finish('too_large', msg, msg);
162
+ }
163
+ return finish('ok', text);
164
+ }
165
+ catch (err) {
166
+ if (err instanceof ToolTimeout) {
167
+ const msg = `Tool "${tool.name}" timed out after ${err.timeoutMs}ms`;
168
+ return finish('timeout', msg, msg);
169
+ }
170
+ // No stack: the client is on the other side of a wire and gets the message only.
171
+ const msg = messageOf(err);
172
+ return finish('error', `Tool "${tool.name}" failed: ${msg}`, msg);
173
+ }
174
+ finally {
175
+ if (timer)
176
+ clearTimeout(timer);
177
+ extra.signal.removeEventListener('abort', onClientAbort);
178
+ timedOut.catch(() => undefined);
179
+ }
180
+ }
181
+ class ToolTimeout extends Error {
182
+ timeoutMs;
183
+ constructor(timeoutMs) {
184
+ super(`timed out after ${timeoutMs}ms`);
185
+ this.timeoutMs = timeoutMs;
186
+ }
187
+ }
188
+ function contextFor(opts, info, signal) {
189
+ if (typeof opts.context === 'function')
190
+ return opts.context({ ...info, signal });
191
+ return (0, createToolContext_1.createToolContext)({
192
+ agentId: opts.name,
193
+ sessionId: info.sessionId ?? 'mcp',
194
+ ...opts.context,
195
+ signal,
196
+ });
197
+ }
198
+ async function audit(opts, record) {
199
+ if (!opts.audit)
200
+ return;
201
+ try {
202
+ await opts.audit(record);
203
+ }
204
+ catch (err) {
205
+ process.stderr.write(`[${opts.name}] audit hook failed for ${record.tool}: ${messageOf(err)}\n`);
206
+ }
207
+ }
208
+ /** SHA-256 over the canonical JSON (sorted keys at every level) so equal arguments hash equal. */
209
+ function hashArgs(args) {
210
+ return (0, node_crypto_1.createHash)('sha256').update(canonicalJson(args)).digest('hex');
211
+ }
212
+ function canonicalJson(value) {
213
+ if (value === null || typeof value !== 'object')
214
+ return JSON.stringify(value) ?? 'null';
215
+ if (Array.isArray(value))
216
+ return `[${value.map(canonicalJson).join(',')}]`;
217
+ const entries = Object.keys(value).sort()
218
+ .map(k => `${JSON.stringify(k)}:${canonicalJson(value[k])}`);
219
+ return `{${entries.join(',')}}`;
220
+ }
221
+ function messageOf(err) {
222
+ return err instanceof Error ? err.message : String(err);
223
+ }
224
+ //# sourceMappingURL=tool-server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-server.js","sourceRoot":"","sources":["../../src/mcp/tool-server.ts"],"names":[],"mappings":";;AAgGA,kDAIC;AAMD,0DAOC;AAGD,4CAEC;AAwLD,4BAEC;AAhTD,oEAAoE;AAEpE,6CAAyC;AACzC,6BAAwB;AAExB,kEAA+D;AAC/D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C,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAcvE;AAED,wBAAsB,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAclF"}
1
+ {"version":3,"file":"atomic-write.d.ts","sourceRoot":"","sources":["../../../src/shared/utils/atomic-write.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAWH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAcvE;AAED,wBAAsB,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAclF"}
@@ -9,8 +9,11 @@ exports.atomicWrite = atomicWrite;
9
9
  const fs_1 = require("fs");
10
10
  const promises_1 = require("fs/promises");
11
11
  const path_1 = require("path");
12
+ const crypto_1 = require("crypto");
13
+ // One temp file per write (pid + random): concurrent writers of the same file do not collide.
14
+ const tmpPath = (filePath) => `${filePath}.${process.pid}.${(0, crypto_1.randomBytes)(6).toString('hex')}.tmp`;
12
15
  function atomicWriteSync(filePath, content) {
13
- const tmp = `${filePath}.tmp`;
16
+ const tmp = tmpPath(filePath);
14
17
  (0, fs_1.writeFileSync)(tmp, content, 'utf-8');
15
18
  try {
16
19
  (0, fs_1.renameSync)(tmp, filePath);
@@ -30,7 +33,7 @@ function atomicWriteSync(filePath, content) {
30
33
  }
31
34
  }
32
35
  async function atomicWrite(filePath, content) {
33
- const tmp = `${filePath}.tmp`;
36
+ const tmp = tmpPath(filePath);
34
37
  await (0, promises_1.writeFile)(tmp, content, 'utf-8');
35
38
  try {
36
39
  await (0, promises_1.rename)(tmp, filePath);
@@ -1 +1 @@
1
- {"version":3,"file":"atomic-write.js","sourceRoot":"","sources":["../../../src/shared/utils/atomic-write.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AAMH,0CAcC;AAED,kCAcC;AAlC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M,CAAC;YACN,MAAM,CAAC,CAAC;QACV,CAAC;IACH,CAAC;AACH,CAAC;AAEM,KAAK,UAAU,WAAW,CAAC,QAAgB,EAAE,OAAe;IACjE,MAAM,GAAG,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC9B,MAAM,IAAA,oBAAS,EAAC,GAAG,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IACvC,IAAI,CAAC;QACH,MAAM,IAAA,iBAAM,EAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IAC9B,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,IAAK,CAA2B,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;YAClD,MAAM,IAAA,gBAAK,EAAC,IAAA,cAAO,EAAC,QAAQ,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;YACpD,MAAM,IAAA,mBAAQ,EAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;YAC9B,IAAI,CAAC;gBAAC,MAAM,IAAA,iBAAM,EAAC,GAAG,CAAC,CAAC;YAAC,CAAC;YAAC,MAAM,CAAC,CAAC,aAAa,CAAC,CAAC;QACpD,CAAC;aAAM,CAAC;YACN,MAAM,CAAC,CAAC;QACV,CAAC;IACH,CAAC;AACH,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"project-key.d.ts","sourceRoot":"","sources":["../../../src/shared/utils/project-key.ts"],"names":[],"mappings":"AAGA,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAKnD;AAED,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAGvD;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,GAAE,MAAsB,GAAG,MAAM,CAElF"}
1
+ {"version":3,"file":"project-key.d.ts","sourceRoot":"","sources":["../../../src/shared/utils/project-key.ts"],"names":[],"mappings":"AAGA,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAKnD;AAUD,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAGvD;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,GAAE,MAAsB,GAAG,MAAM,CAElF"}
@@ -44,9 +44,16 @@ function cwdToProjectKey(cwd) {
44
44
  .replace(/:[/\\]/g, '--')
45
45
  .replace(/[^a-zA-Z0-9-]/g, '-');
46
46
  }
47
+ /** The app name becomes a directory under the home dir: only [a-zA-Z0-9_-] so it cannot climb out of it. */
48
+ function assertSafeAppName(appName) {
49
+ if (!/^[a-zA-Z0-9_-]+$/.test(appName)) {
50
+ throw new Error(`Invalid appName: "${appName}" (only letters, digits, hyphen and underscore)`);
51
+ }
52
+ return appName;
53
+ }
47
54
  function getFrameworkDir(appName) {
48
55
  const home = process.env.USERPROFILE ?? process.env.HOME ?? os.homedir();
49
- return path.join(home, `.${appName}`);
56
+ return path.join(home, `.${assertSafeAppName(appName)}`);
50
57
  }
51
58
  function getProjectDir(appName, cwd = process.cwd()) {
52
59
  return path.join(getFrameworkDir(appName), 'projects', cwdToProjectKey(cwd));
@@ -1 +1 @@
1
- {"version":3,"file":"project-key.js","sourceRoot":"","sources":["../../../src/shared/utils/project-key.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,0CAKC;AAED,0CAGC;AAED,sCAEC;AAjBD,uCAAyB;AACzB,2CAA6B;AAE7B,SAAgB,eAAe,CAAC,GAAW;IACvC,OAAO,GAAG;SACL,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC;SACrB,OAAO,CAAC,SAAS,EAAE,IAAI,CAAC;SACxB,OAAO,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAC;AACxC,CAAC;AAED,SAAgB,eAAe,CAAC,OAAe;IAC3C,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI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,MAAc,OAAO,CAAC,GAAG,EAAE;IACtE,OAAO,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,EAAE,UAAU,EAAE,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC;AACjF,CAAC"}
@@ -0,0 +1,15 @@
1
+ import type { ExecutionContext, SessionMemoryData } from '../types';
2
+ /** Everything in `ExecutionContext` is optional here; what is missing gets a safe default. */
3
+ export type ToolContextOptions = Partial<ExecutionContext>;
4
+ /** Session memory that lives only as long as the context object. */
5
+ export declare function createInMemorySessionMemory(): SessionMemoryData;
6
+ /**
7
+ * Builds an `ExecutionContext` for running a tool outside an `AgentEngine`: tests, scripts, cron jobs and
8
+ * the MCP tool server. Defaults: `agentId: 'direct'`, `sessionId: 'direct'`, in-memory session memory and an
9
+ * `askAgent` that rejects (there is no engine to ask). Pass `signal` so the tool can be cancelled.
10
+ *
11
+ * @example
12
+ * const out = await myTool.execute({ id: 7 }, createToolContext({ workingDir: process.cwd() }));
13
+ */
14
+ export declare function createToolContext(opts?: ToolContextOptions): ExecutionContext;
15
+ //# sourceMappingURL=createToolContext.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createToolContext.d.ts","sourceRoot":"","sources":["../../src/tools/createToolContext.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAEpE,8FAA8F;AAC9F,MAAM,MAAM,kBAAkB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;AAE3D,oEAAoE;AACpE,wBAAgB,2BAA2B,IAAI,iBAAiB,CAO/D;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,GAAE,kBAAuB,GAAG,gBAAgB,CAWjF"}
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createInMemorySessionMemory = createInMemorySessionMemory;
4
+ exports.createToolContext = createToolContext;
5
+ /** Session memory that lives only as long as the context object. */
6
+ function createInMemorySessionMemory() {
7
+ const data = new Map();
8
+ return {
9
+ get: key => data.get(key),
10
+ set: (key, value) => { data.set(key, value); },
11
+ getAll: () => Object.fromEntries(data),
12
+ };
13
+ }
14
+ /**
15
+ * Builds an `ExecutionContext` for running a tool outside an `AgentEngine`: tests, scripts, cron jobs and
16
+ * the MCP tool server. Defaults: `agentId: 'direct'`, `sessionId: 'direct'`, in-memory session memory and an
17
+ * `askAgent` that rejects (there is no engine to ask). Pass `signal` so the tool can be cancelled.
18
+ *
19
+ * @example
20
+ * const out = await myTool.execute({ id: 7 }, createToolContext({ workingDir: process.cwd() }));
21
+ */
22
+ function createToolContext(opts = {}) {
23
+ const { agentId, sessionId, memory, askAgent, ...rest } = opts;
24
+ return {
25
+ ...rest,
26
+ agentId: agentId ?? 'direct',
27
+ sessionId: sessionId ?? 'direct',
28
+ memory: memory ?? createInMemorySessionMemory(),
29
+ askAgent: askAgent ?? (async (target) => {
30
+ throw new Error(`askAgent("${target}") is not available outside an AgentEngine`);
31
+ }),
32
+ };
33
+ }
34
+ //# sourceMappingURL=createToolContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createToolContext.js","sourceRoot":"","sources":["../../src/tools/createToolContext.ts"],"names":[],"mappings":";;AAMA,kEAOC;AAUD,8CAWC;AA7BD,oEAAoE;AACpE,SAAgB,2BAA2B;IACvC,MAAM,IAAI,GAAG,IAAI,GAAG,EAAkB,CAAC;IACvC,OAAO;QACH,GAAG,EAAE,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;QACzB,GAAG,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;QAC9C,MAAM,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC;KACzC,CAAC;AACN,CAAC;AAED;;;;;;;GAOG;AACH,SAAgB,iBAAiB,CAAC,OAA2B,EAAE;IAC3D,MAAM,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC;IAC/D,OAAO;QACH,GAAG,IAAI;QACP,OAAO,EAAE,OAAO,IAAI,QAAQ;QAC5B,SAAS,EAAE,SAAS,IAAI,QAAQ;QAChC,MAAM,EAAE,MAAM,IAAI,2BAA2B,EAAE;QAC/C,QAAQ,EAAE,QAAQ,IAAI,CAAC,KAAK,EAAE,MAAc,EAAE,EAAE;YAC5C,MAAM,IAAI,KAAK,CAAC,aAAa,MAAM,4CAA4C,CAAC,CAAC;QACrF,CAAC,CAAC;KACL,CAAC;AACN,CAAC"}
@@ -1,18 +1,55 @@
1
1
  import { z } from 'zod';
2
2
  import type { ToolDefinition, ExecutionContext } from '../types';
3
3
  export { z };
4
- export interface TypedToolOptions<TInput extends z.ZodTypeAny> {
4
+ /** Declarative facts about a tool that the engine and MCP clients use to decide how to treat it. */
5
+ export interface ToolMetadata {
6
+ /** Human-readable name for UIs and MCP clients. */
7
+ title?: string;
8
+ /** Mutates nothing. Implies `concurrencySafe`; incompatible with `destructive`. MCP: `readOnlyHint`. */
9
+ readOnly?: boolean;
10
+ /** A write that cannot be undone from the outside. MCP: `destructiveHint`. */
11
+ destructive?: boolean;
12
+ /** Calling it again with the same arguments has no additional effect. MCP: `idempotentHint`. */
13
+ idempotent?: boolean;
14
+ /** Talks to entities outside the system. MCP: `openWorldHint`. */
15
+ openWorld?: boolean;
16
+ /** Free-form metadata for governance clients (never read by the engine). MCP: `_meta`. */
17
+ meta?: Record<string, unknown>;
18
+ }
19
+ export interface TypedToolOptions<TInput extends z.ZodTypeAny> extends ToolMetadata {
5
20
  name: string;
6
21
  description: string;
7
22
  /** Zod schema for the tool's input. Used for validation and JSON Schema generation. */
8
23
  input: TInput;
9
- /** Safe to run in parallel with other concurrencySafe tools. Default false. */
24
+ /** Safe to run in parallel with other concurrencySafe tools. Default false (true when `readOnly`). */
10
25
  concurrencySafe?: boolean;
11
26
  /** Time limit for one call in ms (overrides the engine's `toolTimeoutMs`). Default: none. */
12
27
  timeoutMs?: number;
13
28
  /** Type-safe execute handler — args are already validated and typed. */
14
29
  execute(args: z.infer<TInput>, ctx: ExecutionContext): Promise<string>;
15
30
  }
31
+ /** A tool whose declared facts contradict each other (thrown at definition time, never at call time). */
32
+ export declare class ToolDefinitionError extends Error {
33
+ readonly toolName: string;
34
+ constructor(toolName: string, message: string);
35
+ }
36
+ /**
37
+ * Checks that a tool's declared facts are consistent. `defineTool` calls it; call it yourself on a hand-written
38
+ * `ToolDefinition` before exposing it (the MCP tool server does).
39
+ *
40
+ * - `readOnly` and `destructive` cannot both be true.
41
+ * - `concurrencySafe` means "read-only, order-independent", so a `destructive` tool cannot declare it.
42
+ * - `timeoutMs`, when present, must be a positive number.
43
+ * - `parameters` must describe an object.
44
+ */
45
+ export declare function validateToolDefinition(tool: ToolDefinition): void;
46
+ /** The Zod schema a tool was defined with, or undefined for a hand-written ToolDefinition. */
47
+ export declare function getToolInputSchema(tool: ToolDefinition): z.ZodTypeAny | undefined;
48
+ /**
49
+ * Converts a Zod schema to the plain JSON Schema sent to LLMs (tool parameters, structured output):
50
+ * OpenAPI 3 flavour, no `$ref`s, without the top-level `$schema` / `definitions` meta.
51
+ */
52
+ export declare function zodToParameters(schema: z.ZodTypeAny): Record<string, unknown>;
16
53
  /**
17
54
  * Creates a fully type-safe ToolDefinition backed by a Zod schema.
18
55
  *
@@ -20,10 +57,14 @@ export interface TypedToolOptions<TInput extends z.ZodTypeAny> {
20
57
  * validated at runtime before being passed to the execute handler.
21
58
  * Validation errors are returned as tool result strings (not thrown).
22
59
  *
60
+ * Declared facts (`readOnly`, `destructive`, `idempotent`, `openWorld`, `meta`, `title`) are checked for
61
+ * consistency here and throw `ToolDefinitionError` at definition time. `readOnly: true` implies `concurrencySafe`.
62
+ *
23
63
  * @example
24
64
  * const readFileTool = defineTool({
25
65
  * name: 'read_file',
26
66
  * description: 'Read a file from disk',
67
+ * readOnly: true,
27
68
  * input: z.object({
28
69
  * path: z.string().describe('Absolute path to the file'),
29
70
  * encoding: z.enum(['utf-8', 'base64']).default('utf-8'),
@@ -34,10 +75,5 @@ export interface TypedToolOptions<TInput extends z.ZodTypeAny> {
34
75
  * },
35
76
  * });
36
77
  */
37
- /**
38
- * Converts a Zod schema to the plain JSON Schema sent to LLMs (tool parameters, structured output):
39
- * OpenAPI 3 flavour, no `$ref`s, without the top-level `$schema` / `definitions` meta.
40
- */
41
- export declare function zodToParameters(schema: z.ZodTypeAny): Record<string, unknown>;
42
78
  export declare function defineTool<TInput extends z.ZodTypeAny>(opts: TypedToolOptions<TInput>): ToolDefinition;
43
79
  //# sourceMappingURL=defineTool.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"defineTool.d.ts","sourceRoot":"","sources":["../../src/tools/defineTool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAGjE,OAAO,EAAE,CAAC,EAAE,CAAC;AAIb,MAAM,WAAW,gBAAgB,CAAC,MAAM,SAAS,CAAC,CAAC,UAAU;IACzD,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,uFAAuF;IACvF,KAAK,EAAE,MAAM,CAAC;IACd,+EAA+E;IAC/E,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,6FAA6F;IAC7F,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,wEAAwE;IACxE,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CAC1E;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH;;;GAGG;AACH,w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G,OAAO,CAAC,MAAM,CAAC,CAAC;CAC1E;AAED,yGAAyG;AACzG,qBAAa,mBAAoB,SAAQ,KAAK;IAC9B,QAAQ,CAAC,QAAQ,EAAE,MAAM;gBAAhB,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;CAIzD;AAED;;;;;;;;GAQG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,cAAc,GAAG,IAAI,CAcjE;AAMD,8FAA8F;AAC9F,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,cAAc,GAAG,CAAC,CAAC,UAAU,GAAG,SAAS,CAEjF;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,CAAC,CAAC,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAE7E;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,UAAU,CAAC,MAAM,SAAS,CAAC,CAAC,UAAU,EAClD,IAAI,EAAE,gBAAgB,CAAC,MAAM,CAAC,GAC/B,cAAc,CA+BhB"}
@@ -1,10 +1,61 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.z = void 0;
3
+ exports.ToolDefinitionError = exports.z = void 0;
4
+ exports.validateToolDefinition = validateToolDefinition;
5
+ exports.getToolInputSchema = getToolInputSchema;
4
6
  exports.zodToParameters = zodToParameters;
5
7
  exports.defineTool = defineTool;
6
8
  const zod_1 = require("zod");
7
9
  Object.defineProperty(exports, "z", { enumerable: true, get: function () { return zod_1.z; } });
10
+ /** A tool whose declared facts contradict each other (thrown at definition time, never at call time). */
11
+ class ToolDefinitionError extends Error {
12
+ toolName;
13
+ constructor(toolName, message) {
14
+ super(`Tool "${toolName}": ${message}`);
15
+ this.toolName = toolName;
16
+ this.name = 'ToolDefinitionError';
17
+ }
18
+ }
19
+ exports.ToolDefinitionError = ToolDefinitionError;
20
+ /**
21
+ * Checks that a tool's declared facts are consistent. `defineTool` calls it; call it yourself on a hand-written
22
+ * `ToolDefinition` before exposing it (the MCP tool server does).
23
+ *
24
+ * - `readOnly` and `destructive` cannot both be true.
25
+ * - `concurrencySafe` means "read-only, order-independent", so a `destructive` tool cannot declare it.
26
+ * - `timeoutMs`, when present, must be a positive number.
27
+ * - `parameters` must describe an object.
28
+ */
29
+ function validateToolDefinition(tool) {
30
+ if (!tool.name)
31
+ throw new ToolDefinitionError(tool.name ?? '', 'name is required');
32
+ if (tool.readOnly && tool.destructive) {
33
+ throw new ToolDefinitionError(tool.name, 'cannot be both readOnly and destructive');
34
+ }
35
+ if (tool.destructive && tool.concurrencySafe) {
36
+ throw new ToolDefinitionError(tool.name, 'a destructive tool cannot be concurrencySafe');
37
+ }
38
+ if (tool.timeoutMs !== undefined && !(Number.isFinite(tool.timeoutMs) && tool.timeoutMs > 0)) {
39
+ throw new ToolDefinitionError(tool.name, `timeoutMs must be a positive number (got ${String(tool.timeoutMs)})`);
40
+ }
41
+ if (tool.parameters && tool.parameters.type !== undefined && tool.parameters.type !== 'object') {
42
+ throw new ToolDefinitionError(tool.name, `parameters must describe an object (got type "${String(tool.parameters.type)}")`);
43
+ }
44
+ }
45
+ // Zod schema of each tool created by defineTool, so the MCP tool server can register the exact schema instead of
46
+ // converting the JSON Schema back. A WeakMap keeps ToolDefinition a plain, serialisable object.
47
+ const inputSchemas = new WeakMap();
48
+ /** The Zod schema a tool was defined with, or undefined for a hand-written ToolDefinition. */
49
+ function getToolInputSchema(tool) {
50
+ return inputSchemas.get(tool);
51
+ }
52
+ /**
53
+ * Converts a Zod schema to the plain JSON Schema sent to LLMs (tool parameters, structured output):
54
+ * OpenAPI 3 flavour, no `$ref`s, without the top-level `$schema` / `definitions` meta.
55
+ */
56
+ function zodToParameters(schema) {
57
+ return stripTopLevelMeta(zod_1.z.toJSONSchema(schema, { target: 'openapi-3.0', unrepresentable: 'any', io: 'input' }));
58
+ }
8
59
  /**
9
60
  * Creates a fully type-safe ToolDefinition backed by a Zod schema.
10
61
  *
@@ -12,10 +63,14 @@ Object.defineProperty(exports, "z", { enumerable: true, get: function () { retur
12
63
  * validated at runtime before being passed to the execute handler.
13
64
  * Validation errors are returned as tool result strings (not thrown).
14
65
  *
66
+ * Declared facts (`readOnly`, `destructive`, `idempotent`, `openWorld`, `meta`, `title`) are checked for
67
+ * consistency here and throw `ToolDefinitionError` at definition time. `readOnly: true` implies `concurrencySafe`.
68
+ *
15
69
  * @example
16
70
  * const readFileTool = defineTool({
17
71
  * name: 'read_file',
18
72
  * description: 'Read a file from disk',
73
+ * readOnly: true,
19
74
  * input: z.object({
20
75
  * path: z.string().describe('Absolute path to the file'),
21
76
  * encoding: z.enum(['utf-8', 'base64']).default('utf-8'),
@@ -26,21 +81,21 @@ Object.defineProperty(exports, "z", { enumerable: true, get: function () { retur
26
81
  * },
27
82
  * });
28
83
  */
29
- /**
30
- * Converts a Zod schema to the plain JSON Schema sent to LLMs (tool parameters, structured output):
31
- * OpenAPI 3 flavour, no `$ref`s, without the top-level `$schema` / `definitions` meta.
32
- */
33
- function zodToParameters(schema) {
34
- return stripTopLevelMeta(zod_1.z.toJSONSchema(schema, { target: 'openapi-3.0', unrepresentable: 'any', io: 'input' }));
35
- }
36
84
  function defineTool(opts) {
37
85
  const parameters = zodToParameters(opts.input);
38
- return {
86
+ const concurrencySafe = opts.concurrencySafe || opts.readOnly === true;
87
+ const tool = {
39
88
  name: opts.name,
40
89
  description: opts.description,
41
90
  parameters,
42
- ...(opts.concurrencySafe ? { concurrencySafe: true } : {}),
91
+ ...(opts.title !== undefined ? { title: opts.title } : {}),
92
+ ...(concurrencySafe ? { concurrencySafe: true } : {}),
43
93
  ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}),
94
+ ...(opts.readOnly !== undefined ? { readOnly: opts.readOnly } : {}),
95
+ ...(opts.destructive !== undefined ? { destructive: opts.destructive } : {}),
96
+ ...(opts.idempotent !== undefined ? { idempotent: opts.idempotent } : {}),
97
+ ...(opts.openWorld !== undefined ? { openWorld: opts.openWorld } : {}),
98
+ ...(opts.meta !== undefined ? { meta: opts.meta } : {}),
44
99
  execute: async (rawArgs, ctx) => {
45
100
  const result = opts.input.safeParse(rawArgs);
46
101
  if (!result.success) {
@@ -52,6 +107,9 @@ function defineTool(opts) {
52
107
  return opts.execute(result.data, ctx);
53
108
  },
54
109
  };
110
+ validateToolDefinition(tool);
111
+ inputSchemas.set(tool, opts.input);
112
+ return tool;
55
113
  }
56
114
  // ── Helper ────────────────────────────────────────────────────────────────────
57
115
  /** Remove top-level JSON Schema meta fields ($schema, definitions, etc.) */
@@ -1 +1 @@
1
- {"version":3,"file":"defineTool.js","sourceRoot":"","sources":["../../src/tools/defineTool.ts"],"names":[],"mappings":";;;AA8CA,0CAEC;AAED,gCAsBC;AAxED,6BAAwB;AAIf,kFAJA,OAAC,OAIA;AAiBV;;;;;;;;;;;;;;;;;;;;GAoBG;AACH;;;GAGG;AACH,SAAgB,eAAe,CAAC,MAAoB;IAChD,OAAO,iBAAiB,CAAC,OAAC,CAAC,YAAY,CAAC,MAAM,EAAE,EAAE,MAAM,EAAE,aAAa,EAAE,eAAe,EAAE,KAAK,EAAE,EAAE,EAAE,OAAO,EAAE,CAA4B,CAAC,CAAC;AAChJ,CAAC;AAED,SAAgB,UAAU,CACtB,IAA8B;IAE9B,MAAM,UAAU,GAAG,eAAe,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAE/C,OAAO;QACH,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,UAAU;QACV,GAAG,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,eAAe,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC1D,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACxD,OAAO,EAAE,KAAK,EAAE,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AAC5E,SAAS,iBAAiB,CAAC,MAA+B;IACtD,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,GAAG,IAAI,EAAE,GAAG,MAAM,CAAC;IACjD,KAAK,OAAO,CAAC;IAAC,KAAK,WAAW,CAAC;IAC/B,OAAO,IAAI,CAAC;AAChB,CAAC"}
@@ -52,6 +52,8 @@ export interface ToolDefinition {
52
52
  name: string;
53
53
  description: string;
54
54
  parameters: JSONSchema;
55
+ /** Human-readable name for UIs and MCP clients. Default: none (clients fall back to `name`). */
56
+ title?: string;
55
57
  /** Safe to run alongside other concurrencySafe tools in the same turn (read-only, order-independent). Default false. */
56
58
  concurrencySafe?: boolean;
57
59
  /**
@@ -59,6 +61,26 @@ export interface ToolDefinition {
59
61
  * `ctx.signal` is aborted and the model gets a `TOOL_TIMEOUT` error. Default: none.
60
62
  */
61
63
  timeoutMs?: number;
64
+ /**
65
+ * The tool mutates nothing. Implies `concurrencySafe` and is incompatible with `destructive`.
66
+ * Exposed to MCP clients as `readOnlyHint`. Default: unknown (the field is absent).
67
+ */
68
+ readOnly?: boolean;
69
+ /**
70
+ * The tool performs a write that cannot be undone from the outside (pay, delete, post, send).
71
+ * A server that exposes such a tool directly must authorize every call (see `createToolServer`).
72
+ * Exposed to MCP clients as `destructiveHint`.
73
+ */
74
+ destructive?: boolean;
75
+ /** Calling it again with the same arguments has no additional effect. Exposed as `idempotentHint`. */
76
+ idempotent?: boolean;
77
+ /** Interacts with entities outside the system (the web, third parties). Exposed as `openWorldHint`. */
78
+ openWorld?: boolean;
79
+ /**
80
+ * Free-form metadata for governance clients (autonomy level, ERP operation, version...). The engine never
81
+ * reads it. Exposed to MCP clients as `_meta`, and read back from MCP servers only with `trustAnnotations`.
82
+ */
83
+ meta?: Record<string, unknown>;
62
84
  execute(args: unknown, ctx: ExecutionContext): Promise<string>;
63
85
  }
64
86
  export interface ExecutionContext {