agent.ts file inside any folder under server/routes/ and Anvil automatically mounts it as a POST endpoint that streams the Vercel AI SDK data stream protocol. Because the wire format is compatible, you can point useChat directly at an agent route with no extra adapter code.
How an agent route works
Anagent.ts file exports a handler built with defineAgent. When a request arrives, the runtime:
- Extracts the
messagesarray from the JSON request body (AI SDKuseChatshape by default). - Runs the model↔tool loop — calls the model, executes any tools the model requests, feeds results back, and repeats.
- Streams each text token, tool call, and tool result back to the client as data stream parts.
- Emits a final summary event with token usage and cost once the model produces a response with no tool calls (or the iteration cap is reached).
- Iteration cap —
maxIterations(default10) prevents the loop from running forever on a runaway tool-calling sequence. - AbortSignal propagation — when the HTTP client disconnects, the cancellation signal flows into every model call and tool execution. Partial work is stopped immediately.
- Zod schema validation — each tool’s
zodSchemais checked beforeexecuteruns. Invalid inputs return an error result to the model rather than crashing the handler. - Token tracking — input and output tokens are accumulated across every turn and reported in the
finalevent.
File conventions
agent.ts and post.ts work. Use agent.ts as the conventional name for routes whose primary purpose is running an agent loop.
Connecting a frontend
Because Anvil streams the Vercel AI SDK data stream protocol,useChat works out of the box:
streamProtocol: 'data' is required. Anvil uses the prefix-coded data stream format, not raw text streaming.What’s in this section
Define Agent
The
defineAgent API — system prompts, tools, context pipelines, budgets, and the withLlm middleware.LLM Client
LlmClient and its drivers for Anthropic, OpenAI, and Gemini — plus fallback chains and structured output.Agent Tools
The
AgentTool interface — Zod schemas, side-effect fencing, and the maxIterations safeguard.Orchestration
AgentRegistry, agentAsTool, and withAgents — compose multi-agent systems without HTTP round-trips.