Originally published on tamiz.pro.

Running a single AI agent is easy. Running fifty of them — each with its own tools, memory, and failure modes — is a distributed-systems problem. That's the gap this guide closes: how to use Orca, an open-source agent-orchestration framework, together with the Model Context Protocol (MCP) to build, connect, and operate a fleet of specialized bots that cooperate on real work.

You'll learn the architecture, write a working MCP tool server, define agents in Orca, wire them into orchestration patterns, and harden the fleet with health checks, retries, rate limits, and tracing. Everything is hands-on and runnable.

A single monolithic prompt fails in three ways: it hits context limits, it mixes concerns, and it can't parallelize. A fleet of specialized agents fixes all three — but only if something coordinates them.

Orca is an orchestration layer that treats agents as first-class units: you declare a graph of agents, assign each one a role and a toolset, and Orca handles routing, state passing, and scheduling. MCP (Model Context Protocol) is the standard by which agents reach external systems — databases, APIs, files, SaaS tools — through a uniform JSON-RPC interface. Together they give you the two things every serious agent system needs: a planner and a socket wrench.

The core insight: MCP makes tools portable; Orca makes agents composable. Neither alone gives you a fleet. You need both.

OPENAI_API_KEY) or a local model server (Ollama, vLLM) Here's the topology we'll build:

┌────────────────────────────────────────────────────────────┐
│                        ORCA ORCHESTRATOR                   │
│                                                            │
│   ┌──────────┐   ┌──────────┐   ┌──────────┐   ┌────────┐ │
│   │ Planner  │──▶│ Resolver │──▶│ Executor │──▶│ Fleet  │ │
│   │ (LLM)    │   │ (Graph)  │   │ (Queue)  │   │ Manager│ │
│   └────┬─────┘   └────┬─────┘   └────┬─────┘   └───┬────┘ │
│        │              │              │              │      │
└────────┼──────────────┼──────────────┼──────────────┼──────┘
         │              │              │              │
         ▼              ▼              ▼              ▼
   ┌──────────────────────────────────────────────────────┐
   │                    MCP CLIENT LAYER                   │
   │  ┌───────────┐  ┌───────────┐  ┌───────────┐         │
   │  │ Agent A   │  │ Agent B   │  │ Agent C   │  ...    │
   │  └─────┬─────┘  └─────┬─────┘  └─────┬─────┘         │
   └────────┼──────────────┼──────────────┼───────────────┘
            │              │              │
            ▼              ▼              ▼
   ┌────────────┐  ┌────────────┐  ┌────────────┐
   │ MCP Server │  │ MCP Server │  │ MCP Server │
   │ (weather)  │  │ (database) │  │ (search)   │
   └────────────┘  └────────────┘  └────────────┘

Three layers: Orca orchestrator (planning and scheduling), MCP client layer (each agent holds connections to tool servers), and MCP servers (the actual tools). The fleet manager sits inside Orca and watches every agent's health.

Create a TypeScript monorepo with three packages: tools (MCP servers), agents (Orca agent definitions), and orchestrator (the entry point).

mkdir orca-fleet && cd orca-fleet
npm init -y
npm install typescript tsx @modelcontextprotocol/sdk @orca/agents zod dotenv
npx tsc --init --module NodeNext --target ES2022 --moduleResolution NodeNext

Add a .env file:

OPENAI_API_KEY=sk-...
DATABASE_URL=postgres://user:pass@localhost:5432/app

MCP servers expose tools over JSON-RPC. The official SDK makes this trivial. Here's a weather server with one tool, get_forecast, that validates input with Zod and returns structured data:

// tools/weather-server.ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({
  name: "weather",
  version: "1.0.0",
});

server.tool(
  "get_forecast",
  "Fetch a 5-day forecast for a city.",
  { city: z.string(), units: z.enum(["metric", "imperial"]).default("metric") },
  async ({ city, units }) => {
    // In production, call a real weather API here.
    const forecast = [
      { day: "Mon", high: 21, low: 12, condition: "sunny" },
      { day: "Tue", high: 19, low: 11, condition: "cloudy" },
    ];
    return {
      content: [{ type: "text", text: JSON.stringify({ city, units, forecast }, null, 2) }],
    };
  }
);

const transport = new StdioServerTransport();
await server.connect(transport);
console.error("weather MCP server running on stdio");

Build a second server for database access — this is what a "data agent" will use:

// tools/db-server.ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({ name: "database", version: "1.0.0" });

server.tool(
  "query_orders",
  "Run a read-only SQL query against the orders table.",
  { limit: z.number().int().min(1).max(100).default(10) },
  async ({ limit }) => {
    // In production: pool.query("SELECT * FROM orders LIMIT $1", [limit])
    const rows = [{ id: 1001, total: 249.99, status: "shipped" }];
    return { content: [{ type: "text", text: JSON.stringify(rows) }] };
  }
);

await server.connect(new StdioServerTransport());

Both servers speak over stdio, which keeps them as isolated child processes — a clean security boundary. Orca will spawn them on demand.

Now define the agents. Each agent gets a name, a role description (used by the planner), a model, and a list of MCP servers it can call. Here's a WeatherAgent and a DataAgent:

// agents/weather.agent.ts
import { Agent } from "@orca/agents";

export const weatherAgent = new Agent({
  name: "weather-agent",
  role: "You retrieve weather forecasts for any city and summarize them for the user.",
  model: "gpt-4o",
  tools: {
    mcpServers: ["weather"],
  },
  systemPrompt: "You are a weather specialist. Always use the get_forecast tool.",
});
js
// agents/data.agent.ts
import { Agent } from "@orca/agents";

export const dataAgent = new Agent({
  name: "data-agent",
  role: "You query order data and answer business questions with real numbers.",
  model: "gpt-4o-mini",
  tools: {
    mcpServers: ["database"],
  },
  systemPrompt: "You are a data analyst. Use query_orders to fetch data, never guess.",
});

And a coordinator agent that has no tools of its own but can delegate:

// agents/coordinator.agent.ts
import { Agent } from "@orca/agents";

export const coordinator = new Agent({
  name: "coordinator",
  role: "You decompose user requests into subtasks and delegate to specialist agents.",
  model: "gpt-4o",
  tools: { mcpServers: [] },
  systemPrompt: "You are a project lead. Break the request into steps, then call the right agent for each.",
});

Register everything in one place:

// orchestrator/index.ts
import { Orca } from "@orca/agents";
import { weatherAgent } from "../agents/weather.agent.js";
import { dataAgent } from "../agents/data.agent.js";
import { coordinator } from "../agents/coordinator.agent.js";

const orca = new Orca({
  agents: [coordinator, weatherAgent, dataAgent],
  mcpServers: {
    weather: { command: "node", args: ["tools/weather-server.js"] },
    database: { command: "node", args: ["tools/db-server.js"] },
  },
});

await orca.start();
const result = await orca.run("What's the weather in Tokyo and our top order this week?");
console.log(result);
await orca.shutdown();

Orca's planner reads the role fields, decides which agents are relevant, and routes the request. The mcpServers map tells Orca how to spawn each tool server as a child process and inject its connection into the right agents.

A fleet is only as good as its coordination. Orca supports several patterns; pick per task, not per fleet.

| Pattern | Use case | Trade-off | |---|---|---| | Sequential | Dependent steps (fetch data, then summarize) | Slow, but deterministic | | Parallel fan-out | Independent subtasks (weather + orders) | Fast, needs merge step | | Hierarchical | Coordinator delegates to specialists | Most flexible, harder to debug | | Swarm / peer | Many agents bid on a task | Resilient, unpredictable |

const result = await orca.sequence([
  { agent: "data-agent", task: "Fetch the top order this week." },
  { agent: "weather-agent", task: "Summarize the forecast for the order's delivery city." },
]);

Each agent's output is passed as context to the next.

const [weather, orders] = await orca.parallel([
  { agent: "weather-agent", task: "Forecast for Tokyo, metric units." },
  { agent: "data-agent", task: "Top 5 orders by total, this week." },
]);

Both run concurrently; Orca merges the results when both settle.

const result = await orca.delegate({
  from: "coordinator",
  to: ["weather-agent", "data-agent"],
  task: "Plan a delivery schedule using weather and order data.",
});

The coordinator breaks the task into subtasks and hands them to specialists, then synthesizes the final answer.

Rule of thumb: use parallel when tasks are independent, sequential when they chain, and hierarchical when you want a single human-facing answer from many specialists.

Now the production concerns. Every agent is a process with a heartbeat. Orca's fleet manager exposes hooks for health checks and retries.

import { HealthCheck } from "@orca/fleet";

const health = new HealthCheck({
  intervalMs: 10_000,
  timeoutMs: 2_000,
  onUnhealthy: async (agentName, error) => {
    console.error(`[FLEET] ${agentName} unhealthy:`, error.message);
    await orca.restart(agentName); // restart the agent's MCP connections
  },
});

await health.monitor(orca);

Orca pings each agent's MCP transport; if a server hangs, the agent is restarted and its connections re-established.

const result = await orca.run("Fetch forecast for Berlin", {
  retry: {
    maxAttempts: 3,
    backoff: (attempt) => Math.min(1000 * 2 ** attempt, 10_000),
    onRetry: (attempt, error) => console.warn(`Retry ${attempt}: ${error.message}`),
  },
});

LLM calls are expensive and APIs throttle. Use a token bucket per agent:

import { RateLimiter } from "@orca/fleet";

const limiter = new RateLimiter({
  capacity: 10,       // burst
  refillPerSecond: 2, // sustained
});

await orca.run("Heavy batch job", {
  beforeAgent: async (agentName) => {
    await limiter.acquire();
  },
});

If an MCP server starts failing repeatedly, open the circuit so the fleet degrades gracefully instead of hammering a dead dependency:

import { CircuitBreaker } from "@orca/fleet";

const breaker = new CircuitBreaker({
  failureThreshold: 5,
  cooldownMs: 30_000,
});

await orca.run("Query orders", {
  beforeTool: async (toolName) => {
    if (!breaker.canPass(toolName)) throw new Error("Circuit open for " + toolName);
  },
  afterTool: (toolName, ok) => breaker.record(toolName, ok),
});

You can't debug a fleet you can't see. Instrument every agent with OpenTelemetry spans and structured logs.

import { trace, context } from "@opentelemetry/api";

const tracer = trace.getTracer("orca-fleet");

await orca.run("Plan delivery", {
  onAgentStart: (agentName, taskId) => {
    const span = tracer.startSpan(`agent:${agentName}`);
    span.setAttribute("task.id", taskId);
    context.with(trace.setSpan(context.active(), span), () => {});
  },
  onAgentEnd: (agentName, result, span) => {
    span.setAttribute("result.length", result.length);
    span.end();
  },
});

Log every tool call with its latency and token usage:

import { pino } from "pino";

const logger = pino({ level: "info" });

orca.on("tool.call", (event) => {
  logger.info({
    agent: event.agentName,
    tool: event.toolName,
    durationMs: event.durationMs,
    tokens: event.tokens,
  }, "tool invocation");
});

Export traces to Jaeger or a managed backend via the OTLP exporter, and you'll see the full DAG of every request — which agent ran, which tool it called, and where it stalled.

Package each MCP server as its own container, and run Orca as a stateless service that spawns them as sidecars.

# Dockerfile.weather
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
CMD ["node", "tools/weather-server.js"]
# docker-compose.yml
services:
  orchestrator:
    build: .
    environment:
      - OPENAI_API_KEY=${OPENAI_API_KEY}
    depends_on:
      - weather-server
      - db-server
  weather-server:
    build: { context: ., dockerfile: Dockerfile.weather }
  db-server:
    build: { context: ., dockerfile: Dockerfile.db }

Scale horizontally by running multiple orchestrator replicas behind a load balancer. Each replica is stateless; MCP connections are per-request, so there's no shared state to synchronize. For long-running fleets, use a queue (BullMQ, SQS) to feed tasks to Orca instead of direct HTTP calls.

Q: When should I use MCP versus a direct function call?

Use MCP whenever the tool is reusable across agents or teams, or when it touches an external system (DB, API, files). Direct calls are fine for pure in-process helpers. MCP's main win is portability and a clean security boundary.

Q: How do I handle an agent that returns malformed output?

Validate the output with Zod before it enters the orchestration graph. If validation fails, treat it as a retryable error — Orca's retry policy will re-invoke the agent, and the circuit breaker will trip if it keeps happening.

Q: Can I mix models in one fleet?

Yes. Assign gpt-4o to the coordinator and data agents for accuracy, and gpt-4o-mini to high-volume, low-stakes agents. Orca routes per-agent, so you control cost per role.

This guide pairs the orchestration power of Orca with the tooling standard of MCP. For more on agent patterns and production hardening, see Tamiz's Insights.

To understand how Orca manages fleets effectively, we need to look at its core abstraction: the Role. A role is not merely a configuration object—it is a declarative contract that defines what a bot should do, how it should do it, and under what constraints.

Every role in Orca consists of three primary components:

# Example role definition in Orca's declarative format
role_definition = {
    "name": "code-reviewer",
    "capabilities": ["git.diff", "static_analysis.scan", "llm.summarize"],
    "policies": {
        "max_concurrency": 3,
        "retry": {"max_attempts": 2, "backoff": "exponential"},
        "cost_ceiling": 0.05  # USD per invocation
    },
    "bindings": {
        "mcp_servers": ["github", "sonarqube"],
        "llm_profile": "fast-inference"
    }
}

Orca employs a hierarchical scheduler rather than a flat queue. This is critical for fleet management because it allows you to express dependencies and priorities without creating circular waits.

graph TD
    A[Orchestrator] --> B[Role Manager: Code Reviewer]
    A --> C[Role Manager: Data Fetcher]
    A --> D[Role Manager: Report Generator]
    B --> E[Worker 1]
    B --> F[Worker 2]
    C --> G[Worker 3]
    D --> H[Worker 4]

This hierarchy ensures that a failure in one role manager does not cascade to the entire fleet. The orchestrator can spin up a replacement manager while the other roles continue processing.

Now that we understand Orca's orchestration, let's explore how to wire MCP servers into this architecture. The key insight is that MCP servers are stateless protocol endpoints—they don't know about fleet orchestration. You need a client adapter that bridges the gap.

The simplest pattern is to expose each MCP server as a set of tools through a proxy. This proxy handles authentication, rate limiting, and tool discovery.

import mcp
from orca import RoleClient

class MCPToolProxy:
    def __init__(self, server_url, auth_token):
        self.client = mcp.Client(server_url, auth_token)
        self.tool_cache = {}

    def discover_tools(self):
        # Cache tool schemas to avoid repeated handshakes
        if not self.tool_cache:
            self.tool_cache = self.client.list_tools()
        return self.tool_cache

    def invoke(self, tool_name, arguments):
        # Apply role-based rate limiting here
        return self.client.call_tool(tool_name, arguments)

For long-running tasks (like data extraction or report generation), you need to bridge MCP's request-response model with Orca's async task queues.

import asyncio
from orca import TaskQueue

async def stream_mcp_task(proxy, tool_name, params, task_queue):
    """Convert an MCP call into a streamed task for Orca."""
    task_id = task_queue.submit(tool_name, params)

    # Poll for completion or stream partial results
    async for chunk in proxy.stream_call(tool_name, params):
        task_queue.update_progress(task_id, chunk)

    return task_queue.get_result(task_id)

This is where Orca shines. Instead of hardcoding tool calls, you register capabilities dynamically. This allows you to swap MCP servers without redeploying the fleet.

from orca import CapabilityRegistry

registry = CapabilityRegistry()

# Register tools from multiple MCP servers
registry.register_server("github", github_proxy)
registry.register_server("sonarqube", sonar_proxy)
registry.register_server("internal-db", db_proxy)

# Now roles can reference tools by name, not by server
role_definition["capabilities"] = ["github.get_pr_diff", "sonarqube.analyze"]

Managing a fleet isn't just about orchestration—it's about operational resilience. Let's look at three critical aspects.

Orca supports three autoscaling modes:

# Orca autoscaling configuration
autoscaling:
  mode: cost_aware
  min_workers: 2
  max_workers: 20
  cost_budget: 50  # USD per hour
  scale_up_threshold: 0.8  # 80% utilization
  scale_down_threshold: 0.3

Bots fail in production. The key is detecting failure early and preventing cascading issues.

from orca import HealthMonitor, CircuitBreaker

class FleetHealthMonitor:
    def __init__(self):
        self.monitor = HealthMonitor(interval=30)  # Check every 30s
        self.breakers = {}

    def register_worker(self, worker_id, health_endpoint):
        breaker = CircuitBreaker(
            failure_threshold=3,
            recovery_timeout=60,
            fallback=self._handle_worker_failure
        )
        self.breakers[worker_id] = breaker
        self.monitor.register(worker_id, health_endpoint, breaker)

    def _handle_worker_failure(self, worker_id):
        # Orchestrator takes over: requeue tasks and spawn replacement
        orchestrator.requeue_tasks(worker_id)
        orchestrator.spawn_replacement(worker_id)

When resources are constrained, you need to decide what to sacrifice. Orca implements a priority ladder:

class PriorityLadder:
    def __init__(self, orchestrator):
        self.orchestrator = orchestrator
        self.levels = {
            0: {"max_workers": 10, "timeout": 30},
            1: {"max_workers": 5, "timeout": 120},
            2: {"max_workers": 2, "timeout": 300}
        }

    def allocate_resources(self):
        # Under pressure, shed lower-priority tasks first
        if self.orchestrator.under_pressure():
            self.orchestrator.pause_level(2)
            self.orchestrator.reduce_workers(1, by=2)

Before deploying your fleet, ensure you've addressed these operational concerns:

Building a fleet of AI agents is not about writing clever prompts—it's about engineering discipline. The combination of Orca's role-based orchestration and MCP's standardized tooling gives you a foundation that is:

The future of AI isn't a single monolithic model—it's a coordinated fleet of specialized agents working together. By adopting these patterns, you're not just automating tasks; you're building a system that can scale, adapt, and survive production reality.

原文来源:dev.to