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.

  • 1. Why Orchestrate a Fleet?
  • 2. Prerequisites
  • 3. Architecture Overview
  • 4. Step 1 — Scaffold the Project
  • 5. Step 2 — Build an MCP Tool Server
  • 6. Step 3 — Define Agents in Orca
  • 7. Step 4 — Orchestration Patterns
  • 8. Step 5 — Fleet Management: Health, Retries, and Rate Limits
  • 9. Step 6 — Observability and Tracing
  • 10. Step 7 — Deploy and Scale
  • 11. Frequently Asked Questions

1. Why Orchestrate a Fleet?

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.

2. Prerequisites

  • Node.js 20+ and npm/pnpm
  • An OpenAI-compatible API key (OPENAI_API_KEY) or a local model server (Ollama, vLLM)
  • Basic TypeScript knowledge
  • Docker (for the deployment section)

3. Architecture Overview

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.

4. Step 1 — Scaffold the Project

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 

5. Step 2 — Build an MCP Tool Server

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.

6. Step 3 — Define Agents in Orca

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.", }); 
// 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.

7. Step 4 — Orchestration Patterns

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

Sequential

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.

Parallel fan-out

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.

Hierarchical delegation

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.

8. Step 5 — Fleet Management: Health, Retries, and Rate Limits

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

Health checks

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.

Retries with exponential backoff

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}`), }, }); 

Rate limiting

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(); }, }); 

Circuit breaker

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), }); 

9. Step 6 — Observability and Tracing

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.

10. Step 7 — Deploy and Scale

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.

11. Frequently Asked Questions

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.

Deep Dive: Orca's Orchestration Model

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.

The Role Contract

Every role in Orca consists of three primary components:

  1. Capabilities: The set of MCP tools or internal functions the bot can invoke.
  2. Policies: Operational rules governing concurrency, retry behavior, and resource allocation.
  3. Bindings: The specific MCP servers or external services the role is permitted to interact with.
# 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" } } 

The Scheduler: A Hierarchical Approach

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.

  • Tier 0: The Orchestrator itself—a lightweight process that maintains the fleet's desired state.
  • Tier 1: Role Managers—one per role type, handling task assignment and health monitoring.
  • Tier 2: Worker Nodes—the actual bot processes, which may be containerized or serverless.
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.

Practical MCP Integration Patterns

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.

Pattern 1: The Tool Proxy

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 Source:https://dev.to/tamizuddin/orchestrating-ai-agent-fleets-a-practical-guide-to-orca-mcp-and-bot-management-349d

Related posts