Skip to content

Agent middleware

Extend your agent with custom business logic using middleware. Compose cross-cutting behavior like routing, telemetry, rate limiting, analytics, and feature flags, or plug in your own.

Middleware can be registered with agent.use either one at a time or as an array. They are executed in the order they were added.

Middleware functions receive a ctx (context) object and a next function. Normally, middleware calls next() to hand off control to the next one in the chain. However, middleware can also alter the flow in the following ways:

ActionResult
await next()Continue the main chain
returnStop the chain and do not emit the event
throw errorStart the error middleware chain
import type {
type AgentMiddleware<ContentTypes = unknown> = (ctx: MessageContext<unknown, ContentTypes>, next: () => Promise<void> | void) => Promise<void>

Processes a message and calls next to continue the middleware chain.

AgentMiddleware
} from "@xmtp/agent-sdk";
const
const ignoreSelf: AgentMiddleware
ignoreSelf
:
type AgentMiddleware<ContentTypes = unknown> = (ctx: MessageContext<unknown, ContentTypes>, next: () => Promise<void> | void) => Promise<void>

Processes a message and calls next to continue the middleware chain.

AgentMiddleware
= async (
ctx: MessageContext<unknown, unknown>
ctx
,
next: () => Promise<void> | void
next
) => {
if (
ctx: MessageContext<unknown, unknown>
ctx
.
MessageContext<unknown, unknown>.message: DecodedMessageWithContent<unknown>

Return the decoded message.

message
.
DecodedMessage<unknown>.senderInboxId: string
senderInboxId
===
ctx: MessageContext<unknown, unknown>
ctx
.
ClientContext<unknown>.client: Client<unknown>

Return the wrapped XMTP client.

client
.
Client<unknown>.inboxId: string

Gets the inbox ID associated with this client

inboxId
) return;
await
next: () => Promise<void> | void
next
();
};
const agent: Agent<BuiltInContentTypes>
agent
.
Agent<BuiltInContentTypes>.use(...middleware: (AgentMiddleware<BuiltInContentTypes> | AgentMiddleware<BuiltInContentTypes>[])[]): Agent<BuiltInContentTypes>

Add message middleware. Middleware runs in registration order.

use
(
const ignoreSelf: AgentMiddleware
ignoreSelf
);

Register error middleware with agent.errors.use().

Error middleware can be registered with agent.errors.use either one at a time or as an array. They are executed in the order they were added.

Error middleware receives the error, ctx, and a next function. Just like regular middleware, the flow in error middleware depends on how to use next:

ActionResult
await next()Mark the error handled and continue the main chain
await next(error)Send an error to the next error handler
returnStop error handling and the main chain
throw errorSend a new error through the error chain