Skip to content

Built-in Middleware

Agent Express ships with 16 middleware functions organized into 6 namespaces. All are imported from agent-express:

import { guard, observe, model, memory, tools, dev } from "agent-express"

By default, every Agent automatically applies a sensible set of middleware via the defaults() function. This includes:

  • model.retry() — exponential backoff for transient LLM failures
  • observe.usage() — token tracking
  • observe.tools() — tool call recording
  • observe.duration() — turn timing
  • guard.maxIterations() — loop iteration limit (default: 25)
// Defaults with custom options
const agent = new Agent({
name: "my-agent",
model: "anthropic/claude-sonnet-4-6",
instructions: "...",
defaults: { maxIterations: 10, retry: { maxRetries: 3 } },
})
// Bare minimum: no defaults applied
const agent = new Agent({
name: "my-agent",
model: "anthropic/claude-sonnet-4-6",
instructions: "...",
defaults: false,
})
import { defaults } from "agent-express"
// Get the default middleware array for custom composition
const defaultMiddleware = defaults({ maxIterations: 15 })
agent.use(defaultMiddleware)

Agent Express organizes its built-in middleware into 6 namespaces:

  • Guard — Safety middleware: budget, input/output validation, timeouts, iteration limits, tool approval.
  • Observe — Observability middleware: token usage, tool calls, duration, structured logging.
  • Model — Model middleware: retry with backoff, complexity-based routing.
  • Memory — Memory middleware: context window compaction with 5 strategies.
  • Tools — Tool middleware: TypeScript function tools with Zod schemas, MCP server connection.
  • Dev — Development middleware: full lifecycle terminal trace.