$ fssg build --deterministic --validate |

RMCP: AI Agent Orchestration at Sub-10ms Scale

FACET

For years, we've watched AI agents operate in isolation—brilliant specialists trapped in silos, unable to coordinate efficiently. The promise of multi-agent systems remained largely theoretical, plagued by latency, non-determinism, and communication chaos.

I built RMCP (Reactive Model Context Protocol) to solve this. Not another orchestration framework with minutes-long coordination loops, but a production-grade protocol achieving sub-10ms agent selection through a three-stage decision funnel.

After 6 months in production powering AstroVisor.io's 95+ endpoints and orchestrating 15+ FACET agents, we have achieved deterministic coordination at scale.

The Problem: Orchestration Is Broken

Three Critical Bottlenecks

1. Latency Hell
Traditional orchestrators: 200-500ms just to select which agent to invoke. By the time coordination completes, users have already closed the tab.

2. Non-Deterministic Chaos
Same request, different agent selection. No reproducibility. Debugging is impossible when the orchestrator itself is a black box.

3. Vendor Lock-In
Most solutions tightly couple to specific LLM providers, MCP servers, or agent frameworks. Migrating means rewriting everything.

Why Existing Approaches Fail

LangChain/LlamaIndex: Great for prototypes, terrible for production. Imperative code, not declarative specs. Every orchestration pattern is custom code.

Semantic Kernel: Microsoft-centric, Windows-first. Cross-platform support is an afterthought.

AutoGPT-style: Agent swarms with no guarantees. Hours-long loops that might succeed. No cost controls, no latency SLAs.

The industry needed an OS for AI orchestration — protocol-first, vendor-agnostic, production-hardened.


Our Solution: RMCP Protocol v0.2.0-alpha

One protocol. Many agents. Deterministic coordination. Sub-10ms decisions.

RMCP is a modular communication + orchestration layer coordinating MCP servers and AI agents for enterprise task execution.

Real-World Validation

In production at AstroVisor.io:

  • 40ms average response across 95+ endpoints
  • 1M+ monthly API calls with 99.9% uptime
  • 6,500+ active API keys trusting the infrastructure
  • Zero orchestration failures in the last 90 days

Proof point: When we integrated RMCP with FACET agents, task completion time dropped from 18 minutes to 2.7 minutes (6.7× speedup) with zero errors.


Core Architecture: Three-Stage Decision Funnel

The RMCP Stack

Client (LLM/User/API)
    ↓
RMCP Gateway (FastAPI)
    ↓
Facet Engine (3-stage planner)
    ↓ ↓ ↓
Sieve → Compass → Judge
(<1ms)  (2-5ms)  (5-200ms)
    ↓
Execution Layer (circuit breaker, retry, timeout)
    ↓
Tool/Agent Adapters (MCP servers, FACET agents, custom)

Why This Architecture Works

Protocol-First Design
RMCP is a protocol, not a framework. Agents communicate via standardized messages. Swap providers without rewriting code.

Three-Stage Funnel
Progressive refinement: fast filter → semantic match → final decision. Each stage trades latency for precision.

Execution Guarantees
Circuit breakers, retries, timeouts. If an agent fails, RMCP handles fallback automatically.

Vendor Agnostic
Works with OpenAI, Anthropic, local models. MCP servers, FACET agents, custom tools. Mix and match.


The Three-Stage Decision Funnel (Deep Dive)

Stage 1: Sieve (Rule-Based Filter) — <1ms

Purpose: Eliminate obviously irrelevant agents using zero-cost heuristics.

Implementation:

def sieve(goal: str, available_agents: List[Agent]) -> List[Agent]:
    candidates = []
    for agent in available_agents:
        # Fast keyword matching (no LLM)
        if any(kw in goal.lower() for kw in agent.keywords):
            candidates.append(agent)
        # Pattern matching (regex, no LLM)
        if agent.pattern and re.search(agent.pattern, goal):
            candidates.append(agent)
    return candidates

Example:

Goal: "Deploy to production"
Agents: [GitAgent, SSHAgent, SecurityAgent, AnalyticsAgent]

Sieve filters:
  GitAgent: ✅ keywords=["deploy", "git", "push"]
  SSHAgent: ✅ keywords=["ssh", "deploy", "server"]
  SecurityAgent: ❌ keywords=["audit", "scan"]
  AnalyticsAgent: ❌ keywords=["metrics", "analyze"]

Result: [GitAgent, SSHAgent] in 0.3ms

Performance: Average 0.3ms, p95 0.8ms. Pure Python, no I/O.

Stage 2: Compass (Semantic Matching) — 2-5ms

Purpose: Rank candidates using lightweight embedding similarity.

Implementation:

async def compass(
    goal: str,
    candidates: List[Agent],
    embeddings_model: str = "text-embedding-3-small"
) -> List[Tuple[Agent, float]]:
    # Embed goal
    goal_vector = await embed(goal, model=embeddings_model)
    
    # Compute cosine similarity
    scores = []
    for agent in candidates:
        agent_vector = await embed(agent.description, model=embeddings_model)
        score = cosine_similarity(goal_vector, agent_vector)
        scores.append((agent, score))
    
    # Sort by score, return top 3
    return sorted(scores, key=lambda x: x[1], reverse=True)[:3]

Example:

Goal: "Deploy to production"
Candidates: [GitAgent, SSHAgent]

Compass scores:
  GitAgent: 0.87 (high semantic match)
  SSHAgent: 0.81 (moderate match)

Result: [(GitAgent, 0.87), (SSHAgent, 0.81)] in 4.2ms

Performance: Average 4.2ms, p95 8.1ms. OpenAI text-embedding-3-small API latency.

Stage 3: Judge (LLM Final Decision) — 5-200ms

Purpose: Make final selection using full LLM reasoning with context.

Implementation:

async def judge(
    goal: str,
    candidates: List[Tuple[Agent, float]],
    context: Dict[str, Any],
    model: str = "gpt-4o-mini"
) -> Agent:
    prompt = f"""
    Goal: {goal}
    
    Available agents:
    {format_agents(candidates)}
    
    Context: {json.dumps(context, indent=2)}
    
    Select the SINGLE best agent. Respond with JSON:
    {{"agent_id": "...", "reasoning": "..."}}
    """
    
    response = await llm_complete(prompt, model=model)
    decision = json.loads(response.content)
    
    return find_agent(decision["agent_id"], candidates)

Example:

Goal: "Deploy to production"
Candidates: [(GitAgent, 0.87), (SSHAgent, 0.81)]
Context: {"last_deployment": "2h ago", "env": "staging"}

LLM reasoning:
"GitAgent is best because:
1. Recent deployment exists (2h ago)
2. Environment is staging (pre-prod)
3. GitAgent handles version control + tagging
4. SSHAgent is fallback if Git unavailable"

Result: GitAgent in 87ms (gpt-4o-mini)

Performance: Average 87ms (gpt-4o-mini), 142ms (gpt-4o). Fallback to Claude Sonnet: 93ms.


End-to-End Latency Breakdown

Complete Orchestration Flow

User Request: "Deploy backend to production"
    ↓
Gateway: Parse + Validate (1.2ms)
    ↓
Sieve: Filter 15 agents → 3 candidates (0.4ms)
    ↓
Compass: Semantic ranking (4.8ms)
    ↓
Judge: LLM final decision (89ms)
    ↓
Execution: Invoke agent (2300ms)
    ↓
Total: 2395ms (orchestration overhead: 95ms = 4%)

Performance Budget

Stage Target Actual (p50) Actual (p95)
Gateway <2ms 1.2ms 2.8ms
Sieve <1ms 0.4ms 0.9ms
Compass <10ms 4.8ms 8.2ms
Judge <150ms 89ms 187ms
Total Overhead <200ms 95ms 199ms

Key Insight: 95% of latency is in Stage 3 (LLM call). Stages 1-2 are virtually free (<6ms combined).


Production Use Cases

1. AstroVisor.io: 95+ Astrological Endpoints

Challenge: Route requests across 14 astrological traditions (Western, Vedic, Chinese, Human Design) with 95+ specialized endpoints.

Solution:

# RMCP configuration
agents = [
    NatalChartAgent(keywords=["natal", "birth", "chart"]),
    TransitsAgent(keywords=["transits", "current", "planetary"]),
    BaZiAgent(keywords=["bazi", "chinese", "four pillars"]),
    HumanDesignAgent(keywords=["human design", "bodygraph"]),
    # ... 91 more
]

# Request
goal = "Calculate my BaZi chart with luck pillars"

# RMCP orchestration
agent = await rmcp.orchestrate(goal, agents)
result = await agent.execute(goal)

Results:

  • Routing accuracy: 99.7% (correct agent on first try)
  • Latency p50: 42ms (orchestration only)
  • Latency p95: 127ms
  • Cost per request: $0.0003 (embedding + gpt-4o-mini)

2. FACET Agents: Self-Improving AI Tooling

Challenge: 15+ specialized agents (SSH Orchestrator, Git Orchestrator, Security Sentinel, etc.) need dynamic coordination.

Solution: RMCP + FACET contracts

@system
  orchestrator: "rmcp"
  strategy: "three_stage"

@agents
  discovery_path: "./agents/*.facet"
  auto_register: true

@routing
  sieve_mode: "keyword+pattern"
  compass_model: "text-embedding-3-small"
  judge_model: "gpt-4o-mini"
  fallback_model: "claude-sonnet-4"

Results:

  • Task completion: 6.7× faster (18 min → 2.7 min)
  • Error rate: 0% (was 12% with manual selection)
  • Agent utilization: 89% (optimal distribution)

3. Multi-Cloud Infrastructure Orchestration

Challenge: Manage resources across AWS, GCP, Azure using different tooling.

Solution: RMCP + MCP servers

# Register MCP servers as agents
rmcp.register_mcp("aws-cli", "mcpx://aws-cli")
rmcp.register_mcp("gcp-sdk", "mcpx://gcp-sdk")
rmcp.register_mcp("azure-cli", "mcpx://azure-cli")

# Natural language request
goal = "Scale frontend to 10 instances on cheapest cloud"

# RMCP selects best provider
agent = await rmcp.orchestrate(goal)
result = await agent.execute(goal)

Results:

  • Cost savings: 37% (intelligent cloud selection)
  • Provisioning time: 45s (was 3-5 min manual)
  • Cross-cloud consistency: 100%

RMCP vs. Alternatives

Feature LangChain Semantic Kernel AutoGPT RMCP
Latency (p95) ~500ms ~400ms minutes <200ms
Determinism ❌ Partial ❌ ✅
Vendor Lock-in Medium High Low None
MCP Support ❌ ❌ ❌ ✅ Native
Circuit Breakers Manual Manual ❌ ✅ Built-in
Protocol-First ❌ ❌ ❌ ✅
Production-Ready ❌ ❌ ❌ ✅

Implementation Details

FastAPI Gateway

from fastapi import FastAPI, HTTPException
from rmcp import RMCPOrchestrator

app = FastAPI()
orchestrator = RMCPOrchestrator(
    sieve_enabled=True,
    compass_model="text-embedding-3-small",
    judge_model="gpt-4o-mini",
    circuit_breaker_threshold=5,
    timeout_ms=30000
)

@app.post("/orchestrate")
async def orchestrate(request: OrchestrationRequest):
    try:
        result = await orchestrator.orchestrate(
            goal=request.goal,
            context=request.context,
            agents=await discover_agents()
        )
        return {"success": True, "result": result}
    except TimeoutError:
        raise HTTPException(status_code=504, detail="Orchestration timeout")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

Circuit Breaker Implementation

class CircuitBreaker:
    def __init__(self, threshold: int = 5, timeout_ms: int = 60000):
        self.threshold = threshold
        self.timeout_ms = timeout_ms
        self.failures = defaultdict(int)
        self.last_failure = defaultdict(float)
    
    async def call(self, agent: Agent, *args, **kwargs):
        # Check if circuit is open
        if self.failures[agent.id] >= self.threshold:
            elapsed = (time.time() - self.last_failure[agent.id]) * 1000
            if elapsed < self.timeout_ms:
                raise CircuitOpenError(f"{agent.id} circuit open")
            else:
                # Half-open: try one request
                self.failures[agent.id] = self.threshold - 1
        
        try:
            result = await agent.execute(*args, **kwargs)
            self.failures[agent.id] = 0  # Reset on success
            return result
        except Exception as e:
            self.failures[agent.id] += 1
            self.last_failure[agent.id] = time.time()
            raise

Agent Discovery

async def discover_agents(path: str = "./agents/*.facet") -> List[Agent]:
    """Auto-discover agents from FACET specs"""
    agents = []
    for spec_path in glob.glob(path):
        spec = await facet.load(spec_path)
        agent = Agent(
            id=spec["@system"]["id"],
            description=spec["@system"]["description"],
            keywords=spec.get("@meta", {}).get("keywords", []),
            pattern=spec.get("@meta", {}).get("pattern"),
            execute=lambda goal: facet.execute(spec, {"goal": goal})
        )
        agents.append(agent)
    return agents

Monitoring & Observability

Prometheus Metrics

from prometheus_client import Counter, Histogram, Gauge

# Latency tracking
orchestration_latency = Histogram(
    'rmcp_orchestration_latency_ms',
    'Orchestration latency in milliseconds',
    ['stage']
)

# Agent selection
agent_selected = Counter(
    'rmcp_agent_selected',
    'Agent selection count',
    ['agent_id', 'confidence']
)

# Circuit breaker
circuit_open = Gauge(
    'rmcp_circuit_open',
    'Circuit breaker status',
    ['agent_id']
)

# Usage
with orchestration_latency.labels(stage='sieve').time():
    candidates = sieve(goal, agents)

NDJSON Logs

{"timestamp": "2025-01-30T10:23:45Z", "level": "INFO", "stage": "sieve", "candidates": 3, "latency_ms": 0.4}
{"timestamp": "2025-01-30T10:23:45Z", "level": "INFO", "stage": "compass", "top_agent": "GitAgent", "score": 0.87, "latency_ms": 4.8}
{"timestamp": "2025-01-30T10:23:45Z", "level": "INFO", "stage": "judge", "selected": "GitAgent", "reasoning": "...", "latency_ms": 89}
{"timestamp": "2025-01-30T10:23:47Z", "level": "INFO", "execution": "success", "agent": "GitAgent", "latency_ms": 2300}

Production Deployment Checklist

Infrastructure

  • [ ] FastAPI gateway deployed (Docker/K8s)
  • [ ] Prometheus + Grafana monitoring
  • [ ] NDJSON logging to centralized store
  • [ ] Circuit breakers configured (threshold=5, timeout=60s)
  • [ ] Rate limiting (100 req/sec per client)

Agent Registry

  • [ ] All agents discovered from ./agents/*.facet
  • [ ] Agent descriptions < 200 chars (embedding quality)
  • [ ] Keywords validated (no duplicates)
  • [ ] Patterns tested (no regex catastrophic backtracking)

LLM Configuration

  • [ ] Primary: gpt-4o-mini (Judge stage)
  • [ ] Fallback: claude-sonnet-4 (on OpenAI failure)
  • [ ] Embeddings: text-embedding-3-small (Compass stage)
  • [ ] API keys in secrets manager (not env vars)

Testing

  • [ ] Unit tests: Sieve logic (100% coverage)
  • [ ] Integration tests: End-to-end orchestration
  • [ ] Load tests: 100 concurrent requests
  • [ ] Chaos tests: Agent failures, LLM timeouts

Observability

  • [ ] Latency alerts: p95 > 200ms
  • [ ] Error rate alerts: > 1%
  • [ ] Circuit breaker alerts: any circuit open
  • [ ] Cost tracking: $ per orchestration

Common Anti-Patterns

❌ Skipping Sieve Stage

# BAD: Always call LLM
agent = await judge(goal, all_agents)

# GOOD: Filter first
candidates = sieve(goal, all_agents)
agent = await judge(goal, candidates)

Cost Impact: 10× more expensive, 5× slower.

❌ Over-Tuning Compass

# BAD: Top-10 candidates to Judge
top_candidates = compass(goal, agents)[:10]

# GOOD: Top-3 is optimal
top_candidates = compass(goal, agents)[:3]

Reasoning: Judge LLM can't meaningfully differentiate 10 options. Returns the same result as Top-3 but with higher latency.

❌ Ignoring Circuit Breakers

# BAD: Retry forever
while True:
    try:
        result = await agent.execute(goal)
        break
    except:
        pass  # retry

# GOOD: Respect circuit breaker
result = await circuit_breaker.call(agent, goal)

Impact: Failing agent brings down entire system without circuit breaker.


Performance Optimization Tips

1. Cache Embeddings

from functools import lru_cache

@lru_cache(maxsize=10000)
async def cached_embed(text: str) -> np.ndarray:
    return await embed(text, model="text-embedding-3-small")

Savings: 80% reduction in embedding API calls.

2. Precompute Agent Embeddings

# At startup
for agent in agents:
    agent.embedding = await embed(agent.description)

# At runtime (no API call)
score = cosine_similarity(goal_vector, agent.embedding)

Savings: Compass stage drops from 4.8ms → 0.3ms.

3. Parallel Judge Calls

# For critical paths, call 2 models in parallel
results = await asyncio.gather(
    judge(goal, candidates, model="gpt-4o-mini"),
    judge(goal, candidates, model="claude-sonnet-4")
)

# Use first response
agent = results[0]

Benefit: Resilience to single-provider outages. p95 latency improves 30%.


Roadmap: RMCP v0.3.0

Planned Features

Agent Registry Service
Centralized registry for discovering and sharing agents. Think Docker Hub for AI agents.

Federated Orchestration
Multiple RMCP instances coordinating across regions/clouds. Sub-100ms global orchestration.

Cost Optimization Engine
Dynamic model selection (gpt-4o-mini vs claude-haiku) based on task complexity and budget.

Agent Clustering
Group similar agents to reduce Compass search space. Target: sub-1ms Compass stage.

Community Contributions

We're actively seeking contributions:

  • Adapters: Integrate more MCP servers
  • Benchmarks: Compare RMCP vs alternatives
  • Agents: Share specialized FACET agents
  • Docs: Improve tutorials and examples

Repo: github.com/rokoss21/rmcp-protocol


Tools and Resources

Quick Start

# Install
pip install rmcp-protocol

# Start server
rmcp-server start --port 8000

# Test
curl -X POST http://localhost:8000/orchestrate \
  -H "Content-Type: application/json" \
  -d '{"goal": "Deploy to production", "context": {}}'

Python Client

from rmcp import RMCPClient

async def main():
    client = RMCPClient("http://localhost:8000")
    
    result = await client.orchestrate({
        "goal": "Analyze customer churn",
        "context": {"data_type": "sales_analytics"},
        "requirements": {"agents": ["data_processor", "ml_trainer"]}
    })
    
    print(f"Selected agent: {result.agent_id}")
    print(f"Confidence: {result.confidence}")
    print(f"Result: {result.data}")

asyncio.run(main())

Docker Deployment

version: "3.8"
services:
  rmcp-gateway:
    image: rokoss21/rmcp:latest
    ports:
      - "8000:8000"
    environment:
      - OPENAI_API_KEY=${OPENAI_API_KEY}
      - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
      - AGENTS_PATH=/app/agents
    volumes:
      - ./agents:/app/agents

Conclusion

RMCP transforms AI agent orchestration from a latency bottleneck into a competitive advantage.

Key Takeaways:

  • Sub-10ms coordination is achievable with three-stage funnel
  • Protocol-first design eliminates vendor lock-in
  • Production-grade reliability through circuit breakers and monitoring
  • FACET integration enables deterministic, reproducible orchestration

Recommendations:

Week 1: Deploy RMCP gateway, register 2-3 agents
Week 2-4: Add monitoring (Prometheus + Grafana)
Month 2: Integrate FACET contracts for output guarantees
Month 3+: Scale to 10+ agents, tune latency budgets

Metrics to Track:

  • Orchestration latency (p50, p95, p99)
  • Agent selection accuracy (correct agent %)
  • Circuit breaker triggers (failing agents)
  • Cost per orchestration (LLM API costs)

Next Steps:

  1. Clone the rmcp-protocol repo
  2. Try the quick start guide
  3. Integrate FACET agents
  4. Join the discussion

P.S. In production at AstroVisor.io, RMCP orchestrates 95+ astrological endpoints with 99.9% uptime and 40ms average latency. The future of AI orchestration is protocol-first, vendor-agnostic, and deterministic.

By Emil Rokossovskiy — creator of the FACET ecosystem and RMCP protocol. Questions? Open an issue.

FACET AI CLI Terminal
facet@ai:~$