Your functions as tools
A tool is one of your functions, which the agent may call: defineTool in openlegion/tools.ts, listed in your template's tools. Your app serves it from its OpenLegion route, and OpenLegion calls it signed, for one customer at a time.
import { defineTool, refuse } from "@openlegion/platform";
import { z } from "zod";
export const lookupOrder = defineTool({
description: "Look up one of the customer's orders by its number: its status and when it should arrive.",
input: z.object({ number: z.string().describe("The order number, e.g. A-1001") }),
trust: "tool_verified", // your own data. "web_low": it carries other people's words
effect: "read", // read | draft | write | egress
run: async ({ number }, ctx) => {
// ctx.external_ref is the customer OpenLegion signed this call for. Scope every read by it.
const order = await db.orders.find({ customer: ctx.external_ref, number });
return order ?? refuse(`There is no order ${number} for this customer.`, "order_not_found");
},
});
A template with several agents gives each of your tools to all of them. To give one to some agents only, name them in toolAgents on defineTemplate, by agent key: toolAgents: { cancel_subscription: ["assistant"] }. An agent that is not named is never offered the tool and can't call it. Starters your customers pick from has it in a template.
What a tool takes and returns
inputis zod 4, or any schema that implements Standard Schema together with its JSON Schema extension. The arguments are validated beforerunsees them.runreturns one of three things:- a string;
- an object, which the model gets as JSON (a plain object also goes out as
structuredContent); refuse(message, code?), a refusal the model reads. Thecodeis for you:GET /connectors/{id}/callslists it astool_refusal_code, andnpx openlegion devprints it.
- If
runthrows, the model is told only that the tool failed. The error itself goes to your route'sonError.
What later runs read of a call
When a call waited for your user's decision (the tool has requiresApproval: true, or your template's policy held it), later runs in the same conversation are shown that call again. They see the agent's own call with its input, what your user decided, and what your tool returned. The newest six are shown whole and older ones as short excerpts. The agent reads your result as a claim from your app, so a result that was fine for the run that made the call can mislead every run after it.
- A refusal is shown the same way. If your user approved the call and your tool answered
refuse(message), later runs read that message as the call's result. - A rejected or expired call never reached your tool, so later runs read OpenLegion's words for it: it did not run.
- A call that did not wait for a decision is not shown again. Later runs read only the agent's reply about it. The exception is a reply your user stopped: the next answer in that conversation is handed the calls the stopped reply made, so it does not make them again.
Five rounds with a real model, on a tool that emails the person, taught these rules for a result:
- Say it in the person's terms. "Sent to the address the person you are talking to signed in with", not your system's words for it.
- Put no identifier in it that the model cannot check and does not need, such as an email address or an account id. The agent is told its user's display name when you send one, never their address or an account id, so an address it has never seen reads as someone else's: a result that returned
to: <address>made later runs refuse to email the person. - Put one fact in one field, never the same thing twice in different words.
tobesiderecipient: "the person you are talking to"was read as two different people. - If something was not done, say what will not happen later. Write "Nothing was sent, and this message will not be sent later", or the agent promises the person it will be sent once email is on.
- Name a place in your app only with exactly what is and is not there. Write "Only its subject is listed in Settings, under Notifications; its text is only in this conversation", or the agent tells the person to read it, or send it, from there.
- Say whose switch it is. Write "Email isn't switched on in this app yet, and the person cannot switch it on themselves", or the agent tells them to turn it on.
What a call knows: ctx
ctx holds the signed call's context: org, workspace, external_ref, agent, run, action, subject, tainted, taint_sources, plus request and signal.
external_refis your id for the customer the call is for. Scope every read and write by it.subjectis your user id of the one person the run acts for (thesubjectyour chat route orOpenLegion-Subjectnamed), so you can apply that person's permissions. It isnullwhen there is no single signed-in person: a schedule, an inbound event, a hand-off, several people in one run, your service principal, or a user being erased. Treatnullas the least-privileged case, never as an admin.runis therun_…id thatGET /runs/{id}and the action'srunuse.action(act_…) stays the same when OpenLegion retries the same action: use it as your idempotency key.
Trust and effect
trust and effect sit next to the code they describe, so the person who knows what the function does makes the security declaration.
trust:tool_verifiedwhen the result is your own data;web_lowwhen it carries other people's words, such as a review, a support ticket's text or a forwarded email.effect:read,draft,writeoregress(it sends something out of your product). The template's policy decides on it, and a tool may require approval outright: Approvals and roles.
What a person sees of a tool
description is for the model. A person never reads it. Two optional fields are for people:
title: the tool's name in a person's words, such as "Email you". It is the title of the approval card when a call waits for a person, with a question mark.approvalTitle: the whole sentence for that card, with values from the call, such asEmail you "{subject}"?. See What the person reads.
The line <AgentChat> writes while a tool runs is set on the chat, not here: labels.tools.
Tainted runs
A run that has read untrusted content is tainted: a web page, a web_low result, a recalled note, untrusted earlier turns. Untrusted content can carry instructions aimed at the agent, so your tools are told.
ctx.tainted: truemeans the run has already read untrusted content.ctx.taint_sourcessays which, as ids, never text or URLs:event:<type>(an event the run started from),tool:<tool id>(a result it read, such astool:mcp.yourapp.list_commentsortool:web.fetch),memory(a recalled note),conversation(earlier turns),classifierorunknown. It is[]when the run is clean.requiresApproval: trueholds every call to the tool until a person approves it, tainted or not. Every other tool runs, tainted or not, and what it does with a tainted call is yours to decide:- refuse it:
refuseIfTainted(ctx, message?)returns a refusal with the codetainted(listed astool_refusal_code), ornullwhen the run is clean; - hold it in your own product;
- or mark what you store: wrap anything you keep from a tainted call in
markUntrusted(item), so whoever reads it later is tainted in turn.
- refuse it:
Links the agent may open
On a run that has read untrusted content and private data, web.fetch opens only links the agent could not have written:
- a person's message, your inbound fact or run input;
- the template's instructions;
- a search result, or a page it fetched and that page's links.
A link your own tools return does not count, and neither do the agent's replies, files, notes or schedules, another agent's hand-off, or a sandbox's output. If your tools return links the agent should open, allowlist those hosts: allowHosts in policy_envelope.tools["web.fetch"] (status: "limited", limits: { allowHosts: [...] }), then publish and promote the version. web.fetch then opens only the hosts allowHosts lists, on every run: a search result or any other site is refused. An allowlisted host passes whatever the URL carries, so allowlist only hosts you control.
Rendering replies safely
A reply can be steered by what the agent read. Every message says whether that happened: a stored message has tainted (GET /threads/{id}/messages), and a streamed reply ends with a message-metadata part { tainted }. A reply still streaming counts as tainted until that part says otherwise.
Whatever you draw, load no remote image from a tainted reply: an image URL is a request your user's browser makes, unasked, to the page that wrote it. Its links are your call. The kit draws them with their hosts shown. To draw them as words, with the host and nothing to click, use the kit's renderer with taintedLinks="text" (<MarkdownText text={text} tainted={info.tainted} taintedLinks="text" />, or renderMarkdown(text, { tainted, taintedLinks }) for a renderer of your own). The same choice applies when you render a reply on your server, in an email or a notification.
A value shaped like a credential (an API key, a token, a private key) never reaches your UI as itself: in a tool call's input on the stream, in a stored event and in a replay, it reads as a marker such as [redacted:github_pat].