Chain of Responsibility

orchestrationEasy
Applicability

When to Use

When processing logic has multiple conditional steps
When handlers should be configurable and reorderable
When not every request needs every processing step
Overview

How It Works

The Chain of Responsibility pattern creates a pipeline of handlers, each connected to an MCP server. A request passes through the chain; each handler either processes it (potentially modifying it) and passes it on, or handles it completely and stops the chain. This is ideal for processing pipelines where different MCP servers handle different aspects: validation, enrichment, transformation, and storage. Each handler is independent and can be added, removed, or reordered without affecting others.
Implementation

Code Example

typescript
type Handler = (data: any, next: () => Promise<any>) => Promise<any>;

const pipeline: Handler[] = [
  async (data, next) => {
    // Validate
    if (!data.email) throw new Error("Email required");
    return next();
  },
  async (data, next) => {
    // Enrich from database
    const existing = await postgres.query("SELECT * FROM users WHERE email=$1", [data.email]);
    data.existingUser = existing.rows[0];
    return next();
  },
  async (data, next) => {
    // Store
    await postgres.query("INSERT INTO submissions (data) VALUES ($1)", [JSON.stringify(data)]);
    return next();
  },
  async (data, next) => {
    // Notify
    await slack.sendMessage({ channel: "#submissions", text: `New: ${data.email}` });
    return data;
  }
];

async function runPipeline(data) {
  let index = 0;
  const next = () => pipeline[++index]?.(data, next) ?? data;
  return pipeline[0](data, next);
}

Quick Info

Categoryorchestration
ComplexityEasy

Need Architecture Help?

Our team designs custom automation architectures.

Get in Touch
CortexAgent Customer Service

Want to skip the form?

Our team is available to help you get started with CortexAgent.

This chat may be recorded for quality assurance. You can view our Privacy Policy.