stratus

Tools

Give agents the ability to call functions

Tools let agents call your TypeScript functions. Each tool has a name, description, Zod parameter schema, and an execute function.

Stratus handles the full tool loop automatically - Zod validation, parallel execution, error recovery, and 429 retries. No JSON.parse(), no dispatch tables, no manual message management. See the Agentic Tool Use guide for the full picture.

Defining a Tool

tools.ts
import { tool } from "stratus-sdk/core";
import { z } from "zod";

const getWeather = tool({
  name: "get_weather",
  description: "Get the current weather for a city",
  parameters: z.object({
    city: z.string().describe("City name"),
    unit: z.enum(["celsius", "fahrenheit"]).optional(),
  }),
  execute: async (_ctx, { city, unit }) => {
    const temp = await fetchWeather(city, unit);
    return `${temp}° in ${city}`;
  },
});

Tool Anatomy

PropertyTypeDescription
namestringUnique tool name sent to the model
descriptionstringWhat the tool does (helps the model decide when to use it)
parametersz.ZodTypeZod schema for the parameters
execute(context, params, options?) => stringFunction that runs when the model calls the tool

The execute function receives up to three arguments:

  1. context - The context object passed via run() options or session config
  2. params - Parsed and validated parameters matching the Zod schema
  3. options - Optional ToolExecuteOptions with an AbortSignal for cancellation

Using Context

Tools can access shared context for things like database connections, API clients, or user info:

context-tool.ts
interface AppContext {
  userId: string;
  db: Database;
}

const lookupOrder = tool({
  name: "lookup_order",
  description: "Look up an order by ID",
  parameters: z.object({ orderId: z.string() }),
  execute: async (ctx: AppContext, { orderId }) => {
    const order = await ctx.db.orders.find(orderId, ctx.userId);
    return JSON.stringify(order);
  },
});

const agent = new Agent<AppContext>({
  name: "support",
  model,
  tools: [lookupOrder],
});

await run(agent, "Where is my order #123?", {
  context: { userId: "user_abc", db: myDb },
});

Passing Tools to Agents

const agent = new Agent({
  name: "assistant",
  model,
  tools: [getWeather, lookupOrder, searchDocs],
});

Passing Tools to Sessions

const session = createSession({
  model,
  tools: [getWeather, lookupOrder],
});

Tool Call Flow

Model returns a tool call

The model responds with a tool call containing a name and JSON arguments.

Arguments are parsed

Stratus parses the arguments JSON and validates them against the Zod schema.

Execute function runs

The execute function runs with the parsed parameters and context.

Result sent back to model

The result string is sent back to the model as a tool message.

Model generates final response

The model generates a final response (or calls more tools). This loop continues until the model responds without tool calls, or toolUseBehavior causes an early stop.

Abort Signal

When a run is started with an AbortSignal, it's passed to each tool's execute function via the options parameter. Use it to cancel long-running operations:

abort-aware-tool.ts
const searchTool = tool({
  name: "search",
  description: "Search documents",
  parameters: z.object({ query: z.string() }),
  execute: async (_ctx, { query }, options) => { 
    const res = await fetch(`/api/search?q=${query}`, {
      signal: options?.signal, 
    });
    return await res.text();
  },
});

See Streaming - Abort Signal for details on passing a signal.

Error Handling

If a tool's execute function throws, the error message is sent back to the model as the tool result. This lets the model recover gracefully:

execute: async (_ctx, { query }) => {
  const results = await search(query);
  if (results.length === 0) {
    throw new Error("No results found. Try a different query.");
  }
  return JSON.stringify(results);
},

Schema Conversion

Stratus converts Zod schemas to JSON Schema for the Azure API. The conversion adds additionalProperties: false to all objects for Azure strict mode compatibility.

Supported Zod types include objects, strings, numbers, booleans, arrays, enums, optionals, nullables, defaults, unions, and descriptions.

Edit on GitHub

Last updated on

On this page