teammate-mcp
teammate-mcp
Позвольте Claude Code и OpenAI Codex задавать друг другу вопросы через ваши панели iTerm. Никаких демонов. Никаких
.config, которые нужно редактировать вручную для каждого проекта. Просто откройте две панели, и они смогут общаться.
┌──────────── iTerm window ─────────────┐
│ claude (left) codex (right) │
│ ─────────────────── ─────────────── │
│ > implement quoter > [teammate-mcp │
│ I'll ask Codex... ASK ... what │
│ ⏺ Codex answered: is 2+2?] │
│ 4 • 4 │
└───────────────────────────────────────┘teammate-mcp — это крошечный MCP-сервер, который предоставляет два инструмента для любого
CLI, который его загружает:
mcp__teammate__ask_codex(question, timeout)— вызов из Claudemcp__teammate__ask_claude(question, timeout)— вызов из Codex
Сервер использует Python API iTerm2 для отправки вопроса в другую панель и считывания ответа. Целевая панель определяется автоматически запущенным процессом — вам не нужно помечать вкладки или что-либо настраивать для каждого проекта.
Зачем?
Существующие системы для работы с несколькими агентами делятся на два лагеря:
Тяжеловесные: демон, файлы конфигурации для каждого проекта, непрозрачное состояние сессии. Отлично работает, пока что-то не сломается в 2 часа ночи, и вы не поймете почему.
Однопроцессные: одна модель, управляющая под-агентами внутри себя, поэтому пользователь видит только финальный ответ.
teammate-mcp предлагает третий вариант: два агента наглядно работают в вашем терминале рядом друг с другом, вы можете читать оба транскрипта в реальном времени, а вся «инфраструктура» — это несколько сотен строк Python, которые отправляют текст и считывают содержимое экрана.
Related MCP server: claude-mux-iterm
Проверенный двусторонний цикл
Записано в реальном времени во время разработки на macOS 14, iTerm 3.6.8, Claude Code 2.1.119 + Opus 4.7, Codex 0.125.0:
{"event":"ask.enqueue","id":"…c5d085","from_":"claude","to":"codex","len":49}
{"event":"ask.send", "id":"…c5d085","to":"codex","session_id":"7E39032F-…"}
{"event":"ask.complete","id":"…c5d085","answer_len":3}Интервал ask.send → ask.complete составил 3,0 секунды для запроса «Сколько будет два плюс два? Ответь только цифрой» — большая часть этого времени уходит на размышления Codex, а не на мост. Пять последовательных запусков завершили цикл за 1,5–4,5 секунды.
Шесть независимых отчетов о времени выполнения, сохраненных в tests/results/, включены в репозиторий, чтобы вы могли самостоятельно проверить цифры.
Быстрый старт
1. Установка
git clone https://github.com/jonghklee/teammate-mcp.git
cd teammate-mcp
uv venv
uv pip install -e .2. Регистрация сервера в обоих CLI
# Claude Code
claude mcp add teammate -s user -- $PWD/.venv/bin/teammate-mcp serve
# Codex
codex mcp add teammate -- $PWD/.venv/bin/teammate-mcp serve3. Открытие панелей
У вас есть два варианта:
Вариант А — позвольте bin/team открыть для вас новое окно iTerm:
./bin/teamВариант Б — используйте любое уже открытое окно iTerm. Просто запустите
claude в одной панели и codex в другой. teammate-mcp найдет их
по имени процесса; метки не нужны.
4. (Один раз) Передайте агентам правила работы
Поместите templates/AGENTS.md в корень вашего проекта. И Claude Code, и Codex автоматически подхватят его (это соглашение, которому они оба следуют). Файл объясняет им, как и когда вызывать друг друга.
5. Попробуйте
В панели Claude:
Ask Codex what timezone library it prefers in Python and tell me what
it said.Вы увидите, как Claude вызывает mcp__teammate__ask_codex, вопрос появится в правой панели, Codex ответит, а Claude передаст ответ.
Как это работает
┌──────────────────────────────────────────────────────┐
│ Claude pane Codex pane │
│ ───────────── ───────────── │
│ user prompt [teammate-mcp ASK …] │
│ │ tool call ▲ │
│ ▼ │ async_send_text │
│ ┌──────────────┐ │ │
│ │ teammate-mcp │ ─────────────┘ │
│ │ (FastMCP) │ ◄────── async_get_screen_contents │
│ └──────────────┘ │
│ │ │
│ └─► returns extracted answer to Claude │
└──────────────────────────────────────────────────────┘Для каждого вызова ask_codex (или ask_claude):
Генерируется уникальный маркер, сообщение ставится в очередь на диске (
pending/→inflight/атомарное переименование).Находится целевая панель:
предпочтение отдается переменной окружения
TEAMMATE_<UPPER>_SESSION_IDв противном случае перечисляются все активные процессы (в стиле
ps), находится любой процессclaudeилиcodex, считывается его переменная окруженияTERM_SESSION_ID, и она сопоставляется со списком сессий iTerm. Это работает черезtmux, оболочки входа и обертки pyenv — везде, где наследуется переменная окружения.в качестве запасного варианта используется сопоставление
jobName/commandLineс предпочтением текущей рабочей директории (cwd).
async_send_textотправляет промпт + запрос завершить ответ маркером.Опрашивается
async_get_screen_contentsна наличие маркера. Поскольку промпт, который мы ввели, содержит текст маркера (он эхом отображается в панели), сервер требует, чтобы маркер появился дважды, прежде чем считать ответ завершенным.Ответ извлекается между двумя вхождениями маркера, записывается
ask.complete, ответ возвращается вызывающей стороне.
Что на самом деле означает «без конфигурации»
Есть ровно одна вещь, которую нужно настроить (один раз): регистрация MCP в шаге 2 выше. После этого любое окно iTerm с панелями claude+codex просто работает — включая окна, которые были открыты до установки teammate-mcp.
Вам никогда не нужно писать .teammate.toml, никогда не нужно делать teammate start, никогда не нужно запоминать, какой id сессии к чему относится.
Тестирование
uv pip install -e ".[dev]"
pytest # 18 unit + integration tests
python scripts/auto_demo.py # full end-to-end demo (spawns iTerm)Модульные тесты покрывают очередь, обработку ANSI/маркеров, импорт серверного модуля и логику обнаружения сессий iTerm с использованием заглушек (mocks). Сквозная демонстрация открывает реальное окно iTerm и выполняет цикл Claude → Codex → Claude; для этого требуется, чтобы оба CLI были авторизованы, и это повлечет за собой обычные расходы на API.
Отчеты о времени выполнения для каждого запуска записываются в tests/results/*.jsonl. Те, что уже закоммичены в репозиторий, являются реальными, а не синтетическими.
Устранение неполадок
«iTerm Python API is not enabled» — Настройки → Основные → Magic → «Enable Python API» ✓. При первом подключении teammate-mcp iTerm также запросит разрешение; нажмите Allow.
«asyncio.run() cannot be called from a running event loop» — вы используете версию teammate-mcp старше 0.1.0. Обновитесь до main; инструменты теперь объявлены как async.
«Инструмент вернул ответ, который является просто эхом моего собственного промпта» — целевая панель промпта запускает не тот CLI (например, поиск выбрал соседнюю панель, в которой запущен тот же процесс). Закрепите панель явно:
export TEAMMATE_CLAUDE_SESSION_ID=<unique id from iTerm>
export TEAMMATE_CODEX_SESSION_ID=<unique id from iTerm>(Вы можете прочитать unique id каждой панели в меню Window menu → Window Settings → Identifier или через AppleScript.)
«Маркер не обнаружен в течение времени ожидания» — агент на другом конце забыл вывести <<DONE_…>>. Добавьте явное напоминание в ваш AGENTS.md. Входящий в комплект шаблон уже включает это.
Лицензия
MIT — см. LICENSE.
Благодарности
Этот проект выкристаллизовался из обсуждений на основе публичных исследований того, как Claude Code и Codex используются в 2026 году:
Статьи Anthropic Plan-Generate-Verify и Initializer + Coding Agent (Rajasekaran 2026-03; Justin Young 2025-11).
claude-code-hooks-masteryот IndyDevDan за паттерны наблюдаемости.planning-with-filesот OthmanAdi за идею «структурированные файлы связывают сессии, а не историю чата».Правило «цикла верификации» Бориса Черного из его треда How I use Claude Code.
Цикл Ralph Wiggum от Джеффри Хантли за интуицию «свежий контекст для каждого хода».
Реализация обязана своими паттернами Python API iTerm документации iTerm2 по адресу https://iterm2.com/python-api/.
한국어 요약
CCB 같은 사전 설정 없이 claude / codex가 서로에게 질문할 수 있게 해주는 작은 MCP 서버입니다.
iTerm 두 페인에 그냥
claude와codex를 띄우기만 하면 됩니다. 라벨도, config도, daemon도 없습니다.iTerm Python API로 상대 페인을 자동 탐지(실행 프로세스 + 환경변수
TERM_SESSION_ID매칭)합니다 —tmux안에서 띄워도 작동합니다.메시지는 push, 응답은 polling으로 받고, 모든 round trip은
~/.teammate-mcp/logs/<날짜>.jsonl에 기록됩니다.실측 round-trip 시간: 2 + 2 = 4 질문 기준 send → complete 3.0초 (대부분 Codex thinking 시간).
설치는 위 영문 Quick start 1~3단계, 사용법은 그냥 평소처럼 Claude에게 "Codex에게 물어봐"라고 시키면 됩니다.
Available Tools
4 toolsask_claudeA
Ask the Claude pane a question and return its answer.
Use this from Codex when you want Claude's plan, design feedback, or a sanity check.
| Name | Required | Description | Default |
|---|---|---|---|
| question | Yes | ||
| timeout | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description must carry full burden. It only states it returns an answer, but does not disclose potential side effects, timeout behavior, or whether it is a read-only operation. The agent lacks critical behavioral context.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is concise with only two short sentences, no redundant information, and the primary action is front-loaded. Every word adds value.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The tool is simple with 2 parameters and an output schema, but the description lacks detail on the output format and usage constraints. An agent can infer basic usage but may miss nuances like timeout meaning or question style expectations.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 0%, yet the description adds no information about the 'question' or 'timeout' parameters beyond what the schema provides. For a tool with 2 parameters and no enum constraints, the description should compensate but fails to do so.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the verb 'Ask' and the resource 'Claude pane', specifying that it returns an answer. The sibling tool 'ask_codex' helps differentiate, making the purpose unambiguous.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description explicitly recommends using this tool for 'plan, design feedback, or a sanity check' from Codex, providing clear context. However, it does not mention when to avoid using this tool in favor of alternatives.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
ask_codexB
Ask the Codex pane a question and return its answer.
Use this from Claude when you want Codex's opinion, a code review, or to delegate execution to it.
| Name | Required | Description | Default |
|---|---|---|---|
| question | Yes | ||
| timeout | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations provided, and the description lacks behavioral details such as side effects, authentication requirements, rate limits, or any constraints. Merely states it returns an answer without elaboration.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Three sentences, no fluff. First sentence is clear; second adds usage guidance. Could be slightly more efficient, but overall well-structured for a simple tool.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Lacks details on return value format despite having an output schema. No information on how Codex processes the question or what happens with the timeout. Minimal guidance for an agent to use effectively.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, meaning no parameter descriptions in schema. The description does not explain the 'question' or 'timeout' parameters at all, adding zero value beyond the parameter names.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
Clearly states the verb 'ask' and the resource 'Codex pane', with explicit mention of returning an answer. Distinguishes from sibling 'ask_claude' by naming Codex specifically.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Explicitly says 'Use this from Claude when you want Codex's opinion, a code review, or to delegate execution to it', providing clear context and implicitly contrasting with alternatives.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
broadcastB
Push a message to both panes without waiting for a reply.
| Name | Required | Description | Default |
|---|---|---|---|
| message | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Without annotations, the description carries the burden. It discloses the key behavior of not waiting for a reply, but omits other behavioral traits like side effects, required permissions, or whether the message is stored. This is adequate for a simple tool but not comprehensive.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single sentence with no extraneous words. It is appropriately sized and front-loaded with the key action.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's simplicity (1 parameter, output schema exists), the description is minimally complete. It covers the core action and behavioral note, but does not explain 'both panes' or provide any usage context. It meets the minimum viability for a simple tool.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, so the description must compensate. It says 'message' but adds no detail beyond the schema's type string. It does not explain format, constraints, or expected values, which is insufficient for a parameter with no description in the schema.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool pushes a message to both panes without waiting for a reply, using a specific verb and resource. This distinguishes it from sibling tools like ask_claude and ask_codex, which likely expect replies, and queue_status for status checks.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides no guidance on when to use this tool over alternatives. It does not mention when not to use it or compare it to sibling tools, leaving the agent to infer usage.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
queue_statusA
Return queue counts + recent completions (debugging).
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, but the description clearly indicates it is a non-destructive read (returning counts and completions). There is no behavior beyond what is described, and no contradictions. A slight deduction for not explicitly stating read-only nature.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is extremely concise: a single sentence that immediately states the tool's purpose and context. No fluff or redundant information.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given zero parameters and no output schema, the description sufficiently describes the tool's output. It could be considered complete for a simple status check, though mentioning any authentication or availability requirements would improve completeness.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The input schema has no parameters (0 params, 100% coverage). The description adds value by specifying the return content (queue counts + recent completions). Baseline 4 is appropriate since the schema carries no burden.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool returns queue counts and recent completions, with 'debugging' context. It identifies the specific resource (queue status) and verb (return). It is well distinguished from siblings like ask_claude, ask_codex, and broadcast.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies usage for debugging via the parenthetical '(debugging)'. It does not explicitly state when to use vs. alternatives or when not to use, but the siblings are sufficiently different, so the guidance is adequate but minimal.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
4 tool updates
v0.1.0- First observed
ask_claude - First observed
ask_codex - First observed
broadcast - First observed
queue_status
TDQS
Scored across 4 tools
Each tool has a distinct purpose: ask_claude and ask_codex target specific panes, broadcast sends to both without waiting, and queue_status provides debugging info. No overlap.
All tool names use lowercase with underscores and follow a consistent verb_noun pattern (ask_claude, ask_codex, queue_status) or are a clear verb (broadcast).
4 tools is well-scoped for the server's purpose of inter-pane communication, covering questioning each pane, broadcasting, and status monitoring.
Core workflows are covered, but a minor gap exists: there is no tool to send a one-way message to a specific pane without expecting a reply (only broadcast to both).
Maintenance
Related MCP Connectors
Share context and questions between Claude instances — VS Code, claude.ai web, and mobile.
Use your Mac, Windows or Linux computer from ChatGPT, Claude or Codex: files, commands, documents.
Work on your own computers from Claude or ChatGPT: run commands, edit and search files.
Shared memory for AI tools: save once, recall word for word from Claude, ChatGPT, Codex or Gemini.
Related MCP Servers
- AlicenseAqualityDmaintenanceOrchestrates multiple Claude Code agents across iTerm2 sessions with process-level isolation, enabling collaborative AI development workflows on multiple codebases with task-based inter-agent communication and persistent state management.71MIT
- AlicenseAqualityCmaintenanceEnables communication between Claude Code sessions in iTerm2 panes, primarily for notifying other sessions when a PR is merged to main so they can pull latest changes.6MIT
- AlicenseNot gradedqualityCmaintenanceEnables Claude Desktop to spawn new Claude Code instances in iTerm2 windows for interactive coding sessions.13 npmMIT
- FlicenseNot gradedqualityDmaintenanceGives Claude Code terminal control and multi-agent coordination through tmux sessions.4-