Cogitator
Core

Tools

Create type-safe tools that give agents the ability to interact with external systems.

Overview

Tools enable agents to take actions -- call APIs, read files, execute code, query databases. Cogitator tools are defined with Zod schemas for full type safety and automatic JSON Schema generation for LLM function calling.

import { tool } from '@cogitator-ai/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'),
    units: z.enum(['celsius', 'fahrenheit']).default('celsius'),
  }),
  execute: async ({ city, units }, context) => {
    const response = await fetch(`https://api.weather.com/${city}?units=${units}`, {
      signal: context.signal,
    });
    return response.json();
  },
});

The tool() Factory

function tool<TParams, TResult>(config: ToolConfig<TParams, TResult>): Tool<TParams, TResult>;

ToolConfig

FieldTypeDescription
namestringUnique tool name (used in LLM function calling), see Tool Names
descriptionstringWhat the tool does (sent to the LLM)
parametersZodTypeZod schema defining accepted parameters
execute(params, context) => Promise<TResult>Implementation function
categoryToolCategory'math', 'text', 'file', 'network', 'system', 'utility', 'web', 'database', 'communication' or 'development'
tagsstring[]Optional tags for filtering
sideEffectsSideEffectType[]'filesystem', 'network', 'database', 'process', 'external', shown to approvers
requiresApprovalboolean | (params) => booleanRequire human approval before execution (Approvals)
timeoutnumberPer-call timeout in milliseconds, over the run's timeouts.toolMs (Stage Timeouts)
sandboxSandboxConfigRun in an isolated environment (see below)
maxResultLengthnumberMost characters of a result the model reads, over limits.maxToolResultLength (Result Size)
titlestringName for people, such as an MCP client shows (the model sees name)
outputSchemaZodTypeSchema of the result. Not checked in a run: an MCP server advertises it and sends structuredContent, Gemini reads it as responseJsonSchema
annotationsToolAnnotationsMCP hints: readOnlyHint, destructiveHint, idempotentHint, openWorldHint
providerTypesProviderToolTypesThe tool's type in a provider's own catalog, sent to that provider instead of its schema, such as { anthropic: 'memory_20250818' }
isConcurrencySafeboolean | (params) => booleanMay run beside other safe calls of its step with parallelToolCalls (default: annotations.readOnlyHint), see Concurrency
lockKeys(params, context) => string[]Keys of what a call changes, calls whose keys meet never run at the same time, see Lock Keys
presentationToolPresentation | (params) => ToolPresentationHow clients show a call: label, icon, detail, see Results and Progress
onInputStart, onInputDelta, onInputAvailable, onInputAbandoned(event) => voidThe model writes a call of the tool, in a streamed run, see Streaming Tool Input

Tool Names

A tool name must be one every LLM provider accepts: letters, digits, _ and -, starting with a letter or _, at most 64 characters (/^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/, the strictest of the OpenAI, Anthropic, Gemini and Bedrock rules). tool() throws a TypeError for any other name, so a bad name fails where the tool is defined instead of as a provider error in the middle of a run. The message names the rule and suggests a name that fits:

tool({ name: 'weather.get', ... });
// TypeError: Invalid tool name "weather.get": LLM providers accept letters, digits, "_" and "-",
// starting with a letter or "_", at most 64 characters. For example "weather_get".

For names that come from elsewhere (a config file, a remote service), @cogitator-ai/core exports the same rule:

import {
  TOOL_NAME_MAX_LENGTH, // 64
  isProviderSafeToolName,
  normalizeToolName,
  normalizeToolNames,
} from '@cogitator-ai/core';

isProviderSafeToolName('get_weather'); // true
normalizeToolName('admin.list_users'); // 'admin_list_users'
normalizeToolName('2fa-check'); // '_2fa-check'
normalizeToolNames(['a.b', 'a_b']); // ['a_b_<hash>', 'a_b']

normalizeToolName keeps a valid name as it is, turns every other character into _, adds a leading _ when the name does not start with a letter or _, and cuts a name longer than 64 characters so it ends with _ and 8 hex characters of a SHA-256 hash of the full name, so different long names stay different. normalizeToolNames does the same for a list, in order, and keeps the names distinct: when two of them normalize to the same name, each one that had to change gets the hash of its original name. MCP tools and A2A agent cards are named with the same function.

Tool Context

execute receives the validated parameters and a ToolContext:

FieldDescription
agentId, runIdThe agent and run that called the tool
signalAborted when the run is cancelled, times out, or the tool's timeout passes
threadIdThe conversation
userIdThe user the run acts for (RunOptions.userId)
channelType, channelId, topicId, conversationIdWhere the message came from, for channel gateways
depsThe run's deps (RunOptions.deps), never shown to the model
updateReports what the tool has so far while it runs (Progress)

Annotate the context as ToolContext<YourDeps> to read deps typed, see Dependencies for Tools.

When timeout is set (or the run's timeouts.toolMs for a tool without one), the runtime aborts context.signal once the limit is reached and reports Tool "<name>" timed out after <ms>ms to the model as the tool error, with errorCode: 'TOOL_TIMEOUT' on the ToolResult. Long-running tools should pass context.signal to fetch and other cancellable APIs so the work actually stops.

Parameter Schemas

The parameters field accepts any Zod schema. Cogitator converts it to JSON Schema (OpenAPI 3.0 format) before sending it to the LLM.

const createIssue = tool({
  name: 'create_github_issue',
  description: 'Create a new issue in a GitHub repository',
  parameters: z.object({
    repo: z.string().describe('Repository in owner/repo format'),
    title: z.string().max(256).describe('Issue title'),
    body: z.string().describe('Issue description in markdown'),
    labels: z.array(z.string()).optional().describe('Labels to apply'),
    priority: z.enum(['low', 'medium', 'high']).default('medium'),
  }),
  execute: async ({ repo, title, body, labels, priority }) => {
    const issue = await github.createIssue(repo, { title, body, labels, priority });
    return { issueNumber: issue.number, url: issue.html_url };
  },
});

Use .describe() on each field -- these descriptions are sent to the LLM and significantly improve tool call accuracy.

Arguments the model sends are parsed with the schema before execute runs, so defaults and transforms apply. Arguments that fail validation never reach execute: the model gets Invalid arguments: ... as the tool result and can try again.

Tool Results

The execute function can return any serializable value. Cogitator converts the result to JSON and feeds it back to the LLM as a tool response (return toolOutput() to give your application data the model never reads):

const calculator = tool({
  name: 'calculator',
  description: 'Evaluate a mathematical expression',
  parameters: z.object({
    expression: z.string().describe('Math expression to evaluate'),
  }),
  execute: async ({ expression }) => {
    const result = eval(expression);
    return { result, expression };
  },
});

If the execute function throws, the error message is sent back to the LLM (as { "error": "..." }) so it can retry or adjust its approach. A call to a tool the agent does not have gets Tool not found: <name>.

Images in Tool Results

A result object with a base64 image in image or imageBase64 (PNG, JPEG, GIF or WebP, plain or as a data:image/...;base64, URL) reaches the model as an image, so a vision model sees a screenshot or chart instead of its base64 text. The rest of the object is still sent as JSON, with the image field replaced by "(image attached)":

const renderChart = tool({
  name: 'render_chart',
  description: 'Render a line chart of the given values as a PNG',
  parameters: z.object({ values: z.array(z.number()) }),
  execute: async ({ values }) => {
    const png = await drawChart(values);
    return { points: values.length, image: png.toString('base64') };
  },
});

Each backend places the image where its API allows: inside the tool result for Anthropic, Bedrock and the OpenAI Responses API, after the function responses of the turn for Google, in the tool message's images for Ollama, and in a user message right after the turn's tool messages for Chat Completions (api: 'chat-completions', OpenAI-compatible baseUrl, Azure), whose tool messages take only text. Results of the image-generation tool (imageBase64) and the browser screenshot tools (image) take this path.

Media Results with toolContent

For results made of several parts, or with media other than images, return toolContent(). Text and images reach the model as the tool message's content. JSON and resource parts are described below. File parts (audio, PDFs and other binary data) stay with the result for your application, in onToolResult, and the model sees only a one-line description such as [audio/mpeg file "speech.mp3", 46.9 KB, delivered to the application, not shown here], so the bytes never fill the context:

import { tool, toolContent } from '@cogitator-ai/core';

const screenshotPage = tool({
  name: 'screenshot_page',
  description: 'Screenshot a page',
  parameters: z.object({ url: z.string().url() }),
  execute: async ({ url }) => {
    const png = await capture(url);
    return toolContent(
      { type: 'text', text: `Screenshot of ${url}` },
      { type: 'image', data: png.toString('base64'), mediaType: 'image/png' }
    );
  },
});

Images in formats the providers do not take (anything but PNG, JPEG, GIF and WebP) are described like files. Guardrails that filter tool results read the text and the descriptions, never the base64 data. MCP tools that return image or audio content and AI SDK tools come through as the same parts.

Two more parts carry structured data and resources:

  • { type: 'json', value } keeps a value as it is for your application, and the model reads it as JSON text.
  • { type: 'resource', uri, name?, description?, mediaType?, text?, data? } names a resource the tool read or points to, such as a file or a web page. Set at most one of text and data (base64). With text the model reads a line naming the resource, [resource "name" uri (mediaType) - description], and the text on the next line. With data it reads that line with the size, and the bytes stay with your application like a file. With neither it reads only the line.
execute: async ({ path }) => {
  const text = await readFile(path, 'utf-8');
  return toolContent(
    { type: 'json', value: { path, lines: text.split('\n').length } },
    {
      type: 'resource',
      uri: `file://${path}`,
      name: basename(path),
      mediaType: 'text/markdown',
      text,
    }
  );
};

isToolContentResult, toolResultParts (the parts of any result, including an object with a base64 image) and toolPartsToText (the text the model reads, with every image and file described) are exported from @cogitator-ai/core and from @cogitator-ai/types, for code that reads results without the runtime. When an MCP tool's result carries media, its text resources come through as resource parts.

Result Size

The model reads at most limits.maxToolResultLength characters of a tool result (default 100 000, about 25 000 tokens, DEFAULT_TOOL_RESULT_MAX_LENGTH), so one huge output, such as a long log or a scraped page, cannot fill the context. A tool's own maxResultLength overrides the limit:

const cog = new Cogitator({ limits: { maxToolResultLength: 20_000 } });

const readLog = tool({
  name: 'read_log',
  description: 'Read the build log',
  parameters: z.object({}),
  maxResultLength: 5_000,
  execute: async () => readFile('build.log', 'utf-8'),
});

A longer result keeps its start (three quarters of the budget) and its end (one quarter), where a command's last lines or an error usually are, with a note in the middle such as [... 1000 of 2000 characters of this tool result were left out ...]. Error messages are cut the same way. For a toolContent() result the text parts are cut as one text, so a short first part survives and parts in the middle are left out, and images are never cut. Only what the model reads is cut: onToolResult still gets the whole result, while RunResult.messages and the thread history keep what the model read. truncateToolResultText(text, maxLength) applies the same cut to text of your own.

Typed Tool Sets

A function that returns several tools as Tool[] loses each tool's own parameter types. toolset() keeps them as a tuple, which is still an array an agent accepts:

import { toolset } from '@cogitator-ai/core';

function createIssueTools() {
  return toolset(createIssue, getWeather);
}

const [issues, weather] = createIssueTools();
await weather.execute({ city: 'Tokyo', units: 'celsius' }, context); // typed parameters
const agent = new Agent({
  name: 'ops',
  model: 'openai/gpt-6.1-sol',
  instructions: '...',
  tools: createIssueTools(),
});

Built-in Tools

Cogitator ships with ready-to-use tools (builtinTools is all of them as one array; see Built-in Tools for parameters):

import {
  calculator,
  datetime,
  uuid,
  fileRead,
  fileWrite,
  fileList,
  fileExists,
  fileDelete,
  httpRequest,
  exec,
  webSearch,
  webScrape,
  sqlQuery,
  vectorSearch,
  sendEmail,
  githubApi,
  jsonParse,
  jsonStringify,
  regexMatch,
  regexReplace,
  hash,
  base64Encode,
  base64Decode,
  sleep,
  randomNumber,
  randomString,
} from '@cogitator-ai/core';

Use them directly:

const agent = new Agent({
  name: 'file-assistant',
  model: 'openai/gpt-6.1-sol',
  instructions: 'You help users manage files.',
  tools: [fileRead, fileWrite, fileList, fileDelete],
});

Tool Registry

The ToolRegistry class manages collections of tools and provides lookup by name:

import { ToolRegistry } from '@cogitator-ai/core';

const registry = new ToolRegistry();
registry.register(getWeather);
registry.register(createIssue);
registry.registerMany([calculator, datetime]);

const weatherTool = registry.get('get_weather');
const allNames = registry.getNames();
const schemas = registry.getSchemas();
registry.has('get_weather'); // true
registry.getAll(); // Tool[]
registry.clear();

Registering a tool under a name that already exists replaces it. When the new tool is a different one, the registry logs a warning, since the model can only ever call one of them and a clash is usually a mistake (two MCP servers with a search tool, for example). Pass { replace: true } when replacing is the intent:

registry.register(getWeatherV2, { replace: true });
registry.registerMany([calculator, datetime], { replace: true });

Registering the same tool object again is not a clash and never warns.

The Cogitator runtime uses ToolRegistry internally to resolve tool calls from the LLM. In a run, an agent's own tool replaces a global tool (cogitator.tools) of the same name without a warning.

Tool Schema Conversion

Under the hood, toolToSchema() converts a Zod-based tool into the JSON Schema format that LLM providers expect:

import { toolToSchema } from '@cogitator-ai/core';

const schema = toolToSchema(getWeather);
// {
//   name: 'get_weather',
//   description: 'Get the current weather for a city',
//   parameters: {
//     type: 'object',
//     properties: {
//       city: { type: 'string', description: 'City name' },
//       units: { type: 'string', enum: ['celsius', 'fahrenheit'], default: 'celsius' }
//     },
//     required: ['city']
//   }
// }

The conversion uses the schema's input type, so fields with a .default() are optional for the model; the default is applied when the arguments are parsed. tool.toJSON() returns the same schema.

A tool with providerTypes carries them in its schema. The Anthropic backend sends a tool with providerTypes.anthropic as { type, name } instead of its schema, so a model trained on the tool, such as Claude with the memory tool (memory_20250818), gets it the way it knows it. The memory tool goes this way only to the Claude models that take it, Claude 4 and later, and as its schema to older ones. Every other backend sends the tool's name, description and parameters as usual, and the calls come back as calls of the tool either way, checked against its Zod schema. The memory tool of memory files is one.

Recursive schemas work too. A z.lazy() schema (a tree, a nested comment thread) refers to its definition with $ref: the definitions such refs point to travel along in parameters.$defs, and refs to definitions that are not recursive (a schema reused with .meta({ id })) are inlined, so every provider gets a self-contained schema. Google receives recursive schemas as parametersJsonSchema, the form of its API that can hold $ref. toToolParameters(jsonSchema) applies the same rules to a JSON Schema of your own, and the registry applies them to every tool's toJSON() before a request.

Sandboxed Execution

Tools that run untrusted commands can declare a sandbox. A sandboxed tool does not run its execute function: the runtime executes the call in the sandbox instead (install @cogitator-ai/sandbox):

  • type: 'docker' runs the command argument with sh -c in a container of image, with optional cwd and env arguments, and returns { stdout, stderr, exitCode, timedOut, duration, command }. A command that runs out of time fails the call with errorCode: 'TOOL_TIMEOUT' instead.
  • type: 'wasm' passes the arguments as JSON on stdin to wasmModule and returns its stdout, parsed as JSON when possible. A run that traps or panics, times out, or writes more than the sandbox keeps comes back to the model as a tool error, never as an empty result.
const runPython = tool({
  name: 'run_python',
  description: 'Run a shell command in a Python 3.12 container, e.g. python -c "print(2 ** 10)"',
  parameters: z.object({
    command: z.string().describe('Shell command to run'),
  }),
  execute: async ({ command }) => ({ command }), // not called while the sandbox is available
  sandbox: {
    type: 'docker',
    image: 'python:3.12-slim',
    network: { mode: 'none' },
    resources: { memory: '256MB', cpus: 0.5 },
    timeout: 30_000,
  },
});

The container is managed by the runtime (configure it with sandbox on the Cogitator). Two fallbacks log a warning and run without isolation: when @cogitator-ai/sandbox cannot be loaded, the runtime calls execute natively, so keep execute harmless. When Docker is not available, the sandbox manager runs the command on the host shell. Both are allowed by sandbox.allowNativeFallback (default true). Set it to false on the Cogitator when untrusted commands must never reach the host, and such calls fail instead - see Sandbox.

The run's abort signal reaches the sandbox: cancelling a run (RunOptions.signal) stops a sandboxed command that is still running, killing its process, container or WASM plugin, and the call fails with the abort reason, as a native tool's call does.

Tool Caching

Wrap tools with withCache to avoid repeated expensive calls:

import { withCache } from '@cogitator-ai/core';

const cachedWeather = withCache(getWeather, {
  strategy: 'exact',
  ttl: '5m',
  maxSize: 1000,
  storage: 'memory',
});

See Tool Caching for TTL strategies, semantic matching, and Redis-backed storage.

On this page