Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ venv/
*.so
.DS_Store
.mcp.json
.opencode/opencode.json
105 changes: 59 additions & 46 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

# claude-teams

MCP server that implements Claude Code's [agent teams](https://code.claude.com/docs/en/agent-teams) protocol.
MCP server that implements Claude Code's [agent teams](https://code.claude.com/docs/en/agent-teams) protocol for any MCP client.

</div>

Expand All @@ -12,37 +12,31 @@ https://github.com/user-attachments/assets/531ada0a-6c36-45cd-8144-a092bb9f9a19



## About

Claude Code has a built-in agent teams feature that lets multiple Claude Code instances coordinate as a team -- shared task lists, inter-agent messaging, and tmux-based spawning. But the protocol is internal, tightly coupled to Claude Code's own tooling.

This MCP server reimplements that protocol as a standalone [MCP](https://modelcontextprotocol.io/) server, making it available to any MCP client: [Claude Code](https://docs.anthropic.com/en/docs/claude-code), [OpenCode](https://opencode.ai), or anything else that speaks MCP.

The implementation is based on a [deep dive into Claude Code's internals](https://gist.github.com/cs50victor/0a7081e6824c135b4bdc28b566e1c719) and experimentation with the feature. It may not perfectly match every aspect of Claude Code's native implementation. PRs are welcome.
Claude Code has a built-in agent teams feature (shared task lists, inter-agent messaging, tmux-based spawning), but the protocol is internal and tightly coupled to its own tooling. This MCP server reimplements that protocol as a standalone [MCP](https://modelcontextprotocol.io/) server, making it available to any MCP client: [Claude Code](https://docs.anthropic.com/en/docs/claude-code), [OpenCode](https://opencode.ai), or anything else that speaks MCP. Based on a [deep dive into Claude Code's internals](https://gist.github.com/cs50victor/0a7081e6824c135b4bdc28b566e1c719). PRs welcome.

## Install

Add to your project's `.mcp.json` (Claude Code):
Claude Code (`.mcp.json`):

```json
{
"mcpServers": {
"claude-teams": {
"command": "uvx",
"args": ["--from", "git+https://github.com/cs50victor/claude-code-teams-mcp", "claude-teams"]
"args": ["--from", "git+https://github.com/cs50victor/claude-code-teams-mcp@v0.1.0", "claude-teams"]
}
}
}
```

Or add to `~/.config/opencode/opencode.json` (OpenCode):
OpenCode (`~/.config/opencode/opencode.json`):

```json
{
"mcp": {
"claude-teams": {
"type": "local",
"command": ["uvx", "--from", "git+https://github.com/cs50victor/claude-code-teams-mcp", "claude-teams"],
"command": ["uvx", "--from", "git+https://github.com/cs50victor/claude-code-teams-mcp@v0.1.0", "claude-teams"],
"enabled": true
}
}
Expand All @@ -53,50 +47,69 @@ Or add to `~/.config/opencode/opencode.json` (OpenCode):

- Python 3.12+
- [tmux](https://github.com/tmux/tmux)
- At least one coding agent CLI on PATH:
- [Claude Code](https://docs.anthropic.com/en/docs/claude-code) (`claude`)
- [OpenCode](https://opencode.ai) (`opencode`)
- For OpenCode teammates:
- `OPENCODE_SERVER_URL` must be set (for example, `http://localhost:4096`)
- the `claude-teams` MCP server must be connected in that OpenCode instance
- At least one coding agent on PATH: [Claude Code](https://docs.anthropic.com/en/docs/claude-code) (`claude`) or [OpenCode](https://opencode.ai) (`opencode`)
- OpenCode teammates require `OPENCODE_SERVER_URL` and the `claude-teams` MCP connected in that instance

## Configuration

| Variable | Description | Default |
|----------|-------------|---------|
| `CLAUDE_TEAMS_BACKENDS` | Comma-separated enabled backends (`claude`, `opencode`) | Auto-detect from connecting client |
| `OPENCODE_SERVER_URL` | OpenCode HTTP API URL (required for opencode teammates) | *(unset)* |
| `USE_TMUX_WINDOWS` | Spawn teammates in tmux windows instead of panes | *(unset)* |

Without `CLAUDE_TEAMS_BACKENDS`, the server auto-detects the connecting client and enables only its backend. Set it explicitly to enable multiple backends:

```json
{
"mcpServers": {
"claude-teams": {
"command": "uvx",
"args": ["--from", "git+https://github.com/cs50victor/claude-code-teams-mcp@v0.1.0", "claude-teams"],
"env": {
"CLAUDE_TEAMS_BACKENDS": "claude,opencode",
"OPENCODE_SERVER_URL": "http://localhost:4096"
}
}
}
}
```

## Tools

| Tool | Description |
|------|-------------|
| `team_create` | Create a new agent team. One team per server session. |
| `team_delete` | Delete a team and all its data. Fails if teammates are still active. |
| `spawn_teammate` | Spawn a teammate in tmux (pane by default, window when `USE_TMUX_WINDOWS` is set). |
| `send_message` | Send direct messages (teammates to team-lead), broadcasts (team-lead only), and shutdown/plan responses. |
| `read_inbox` | Read messages from an agent's inbox. |
| `poll_inbox` | Long-poll an inbox for new messages (up to 30s). |
| `read_config` | Read team configuration and member list. |
| `task_create` | Create a new task with auto-incrementing ID. |
| `task_update` | Update task status, owner, dependencies, or metadata. |
| `task_list` | List all tasks for a team. |
| `task_get` | Get full details of a specific task. |
| `force_kill_teammate` | Forcibly kill a teammate's tmux pane/window and clean up. |
| `process_shutdown_approved` | Remove a teammate after graceful shutdown approval. |

## How it works

- **Spawning**: Teammates launch in tmux via `tmux split-window` (default) or `tmux new-window` when `USE_TMUX_WINDOWS` is set. Backend can be Claude (`claude`) or OpenCode (`opencode`). Each gets a unique agent ID (`name@team`) and color.
- **Messaging**: JSON inboxes live under `~/.claude/teams/<team>/inboxes/`. Team lead can message anyone; teammates can message only team lead.
- **Tasks**: JSON task files under `~/.claude/tasks/<team>/`. Tasks have status tracking, ownership, and dependency management (`blocks`/`blockedBy`).
- **Concurrency safety**: Atomic config writes via `tempfile` + `os.replace` (with Windows retry). Cross-platform file locks via `filelock`.

## Storage layout
| `team_create` | Create a new agent team (one per session) |
| `team_delete` | Delete team and all data (fails if teammates active) |
| `spawn_teammate` | Spawn a teammate in tmux |
| `send_message` | Send DMs, broadcasts (lead only), shutdown/plan responses |
| `read_inbox` | Read messages from an agent's inbox |
| `poll_inbox` | Long-poll inbox for new messages (up to 30s) |
| `read_config` | Read team config and member list |
| `task_create` | Create a task (auto-incrementing ID) |
| `task_update` | Update task status, owner, dependencies, or metadata |
| `task_list` | List all tasks |
| `task_get` | Get full task details |
| `force_kill_teammate` | Kill a teammate's tmux pane/window and clean up |
| `process_shutdown_approved` | Remove teammate after graceful shutdown |

## Architecture

- **Spawning**: Teammates launch in tmux panes (default) or windows (`USE_TMUX_WINDOWS`). Each gets a unique agent ID and color.
- **Messaging**: JSON inboxes at `~/.claude/teams/<team>/inboxes/`. Lead messages anyone; teammates message only lead.
- **Tasks**: JSON files at `~/.claude/tasks/<team>/`. Status tracking, ownership, and dependency management.
- **Concurrency**: Atomic writes via `tempfile` + `os.replace`. Cross-platform file locks via `filelock`.

```
~/.claude/
├── teams/<team-name>/
│ ├── config.json # team config + member list
├── teams/<team>/
│ ├── config.json
│ └── inboxes/
│ ├── team-lead.json # lead agent inbox
│ ├── worker-1.json # teammate inboxes
│ ├── team-lead.json
│ ├── worker-1.json
│ └── .lock
└── tasks/<team-name>/
├── 1.json # task files (auto-incrementing IDs)
└── tasks/<team>/
├── 1.json
├── 2.json
└── .lock
```
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ requires-python = ">=3.12"
license = "MIT"
dependencies = [
"fastmcp==3.0.0b1",
"filelock>=3.16",
"filelock==3.16",
]

[dependency-groups]
Expand Down
138 changes: 126 additions & 12 deletions src/claude_teams/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
import os
import time
import uuid
from types import SimpleNamespace
from typing import Any, Literal

from fastmcp import Context, FastMCP
from fastmcp.exceptions import ToolError
from fastmcp.server.lifespan import lifespan
from fastmcp.server.middleware import Middleware

from claude_teams import messaging, opencode_client, tasks, teams
from claude_teams.models import (
Expand All @@ -30,6 +32,33 @@

logger = logging.getLogger(__name__)

KNOWN_CLIENTS: dict[str, str] = {
"claude-code": "claude",
"claude": "claude",
"opencode": "opencode",
}

# NOTE(victor): Mutated by both app_lifespan and HarnessDetectionMiddleware.
# Safe under stdio (single session). Racy under SSE/streamable HTTP.
#
# more context:
# app_lifespan yields _lifespan_state
# -> _lifespan_manager stores as self._lifespan_result (same ref)
# -> _lifespan_proxy yields self._lifespan_result
# -> ctx.lifespan_context in tool handlers returns it
# All references point to the same dict. Middleware mutations propagate.
_lifespan_state: dict[str, Any] = {}
_spawn_tool: Any = None


_VALID_BACKENDS = frozenset(KNOWN_CLIENTS.values())


def _parse_backends_env(raw: str) -> list[str]:
if not raw:
return []
return list(dict.fromkeys(b.strip() for b in raw.split(",") if b.strip() and b.strip() in _VALID_BACKENDS))


_SPAWN_TOOL_BASE_DESCRIPTION = (
"Spawn a new teammate in a tmux {target}. The teammate receives its initial "
Expand All @@ -44,20 +73,26 @@ def _build_spawn_description(
opencode_models: list[str],
opencode_server_url: str | None = None,
opencode_agents: list[dict] | None = None,
enabled_backends: list[str] | None = None,
) -> str:
tmux_target = "window" if use_tmux_windows() else "pane"
parts = [_SPAWN_TOOL_BASE_DESCRIPTION.format(target=tmux_target)]
backends = []
if claude_binary:
show_claude = claude_binary is not None
show_opencode = opencode_binary is not None and opencode_server_url is not None
if enabled_backends is not None:
show_claude = show_claude and "claude" in enabled_backends
show_opencode = show_opencode and "opencode" in enabled_backends
if show_claude:
backends.append("'claude' (default, models: sonnet, opus, haiku)")
if opencode_binary and opencode_server_url:
if show_opencode:
model_list = (
", ".join(opencode_models) if opencode_models else "none discovered"
)
backends.append(f"'opencode' (models: {model_list})")
if backends:
parts.append(f"Available backends: {'; '.join(backends)}.")
if opencode_agents:
if show_opencode and opencode_agents:
agent_lines = [f" - {a['name']}: {a['description']}" for a in opencode_agents]
parts.append(
"Available opencode agents (pass as subagent_type when backend_type='opencode'):\n"
Expand All @@ -66,8 +101,24 @@ def _build_spawn_description(
return " ".join(parts)


def _update_spawn_tool(tool, enabled: list[str], state: dict[str, Any]) -> None:
tool.parameters["properties"]["backend_type"]["enum"] = list(enabled)
if enabled:
tool.parameters["properties"]["backend_type"]["default"] = enabled[0]
tool.description = _build_spawn_description(
state.get("claude_binary"),
state.get("opencode_binary"),
state.get("opencode_models", []),
state.get("opencode_server_url"),
state.get("opencode_agents"),
enabled_backends=enabled,
)


@lifespan
async def app_lifespan(server):
global _spawn_tool

claude_binary = discover_harness_binary("claude")
opencode_binary = discover_harness_binary("opencode")
if not claude_binary and not opencode_binary:
Expand All @@ -87,23 +138,81 @@ async def app_lifespan(server):
logger.warning(
"Failed to fetch opencode agents from %s", opencode_server_url
)

enabled_backends = _parse_backends_env(os.environ.get("CLAUDE_TEAMS_BACKENDS", ""))
if "opencode" in enabled_backends and not opencode_server_url:
enabled_backends.remove("opencode")

tool = await mcp.get_tool("spawn_teammate")
tool.description = _build_spawn_description(
claude_binary,
opencode_binary,
opencode_models,
opencode_server_url,
opencode_agents,
)
_spawn_tool = tool

if enabled_backends:
_update_spawn_tool(tool, enabled_backends, {
"claude_binary": claude_binary,
"opencode_binary": opencode_binary,
"opencode_models": opencode_models,
"opencode_server_url": opencode_server_url,
"opencode_agents": opencode_agents,
})
else:
tool.description = _build_spawn_description(
claude_binary, opencode_binary, opencode_models,
opencode_server_url, opencode_agents,
)

session_id = str(uuid.uuid4())
yield {
_lifespan_state.clear()
_lifespan_state.update({
"claude_binary": claude_binary,
"opencode_binary": opencode_binary,
"opencode_server_url": opencode_server_url,
"opencode_agents": opencode_agents,
"opencode_models": opencode_models,
"enabled_backends": enabled_backends,
"session_id": session_id,
"active_team": None,
}
"client_name": "unknown",
"client_version": "unknown",
})
yield _lifespan_state


class HarnessDetectionMiddleware(Middleware):
# NOTE(victor): ctx.lifespan_context returns {} during on_initialize because
# RequestContext isn't established yet. Client info is accessible from tool
# handlers via ctx.session.client_params.clientInfo (stored by the MCP SDK).

async def on_initialize(self, context, call_next):
_unknown = SimpleNamespace(name="unknown", version="unknown")
client_info = context.message.params.clientInfo or _unknown
client_name = client_info.name
client_version = client_info.version

result = await call_next(context)

logger.info("MCP client connected: %s v%s", client_name, client_version)

native_backend = KNOWN_CLIENTS.get(client_name)
enabled = _lifespan_state.get("enabled_backends", [])

if native_backend and native_backend not in enabled:
if native_backend == "claude" or _lifespan_state.get("opencode_server_url"):
enabled.append(native_backend)

if not enabled:
if _lifespan_state.get("claude_binary"):
enabled.append("claude")
if _lifespan_state.get("opencode_binary") and _lifespan_state.get("opencode_server_url"):
enabled.append("opencode")

_lifespan_state["enabled_backends"] = enabled
_lifespan_state["client_name"] = client_name
_lifespan_state["client_version"] = client_version

if _spawn_tool:
_update_spawn_tool(_spawn_tool, enabled, _lifespan_state)

return result


mcp = FastMCP(
Expand All @@ -114,6 +223,7 @@ async def app_lifespan(server):
),
lifespan=app_lifespan,
)
mcp.add_middleware(HarnessDetectionMiddleware())


def _get_lifespan(ctx: Context) -> dict[str, Any]:
Expand Down Expand Up @@ -167,6 +277,9 @@ def spawn_teammate_tool(
"""Spawn a new teammate in tmux. Description is dynamically updated
at startup with available backends and models."""
ls = _get_lifespan(ctx)
enabled = ls.get("enabled_backends", [])
if enabled and backend_type not in enabled:
raise ToolError(f"Backend {backend_type!r} is not enabled. Enabled: {enabled}")
opencode_agent = None
if backend_type == "opencode":
known = {a["name"] for a in ls.get("opencode_agents", [])}
Expand Down Expand Up @@ -624,6 +737,7 @@ def process_shutdown_approved(team_name: str, agent_name: str, ctx: Context) ->


def main():
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
mcp.run()


Expand Down
Loading