AI agents by framework / JavaScript and TypeScript

How to add an AI agent to a Fastify app

An AI agent in a Fastify app is a POST route that authenticates the request, calls a model with tools bound to the signed-in user and streams the model's steps back to the browser. The AI SDK runs the tool loop and produces a streaming Response that Fastify 5 can send directly; you supply the tools, the auth hook 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 Fastify app is made of

  • A route: a POST /api/chat handler, registered in a plugin like any other route, that holds the model API key and calls the model.
  • Tools: typed functions the model may call, each wrapping a service or query your other routes 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 to the route and renders the streamed reply and tool activity.
  • Authorization and approval: an onRequest or preHandler hook resolves the session into request.user, tools act only as that user, and writes wait for the user to approve them.

Ways to add an agent to Fastify

ApproachGood forWhat you take on
AI SDK in a Fastify routeA custom agent with your own tools, model provider and UI.Tool definitions, authorization in every tool, approval UI, rate and cost limits.
A provider SDK directly (for example openai or @anthropic-ai/sdk)One model provider and full control of the request format.Writing the tool loop, streaming format and approval handling yourself.
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 widgetQuestions 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 Fastify recipe shows the server side. The examples below use AI SDK 7 and Fastify 5. Install it with Zod for tool input schemas, and the React bindings for the client:

Terminal
npm install ai zod @ai-sdk/react

The 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.

src/agent-tools.ts
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 onRequest hook stands in for your existing session handling and sets request.user, declared on FastifyRequest so handlers get a typed value. 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. Fastify 5 streams a returned web Response, so createUIMessageStreamResponse needs no adapter.

src/server.ts
import {
  convertToModelMessages,
  createUIMessageStreamResponse,
  isStepCount,
  streamText,
  toUIMessageStream,
  type UIMessage,
} from "ai";
import Fastify from "fastify";
import { orderTools } from "./agent-tools.js";
import { userFromSession, type User } from "./auth.js"; // your existing session lookup

declare module "fastify" {
  interface FastifyRequest {
    user: User | null;
  }
}

const app = Fastify({ logger: true });
app.decorateRequest("user", null);

// Your existing auth: resolve the session before any handler runs.
app.addHook("onRequest", async (request) => {
  request.user = await userFromSession(request.headers.cookie);
});

app.post<{ Body: { messages: UIMessage[] } }>("/api/chat", async (request, reply) => {
  const user = request.user;
  if (!user) return reply.code(401).send({ error: "unauthorized" });

  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(request.body.messages),
    tools: orderTools(user.id),
    toolApproval: { cancelOrder: "user-approval" },
    experimental_toolApprovalSecret: process.env.TOOL_APPROVAL_SECRET,
    stopWhen: isStepCount(5),
  });

  return reply.send(createUIMessageStreamResponse({ stream: toUIMessageStream({ stream: result.stream }) }));
});

await app.listen({ port: 3000 });

3. The browser client

The client uses useChat from @ai-sdk/react; Vue and Svelte bindings work the same way. The transport posts to /api/chat and sends your CSRF token as a header. 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.

client/agent.tsx
import { useChat } from "@ai-sdk/react";
import { DefaultChatTransport, lastAssistantMessageIsCompleteWithApprovalResponses } from "ai";
import { useState } from "react";

export function Agent({ csrfToken }: { csrfToken: string }) {
  const [input, setInput] = useState("");
  const { messages, sendMessage, addToolApprovalResponse } = useChat({
    transport: new DefaultChatTransport({ api: "/api/chat", headers: { "x-csrf-token": csrfToken } }),
    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 Fastify

  • Authorize in a hook and in every tool. Resolve the session in an onRequest hook registered before the route's plugin (Fastify hooks are encapsulated per plugin), return 401 from the route, and scope every query in the tools to request.user.
  • Protect the route from CSRF. The chat route uses cookies, so register @fastify/csrf-protection and add onRequest: app.csrfProtection to the route; it reads the x-csrf-token header the client sends.
  • 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 with @fastify/rate-limit keyed on the user ID, and set spending limits with your model provider.
  • Allow for long streams. A reply can stay open for a minute or more across several model steps. Check that your proxy does not buffer or cut off streaming responses, and that Fastify's timeouts and your load balancer's idle timeout allow it.
  • Keep secrets server-side. Load the model key and approval secret from the server environment and never render them into templates or client bundles.

Option: embed an in-app agent with Bunkhouse

If the agent's job is to help signed-in users do work your Fastify 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 Fastify backend keeps enforcing its own authorization on every request.

In Fastify, render the identity hook and the loader in the <head> of your layout template (for example an EJS layout served through @fastify/view), before your application's own scripts, so they load once per document. For signed-in users, add a GET /api/agent-identity route, registered after your session hook, that signs a short-lived token for request.user; the signing secret stays in a server environment variable.

views/layout.ejs (excerpt)
<head>
  <script src="/agent-identity.js"><\/script>
  <script src="https://embed.bunkhouse.ai/embed.js" data-public-key="pk_YOUR_SITE_PUBLIC_KEY"><\/script>
  <!-- then your application's own scripts -->
</head>

The tested Fastify 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 Fastify 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 Fastify 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:

Agent trialPrompt for your coding agent
Read https://api.bunkhouse.ai/agent-trial.md and follow it to run a Bunkhouse agent trial on my dummy Fastify 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.