> For the complete documentation index, see [llms.txt](https://dnotifier.gitbook.io/product-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/middleware.md).

# Middleware

**Middleware** lets you run your own code around an agent or workflow without changing every call site. Register it once on `defineAgent` / `define_agent` or on a `Workflow`; the SDK invokes it at the right points.

{% hint style="info" %}
Available in the **JavaScript**, **Python**, and **Dart** SDKs.
{% endhint %}

## Two levels

| Level        | Where                                                                    | Typical uses                                     |
| ------------ | ------------------------------------------------------------------------ | ------------------------------------------------ |
| **Agent**    | Around each agent run, and around each model / tool step for tool agents | Logging, tool allow/deny, prompt tweaks, retries |
| **Workflow** | Around the whole `entry` run                                             | Auth, input validation, metrics, cleanup         |

Agent middleware is per agent. Workflow middleware wraps the full pipeline once.

```
  beforeWorkflow
    → entry
         → beforeAgent → (model / tools…) → afterAgent
         → beforeAgent → … → afterAgent
    → afterWorkflow
  → onWorkflowComplete
```

## Register middleware

Pass a `middleware` array when you define the agent or workflow. Objects can implement any subset of hooks.

```js
const agent = DNotifier.defineAgent({
  name: "support",
  instructions: "Be concise. Use tools when needed.",
  tools: [searchTool],
  middleware: [logging, toolGuard],
});

const workflow = new DNotifier.Workflow({
  name: "support-flow",
  middleware: [requireUser],
  async entry(ctx) {
    return ctx.runAgent("support");
  },
}).registerAgents({ support: agent });
```

Python uses `middleware=[...]` on `define_agent` / `Workflow`. Dart uses `middleware: [...]` with `AgentMiddleware` / `WorkflowMiddleware`.

## Agent hooks

| Hook                              | When                               | Can                                                |
| --------------------------------- | ---------------------------------- | -------------------------------------------------- |
| `beforeAgent` / `before_agent`    | Before the agent starts            | Change `ctx.input`, seed `ctx.state`               |
| `afterAgent` / `after_agent`      | After a successful run             | Transform the result                               |
| `onAgentError` / `on_agent_error` | On failure                         | Recover (return a value) or rethrow                |
| `beforeModel` / `before_model`    | Before each LLM turn (tool agents) | Edit messages, tools, provider, model              |
| `afterModel` / `after_model`      | After each LLM turn                | Inspect or adjust the model response               |
| `wrapModel` / `wrap_model`        | Around each LLM turn               | Retry, timeout, custom transport                   |
| `beforeTool` / `before_tool`      | Before each tool call              | Change args, or skip with `{ skip: true, result }` |
| `afterTool` / `after_tool`        | After each tool call               | Transform the tool result string                   |
| `wrapTool` / `wrap_tool`          | Around each tool execute           | Retry or short-circuit                             |

`before*` hooks run in array order; `after*` run in reverse (onion style).

## Workflow hooks

| Hook                                          | When                       | Can                                  |
| --------------------------------------------- | -------------------------- | ------------------------------------ |
| `beforeWorkflow` / `before_workflow`          | Before `entry`             | Change `ctx.input`, seed `ctx.state` |
| `afterWorkflow` / `after_workflow`            | After a successful `entry` | Transform the workflow result        |
| `onWorkflowError` / `on_workflow_error`       | On failure                 | Recover or rethrow                   |
| `onWorkflowComplete` / `on_workflow_complete` | Always (success or error)  | Logging / metrics (should not throw) |

## Examples

### Logging

```js
const logging = {
  name: "logging",
  async beforeAgent(ctx) {
    console.log("[agent]", ctx.agentName, "input:", ctx.input);
  },
  async afterAgent(ctx, result) {
    console.log("[agent]", ctx.agentName, "done");
    return result;
  },
  async beforeModel(ctx, request) {
    console.log("[model] round", request.round, "messages:", request.messages?.length);
    return request;
  },
  async beforeTool(ctx, call) {
    console.log("[tool]", call.name, call.arguments);
    return call;
  },
  async afterTool(ctx, call, result) {
    console.log("[tool]", call.name, "→", result);
    return result;
  },
};
```

### Tool access control

Block or allow specific tools before they run:

```js
const toolGuard = {
  name: "tool-guard",
  async beforeTool(ctx, call) {
    const blocked = ctx.state.blockedTools || [];
    if (blocked.includes(call.name)) {
      return {
        ...call,
        skip: true,
        result: `Tool ${call.name} is not allowed`,
      };
    }
    return call;
  },
};

const agent = DNotifier.defineAgent({
  name: "billing",
  tools: [getInvoice, refund],
  instructions: "Help with invoices.",
  middleware: [
    {
      async beforeAgent(ctx) {
        // Deny refunds unless the caller is an admin
        ctx.state.blockedTools =
          ctx.state.role === "admin" ? [] : ["billing.refund"];
      },
    },
    toolGuard,
  ],
});
```

### Workflow access check

Gate the whole pipeline (for example require a user id):

```js
const requireUser = {
  name: "require-user",
  async beforeWorkflow(ctx) {
    if (!ctx.senderId) {
      throw new DNotifier.WorkflowError("senderId is required");
    }
  },
  async onWorkflowComplete(ctx, { status, error }) {
    console.log("[workflow]", ctx.workflow?.name ?? "run", status, error?.message);
  },
};

const workflow = new DNotifier.Workflow({
  name: "secured-pipeline",
  middleware: [requireUser],
  async entry(ctx) {
    return ctx.runAgent("billing");
  },
});
```

## Language guides

| Language                | Guide                                                                                                                          |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| JavaScript / TypeScript | [javascript-typescript.md](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/middleware/javascript-typescript.md) |
| Python                  | [python.md](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/middleware/python.md)                               |
| Dart / Flutter          | [dart-flutter.md](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/middleware/dart-flutter.md)                   |

## Next steps

* [**Define an agent**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/define-agent.md)
* [**Tools & MCP agents**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/tools-and-mcp.md)
* [**Build a workflow**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/build-workflow.md)
* [**WorkflowContext reference**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/workflow-context.md)
