How to add an AI agent to a Fiber app
An AI agent in a Fiber app is a route that calls a model with tools, runs the tool calls the model makes against your own data layer as the signed-in user, and streams the reply to the page with Fiber's SSE middleware. The Anthropic Go SDK's tool runner handles the model loop; because Fiber runs on fasthttp, the streaming part works differently from net/http routers. If the agent only needs to do what your pages already do, you can embed one instead.
What an agent in a Fiber app is made of
- A server endpoint: a chain of
fiber.Handlerfunctions on a group such asapp.Group("/api"). It holds the model API key, read from the server environment; the key never goes into templates or static files. - Tools: Go functions the model may call, each wrapping a query or service call your handlers already make. The input schema is generated from a struct's
jsonschematags. - 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 chat UI: a small script on a server-rendered page that posts the conversation and reads the events written through the
middleware/ssestream. - Authorization and approval: middleware stores the signed-in user in
c.Locals, every tool is bound to that user, and changes to data wait until the user confirms them.
Ways to add an agent to Fiber
| Approach | Good for | What you take on |
|---|---|---|
| A model provider's Go SDK in a handler (Anthropic, OpenAI or Google Gen AI) | A custom agent with your own tools, prompts and UI. | Tool definitions, authorization in every tool, streaming, a confirmation flow for writes, rate and cost limits. |
| An agent framework (for example Genkit for Go or Eino) | Multi-step workflows, several model providers, orchestration and tracing. | 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 Anthropic Go SDK
The Anthropic Go SDK is Anthropic's official Go client. Its tool runner, currently in beta, runs the agent loop: it calls the model, runs the tools the model asks for, sends the results back and repeats until the model answers. The examples below use SDK v2.4.0 with Fiber 3.6, which needs Go 1.26 or later. The limiter, SSE and CSRF middleware ship in the Fiber module, so only the SDK is new:
go get github.com/anthropics/anthropic-sdk-go/[email protected]anthropic.NewClient() reads the API key from the ANTHROPIC_API_KEY environment variable, and the model constant anthropic.ModelClaudeSonnet5_5 selects claude-sonnet-5-5. The OpenAI (openai-go) and Google (google.golang.org/genai) Go SDKs fit the same handler; only the tool-calling calls change.
1. Tools bound to the signed-in user
This file has no Fiber code in it. newRunner builds both tools as closures over the user ID, so the model can choose an order ID but never whose orders it reads. toolrunner.NewBetaToolFromJSONSchema derives each tool's input schema from its struct. The cancelOrder tool does not cancel anything: it checks that the order belongs to the user and is open, records it as pending and tells the model the user has to confirm. The runner executes tools in parallel when the model requests several at once, so the pending list has a mutex. An error a tool returns is sent back to the model as an error result.
The browser sends the conversation as plain text turns, and history rebuilds it without any tool calls or tool results, so a client cannot forge them. MaxIterations: 5 caps the run at five model calls.
package main
import (
"context"
"encoding/json"
"errors"
"sync"
"github.com/anthropics/anthropic-sdk-go/v2"
"github.com/anthropics/anthropic-sdk-go/v2/toolrunner"
)
type chatRequest struct {
Messages []struct {
Role string `json:"role"`
Text string `json:"text"`
} `json:"messages"`
}
// history accepts plain text turns only, so a client cannot forge tool calls or tool results.
func (r chatRequest) history() ([]anthropic.BetaMessageParam, error) {
n := len(r.Messages)
if n == 0 || n > 40 || r.Messages[n-1].Role != "user" {
return nil, errors.New("invalid conversation")
}
out := make([]anthropic.BetaMessageParam, 0, n)
for _, m := range r.Messages {
if m.Text == "" {
return nil, errors.New("empty message")
}
text := anthropic.NewBetaTextBlock(m.Text)
switch m.Role {
case "user":
out = append(out, anthropic.NewBetaUserMessage(text))
case "assistant":
out = append(out, anthropic.BetaMessageParam{OfAssistant: &anthropic.BetaAssistantMessageParam{
Content: []anthropic.BetaContentBlockParamUnion{text},
}})
default:
return nil, errors.New("invalid role")
}
}
return out, nil
}
// pendingCancels collects the cancellations the model proposed. The runner may run tools in parallel.
type pendingCancels struct {
sync.Mutex
ids []string
}
type listOrdersInput struct {
Status string `json:"status,omitempty" jsonschema:"enum=open,enum=shipped,enum=cancelled"`
}
type cancelOrderInput struct {
OrderID string `json:"orderId" jsonschema:"required,description=ID of the order to cancel"`
}
func jsonResult(v any) (anthropic.BetaToolResultBlockParamContentUnion, error) {
data, err := json.Marshal(v)
return anthropic.BetaToolResultBlockParamContentUnion{OfText: &anthropic.BetaTextBlockParam{Text: string(data)}}, err
}
// newRunner gives the model two tools that close over the authenticated user:
// the model chooses arguments, never whose orders it reads or cancels.
func newRunner(client anthropic.Client, userID string, history []anthropic.BetaMessageParam) (
*anthropic.BetaToolRunnerStreaming, *pendingCancels, error) {
pending := &pendingCancels{}
listOrders, err := toolrunner.NewBetaToolFromJSONSchema("listOrders", "List the signed-in user's recent orders",
func(ctx context.Context, in listOrdersInput) (anthropic.BetaToolResultBlockParamContentUnion, error) {
orders, err := ListOrders(ctx, userID, in.Status) // your data layer
if err != nil {
return anthropic.BetaToolResultBlockParamContentUnion{}, err
}
return jsonResult(orders)
})
if err != nil {
return nil, nil, err
}
cancelOrder, err := toolrunner.NewBetaToolFromJSONSchema("cancelOrder",
"Propose cancelling one of the signed-in user's open orders. Nothing changes until the user confirms.",
func(ctx context.Context, in cancelOrderInput) (anthropic.BetaToolResultBlockParamContentUnion, error) {
order, err := GetOrder(ctx, userID, in.OrderID) // not found unless it belongs to userID
if err != nil {
return anthropic.BetaToolResultBlockParamContentUnion{}, err
}
if order.Status != "open" {
return anthropic.BetaToolResultBlockParamContentUnion{}, errors.New("only open orders can be cancelled")
}
pending.Lock()
pending.ids = append(pending.ids, order.ID)
pending.Unlock()
return jsonResult(map[string]string{"orderId": order.ID, "status": "waiting for the user to confirm"})
})
if err != nil {
return nil, nil, err
}
runner := client.Beta.Messages.NewToolRunnerStreaming([]anthropic.BetaTool{listOrders, cancelOrder},
anthropic.BetaToolRunnerParams{
BetaMessageNewParams: anthropic.BetaMessageNewParams{
Model: anthropic.ModelClaudeSonnet5_5,
MaxTokens: 2048,
System: []anthropic.BetaTextBlockParam{
{Text: "You help the signed-in user manage their orders. Use the tools; never guess order data."},
},
Messages: history,
},
MaxIterations: 5, // at most five model calls per request
})
return runner, pending, nil
}2. The Fiber routes and the stream
A fasthttp handler cannot write a response body piece by piece while it runs. A streaming response is a body stream writer instead: c.SendStreamWriter hands fasthttp a function (through SetBodyStreamWriter) that fasthttp calls after your handlers have returned. Fiber's middleware/sse builds on it: it sets the event-stream headers, marks the context as abandoned so Fiber does not recycle it while the stream still uses it, flushes every event, and sends a heartbeat comment every 15 seconds. That model has three consequences for the agent route:
- Validate the request in an ordinary handler first.
parseChatcan still answer 400; once the stream writer runs, the 200 status and headers are already fixed. - fasthttp has no per-request disconnect signal.
stream.Context()is canceled when a write fails, so a closed tab is noticed at the next event or heartbeat. The two-minute timeout bounds every run regardless. - Values Fiber returns from the context, such as
c.Paramsor header strings, point into buffers fasthttp reuses after the request (see Fiber's zero allocation note). Copy anything a goroutine keeps beyond the request.
requireUser returns fiber.ErrUnauthorized for signed-out requests and stores the user ID with the generic fiber.Locals, which the stream handler reads back. Fiber's limiter middleware caps runs per user. When the loop ends, the stream sends one confirm event per pending cancellation. The POST /api/orders/:id/cancel route is the only code that cancels an order, and it runs as a normal authenticated request from the user.
package main
import (
"context"
"log"
"time"
"github.com/anthropics/anthropic-sdk-go/v2"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/limiter"
"github.com/gofiber/fiber/v3/middleware/sse"
)
// requireUser rejects signed-out requests and stores the user your session middleware found.
func requireUser(c fiber.Ctx) error {
userID := currentUserID(c) // your existing session lookup
if userID == "" {
return fiber.ErrUnauthorized
}
fiber.Locals(c, "userID", userID)
return c.Next()
}
// parseChat validates the body before the stream starts, while a 400 can still be sent.
func parseChat(c fiber.Ctx) error {
var req chatRequest
if err := c.Bind().Body(&req); err != nil {
return fiber.ErrBadRequest
}
history, err := req.history()
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
fiber.Locals(c, "history", history)
return c.Next()
}
func registerAgentRoutes(app *fiber.App, client anthropic.Client) {
api := app.Group("/api", requireUser)
perUser := limiter.New(limiter.Config{
Max: 10, // runs per user per minute
Expiration: time.Minute,
KeyGenerator: func(c fiber.Ctx) string { return fiber.Locals[string](c, "userID") },
})
api.Post("/agent", perUser, parseChat, sse.New(sse.Config{Handler: agentStream(client)}))
// The only place an order is cancelled: a request the signed-in user confirmed.
api.Post("/orders/:id/cancel", func(c fiber.Ctx) error {
if err := CancelOrder(c.Context(), fiber.Locals[string](c, "userID"), c.Params("id")); err != nil {
return fiber.ErrNotFound
}
return c.SendStatus(fiber.StatusNoContent)
})
}
// agentStream runs inside fasthttp's body stream writer, after the route's handlers have returned.
func agentStream(client anthropic.Client) sse.Handler {
return func(c fiber.Ctx, stream *sse.Stream) error {
userID := fiber.Locals[string](c, "userID")
history := fiber.Locals[[]anthropic.BetaMessageParam](c, "history")
runner, pending, err := newRunner(client, userID, history)
if err != nil {
return err
}
// fasthttp has no per-request disconnect signal: stream.Context() ends when a write fails.
ctx, cancel := context.WithTimeout(stream.Context(), 2*time.Minute)
defer cancel()
send := func(event string, data fiber.Map) error {
return stream.Event(sse.Event{Name: event, Data: data}) // JSON-encoded and flushed
}
for !runner.IsCompleted() {
for event, err := range runner.NextStreaming(ctx) {
if err != nil {
log.Printf("agent: %v", err)
return send("error", fiber.Map{"message": "The assistant stopped. Try again."})
}
switch e := event.AsAny().(type) {
case anthropic.BetaRawContentBlockStartEvent:
if tool, ok := e.ContentBlock.AsAny().(anthropic.BetaToolUseBlock); ok {
err = send("tool", fiber.Map{"name": tool.Name})
}
case anthropic.BetaRawContentBlockDeltaEvent:
if delta, ok := e.Delta.AsAny().(anthropic.BetaTextDelta); ok {
err = send("text", fiber.Map{"text": delta.Text})
}
}
if err != nil {
return err // the client is gone
}
}
}
for _, id := range pending.ids {
if err := send("confirm", fiber.Map{"orderId": id}); err != nil {
return err
}
}
return send("done", fiber.Map{})
}
}Fiber does not enable CSRF protection by default. The csrf middleware with csrf.New() requires its token in the X-Csrf-Token header on every unsafe request; csrf.NewCrossOriginProtection() is a tokenless alternative that checks Sec-Fetch-Site and Origin like Go's http.CrossOriginProtection.
func main() {
app := fiber.New() // leave WriteTimeout unset or longer than an agent run: it also bounds the stream
// app.Use(yourSessionMiddleware)
app.Use(csrf.New()) // unsafe requests need the X-Csrf-Token header
registerAgentRoutes(app, anthropic.NewClient()) // reads ANTHROPIC_API_KEY
log.Fatal(app.Listen(":3000"))
}3. The page script
EventSource can only send GET requests, so the script posts the conversation with fetch and parses the events from the response body. It keeps the text turns in memory, sends them with each message and turns every confirm event into a button that posts to the cancel route with the user's cookies and the CSRF token your layout renders from csrf.TokenFromContext(c).
// Posts the conversation, then reads the Server-Sent Events from the response body.
// Expects <div id="agent-log"></div> and <form id="agent-form"><input name="message"></form> in the page.
const messages = [];
const log = document.querySelector("#agent-log");
const form = document.querySelector("#agent-form");
// Fiber's csrf middleware wants its token on every POST. Render csrf.TokenFromContext(c)
// into <meta name="csrf-token" content="{{.CSRF}}"> in your layout.
const csrf = document.querySelector('meta[name="csrf-token"]')?.content ?? "";
const headers = { "Content-Type": "application/json", "X-Csrf-Token": csrf };
function add(text) {
const p = log.appendChild(document.createElement("p"));
p.textContent = text;
return p;
}
function confirmCancel(orderId) {
const button = log.appendChild(document.createElement("button"));
button.textContent = "Cancel order " + orderId;
button.onclick = async () => {
const res = await fetch("/api/orders/" + encodeURIComponent(orderId) + "/cancel", { method: "POST", headers });
button.replaceWith(add(res.ok ? "Order " + orderId + " cancelled." : "Cancelling failed."));
};
}
form.addEventListener("submit", async (event) => {
event.preventDefault();
const text = form.elements.message.value.trim();
if (!text) return;
form.reset();
messages.push({ role: "user", text });
add(text);
const res = await fetch("/api/agent", { method: "POST", headers, body: JSON.stringify({ messages }) });
if (!res.ok) {
add("Request failed (" + res.status + ").");
messages.pop();
return;
}
let reply = add("");
let answer = "";
let buffer = "";
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
for (;;) {
const { value, done } = await reader.read();
if (done) break;
buffer += value;
let end;
while ((end = buffer.indexOf("\n\n")) >= 0) {
const frame = buffer.slice(0, end);
buffer = buffer.slice(end + 2);
const name = frame.match(/^event: ?(.*)$/m)?.[1];
const data = JSON.parse(frame.match(/^data: ?(.*)$/m)?.[1] ?? "{}");
if (name === "text") {
reply.textContent += data.text;
answer += data.text;
} else if (name === "tool") {
add("Running " + data.name + "...");
reply = add("");
} else if (name === "confirm") {
confirmCancel(data.orderId);
} else if (name === "error") {
add(data.message);
}
}
}
if (answer) messages.push({ role: "assistant", text: answer });
});Production checklist for Fiber
- Authorize in middleware and in every tool. Put the agent and every route it relies on behind the group middleware, and scope each query to the user ID from
c.Locals, never to an ID the model or the browser supplies. - Protect writes against CSRF. Register
csrf.New()orcsrf.NewCrossOriginProtection()withapp.Useso the agent endpoint and the confirmation route are both covered. - 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 your business rules, keep irreversible actions behind a user confirmation, and keep internal details out of tool error messages, because they go to the model.
- Size the write timeout for the stream. fasthttp sets
fiber.Config'sWriteTimeoutas one deadline when your handlers return, so it limits the whole stream, not each write. Leave it unset or longer than a run, keep the SSE heartbeat on so idle proxies do not drop the connection, and turn off response buffering in proxies in front of Fiber (the middleware already sendsX-Accel-Buffering: nofor nginx). - Limit cost. Cap model calls with
MaxIterationsand output withMaxTokens, keep the per-user limiter (its default storage is in memory, per process, so several instances need sharedStorage), and set spending limits with your model provider. - Keep secrets server-side. The model API key belongs in the server environment or a secret manager, never in templates or files served by the static middleware.
Option: embed an in-app agent with Bunkhouse
If the agent's job is to help signed-in users do work your Fiber 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 Fiber backend keeps enforcing its own authorization on every request.
In Fiber, render the loader in the <head> of your layout template, after the identity hook and before your application's scripts, so it loads once per page. For signed-in users, add a GET /api/agent-identity route, registered after your session middleware, that signs a short-lived token for the user it stored in c.Locals; the signing secret stays in a server environment variable.
<!-- In <head>, before your application's own scripts -->
<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 Fiber 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 Fiber 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 Fiber 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 Fiber 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.
Related guides
- How to add AI to your website: chat assistants, in-app agents and custom builds compared
- MCP vs WebMCP: choosing where outside agents act on your site
- AI agents in other Go frameworks: chi, Echo, Gin