UNPKG

eve

Version:

Filesystem-first framework for durable backend AI agents that run anywhere.

295 lines (225 loc) 19 kB
--- title: "Tools" description: "Define typed actions the agent can call, and gate sensitive ones on human approval." url: /tools --- A tool is a typed action the agent can call, such as hitting an API, running a query, or writing a file. Define a tool when you implement the action in code you control. To give the model tools published by an external MCP or OpenAPI service, use a [connection](/docs/connections) instead. Authored tools run in your app runtime with full access to `process.env`, not in the [sandbox](/docs/sandbox). ## Define a tool The filename is the tool name the model sees. A file at `agent/tools/get_weather.ts` is exposed as `get_weather`. ```ts title="agent/tools/get_weather.ts" import { defineTool } from "eve/tools"; import { z } from "zod"; export default defineTool({ description: "Get the current weather for a city.", inputSchema: z.object({ city: z.string().min(1) }), async execute({ city }, ctx) { return { city, condition: "Sunny", temperatureF: 72 }; }, }); ``` A tool definition needs: - a filename slug under `agent/tools/`, the model-facing name. - a `description`: what the tool does, written for the model. - an `inputSchema`: a Zod schema (or any Standard Schema, or a plain JSON Schema object). Required. For no input, pass `z.object({})`. Zod and Standard Schema infer the `input` type in `execute`. Plain JSON Schema types it as `Record<string, unknown>`. - an `execute(input, ctx)`: the implementation. May be sync, async, or an async generator. When a tool returns structured data, add an optional `outputSchema`. With Zod or Standard Schema it also types the `execute` return. ### Hide a tool from delegated agents Set `availableInSubagents: false` when a tool should be callable only in a top-level root session: ```ts title="agent/tools/coordinator.ts" export default defineTool({ availableInSubagents: false, description: "Coordinate work that only the top-level root agent should start.", inputSchema: z.object({ task: z.string() }), execute({ task }) { return coordinate(task); }, }); ``` The option defaults to `true` and works with `defineTool` and `defineWorkflowTool`. A root copy does not receive a tool with this option, and a tool authored inside a declared subagent is unavailable because that agent runs in a delegated session. This controls tool availability only; it does not add or remove entries from a workflow's `ctx.agents` registry. Compiled tools preserve Zod schema composition, including input and output schemas imported from helper modules. Durable replay metadata stays separate from the original schema, so adding it does not mutate shared schema objects. ### Label tool activity Use `label.start(input)` to describe a call in user-facing activity. The callback receives the validated tool input, so it can select the useful fields without exposing the full argument object: ```ts title="agent/tools/deploy.ts" export default defineTool({ description: "Deploy a project to an environment.", inputSchema: z.object({ project: z.string(), environment: z.enum(["preview", "production"]), }), label: { start: ({ project, environment }) => `Deploy ${project} to ${environment}`, }, async execute(input) { return deploy(input); }, }); ``` The label is presentation only. It does not replace the path-derived tool name, enter model input, or change execution. eve records the bounded label on the corresponding public action event so activity renderers and other authorized stream consumers can use it without interpreting raw tool data. Built-in channel activity can show `Deploy storefront to production` instead of `deploy`; if the callback throws or returns an empty label, activity falls back to the tool name. Provided tools define labels for `bash`, `glob`, `grep`, `load_skill`, `read_file`, `web_fetch`, `web_search`, and `write_file`. ### Stream preliminary tool results For a `defineTool` executor with the default execution mode, an async generator streams complete output snapshots before it finishes. Each `yield` replaces the previous snapshot; the final yield is the normal tool result the model receives: ```ts title="agent/tools/build_report.ts" export default defineTool({ description: "Build a project report.", inputSchema: z.object({ project: z.string() }), label: { start: ({ project }) => `Build report for ${project}`, delta: (_input, partial) => partial.phase, complete: (_input, output) => `Report ready with ${output.report.sections.length} sections`, }, async *execute({ project }) { yield { phase: "Collecting sources", report: null }; const report = await buildReport(project); yield { phase: "Complete", report }; }, }); ``` eve publishes every earlier yield as an `action.partial` stream event. The snapshot is visible to channels, hooks, and clients but never enters model history or `toModelOutput`; only the final yield does. Treat snapshots as last-write-wins by tool call id, not append-only progress. The durable runtime can retry a step and replay overlapping snapshots. A generator `return` value is not used as the result in this mode; yield the final output. Workflow and background generators have different result rules, described under [yield and return](#yield-and-return). Use `label.delta(input, partial)` to project preliminary snapshots into user-facing activity, and `label.complete(input, output)` to describe successful settlement differently. Both callbacks receive the validated input first and the typed value yielded by `execute` second. Each non-empty update replaces the previous activity label; the result projection replaces the latest update immediately before eve marks the action complete. eve normalizes and bounds projected text before rendering it. If either callback throws or returns an empty string, eve keeps the existing activity label. `label.complete` does not run for failed or rejected tool calls. The full values remain available in `action.partial` and `action.result`; renderers receive only the projected text. ### Background execution Background execution controls how a workflow tool delivers its result to the parent agent. Set `execution: "background"` on `defineWorkflowTool`; ordinary `defineTool` calls always finish inside the initiating step. | Definition | Durable waits inside `execute` | Result delivered to the model | | ------------------------------------------------ | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | | `defineTool` | No; the executor runs inside the initiating step. | Executor output after it finishes. | | `defineWorkflowTool` | Yes; the tool call waits while the workflow can suspend. | Workflow output after it finishes. | | `defineWorkflowTool` + `execution: "background"` | Yes; the workflow body can outlive the initiating step. | Task receipt before the body finishes; one combined report after all tasks in its cohort are terminal. | A background workflow tool's result is the receipt `{ status: "working", taskId }`; its eventual output belongs to the task. Use this mode when the conversation should continue while the body waits for a person, webhook, or timer. For background tools, `outputSchema` and `toModelOutput` describe the fixed receipt. The body's return value is available through the completed task's output. The `TaskExec` argument and `task.postMessage` have been removed. Return the terminal result; background yields are consumed without publishing progress or retaining a task-progress stream. In a workflow body, keep values needed after a wait in local variables; workflow replay reconstructs them across durable waits. Use [`ctx.ask`](/docs/tools/workflows#ask-a-human-ctxask) when the body needs an answer from the human. Background tools are a normal execution mode and need no root-agent flag. Built-in, declared local, and remote subagents use this task lifecycle automatically. After the initiating turn accepts background tasks, eve supplies runtime-authored state for that cohort and instructs the model to acknowledge that the work started without waiting for results. [Schedule](/docs/schedules)-initiated turns are the exception: no user prompted them, so their launches keep conditional delivery and send no acknowledgement. Channel sessions default to `taskDeliveryPolicy: "auto"`: ready results can invoke the parent while other tasks continue. The parent reports independently useful results and can stay silent until related work settles. Each reporting context includes the whole cohort and available outputs, including previously withheld results. Ready results may share a turn. Schedules default to `"cohort"`: terminal outcomes wait for overlapping tasks to settle, then arrive together. Pass `taskDeliveryPolicy` to `send(...)` to select or update the session policy. See [Background task results](/docs/channels/overview#background-task-results) and [Schedules](/docs/schedules#background-task-results). User questions, input requests, and explicit task messages do not wait for the cohort under either policy. Failure and cancellation update lifecycle state immediately; their automatic reports follow the selected policy. See [Completion batching](/docs/subagents#completion-batching). ### Yield and return `yield` hands a value to eve's generator consumer, which processes it and advances the generator. It does not by itself create a durable wait for a person, timer, or external event. The value's meaning depends on the tool's execution mode: | Executor | Ordinary `yield value` | Final output | | --------------------------------------------------- | --------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | | `defineTool`, default execution | Earlier values are `action.partial` snapshots; the final yield becomes the tool result. | Last yielded value; a generator `return` value is ignored. | | `defineWorkflowTool`, default execution | Every yield is an `action.partial` snapshot. | Explicit return value; falls back to the last yield if the return is `null` or `undefined`, then to `null`. | | `defineWorkflowTool` with `execution: "background"` | Consumed without publishing progress or requesting a parent-agent turn. | Explicit return value becomes the task output; no return completes with `null`. The last yield is not a fallback. | For a background workflow tool, return completes the task and throw fails it. The automatic cohort report is separate from the original tool call's receipt. Progress snapshots do not enter model history as intermediate tool results. For a default executor, the final output selected by the rules above becomes the tool result. For a background executor, the terminal cohort report provides input to a later parent-agent turn. ### Workflows as tools Use `defineWorkflowTool` from `eve/tools` to run each call as a durable Workflow run. Its executor must start with `"use workflow"` and receives `ctx.agent` and `ctx.ask`. The tool can wait for a person, webhook, or timer without holding compute, then return its result to the model. See [Workflows as tools](/docs/tools/workflows) for the authoring rules and examples. ### The `ctx` parameter `execute` gets a `ctx` carrying the runtime accessors: - `ctx.session`: session metadata, turn, auth, parent lineage. - `ctx.callId`: the id of the current tool call, carried by the call's [stream events](/docs/concepts/sessions-runs-and-streaming) and approval context. - `ctx.toolName`: the final runtime name the model called, including any namespace qualification. - `ctx.abortSignal`: aborts when the active turn is cancelled. Pass it to cancellation-aware work; sandbox sessions from `ctx.getSandbox()` are already bound to it. - `ctx.getSandbox()`: the live [sandbox](/docs/sandbox) handle. - `ctx.getSkill(id)`: read a packaged [skill](/docs/skills)'s metadata and files. Running in the app runtime is what lets a tool import shared code from `lib/`, read `process.env`, and take part in eve’s durable pause/resume model. eve never runs authored tools during discovery. The model sees descriptors first, and only what it actually calls gets executed. Completed steps never re-run; eve replays the recorded result. A step interrupted mid-execution re-runs, so make non-idempotent side effects like charges or emails idempotent, or gate them with approval. ## When a tool throws If an authored tool's `execute` function throws, eve records a failed `action.result` and gives the error to the model as a tool error. The model can respond, choose another action, or call the tool again. eve does not automatically call the tool again based on the exception type, an upstream HTTP status, or a `retryable` property. Authored tools have no public terminal-error class or retry policy for thrown exceptions. Handle retry policy inside the tool when the operation is safe to retry, and return or throw an actionable error when it is not. Do not rely on that distinction to protect a write: an interruption before the durable step completes can re-run the step and execute the tool again even if the first request reached the upstream service. Protect non-idempotent operations with the strongest mechanism the service supports: 1. Pass a stable idempotency key to the upstream API. 2. Otherwise, record a unique application operation before writing and check it on every attempt. 3. Use human approval when a person must authorize each execution, not as a substitute for deduplication after an ambiguous network result. See [Execution model and durability](/docs/concepts/execution-model-and-durability#resuming-after-a-crash) for step replay semantics. For one-way provider notifications, see [Durable cross-channel notifications](/docs/patterns/durable-cross-channel-notifications). ## Gate a tool on human approval A tool can require a person to sign off before it runs. Set `approval` with the helpers from `eve/tools/approval`: ```ts title="agent/tools/refund_charge.ts" import { defineTool } from "eve/tools"; import { always } from "eve/tools/approval"; import { z } from "zod"; export default defineTool({ description: "Refund a charge.", inputSchema: z.object({ chargeId: z.string(), amount: z.number() }), approval: always(), // or auto() / once() / never() / a policy async execute(input) { return refund(input); }, }); ``` Approval is one half of eve's [human-in-the-loop](./human-in-the-loop) model — the page covers the `auto`/`always`/`once`/`never` helpers, input-dependent policies, and how a gated call pauses and resumes durably. ## Shape what the model sees with `toModelOutput` By default the model sees the full `execute` return. When a tool returns rich data a channel needs for rendering but the model only needs the gist, project it down with `toModelOutput`: ```ts toModelOutput(output) { return { type: "text", value: `Report for ${output.domain}: score ${output.score}.` }; }, ``` `toModelOutput` receives the final, typed `execute` return and only affects the model. Channel event handlers and hooks still get the full output on `action.result`, so a channel can render rich platform output (Slack Block Kit, say) the model never sees. Return `{ type: "text", value }` for a summary, or `{ type: "json", value }` for a smaller object. Tool outputs must be JSON-serializable. Return plain objects, arrays, strings, numbers, booleans, or `null`; convert values like `Date`, `Map`, `Set`, `NaN`, and cyclic objects before returning them from `execute` or from a `{ type: "json" }` `toModelOutput`. ### Send images to the model with content parts A tool that produces an image — a screenshot, a rendered chart — can hand the pixels to a vision-capable model by returning a `content` output from `toModelOutput`. Build outputs with the `toolOutput` helpers and parts with the `toolOutputPart` helpers, both from `eve/tools`: ```ts import { defineTool, toolOutput, toolOutputPart } from "eve/tools"; export default defineTool({ description: "Capture a screenshot of the current page", inputSchema: z.object({ url: z.string() }), async execute(input) { const png = await captureScreenshot(input.url); return { path: png.path, screenshotBase64: png.base64 }; }, toModelOutput(output) { return toolOutput.content([ toolOutputPart.text(`Screenshot of ${output.path}:`), toolOutputPart.file(output.screenshotBase64, { mediaType: "image/png" }), ]); }, }); ``` The `toolOutput.text` and `toolOutput.json` builders construct the other two output shapes; hand-written literals remain valid everywhere. File payloads must be base64 strings — raw bytes (`Uint8Array`, `Buffer`) are rejected because they do not survive eve's durable JSON boundary. Keep payloads small: a content-part image is persisted in session history and re-sent on every subsequent model call, and eve warns above 3 MiB. Sending image parts to a model without vision support fails with that provider's error, the same as image parts in user messages. When older turns are compacted, file payloads are dropped from the summary and replaced with a text stub naming the file and media type — the model cannot re-see a compacted image. Content parts are for "look at this now"; if the agent may need an artifact again later, write it to the [sandbox](/docs/sandbox) and return its path. Do not return secrets, credentials, unnecessary personal data, or unbounded sensitive content from tools. Filter, minimize, and redact tool outputs before returning them. ## What to read next - [Human-in-the-loop](./human-in-the-loop): gate a tool on approval, or have the agent ask a question - [Skills](/docs/skills): on-demand procedures the model loads when relevant - [Built-in tools](/docs/concepts/built-in-tools): the default and opt-in framework tools and how to override or disable them - [Dynamic capabilities](/docs/guides/dynamic-capabilities): tools whose set is resolved per session with `defineDynamic` - [Authentication](/docs/guides/auth-and-route-protection): authenticate a tool to an external service