> 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/dart-flutter.md). Agents can also search and read this documentation through its [MCP server](https://dnotifier.gitbook.io/product-docs/~gitbook/mcp).

# Dart / Flutter

Register middleware with `AgentMiddleware` / `WorkflowMiddleware` on `defineAgent` or `Workflow`. Hook names use **camelCase**.

## Logging middleware

```dart
final logging = AgentMiddleware(
  name: 'logging',
  beforeAgent: (ctx) async {
    print('[agent:start] ${ctx.agentName} ${ctx.input}');
  },
  afterAgent: (ctx, result) async {
    print('[agent:done] ${ctx.agentName}');
    return result;
  },
  onAgentError: (ctx, err) async {
    print('[agent:error] $err');
    throw err;
  },
  beforeModel: (ctx, request) async {
    print('[model] round=${request['round']} model=${request['model']}');
    return request;
  },
  beforeTool: (ctx, call) async {
    print('[tool:call] ${call['name']} ${call['arguments']}');
    return call;
  },
  afterTool: (ctx, call, result) async {
    print('[tool:result] ${call['name']} $result');
    return result;
  },
);

final agent = DNotifier.defineAgent(
  name: 'assistant',
  instructions: 'Use tools when needed.',
  tools: [searchTool],
  middleware: [logging],
);

await notifier.runAgent(agent, input: 'Find the refund policy');
```

## Tool access middleware

```dart
final allowlist = AgentMiddleware(
  name: 'tool-allowlist',
  beforeTool: (ctx, call) async {
    final allowed = (ctx.state['allowedTools'] as List?)?.cast<String>() ?? [];
    final name = call['name'] as String?;
    if (name == null || !allowed.contains(name)) {
      return {
        ...call,
        'skip': true,
        'result': {'error': 'tool_not_allowed', 'name': name},
      };
    }
    return call;
  },
);

final agent = DNotifier.defineAgent(
  name: 'ops',
  tools: [readMetric, restartService],
  instructions: 'Help with ops questions.',
  middleware: [
    AgentMiddleware(
      beforeAgent: (ctx) async {
        ctx.state['allowedTools'] = ctx.state['role'] == 'sre'
            ? ['ops.readMetric', 'ops.restartService']
            : ['ops.readMetric'];
      },
    ),
    allowlist,
  ],
);
```

## Workflow access middleware

```dart
final access = WorkflowMiddleware(
  name: 'workflow-access',
  beforeWorkflow: (ctx) async {
    if (ctx.senderId.isEmpty) {
      throw WorkflowError('Authentication required');
    }
    ctx.state['startedAt'] = DateTime.now().millisecondsSinceEpoch;
  },
  afterWorkflow: (ctx, result) async {
    final started = ctx.state['startedAt'] as int? ??
        DateTime.now().millisecondsSinceEpoch;
    final durationMs = DateTime.now().millisecondsSinceEpoch - started;
    if (result is Map) {
      return {...result, 'durationMs': durationMs};
    }
    return {'result': result, 'durationMs': durationMs};
  },
  onWorkflowComplete: (ctx, info) async {
    print('[workflow] ${info['status']} ${info['error']}');
  },
);

final workflow = Workflow(
  name: 'ops-flow',
  middleware: [access],
  entry: (ctx) => ctx.runAgent('ops'),
).registerAgents({'ops': agent});

await notifier.runWorkflow(
  workflow: workflow,
  input: {'question': 'CPU for api-1?'},
  senderId: 'user_123',
);
```

## See also

* [**Middleware overview**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/middleware.md)
* [**Define an agent**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/define-agent/dart-flutter.md)
* [**Build a workflow**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/build-workflow/dart-flutter.md)
