Files
infrapuzzle/docs/adr/0001-hybrid-mcp-tool-search-and-subagents.md
T

10 KiB
Raw Blame History

status, date, decision-makers, consulted, informed
status date decision-makers consulted informed
accepted 2026-09-12
Moritz Graf
Antigravity

ADR 0001: Hybrid MCP Tool Search and Subagent Delegation for AI Agents

Context and Problem Statement

OpenClaw operates as the personal AI concierge for the Graf family, communicating primarily via Telegram and web interfaces. It integrates external systems via the Model Context Protocol (MCP) (e.g., Home Assistant, Prometheus, Spotify, weather, shopping).

When integrating comprehensive domain services like Garmin Connect via Taxuspt/garmin_mcp, the server exposes 148 distinct tools spanning activity analysis, workout builders, physiological trends, sleep, stress, HRV, and gear tracking.

In standard MCP implementations, all tool schemas are transmitted in the LLM's tools array on every single request turn. For 148 tools, this imposes a ~25,000–30,000 token tax per turn before a single word of user prompt is evaluated. This creates severe issues:

  1. Severe Token & Cost Bloat: Inflates inference costs on OpenRouter across thousands of daily family turns.
  2. Turn Latency & Degradation: Slows down response times on mobile Telegram and impairs the reasoning accuracy of fast conductor models (e.g. deepseek-v4.1-flash) due to tool schema noise.
  3. Imbalance for Simple Checks: A simple query like "Wie war mein Schlaf?" should not require dragging 148 tool definitions into context or, conversely, incurring the multi-second startup latency of a full subagent session.

How do we grant OpenClaw full access to large, complex MCP tool catalogs without polluting everyday conversational context?


Decision Drivers

  • Token Economics: Minimize idle token overhead on routine conversational turns.
  • Low Latency: Provide instant answers for routine, single-step lookups.
  • Complex Multi-Step Capabilities: Enable autonomous, deep reasoning for tasks like workout generation, periodization, and multi-source research without cluttering the primary conversation transcript.
  • Protocol Standards: Adhere to upstream MCP standards rather than writing fragile, non-standard CLI wrappers for every API.
  • Architectural Consistency: Establish an extensible pattern that can later be applied to refactor other domains (e.g. Supermarket shopping, Jellyfin media, and Regensburg Stadtrat local news research).

Considered Options

  1. Option 1: Global Eager MCP Registration

    • Register all 148 tools directly under mcp.servers.
    • Drawback: Unacceptable ~30k token tax on every message; high cost and latency.
  2. Option 2: Pure CLI / Script Wrapper Skill

    • Avoid MCP entirely; write custom Python CLI scripts in mop-skills executed via bash.
    • Drawback: Re-invents the wheel, ignores the 1,150-star community MCP server, requires maintaining hundreds of lines of bespoke CLI parsing code.
  3. Option 3: Subagent Delegation Only

    • Hide all domain tools from the main agent and mandate that every query spawns a subagent via sessions_spawn.
    • Drawback: Adds unnecessary latency (2–4 seconds) and session overhead for trivial questions like "Wie hoch ist meine Body Battery?".
  4. Option 4: Hybrid Tool Search + Subagent Delegation (Selected)

    • Enable OpenClaw's native Tool Search (tools.toolSearch.mode: "directory") for the main agent so large tool catalogs are deferred behind lightweight search/describe/call operations (~600 tokens).
    • Empower the main conductor to dynamically decide:
      • Execute directly via Tool Search for fast, single-step queries.
      • Delegate to an isolated subagent (sessions_spawn) for deep, multi-step, stateful reasoning.

Decision Outcome

Chosen Option: Option 4: Hybrid Tool Search + Subagent Delegation.

1. Dual-Path Architecture

User Query (Telegram)
         │
         ▼
 ┌────────────────────────────────────────┐
 │       OpenClaw Main Conductor          │
 │       (DeepSeek v4.1 Flash)            │
 └───────────────────┬────────────────────┘
                     │
         Is this a deep/multi-step task?
        ┌────────────┴────────────┐
        │ NO                      │ YES
        ▼                         ▼
 ┌───────────────┐        ┌─────────────────────────┐
 │ Direct Tool   │        │ Subagent Delegation     │
 │ Search        │        │ (sessions_spawn)        │
 ├───────────────┤        ├─────────────────────────┤
 │ • tool_search │        │ • Dedicated Context     │
 │ • tool_call   │        │ • Full Tool Access      │
 │ • Single Turn │        │ • Multi-Step Reasoning  │
 └───────┬───────┘        └────────────┬────────────┘
         │                             │
         └──────────────┬──────────────┘
                        ▼
       ┌─────────────────────────────────┐
       │   Taxuspt/garmin_mcp (148 Tools)│
       │   Garmin Connect Cloud API      │
       └─────────────────────────────────┘

2. Main Conductor Routing Heuristic

The main conductor is guided by explicit system prompt rules:

Query Type Routing Path Examples
Simple Vitals & Lookups Direct Tool Search • "Wie war mein Schlaf letzte Nacht?"
• "Wie ist meine Body Battery?"
• "Was habe ich gestern trainiert?"
Deep Analysis & Creation Subagent Delegation (sessions_spawn) • "Erstelle mir ein 45-minütiges Oberkörper-Superset-Workout für heute auf meiner Uhr."
• "Analysiere mein Krafttraining der letzten 3 Wochen auf Progressive Overload und plane die nächste Woche."
• "Erstelle ein Periodisierungskonzept für den nächsten Monat."

Consequences

Positive

  • 98% Token Reduction on Idle Turns: The tool catalog is deferred behind OpenClaw's native Tool Search, dropping tool schema overhead from ~30,000 tokens to ~600 tokens.
  • Instant Answers for Vitals: Quick checks are answered in a single turn without waiting for subagent spin-up.
  • Isolated Deep Reasoning: Heavy multi-turn planning and JSON compilation occur inside temporary subagents, keeping the main Telegram conversation transcript lightweight and readable.
  • Standard-Compliant: Uses standard upstream MCP (Taxuspt/garmin_mcp) and standard OpenClaw features (tools.toolSearch, sessions_spawn).

Negative & Mitigations

  • Two-Step Tool Search Latency: For the first direct lookup of a tool, OpenClaw performs a search step before calling the tool.
    • Mitigation: OpenClaw's directory mode caches known tool descriptors and allows direct calls when the exact tool name is known.
  • Model Prompt Instruction: Requires clear guidelines in the system prompt so the conductor consistently knows when to delegate vs. query directly.

Future Roadmap: Monorepo Refactoring Blueprint

This Hybrid MCP architecture serves as the official template for all agentic workflows in infrapuzzle. On 2026-09-16, this architecture was formally expanded into the Full-Spectrum Multi-Agent Architecture with 9 specialized subagents:

1. Agents-as-Code in the Knowledge Wiki (knowledge-wiki/agents/)

Subagent specifications, system prompts, tool assignments, and domain guidelines are decoupled from Kubernetes deployment manifests and stored as versioned Markdown files in knowledge-wiki/agents/<name>.md.

  • Zero-Deployment Tuning: Adding or refining an agent requires no Kubernetes pod restarts; changes synced via Git are immediately effective.
  • Extensibility Blueprint: Adding a 10th agent requires simply adding agents/<new-agent>.md with YAML frontmatter specifying model, tools, and owned concepts.

2. The 9 Specialized Subagents Roster

  1. 🩺 Digitale Hebamme Agent (agents/hebamme.md): Baby milestones, sleep windows, BLW, pediatrician safety boundaries.
  2. 🍳 Koch Agent (agents/koch.md): Ninja CREAMi Deluxe, Airfryer, KitchenAid, leftover utilization, exact recipes.
  3. 🏡 Grabengasse Agent (agents/grabengasse.md): Home Assistant, Philips Hue, Sonos multiroom, house systems.
  4. 🏰 Regensburg Agent (agents/regensburg.md): Regensburg & Stadtamhof insider, local places, RVV transit, city notices.
  5. ✈️ Travel Agent (agents/travel.md): Vacation planning, itineraries, packing checklists, on-the-road travel concierge.
  6. 🎬 Media Agent (agents/media.md): Jellyfin streaming/requests, Jellyseerr, Spotify audiobooks & playlists.
  7. 🔍 Recherche Agent (agents/recherche.md): Deep research engine (iterative multi-hop), ALLRIS Stadtrat, Friday bridge updates.
  8. 🛒 Shopping Agent (agents/shopping.md): Deal hunter, Geizhals all-time lows, supermarket deals, multi-tier webshop extraction.
  9. 🏋️ Fitness Coach Agent (agents/fitness.md): Garmin Connect (148 tools), Tacx Flux 2 (FTP 275 W), home gym supersets.

3. Multi-Turn Continuity: Domain Stickiness & Rich State Bridge

To prevent context loss during ongoing step-by-step dialogues (e.g. interactive cooking or workout design):

  • Domain Stickiness: Follow-up questions on the active topic remain within the specialized subagent domain until an explicit topic shift occurs.
  • Rich State Bridge (<!-- DOMAIN_STATE -->): Every subagent embeds a compact JSON state comment at the end of its response. The Conductor uses this state to answer trivial micro-checks in < 1s, or feeds it back into the subagent for complex modifications.

4. 3-Tier Session Lifecycle (Preventing Unbounded Session Growth)

  1. Conversational Close: Topic shifts or explicit user completion ("Danke, das war's") reset the active domain pointer.
  2. Ephemeral Inactivity Cleanup: Subagent child sessions inactive for > 60 minutes (subagents.archiveAfterMinutes: 60) are automatically archived.
  3. Deterministic Nightly Compaction: Nightly 03:30 AM CET compaction vacuums expired child sessions from the SQLite store.