Interface: Middleware
@providerprotocol/agents / index / Middleware
Interface: Middleware
Section titled “Interface: Middleware”Defined in: src/middleware/types.ts:107
Middleware interface for implementing cross-cutting concerns in agent execution.
Middleware provides hooks into the agent lifecycle, allowing you to:
- Log execution details
- Track metrics and performance
- Modify context before execution
- Transform results after execution
- Handle and recover from errors
Remarks
Section titled “Remarks”Middleware executes in a specific order:
- before: Runs in registration order (first registered runs first)
- after: Runs in reverse registration order (last registered runs first)
- onError: Runs in reverse order until one returns a result to recover
This ordering allows outer middleware to wrap inner middleware behavior, similar to the onion model used in Express/Koa.
Example
Section titled “Example”const timingMiddleware: Middleware = { name: 'timing',
async before(context) { context.metadata.set('startTime', Date.now()); return context; },
async after(context, result) { const startTime = context.metadata.get('startTime') as number; console.log(`Execution took ${Date.now() - startTime}ms`); return result; },
async onError(context, error) { console.error('Agent failed:', error.message); // Return undefined to let error propagate return undefined; },};- MiddlewareContext for the context object passed to hooks
- logging for a built-in logging middleware implementation
Properties
Section titled “Properties”name:
string
Defined in: src/middleware/types.ts:114
Unique name identifying this middleware.
Used for debugging and logging purposes. Should be descriptive and unique within the middleware chain.
Methods
Section titled “Methods”after()?
Section titled “after()?”
optionalafter(context,result):Promise<GenerateResult>
Defined in: src/middleware/types.ts:161
Hook called after agent execution completes successfully.
Use this to:
- Log execution results
- Transform or enrich the result
- Record metrics (timing, token usage, etc.)
- Clean up resources
Parameters
Section titled “Parameters”context
Section titled “context”The execution context (same instance from before hook)
result
Section titled “result”The generation result from the agent
Returns
Section titled “Returns”Promise<GenerateResult>
The (optionally modified) result
Example
Section titled “Example”async after(context, result) { const requestId = context.metadata.get('requestId'); console.log(`[${requestId}] Generated ${result.turn.usage?.totalTokens} tokens`); return result;}before()?
Section titled “before()?”
optionalbefore(context):Promise<void|MiddlewareContext>
Defined in: src/middleware/types.ts:137
Hook called before agent execution begins.
Use this to:
- Log or record the incoming request
- Validate or modify the context
- Store timing or tracking data in metadata
- Short-circuit execution by throwing an error
Parameters
Section titled “Parameters”context
Section titled “context”The execution context containing agent, input, state, and metadata
Returns
Section titled “Returns”Promise<void | MiddlewareContext>
The (optionally modified) context, or void to pass through unchanged
Example
Section titled “Example”async before(context) { // Add request ID for tracing context.metadata.set('requestId', crypto.randomUUID()); return context;}onError()?
Section titled “onError()?”
optionalonError(context,error):Promise<void|GenerateResult>
Defined in: src/middleware/types.ts:192
Hook called when an error occurs during agent execution.
This hook can either:
- Return a
GenerateResultto recover from the error gracefully - Return
undefined(or void) to let the error propagate
Parameters
Section titled “Parameters”context
Section titled “context”The execution context at the time of the error
Error
The error that occurred
Returns
Section titled “Returns”Promise<void | GenerateResult>
A recovery result, or undefined to propagate the error
Remarks
Section titled “Remarks”Error hooks are called in reverse middleware order. The first middleware to return a result stops the error propagation and that result is used.
Example
Section titled “Example”async onError(context, error) { if (error.message.includes('rate limit')) { // Log and let it propagate for retry logic console.warn('Rate limited, should retry'); return undefined; } // For other errors, log details console.error('Agent error:', error); return undefined;}