Context and tools
The context function, and everything a tool receives as options.context.
What these are for, and when to use which: Principal, context and params.
The context function
export const context = async ({ principal }: { principal: Principal }) => ({
db: dbFor(principal.orgId),
plan: await planOf(principal.orgId),
});
export type Ctx = Awaited<ReturnType<typeof context>>;
createRuntime({ storage, context, agents });- Called at the start of every turn: new messages, the continuation after an approval, crash recovery, schedule fires, subagent runs.
- Gets only the principal. That's all Latch has when an answer continues without a request.
- Never saved, so it can return clients and functions, and always reads current values.
- Optional. Without it, the context is
{}.
The { build } object from defineContext still works but is deprecated: its request and turnContext are missing whenever an answer continues.
What a tool receives
Every tool gets what the context function returned, plus what Latch adds, as options.context:
import { toolFor } from "@intentface/latch-core";
const tool = toolFor<Principal, Ctx, TicketParams, View>();
const close_ticket = tool({
inputSchema: z.object({ reason: z.string() }),
execute: async ({ reason }, { context }) => {
const { db, principal, params, messageContext } = context; // typed, no cast
return db.tickets.close(params.ticketId, { by: principal.userId, reason });
},
});toolFor<Principal, Ctx, Params, MessageContext>() is for typing only. It returns the AI SDK's tool() with options.context typed as ToolContext<Principal, Ctx, Params, MessageContext>; at runtime it is tool(), and the tools it makes are ordinary AI SDK tools. Make it once and use it for every tool, or keep plain tool() and the cast below: both work the same. The AI SDK on its own types a tool's context only from a contextSchema, which validates at runtime and can't describe clients and functions. With a plain tool(), cast instead: context as ToolContext<Principal, Ctx>.
| Option | Type | Default | Details |
|---|---|---|---|
principal | P | — | |
run | object | — | |
writer | TurnWriter | — | |
runtime | Runtime<P> | — | |
params | Params | — | |
messageContext | MessageContext | — |
A field your context function returns with one of these names is replaced by Latch's.
What the agent function receives
| Option | Type | Default | Details |
|---|---|---|---|
context | RuntimeContext | — | |
principal | P | — | |
messageContext? | unknown | — | |
turnContext? | unknown | — | |
params? | Params | — |