AI agents by framework / JavaScript and TypeScript
How to add an AI agent to a Hono app
An AI agent in a Hono app is a route that authenticates the request, calls a model with tools bound to the signed-in user and returns the model's steps as a streaming Response. Hono handlers already return web Responses, so the AI SDK's stream drops in on Node.js, Bun, Deno or Cloudflare Workers; you supply the tools, the auth middleware and the limits. If the agent only needs to do what your app already does, you can embed one instead.
What an agent in a Hono app is made of
- A route: an
app.post("/api/chat")handler that holds the model API key, calls the model and returns a streamingResponse. - Tools: typed functions the model may call, each wrapping a query or service call your other handlers already use.
- The agent loop: the model calls a tool, receives the result and decides the next step until it can answer. Cap the number of steps.
- A browser client: a chat component that posts the conversation and renders the streamed reply and tool activity. Pages rendered with
hono/jsxcan mount it as a client-side island. - Authorization and approval: middleware puts the signed-in user in the context with
c.set(), tools act only as that user, and writes wait for the user to approve them.
Ways to add an agent to Hono
| Approach | Good for | What you take on |
|---|---|---|
| AI SDK in a Hono route | A custom agent with your own tools, model provider and UI, on any runtime Hono supports. | Tool definitions, authorization in every tool, approval UI, rate and cost limits. |
| Cloudflare Agents SDK | Hono on Cloudflare Workers, with per-agent state in Durable Objects. | A Cloudflare-only deployment model, plus your own tools and authorization. |
| An agent framework (for example Mastra or LangGraph.js) | Long-running or multi-agent workflows with memory and orchestration. | Another layer to learn and deploy, plus everything in the row above. |
| Hosted answer-only chat widget | Questions about your docs or help center. | Keeping its content current. It does not act in your app. |
| Embedded in-app agent (Bunkhouse) | Letting signed-in users get tasks done through the pages and API you already have. | A script tag, an identity endpoint and hints for operations discovery cannot see. |
Build an agent with the AI SDK
The AI SDK is Vercel's TypeScript library for model calls, tool calling and chat UIs, and its Hono recipe shows the server side. The examples below use AI SDK 7 and Hono 4 on Node.js through @hono/node-server. Install it with Zod for tool input schemas, and the React bindings for the client:
npm install ai zod @ai-sdk/reactThe model string "anthropic/claude-sonnet-5.5" goes through the Vercel AI Gateway, which reads the API key from the AI_GATEWAY_API_KEY variable. To call a provider directly, install its package (for example @ai-sdk/openai) and pass its model instead.
1. Tools scoped to the user
Define the tools in a function that takes the authenticated user's ID. Each tool wraps an operation your app already has and closes over that ID, so the model can choose an order ID but never whose orders it reads or cancels. Your data layer should still check that the order belongs to the user.
import { tool } from "ai";
import { z } from "zod";
import { cancelOrder, listOrders } from "./orders.js"; // your existing data layer
// The tools close over the authenticated user's ID; the model never chooses whose data they touch.
export function orderTools(userId: string) {
return {
listOrders: tool({
description: "List the signed-in user's recent orders",
inputSchema: z.object({ status: z.enum(["open", "shipped", "cancelled"]).optional() }),
execute: async ({ status }) => listOrders(userId, { status }),
}),
cancelOrder: tool({
description: "Cancel one of the signed-in user's open orders",
inputSchema: z.object({ orderId: z.string() }),
execute: async ({ orderId }) => cancelOrder(userId, orderId),
}),
};
}2. The streaming route
The middleware stands in for your existing session handling; typing the app with Variables makes c.get("user") typed in every handler. The route rejects anonymous requests before the model is called. The condition isStepCount(5) lets the model call tools and continue for up to five steps, and toolApproval makes cancelOrder pause until the user answers. The option experimental_toolApprovalSecret signs approval requests so a client cannot forge one in the message history it sends back. Passing c.req.raw.signal stops the model call when the browser disconnects.
import { serve } from "@hono/node-server";
import {
convertToModelMessages,
createUIMessageStreamResponse,
isStepCount,
streamText,
toUIMessageStream,
type UIMessage,
} from "ai";
import { Hono } from "hono";
import { csrf } from "hono/csrf";
import { createMiddleware } from "hono/factory";
import { orderTools } from "./agent-tools.js";
import { userFromSession, type User } from "./auth.js"; // your existing session lookup
type Env = { Variables: { user: User | null } };
const app = new Hono<Env>();
app.use(csrf());
app.use(
createMiddleware<Env>(async (c, next) => {
c.set("user", await userFromSession(c.req.header("cookie")));
await next();
}),
);
app.post("/api/chat", async (c) => {
const user = c.get("user");
if (!user) return c.json({ error: "unauthorized" }, 401);
const { messages } = await c.req.json<{ messages: UIMessage[] }>();
const result = streamText({
model: "anthropic/claude-sonnet-5.5",
instructions: "You help the signed-in user manage their orders. Use the tools; never guess order data.",
messages: await convertToModelMessages(messages),
tools: orderTools(user.id),
toolApproval: { cancelOrder: "user-approval" },
experimental_toolApprovalSecret: process.env.TOOL_APPROVAL_SECRET,
stopWhen: isStepCount(5),
abortSignal: c.req.raw.signal,
});
return createUIMessageStreamResponse({ stream: toUIMessageStream({ stream: result.stream }) });
});
serve({ fetch: app.fetch, port: 3000 });The handler itself is runtime-neutral. Only two lines depend on Node.js: serve() from @hono/node-server, and process.env. On Cloudflare Workers, export the app as the default export instead of calling serve(), and read secrets from bindings with c.env (declared in the app's Bindings type). Bun and Deno serve app.fetch directly. The AI Gateway model string works on all of them because the call is a plain fetch.
3. The browser client
The client uses useChat from @ai-sdk/react, which posts to /api/chat by default and streams the reply into its state; Vue and Svelte bindings work the same way. When the model calls cancelOrder, the tool part arrives in the state approval-requested. The answer is sent with addToolApprovalResponse, and sendAutomaticallyWhen resumes the run once every pending approval has a response.
import { useChat } from "@ai-sdk/react";
import { lastAssistantMessageIsCompleteWithApprovalResponses } from "ai";
import { useState } from "react";
export function Agent() {
const [input, setInput] = useState("");
const { messages, sendMessage, addToolApprovalResponse } = useChat({
sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses,
});
return (
<div>
{messages.map((message) =>
message.parts.map((part, i) => {
const key = `${message.id}-${i}`;
if (part.type === "text") return <p key={key}>{part.text}</p>;
if (part.type === "tool-cancelOrder" && part.state === "approval-requested" && !part.approval.isAutomatic) {
const { id } = part.approval;
return (
<div key={key}>
<p>Cancel order {JSON.stringify(part.input)}?</p>
<button onClick={() => addToolApprovalResponse({ id, approved: true })}>Approve</button>
<button onClick={() => addToolApprovalResponse({ id, approved: false })}>Deny</button>
</div>
);
}
return null;
}),
)}
<form
onSubmit={(e) => {
e.preventDefault();
sendMessage({ text: input });
setInput("");
}}
>
<input aria-label="Message" value={input} onChange={(e) => setInput(e.currentTarget.value)} />
</form>
</div>
);
}Production checklist for Hono
- Authorize in middleware and in every tool. Register the session middleware before the route, return 401 from the route, and scope every query in the tools to
c.get("user"). - Keep CSRF protection on. Hono's CSRF middleware checks
OriginandSec-Fetch-Sitefor form-style requests. The chat client posts JSON, which browsers only send cross-origin after a CORS preflight, so do not enable credentialed CORS for other origins on this route. - Treat tool input and tool results as untrusted. The model chooses tool arguments, and data a tool returns (user-written text, emails, web pages) can contain instructions. Validate arguments with the schema and your own business rules, and require approval for anything irreversible.
- Limit cost. Cap steps, rate-limit the route per user (in your middleware, or with a platform limiter such as the Workers rate limiting binding), and set spending limits with your model provider.
- Check runtime limits for long streams. On Node.js, make sure your proxy does not buffer streaming responses. On edge runtimes, check the platform's wall-clock and CPU-time limits; time spent waiting on the model is I/O, but several steps add up.
- Keep secrets server-side. The model key and approval secret belong in environment variables or platform secrets, never in client bundles or rendered pages.
Option: embed an in-app agent with Bunkhouse
If the agent's job is to help signed-in users do work your Hono app already supports, you may not need to build the tools, agent loop and chat UI yourself. Bunkhouse adds an Assistant pane to an existing web app with one script tag. When a user opens it, the assistant works with what the page already offers: buttons, links, form fields and tables, the API requests your app makes, a hints file you publish for operations it cannot see, and WebMCP tools your page declares.
The model writes small programs that run in a sandbox on the embed origin, not in your page. They can only call capabilities the assistant has discovered and your configuration allows. Write actions are shown to the user for review before they run, the model never sees credentials, and your Hono backend keeps enforcing its own authorization on every request.
In Hono, render the identity hook and the loader in the <head> of your server-rendered layout (for example a hono/jsx component), before your application's own scripts, so they load once per document. For signed-in users, add a GET /api/agent-identity route, mounted after your session middleware, that signs a short-lived token for c.get("user"); the signing secret stays in a server environment variable.
export const AgentEmbed = () => (
<>
<script src="/agent-identity.js"><\/script>
<script src="https://embed.bunkhouse.ai/embed.js" data-public-key="pk_YOUR_SITE_PUBLIC_KEY"><\/script>
</>
);The tested Hono integration guide has the complete code for each session mode (signed identity token, server mint and anonymous), CSRF headers and Content Security Policy settings.
When Bunkhouse fits, and when to build it yourself
- Bunkhouse fits when users want tasks done inside your existing pages, such as filtering, editing or submitting through the controls and API you already have, and you would rather not write and maintain a tool definition for each action, a sandbox for model-written code, an approval UI and usage metering.
- Build it yourself when the agent must run without a browser page (background jobs, email, chat platforms, scheduled work), when you need to choose the model provider, use your own keys or run inference on your own infrastructure, or when the conversation must be part of your own UI components.
- Plan for the limits: discovery cannot see server-only routes, workflows the user has not visited, closed shadow roots or cross-origin frames (describe those in a hints file); some controls need a real user gesture; password, payment and file fields are never read, and you can mark other content private.
- Cost: production use is $49 per month, including $20 of usage credit per paid billing period, then $1 per million input tokens and $3 per million output tokens. See billing.
Try it on your Hono app first
A coding agent such as Claude Code, Codex or Cursor can run a free, disposable agent trial on a dummy page of your Hono app. No account, card or model API key is needed: your coding agent acts as the assistant's model. A trial lasts 24 hours and allows 100 turns. Give your agent this instruction, changing the address if your app runs elsewhere:
Read https://api.bunkhouse.ai/agent-trial.md and follow it to run a Bunkhouse agent trial on my dummy Hono page at http://localhost:3000.Use a page with disposable data: everything the assistant reads is sent to your agent.
The trial evaluation checklist shows how to test a read, a rejected write and an approved change, and what a trial does not prove about production use.