Designing Multi-Agent Collaboration Frameworks with Context Sharing: A Production-Ready Implementation

The bojieli/ai-agent-book repository provides production-ready multi-agent collaboration frameworks that enable secure context sharing through explicit JSON payloads and role-based isolation, implemented in Chapter 10's staged-system-prompt and voice-werewolf modules.

The bojieli/ai-agent-book repository offers a complete reference implementation for designing multi-agent collaboration frameworks with context sharing. Chapter 10 introduces two complementary architectures that demonstrate how to orchestrate multiple LLM agents while maintaining fine-grained control over information flow. These patterns enable developers to build scalable systems where specialized agents share necessary context without leaking privileged data.

Core Architecture Components

The framework organizes functionality into distinct layers that separate concerns between tool discovery, LLM interaction, and agent orchestration.

Provider Registry and Tool Discovery

The Provider Registry (agentbook/providers/registry.py) dynamically discovers and loads MCP (Multi-Channel Protocol) tool servers. This layer manages external capabilities such as collaboration-tools and execution-tools, allowing agents to access specialized functions on demand. The registry instantiates tool servers as lightweight subprocesses using mcp.run(transport="stdio"), enabling parallel execution across multiple CPU cores.

LLM Backend Integration

The OpenRouter provider (agentbook/providers/openrouter.py) serves as the unified interface for LLM calls. It handles prompt formatting and JSON-structured responses, ensuring consistent communication between the coordinator and individual agents. This abstraction allows the framework to swap underlying models without modifying orchestration logic.

Agent Base Class and State Management

All agents inherit from the Agent base class defined in agentbook/providers/models.py. This contract standardizes the input-to-output pipeline and handles state serialization through AgentConfig objects. Each agent maintains isolated state containing memory and toolbox references, while the AgentResult structure facilitates data exchange through explicit payload objects.

Staged System-Prompt Framework

The staged-system-prompt implementation (chapter10/staged-system-prompt/tools.py) demonstrates a coordinator pattern where a central LLM decomposes user requests into sub-tasks and delegates them to specialized agents.

The coordinator receives a user request and decides which sub-tasks require specialized agents. It forwards appropriate prompts to each sub-agent, which runs with its own isolated state. Intermediate results return to the coordinator via JSON payloads, enabling fine-grained control over what each agent sees during the aggregation phase.


# File: chapter10/staged-system-prompt/tools.py

def orchestrate_task(user_prompt: str):
    # 1️⃣ Decompose the request

    plan = llm_call(
        model="gpt-4",
        prompt=f"Decompose this request into sub‑tasks:\n{user_prompt}"
    )
    # 2️⃣ Dispatch each sub‑task to a dedicated agent

    results = []
    for sub in plan["tasks"]:
        agent = load_agent(sub["agent_type"])
        payload = {"task": sub["instruction"], "context": sub["context"]}
        results.append(agent.run(payload))
    # 3️⃣ Merge the partial answers

    final = llm_call(
        model="gpt-4",
        prompt=f"Combine these results into a single answer:\n{json.dumps(results)}"
    )
    return final["answer"]

This approach ensures that agents only receive the specific context required for their assigned sub-task, preventing contamination from unrelated workflow stages.

Voice Werewolf Multi-Agent Simulation

The Voice Werewolf game (chapter10/voice-werewolf/) provides an end-to-end example of social deduction where multiple autonomous agents assume distinct roles (werewolf, seer, villager) and communicate via a shared town hall. The game engine (werewolf/game.py) maintains a global world state that is selectively exposed to agents through context objects (werewolf/agent.py).

Each role inherits from BaseRoleAgent and implements role-specific logic while adhering to the isolation boundaries enforced by the coordinator:


# File: chapter10/voice-werewolf/werewolf/roles.py

from werewolf.agent import BaseRoleAgent

class SeerAgent(BaseRoleAgent):
    """Agent that can peek at another player's hidden card."""
    def decide(self, world_snapshot):
        # Only receive the public game state plus a list of other players

        target = self.choose_target(world_snapshot["players"])
        # Request the hidden role from the coordinator (via payload)

        result = self.request_tool(
            "reveal_role",
            {"player_id": target}
        )
        return {"action": "reveal", "target": target, "info": result}

Agents query the world, propose actions, and react to other agents' moves through the game loop:


# File: chapter10/voice-werewolf/test_live_human.py

from werewolf.game import WerewolfGame

def play_demo():
    game = WerewolfGame(num_players=6)
    game.assign_roles()                 # Randomly picks agents for each role

    while not game.is_over():
        for agent in game.active_agents():
            action = agent.take_turn(game.world_snapshot(agent))
            game.apply_action(agent, action)
    print("Winner:", game.winner())

This demonstrates real-time context sharing while preserving role-specific privacy through selective state snapshots.

Context Sharing and Isolation Mechanisms

The framework implements sophisticated context sharing through explicit architectural controls rather than implicit shared memory.

Explicit Payload Objects

Communication between coordinator and agents happens via JSON payloads using the payload field in AgentResult. This makes data exchange transparent and debuggable, allowing developers to audit exactly what information transfers between agents. The explicit nature of these payloads prevents accidental leakage of internal state.

Selective World State Exposure

Each agent receives a snapshot of the world state containing only fields it is authorized to see. The coordinator builds these snapshots using AgentConfig objects from agentbook/providers/models.py. This isolation versus sharing balance ensures that agents operate with minimal necessary context while preventing cross-contamination of privileged information.

Memory Plugins for Long-Term Persistence

The framework supports plug-in memory back-ends (e.g., agentbook[mem]) that agents query to retrieve past observations or summaries. These memory plugins enable long-term context persistence across runs while maintaining isolation boundaries between different agent instances.

Why This Design Works

Modularity allows adding new agents by implementing the Agent subclass and registering it in the provider registry without modifying coordinator logic.

Scalability emerges from the MCP tool server architecture, where external tools run as subprocesses enabling parallel execution across multiple CPU cores.

Safety is enforced through strict control over world state exposure, preventing accidental leakage of privileged information between agents during multi-agent collaboration.

Summary

  • The staged-system-prompt framework in chapter10/staged-system-prompt/tools.py implements a coordinator pattern that decomposes tasks and aggregates results through explicit JSON payloads.
  • The Voice Werewolf simulation demonstrates real-time multi-agent collaboration with role-based context isolation using the Agent base class from agentbook/providers/models.py.
  • Context sharing is achieved through controlled payload objects rather than shared memory spaces, preventing information leakage between agents.
  • The MCP (Multi-Channel Protocol) tool server architecture enables parallel execution across multiple CPU cores via agentbook/providers/registry.py.
  • Memory plugins provide long-term context persistence while maintaining strict agent isolation boundaries.

Frequently Asked Questions

How does the framework prevent information leakage between agents?

The framework prevents information leakage by constructing selective world state snapshots for each agent using AgentConfig objects in agentbook/providers/models.py. Rather than sharing a global memory space, the coordinator explicitly defines which fields each agent can access. Agents communicate only through JSON payloads in the AgentResult structure, making data flow transparent and auditable.

What is the MCP tool server and how does it enable scalability?

The MCP (Multi-Channel Protocol) tool server is implemented in agentbook/providers/registry.py and dynamically discovers external tool capabilities. Each tool server runs as a lightweight subprocess using mcp.run(transport="stdio"), allowing parallel execution across multiple CPU cores. This architecture prevents tool execution from blocking the main orchestration thread, enabling concurrent agent operations.

Can I integrate custom agents into the staged-system-prompt framework?

Yes. You can integrate custom agents by implementing the Agent base class from agentbook/providers/models.py and registering the implementation in the provider registry. The coordinator in chapter10/staged-system-prompt/tools.py dynamically loads agents by type, requiring no modifications to the orchestration logic when adding new specialized capabilities.

How is multi-agent trajectory visualization implemented?

The framework records multi-agent interactions using a JSON schema defined in extras/agent-lab/SCHEMA.md. The Trajectory Visualiser component (extras/agent-lab/agent-trajectory.js) consumes this schema to render interactive replays of agent runs. This enables debugging complex multi-agent collaborations by replaying the sequence of payload exchanges and state transitions between coordinator and specialized agents.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →