Express
05 Tools and Context
Pass Express auth, request data, and retrieval context into Anvia tools.
Express middleware should authenticate the request. Anvia tools should receive the smallest request-local context they need.
1. Add Auth Middleware
import type { NextFunction, Request, Response } from "express";
declare global {
namespace Express {
interface Request {
user?: { id: string };
}
}
}
export async function requireUser(req: Request, res: Response, next: NextFunction) {
const user = await auth.userFromRequest(req);
if (!user) {
return res.status(401).json({ error: { code: "unauthorized" } });
}
req.user = { id: user.id };
return next();
}2. Build Request-Local Tools
import { createTool } from "@anvia/core";
import { z } from "zod";
export function createAccountTool(input: { userId: string }) {
return createTool({
name: "get_account_status",
description: "Read the authenticated user's account status.",
input: z.object({}),
output: z.object({ plan: z.string(), openTickets: z.number() }),
async execute() {
return db.account.findStatus({ userId: input.userId });
},
});
}3. Attach Context In The Route
supportRouter.post("/support", requireUser, async (req, res, next) => {
try {
const { message } = SupportRequest.parse(req.body);
const userId = req.user?.id;
if (!userId) {
return res.status(401).json({ error: { code: "unauthorized" } });
}
const response = await supportAgent
.prompt(message)
.tool(createAccountTool({ userId }))
.context({ userId })
.send();
return res.json({ output: response.output });
} catch (error) {
return next(error);
}
});4. Add Retrieval Context
const documents = await knowledge.search({
query: message,
filter: { userId: req.user.id },
limit: 5,
});
const response = await supportAgent.prompt(message).documents(documents).send();Next
Persist history in Persistence. Related guides: Runtime Context, Tool Handlers, and RAG Context.
