How to add an AI agent to a chi app
An AI agent in a Go app routed with chi is a plain net/http handler 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 as Server-Sent Events. The Anthropic Go SDK's tool runner handles the model loop; chi middleware and the standard library cover authentication, CSRF and timeouts. If the agent only needs to do what your pages already do, you can embed one instead.
What an agent in a chi app is made of
- A server endpoint: an
http.HandlerFuncmounted in a chi route group. 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 the handler writes and flushes with
http.ResponseController. - Authorization and approval: a
func(http.Handler) http.Handlermiddleware puts the signed-in user in the request context, every tool is bound to that user, and changes to data wait until the user confirms them.
Ways to add an agent to chi
| 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 chi 5.5 and Go 1.25 or later, plus httprate for per-user rate limiting:
go get github.com/anthropics/anthropic-sdk-go/[email protected] github.com/go-chi/[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 chi 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 handler, middleware and routes
Everything here is standard net/http, which is what chi is built on. requireUser answers signed-out requests with 401 and stores the user ID in the request context under an unexported key type, so no other package can overwrite it. r.Group applies it to both routes, and r.With adds an httprate.LimitBy limiter keyed by user to the agent route only.
The handler decodes at most 64 KiB of JSON and validates it before writing anything, so invalid input still gets a 400. http.NewResponseController gives it two things a plain ResponseWriter does not: Flush, which sends each event immediately, and SetWriteDeadline, which extends the server's WriteTimeout for this response only. The run gets r.Context(), which Go cancels when the browser disconnects, with a two-minute limit on top.
When the loop ends, the handler 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"
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"github.com/anthropics/anthropic-sdk-go/v2"
"github.com/go-chi/chi/v5"
"github.com/go-chi/httprate"
)
type userKey struct{}
// requireUser rejects signed-out requests and puts the user your session middleware found in the context.
func requireUser(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := currentUserID(r) // your existing session lookup
if id == "" {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), userKey{}, id)))
})
}
func userID(r *http.Request) string {
id, _ := r.Context().Value(userKey{}).(string)
return id
}
func agentRoutes(r chi.Router, client anthropic.Client) {
r.Group(func(r chi.Router) {
r.Use(requireUser)
perUser := httprate.LimitBy(10, time.Minute, func(r *http.Request) (string, error) { return userID(r), nil })
r.With(perUser).Post("/api/agent", agentHandler(client))
// The only place an order is cancelled: a request the signed-in user confirmed.
r.Post("/api/orders/{id}/cancel", func(w http.ResponseWriter, r *http.Request) {
if err := CancelOrder(r.Context(), userID(r), chi.URLParam(r, "id")); err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
w.WriteHeader(http.StatusNoContent)
})
})
}
func agentHandler(client anthropic.Client) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req chatRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)).Decode(&req); err != nil {
http.Error(w, "invalid JSON", http.StatusBadRequest)
return
}
history, err := req.history()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
runner, pending, err := newRunner(client, userID(r), history)
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
// Canceled when the browser disconnects or the run takes too long.
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
defer cancel()
rc := http.NewResponseController(w)
_ = rc.SetWriteDeadline(time.Now().Add(3 * time.Minute)) // overrides the server's WriteTimeout for this response
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
send := func(event string, data map[string]string) {
payload, _ := json.Marshal(data) // a map[string]string always encodes
fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event, payload)
rc.Flush() // a client that went away cancels ctx, which ends the loop
}
for !runner.IsCompleted() {
for event, err := range runner.NextStreaming(ctx) {
if err != nil {
log.Printf("agent: %v", err)
send("error", map[string]string{"message": "The assistant stopped. Try again."})
return
}
switch e := event.AsAny().(type) {
case anthropic.BetaRawContentBlockStartEvent:
if tool, ok := e.ContentBlock.AsAny().(anthropic.BetaToolUseBlock); ok {
send("tool", map[string]string{"name": tool.Name})
}
case anthropic.BetaRawContentBlockDeltaEvent:
if delta, ok := e.Delta.AsAny().(anthropic.BetaTextDelta); ok {
send("text", map[string]string{"text": delta.Text})
}
}
}
}
for _, id := range pending.ids {
send("confirm", map[string]string{"orderId": id})
}
send("done", map[string]string{})
}
}chi has no CSRF middleware of its own. Go's http.CrossOriginProtection rejects cross-origin POST requests from browsers by their Sec-Fetch-Site and Origin headers, and its Handler method has the func(http.Handler) http.Handler shape, so r.Use takes it directly. The server keeps a 30-second WriteTimeout for every other route.
func main() {
r := chi.NewRouter()
r.Use(middleware.Recoverer)
r.Use(http.NewCrossOriginProtection().Handler) // rejects cross-site POSTs, no token needed
// r.Use(yourSessionMiddleware)
agentRoutes(r, anthropic.NewClient()) // reads ANTHROPIC_API_KEY
srv := &http.Server{
Addr: ":3000",
Handler: r,
ReadHeaderTimeout: 10 * time.Second,
WriteTimeout: 30 * time.Second, // the agent handler extends its own deadline
}
log.Fatal(srv.ListenAndServe())
}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. No CSRF token is needed: http.CrossOriginProtection decides from the Sec-Fetch-Site and Origin headers the browser sets itself.
// 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");
// http.CrossOriginProtection checks Sec-Fetch-Site and Origin, so same-origin fetches need no token.
const headers = { "Content-Type": "application/json" };
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 chi
- 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 the request context, never to an ID the model or the browser supplies.
- Protect writes against CSRF. Keep
http.CrossOriginProtectionin front of every cookie-authenticated POST, or use a token middleware such asgorilla/csrf. - 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.
- Allow for long streams. Extend the write deadline per response as the handler does instead of dropping
WriteTimeoutfor the whole server. chi'smiddleware.Timeoutcancels the request context when it fires, which ends a run, so keep it off the agent route or longer than a run. Turn off response buffering in proxies in front of the app (for nginx, theX-Accel-Buffering: noheader). - Limit cost. Cap model calls with
MaxIterationsand output withMaxTokens, keep the per-user rate limit (httprate counts in memory per process by default; httprate-redis shares counts between instances), 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 static files.
Option: embed an in-app agent with Bunkhouse
If the agent's job is to help signed-in users do work your chi 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 chi backend keeps enforcing its own authorization on every request.
With chi, 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, mounted after your session middleware so r.Context() already holds the user, that signs a short-lived token for the user your session authenticated; 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 chi 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 chi 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 chi 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 chi 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: Echo, Fiber, Gin