@staal/node 0.25.0 → 0.26.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/README.md CHANGED
@@ -51,16 +51,27 @@ const r = await refund.call({ order: '4417', amount: { amount: '35.00', currency
51
51
  A grant is never an argument, and the model never sees one. An app serving several
52
52
  tenants or users from one directory also gives `scope: (customer) => customer.tenantId`,
53
53
  from its own records: `once` keys are then held per scope, and a run's status is given
54
- only in its scope (`refund.status(run, { context: customer })`). One process uses a
54
+ only in its scope (`refund.status(run, { context: customer })`). Inputs that only the
55
+ app may give, such as the customer a call is for, are `appInputs: { customer: (customer)
56
+ => customer.id }`: they are left out of the schema a model sees, and a call whose
57
+ arguments name one is refused. One process uses a
55
58
  journal directory at a time, so give each worker its own directory (whose quotas are
56
59
  then its own), or send the calls through one process.
57
60
 
58
61
  **Agent frameworks.** `functionTool` from `@staal/node/openai-agents` gives an OpenAI
59
62
  Agents SDK tool (grants from the run's `context`), and `structuredTool` from
60
63
  `@staal/node/langgraph` a LangChain tool for LangGraph (context from
61
- `config.configurable.staal_context`). The frameworks are optional peer dependencies.
62
- Both are tested through the framework's own agent loop (@openai/agents 0.20.0,
63
- @langchain/langgraph 1.5.1); the examples are in
64
+ `config.configurable.staal_context`). `aiTools` from `@staal/node/vercel-ai` gives
65
+ Vercel AI SDK tools, an ES module for `ai` 7 (Node 22 or newer), whose context is each
66
+ tool's entry in `toolsContext`; a refusal reaches the model as an error with Staal's
67
+ message. `mcpServer` from `@staal/node/claude-agent-sdk` serves tools to the Claude Agent SDK as
68
+ an in-process MCP server, with the session's context bound when the server is made
69
+ (one per query), and `allowedTools` gives their names for `allowedTools`. The
70
+ frameworks are optional peer dependencies. Each is tested through the framework's own
71
+ agent loop (@openai/agents 0.20.0, @langchain/langgraph 1.5.1, ai 7.0.145,
72
+ @anthropic-ai/claude-agent-sdk 0.3.304, whose loop runs in the CLI it ships, against a
73
+ local stand-in for the Messages API), and once a week against each framework's latest
74
+ release; the examples are in
64
75
  [examples/frameworks](https://github.com/laurells/staal/tree/main/examples/frameworks).
65
76
 
66
77
  **Platforms.** Node 18 or newer, on Linux (x86_64 and arm64, glibc 2.28 or newer) and
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,5 @@
1
+ import type { Tool } from './index.js';
2
+ /** staal Tools as an in-process MCP server config for the Claude Agent SDK's `mcpServers`. */
3
+ export function mcpServer(tools: Tool<any>[], options?: { name?: string; context?: unknown }): { type: 'sdk'; name: string; instance: any };
4
+ /** The names the Agent SDK gives `tools` served under `name`, for `allowedTools`. */
5
+ export function allowedTools(name: string, tools: Tool<any>[]): string[];
@@ -0,0 +1,77 @@
1
+ // staal Tools as an in-process MCP server for the Claude Agent SDK
2
+ // (@anthropic-ai/claude-agent-sdk, with @modelcontextprotocol/sdk 1.x, which the app
3
+ // installs; @staal/node depends on neither). The Agent SDK is published as ES modules
4
+ // only, so this adapter is one too.
5
+ //
6
+ // import { query } from '@anthropic-ai/claude-agent-sdk';
7
+ // import { allowedTools, mcpServer } from '@staal/node/claude-agent-sdk';
8
+ // for await (const message of query({ prompt, options: {
9
+ // mcpServers: { staal: mcpServer([refund], { context: customer }) }, // one per query
10
+ // allowedTools: allowedTools('staal', [refund]),
11
+ // tools: [],
12
+ // } })) { ... }
13
+ //
14
+ // The Agent SDK gives a tool only its arguments, so the app's context for the session
15
+ // (the signed-in customer, the tenant) is bound when the server is made: make one per
16
+ // query, from the app's own records, never from anything the model wrote. Each call
17
+ // runs the Staal program with the grants the app's policy gives for that context.
18
+ //
19
+ // The server is a plain MCP server (the MCP SDK's low-level Server), so the program's
20
+ // argument schema reaches the model as JSON Schema, unconverted, and Staal's own check
21
+ // of the arguments is the one that decides. A refusal, a failure or an unknown tool is
22
+ // a tool result with isError, with Staal's message, so the model can correct itself;
23
+ // nothing is retried. The model sees each tool as `mcp__<name>__<tool name>`.
24
+
25
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
26
+ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
27
+
28
+ const HINTS = ['title', 'readOnlyHint', 'destructiveHint', 'idempotentHint', 'openWorldHint'];
29
+
30
+ function checked(tools) {
31
+ if (!Array.isArray(tools) || tools.length === 0) throw new TypeError('staal: mcpServer takes a list of Tools from Tool.open');
32
+ const byName = new Map();
33
+ for (const t of tools) {
34
+ if (!t || typeof t.call !== 'function' || typeof t.name !== 'string') throw new TypeError('staal: mcpServer takes a list of Tools from Tool.open');
35
+ if (byName.has(t.name)) throw new TypeError(`staal: mcpServer: two tools are named '${t.name}'`);
36
+ byName.set(t.name, t);
37
+ }
38
+ return byName;
39
+ }
40
+
41
+ /**
42
+ * `tools` as an in-process MCP server for the Agent SDK's `mcpServers` option.
43
+ * `options.context` is what each tool's grants (and scope) function receives, for
44
+ * every call made through this server; `options.name` (default "staal") must be the
45
+ * key the server is given in `mcpServers`.
46
+ */
47
+ export function mcpServer(tools, options = {}) {
48
+ const byName = checked(tools);
49
+ const name = options.name ?? 'staal';
50
+ if (typeof name !== 'string' || !/^[A-Za-z0-9_-]+$/.test(name)) throw new TypeError('staal: mcpServer: name is letters, digits, _ and -');
51
+ const context = options.context;
52
+ const server = new Server({ name, version: '1.0.0' }, { capabilities: { tools: {} } });
53
+ const listed = [...byName.values()].map((t) => {
54
+ const annotations = {};
55
+ for (const k of HINTS) if (t.annotations && k in t.annotations) annotations[k] = t.annotations[k];
56
+ return { name: t.name, description: t.description, inputSchema: t.schema, annotations };
57
+ });
58
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: listed }));
59
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
60
+ const t = byName.get(request.params.name);
61
+ if (!t) return { content: [{ type: 'text', text: `there is no tool '${request.params.name}'` }], isError: true };
62
+ try {
63
+ const result = await t.call(request.params.arguments ?? {}, { context });
64
+ return { content: [{ type: 'text', text: result.text }], isError: result.isError };
65
+ } catch (e) {
66
+ // The call did not reach an answer (the host is closed, the grants function
67
+ // threw): the model is told so, as an MCP tool error, not a protocol error.
68
+ return { content: [{ type: 'text', text: `the tool could not be called: ${e && e.message ? e.message : String(e)}` }], isError: true };
69
+ }
70
+ });
71
+ return { type: 'sdk', name, instance: server };
72
+ }
73
+
74
+ /** The names the Agent SDK gives `tools` served under `name`, for `allowedTools`. */
75
+ export function allowedTools(name, tools) {
76
+ return [...checked(tools).keys()].map((n) => `mcp__${name}__${n}`);
77
+ }
package/index.d.ts CHANGED
@@ -127,6 +127,13 @@ export interface ToolOptions<Context = unknown> {
127
127
  * and a run's status is given only in its scope.
128
128
  */
129
129
  scope?: (context: Context) => string | Promise<string>;
130
+ /**
131
+ * Inputs only the app supplies, such as the customer a call is for: each name, an
132
+ * input of the entry function, maps to a function of the call's context giving its
133
+ * value. They are not in the schema a model sees, and a call whose arguments name
134
+ * one is refused.
135
+ */
136
+ appInputs?: { [name: string]: (context: Context) => Json | Promise<Json> };
130
137
  /** A journal directory, or an open host: one is required. */
131
138
  journals?: string;
132
139
  host?: Host;
package/index.js CHANGED
@@ -134,13 +134,22 @@ const SPEC_KEYS = ['title', 'entry', 'quota', 'once', 'deadline', 'max_concurren
134
134
  * same context returning the call's trusted scope as a string (a tenant's or a user's
135
135
  * id, from the app's own records, never from the arguments): a `once` key is held
136
136
  * within its scope, and a run's status is given only in its scope. An app serving more
137
- * than one tenant or user from one journal directory gives a scope. Give `journals`
138
- * (a directory) or `host`.
137
+ * than one tenant or user from one journal directory gives a scope. `appInputs`, if
138
+ * given, maps names of the entry function's inputs to functions of the same context
139
+ * that give their values: inputs only the app supplies, such as the customer a call
140
+ * is for. They are not in the schema a model sees, and a call whose arguments name
141
+ * one is refused. Give `journals` (a directory) or `host`.
139
142
  */
140
143
  class Tool {
141
144
  static async open(program, options) {
142
- const { name, description, grants, scope, journals, host, ...spec } = options || {};
145
+ const { name, description, grants, scope, appInputs, journals, host, ...spec } = options || {};
143
146
  if (scope !== undefined && typeof scope !== 'function') throw new TypeError("staal: Tool: scope is a function of the call's context");
147
+ if (appInputs !== undefined) {
148
+ const entries = appInputs !== null && typeof appInputs === 'object' && !Array.isArray(appInputs) ? Object.entries(appInputs) : [];
149
+ if (entries.length === 0 || !entries.every(([, f]) => typeof f === 'function')) {
150
+ throw new TypeError("staal: Tool: appInputs maps input names to functions of the call's context");
151
+ }
152
+ }
144
153
  for (const k of Object.keys(spec)) {
145
154
  if (!SPEC_KEYS.includes(k)) throw new TypeError(`staal: Tool: unknown option '${k}'`);
146
155
  }
@@ -151,6 +160,7 @@ class Tool {
151
160
  const h = ownHost ? await Host.open(journals) : host;
152
161
  const body = { name, description, program: str(program, 'program') };
153
162
  if (grants !== undefined && typeof grants !== 'function') body.grants = grants;
163
+ if (appInputs !== undefined) body.app_inputs = Object.keys(appInputs);
154
164
  for (const [k, v] of Object.entries(spec)) if (v !== undefined && v !== null) body[k] = v;
155
165
  let out;
156
166
  try {
@@ -159,7 +169,7 @@ class Tool {
159
169
  if (ownHost) await h.close();
160
170
  throw e;
161
171
  }
162
- const t = new Tool(out, h, ownHost, typeof grants === 'function' ? grants : null, scope || null);
172
+ const t = new Tool(out, h, ownHost, typeof grants === 'function' ? grants : null, scope || null, appInputs ? { ...appInputs } : null);
163
173
  if (t.perCallGrants && t._grants === null) {
164
174
  await t.close();
165
175
  throw new TypeError('staal: Tool: the program needs grants; give grants (an object or a function of the context)');
@@ -171,9 +181,10 @@ class Tool {
171
181
  return t;
172
182
  }
173
183
 
174
- constructor(out, host, ownHost, grants, scope) {
184
+ constructor(out, host, ownHost, grants, scope, appInputs) {
175
185
  this._handle = out.tool;
176
186
  this._scope = scope;
187
+ this._appInputs = appInputs;
177
188
  this.host = host;
178
189
  this._ownHost = ownHost;
179
190
  this._grants = grants;
@@ -193,6 +204,9 @@ class Tool {
193
204
  * a refusal is a result too, so a model can be told why.
194
205
  */
195
206
  async call(args = {}, options = {}) {
207
+ if (args === null || typeof args !== 'object' || Array.isArray(args)) {
208
+ throw new TypeError(`staal: the arguments are an object (a JSON object), not ${args === null ? 'null' : Array.isArray(args) ? 'an array' : typeof args}`);
209
+ }
196
210
  let grants;
197
211
  if (this.perCallGrants) {
198
212
  const g = await this._grants(options.context);
@@ -200,7 +214,13 @@ class Tool {
200
214
  grants = JSON.stringify(g);
201
215
  }
202
216
  const scope = this._scope ? scopeOf(await this._scope(options.context)) : undefined;
203
- const out = ok(parse(await addon.toolCall(this._handle, JSON.stringify(args), grants, scope)));
217
+ let inputs;
218
+ if (this._appInputs) {
219
+ const values = {};
220
+ for (const [k, f] of Object.entries(this._appInputs)) values[k] = await f(options.context);
221
+ inputs = JSON.stringify(values);
222
+ }
223
+ const out = ok(parse(await addon.toolCall(this._handle, JSON.stringify(args), inputs, grants, scope)));
204
224
  return {
205
225
  status: out.status,
206
226
  isError: out.is_error,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staal/node",
3
- "version": "0.25.0",
3
+ "version": "0.26.0",
4
4
  "description": "Staal, the programming language for agents, for Node.js: the staalc compiler and runtime, through its C interface",
5
5
  "keywords": [
6
6
  "staal",
@@ -31,7 +31,11 @@
31
31
  "openai-agents.js",
32
32
  "openai-agents.d.ts",
33
33
  "langgraph.js",
34
- "langgraph.d.ts"
34
+ "langgraph.d.ts",
35
+ "vercel-ai.mjs",
36
+ "vercel-ai.d.mts",
37
+ "claude-agent-sdk.mjs",
38
+ "claude-agent-sdk.d.mts"
35
39
  ],
36
40
  "publishConfig": {
37
41
  "access": "public"
@@ -49,7 +53,7 @@
49
53
  ],
50
54
  "scripts": {
51
55
  "test": "node --test test/staal.test.mjs",
52
- "types": "tsc --noEmit -p test/tsconfig.json"
56
+ "types": "tsc --noEmit -p test/tsconfig.json && tsc --noEmit -p test/tsconfig.esm.json"
53
57
  },
54
58
  "devDependencies": {
55
59
  "@types/node": "22.10.2",
@@ -68,11 +72,22 @@
68
72
  "types": "./langgraph.d.ts",
69
73
  "default": "./langgraph.js"
70
74
  },
75
+ "./vercel-ai": {
76
+ "types": "./vercel-ai.d.mts",
77
+ "import": "./vercel-ai.mjs"
78
+ },
79
+ "./claude-agent-sdk": {
80
+ "types": "./claude-agent-sdk.d.mts",
81
+ "import": "./claude-agent-sdk.mjs"
82
+ },
71
83
  "./package.json": "./package.json"
72
84
  },
73
85
  "peerDependencies": {
74
86
  "@openai/agents": ">=0.20.0",
75
- "@langchain/core": ">=1.2.18"
87
+ "@langchain/core": ">=1.2.18",
88
+ "ai": ">=7.0.145",
89
+ "@anthropic-ai/claude-agent-sdk": ">=0.3.304",
90
+ "@modelcontextprotocol/sdk": ">=1.29.0"
76
91
  },
77
92
  "peerDependenciesMeta": {
78
93
  "@openai/agents": {
@@ -80,6 +95,15 @@
80
95
  },
81
96
  "@langchain/core": {
82
97
  "optional": true
98
+ },
99
+ "ai": {
100
+ "optional": true
101
+ },
102
+ "@anthropic-ai/claude-agent-sdk": {
103
+ "optional": true
104
+ },
105
+ "@modelcontextprotocol/sdk": {
106
+ "optional": true
83
107
  }
84
108
  }
85
109
  }
@@ -0,0 +1,5 @@
1
+ import type { Tool } from './index.js';
2
+ /** A staal Tool as a Vercel AI SDK tool; `context` maps the tool's `toolsContext` entry to the staal Tool's context. */
3
+ export function aiTool(staalTool: Tool<any>, options?: { context?: (toolContext: any) => unknown }): any;
4
+ /** Several staal Tools as an AI SDK tool set, keyed by each tool's name. */
5
+ export function aiTools(staalTools: Tool<any>[], options?: { context?: (toolContext: any) => unknown }): Record<string, any>;
package/vercel-ai.mjs ADDED
@@ -0,0 +1,58 @@
1
+ // A staal Tool as a tool of the Vercel AI SDK (`ai`, version 7, which the app installs;
2
+ // @staal/node does not depend on it). The AI SDK is published as ES modules only, so
3
+ // this adapter is one too.
4
+ //
5
+ // import { generateText, stepCountIs } from 'ai';
6
+ // import { aiTools } from '@staal/node/vercel-ai';
7
+ // const result = await generateText({
8
+ // model, prompt, stopWhen: stepCountIs(5),
9
+ // tools: aiTools([refund]),
10
+ // toolsContext: { refund_order: customer }, // the app's context for that tool
11
+ // });
12
+ //
13
+ // Each call runs the Staal program with the grants the app's policy gives for the
14
+ // tool's context: the AI SDK hands each tool its own entry of `toolsContext`, keyed by
15
+ // the tool's name, and that entry is what the Staal tool's grants (and scope) function
16
+ // receives, unless `options.context` maps it to something else. Context never reaches
17
+ // the model.
18
+ //
19
+ // The model is shown the program's argument schema as it is, without validation by
20
+ // the AI SDK: Staal's own check of the arguments is the one that decides, and a call it
21
+ // refuses comes back to the model as an error with Staal's message, as a refusal by the
22
+ // broker does, so the model can correct itself. Nothing is retried. An abort of the
23
+ // generation does not stop a Staal run that has started: its outcome is in its journal
24
+ // and in the tool's status, as with any call.
25
+
26
+ import { tool, jsonSchema } from 'ai';
27
+
28
+ /** `staalTool` (from Tool.open) as an AI SDK tool. Give it to `tools` under `staalTool.name`. */
29
+ export function aiTool(staalTool, options = {}) {
30
+ if (!staalTool || typeof staalTool.call !== 'function' || typeof staalTool.name !== 'string') {
31
+ throw new TypeError('staal: aiTool takes a Tool from Tool.open');
32
+ }
33
+ const pick = options.context || ((context) => context);
34
+ if (typeof pick !== 'function') throw new TypeError('staal: aiTool: options.context is a function of the tool context');
35
+ const schema = { ...staalTool.schema };
36
+ delete schema.$schema;
37
+ return tool({
38
+ description: staalTool.description,
39
+ // No `validate`: the AI SDK passes the model's input on as it is, and Staal checks it.
40
+ inputSchema: jsonSchema(schema),
41
+ execute: async (input, { context }) => staalTool.call(input ?? {}, { context: await pick(context) }),
42
+ // What the model reads: the answer's text, as an MCP client would get it, marked
43
+ // as an error when Staal refused or the run failed.
44
+ toModelOutput: ({ output }) => (output.isError ? { type: 'error-text', value: output.text } : { type: 'text', value: output.text }),
45
+ });
46
+ }
47
+
48
+ /** Several staal Tools as an AI SDK tool set, each under its own name. */
49
+ export function aiTools(staalTools, options = {}) {
50
+ if (!Array.isArray(staalTools)) throw new TypeError('staal: aiTools takes a list of Tools');
51
+ const set = {};
52
+ for (const t of staalTools) {
53
+ const made = aiTool(t, options);
54
+ if (Object.prototype.hasOwnProperty.call(set, t.name)) throw new TypeError(`staal: aiTools: two tools are named '${t.name}'`);
55
+ set[t.name] = made;
56
+ }
57
+ return set;
58
+ }