Hono

05 Tools and Context

Scope Hono request data before exposing tools and retrieval to Anvia.

Hono gives you the raw request. Resolve auth in middleware or the handler, then create scoped tools when a tool needs the current user.

1. Add Auth Middleware

type Variables = {
  userId: string;
};

export const app = new Hono<{ Variables: Variables }>();

app.use("/api/*", async (c, next) => {
  const userId = c.req.header("x-user-id");

  if (!userId) {
    return c.json({ error: "unauthorized" }, 401);
  }

  c.set("userId", userId);
  await next();
});

2. Create a Scoped Agent

import { z } from "zod";
import { AgentBuilder, createTool } from "@anvia/core";
import { model } from "./ai/support-agent";
import { orders } from "./db/orders";

export function createSupportAgent(scope: { userId: string }) {
  const lookupOrder = createTool({
    name: "lookup_order",
    description: "Look up one order owned by the current user.",
    input: z.object({
      orderId: z.string(),
    }),
    output: z.object({
      status: z.string(),
    }),
    async execute({ orderId }) {
      return orders.findForUser(scope.userId, orderId);
    },
  });

  return new AgentBuilder("support", model)
    .instructions("Use tools for account-specific data.")
    .tool(lookupOrder)
    .defaultMaxTurns(3)
    .build();
}

3. Use Request State In The Handler

import { zValidator } from "@hono/zod-validator";
import { z } from "zod";

const SupportRequest = z.object({
  message: z.string().trim().min(1, "message is required"),
});

app.post("/api/support", zValidator("json", SupportRequest), async (c) => {
  const userId = c.get("userId");
  const { message } = c.req.valid("json");

  const agent = createSupportAgent({ userId });
  const response = await agent.prompt(message).send();

  return c.json({ output: response.output });
});

4. Add Retrieval Context

const agent = new AgentBuilder("support", model)
  .instructions("Use retrieved support docs when relevant.")
  .dynamicContext(supportDocsIndex, {
    topK: 3,
    threshold: 0.7,
  })
  .tool(lookupOrder)
  .build();

Use retrieval for knowledge. Use tools for authorization-sensitive application state.

Next

Persist conversations in Persistence. Related guides: Runtime Context, RAG Context, and Tool Handlers.