Skip to main content
Glama
TAO-MINGYU

Codex to OpenCode MCP Server

by TAO-MINGYU

Codex to OpenCode MCP Server

Небольшой локальный MCP-сервер (Model Context Protocol), который позволяет Codex делегировать работу над кодом в OpenCode. В нём используются официальный MCP Python SDK, транспорт stdio и асинхронный дочерний процесс OpenCode.

Инструменты

opencode_execute

opencode_execute(
    task: str,
    working_directory: str,
    model: str | None = None,
    reasoning_effort: str | None = None,
    timeout: int = 1800,
)

Выполняет эту команду без оболочки:

opencode run --format json --dir <working_directory> --auto [--model <model>] [--variant <reasoning_effort>] <task>

reasoning_effort сопоставляется со специфичной для провайдера опцией OpenCode --variant. Обычные значения включают minimal, low, medium, high и max, но доступные варианты определяются выбранным провайдером и моделью. MCP-сервер намеренно принимает любое непустое значение, а не применяет принудительное перечисление, зависящее от провайдера.

Пример:

opencode_execute(
    task="Implement uncertainty propagation and run the unit tests.",
    working_directory="C:\\path\\to\\NuSR",
    model="pinche_10/gpt-5.6-sol",
    reasoning_effort="high",
    timeout=1800,
)

Инструмент возвращает структурированный вывод, содержащий:

  • признак успеха, таймаут, код возврата и затраченное время;

  • идентификатор сеанса OpenCode и итоговую сводку ассистента;

  • выполненные вызовы инструментов OpenCode и ошибки;

  • ограниченные по размеру захваты stdout/stderr;

  • итоговые git status --short, git diff --stat и ограниченный unified diff.

Поля Git — это снимки состояния после завершения работы. Они могут включать изменения, которые уже существовали до вызова. Текстовое содержимое неотслеживаемых файлов представлено в виде патчей новых файлов; по бинарным неотслеживаемым файлам сообщаются их путь и размер.

opencode_check

Определяет настроенный исполняемый файл OpenCode и выполняет opencode --version, не изменяя окружение.

Related MCP server: Claude Code Manager WAN

Установка

Требования: Python 3.11+, Git (необязательно для вывода diff) и OpenCode.

git clone https://github.com/TAO-MINGYU/codex_to_opencode.git
cd codex_to_opencode
uv venv --python 3.11 .venv
uv pip install --python .venv\Scripts\python.exe -e ".[dev]"

OpenCode должен быть установлен и аутентифицирован независимо. Сначала проверьте его:

opencode --version
opencode auth list

Десктопное приложение OpenCode и CLI OpenCode — это разные точки входа в Windows. Вызов OpenCode.exe --version, который открывает графический интерфейс и ничего не печатает, не является рабочим CLI. При необходимости установите официальный CLI:

npm install -g opencode-ai

Если opencode отсутствует в PATH, задайте переменную OPENCODE_MCP_COMMAND, указав абсолютный путь к исполняемому файлу. В npm-установках на Windows предпочитайте нативный бинарник в каталоге node_modules\opencode-ai\bin\opencode.exe; сервер также автоматически обнаруживает и обходит обёртку opencode.cmd.

Подключение Codex

Подключите сервер через Codex CLI — так не придётся редактировать конфигурацию вручную:

codex mcp add opencode --env OPENCODE_MCP_COMMAND=C:\path\to\opencode.exe -- C:\path\to\opencode-mcp\.venv\Scripts\python.exe -m opencode_mcp.server

Когда OpenCode уже есть в PATH, просто опустите опцию --env:

codex mcp add opencode -- C:\path\to\opencode-mcp\.venv\Scripts\python.exe -m opencode_mcp.server

Затем проверьте регистрацию:

codex mcp list

После изменения конфигурации MCP перезапустите Codex. Сервер записывает протокольные сообщения только в stdout, а журналы направляет в stderr, как требует MCP-серверов c транспортом stdio.

Конфигурация

Переменная окружения

По умолчанию

Назначение

OPENCODE_MCP_COMMAND

opencode

Имя исполняемого файла или абсолютный путь

OPENCODE_MCP_ARGS

[]

JSON-массив, вставляемый сразу после исполняемого файла (удобно для обёрток/тестов)

OPENCODE_MCP_AUTO_APPROVE

true

Добавление флага разрешений --auto для OpenCode

OPENCODE_MCP_MAX_OUTPUT_BYTES

2097152

Количество конечных байт, сохраняемых по отдельности для stdout и stderr

OPENCODE_MCP_LOG_LEVEL

INFO

Уровень журналирования сервера, выводящийся в stderr

Установка автоподтверждения в значение false заставляет OpenCode отклонять права, которые он не может запросить в интерактивном режиме:

$env:OPENCODE_MCP_AUTO_APPROVE = "false"

Отладка

Запустите автоматизированные тесты:

.venv\Scripts\python.exe -m pytest --cov=opencode_mcp --cov-fail-under=80
.venv\Scripts\python.exe -m ruff check .
.venv\Scripts\python.exe -m ruff format --check .

Запустите сервер с помощью MCP Inspector:

uv run --python 3.11 --with-editable ".[dev]" mcp dev src\opencode_mcp\server.py

Таймаут MCP-инструмента должен быть немного больше значения timeout, передаваемого в opencode_execute; в противном случае Codex может отменить MCP-запрос до того, как сервер завершится процессом OpenCode и вернёт диагностические сведения.

Модель безопасности

opencode_execute намеренно возможностью записи и потенциально разрушительным инструментом. Он предоставляет OpenCode те же права на файловую систему и процессы, которые есть у самого MCP-сервера. Реализация:

  • никогда не вызывает оболочку для задач OpenCode;

  • требует существующий абсолютный путь к рабочему каталогу;

  • ограничивает захватываемый вывод, защищая контекст Codex;

  • завершает дерево процессов OpenCode при таймауте или отмене MCP-запроса;

  • отключает автоматическое обновление OpenCode во время делегированных выполнений;

  • помечаются MCP-инструментом как неидемпотентный и потенциально-разрушающий.

Для недоверенных задач или репозиториев используйте ограниченную учётную запись ОС или песочницу.

Available Tools

2 tools
opencode_checkCheck the local OpenCode installationA
Read-onlyIdempotent

Resolve the configured OpenCode executable and report its version.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

Output Schema

ParametersJSON Schema
NameRequiredDescription
errorYes
commandYes
versionYes
availableYes
resolved_executableYes

TDQS

A4.5/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already declare readOnlyHint, idempotentHint, and destructiveHint, covering the safety profile. The description adds behavioral detail beyond those annotations by stating the tool resolves a configured executable, which implies reading configuration and locating a binary. No contradiction with annotations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

A single, front-loaded sentence states the key action and outcome, with no filler or redundant detail. Every word earns its space.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The tool has no parameters, a complete annotation set, and an output schema, so the description only needs to convey the high-level purpose and behavior. It does so completely for this simple check operation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

There are zero parameters, so the baseline is 4. The description does not need to explain any parameters, and the schema fully covers them.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description uses a specific verb-resource pair: 'Resolve the configured OpenCode executable and report its version.' It clearly identifies both the action and the subject, and the title reinforces the purpose. It is also easily distinguishable from the sibling tool opencode_execute, which implies running commands rather than checking the installation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies a clear context: this is a verification or preflight check of the local OpenCode installation, distinct from execution. While it does not explicitly cite when-or-when-not to use it relative to opencode_execute, the 'check' framing and resolved-executable behavior provide clear usage context without exclusions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

opencode_executeExecute a coding task with OpenCodeA
Destructive

Delegate one repository coding task to OpenCode.

OpenCode runs non-interactively in the supplied directory, may read and modify files, execute terminal commands, run tests, and use Git. The result contains OpenCode's final text, observed tool calls, diagnostics, and the final Git working-tree diff. The Git diff is a post-run snapshot and can include changes that existed before this call.

ParametersJSON Schema
NameRequiredDescriptionDefault
taskYesComplete coding task and acceptance criteria for OpenCode.
modelNoOptional OpenCode model in provider/model form; omit for its configured default.
timeoutNoMaximum execution time in seconds (default 1800).
reasoning_effortNoOptional provider-specific reasoning effort passed to OpenCode as --variant, for example minimal, low, medium, high, or max.
working_directoryYesAbsolute path to the existing project directory OpenCode may modify.

Output Schema

ParametersJSON Schema
NameRequiredDescription
modelYes
errorsYes
stderrYes
stdoutYes
successYes
summaryYes
git_diffYes
exit_codeYes
timed_outYes
git_statusYes
session_idYes
git_diff_statYes
elapsed_secondsYes
output_truncatedYes
reasoning_effortYes
tool_invocationsYes
working_directoryYes
git_diff_truncatedYes

TDQS

A3.8/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

The description adds meaningful behavior over the annotations (destructiveHint=true, readOnlyHint=false) by disclosing non-interactive execution, possible file modifications, CLI/Git actions, and execution of tests. It also warns that the returned Git diff is a post-run snapshot and may include pre-existing changes. This is useful, though it does not enumerate every destructive action or limitation.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is focused: one purpose-driven opening sentence followed by a terse but information-dense paragraph about behavior and result shape. Every sentence earns its place, including the important Git-diff caveat. The length is appropriate for the tool's complexity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

With a complete input schema and an output schema present, the description covers the main operational ambiguity: non-interactive execution, mutation of files, and the non-isolated nature of the Git diff. It is mostly complete, but it leaves the distinction versus opencode_check unstated, and it does not describe interaction between the timeout/model parameters and the result.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100%, so the parameter descriptions in the schema already carry the meaning for task, working_directory, model, timeout, and reasoning_effort. The tool description does not add extra parameter syntax, examples, or semantic clarifications beyond what the schema provides.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description immediately states a specific operation: delegating one repository coding task to OpenCode, and enumerates what the tool can do (read/modify files, run commands, tests, Git). It is clear, but it does not explicitly contrast with the sibling tool opencode_check, so it stops short of full differentiation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The first sentence implies the usage: delegate a coding task to OpenCode. The description also clarifies that it runs non-interactively in a repository, which helps the agent set expectations. However, there is no explicit 'when not to use' or comparison with the sibling opencode_check; usage guidance is present but largely implicit.

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. Dates show when Glama detected each change.

  1. 2 tool updatesv0.1.0
    • First observedopencode_check
    • First observedopencode_execute

TDQS

A4/5.0
Disambiguation4/5

The two tools have clearly distinct roles: opencode_execute delegates a coding task, while opencode_check resolves the executable and reports its version. There is no realistic confusion between performing an action and checking the installation.

Naming Consistency5/5

Both tools use the same opencode_ prefix followed by a concise imperative verb, maintaining a consistent snake_case pattern. Though the prefix is a product name, the convention is uniform and predictable.

Tool Count3/5

Two tools is at the low end of typical server scope and feels thin for a coding integration. However, the narrow focus on delegating a single task plus a health check is reasonable enough to be borderline appropriate.

Completeness4/5

The server covers its core purpose: opencode_execute handles task delegation, and opencode_check verifies the underlying executable. Obvious lifecycle tools such as cancellation or querying current task status are absent, but they fall outside the stated minimal purpose.

Maintenance

ActivityMaintained
ResponsivenessNo issues

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/TAO-MINGYU/codex_to_opencode'

If you have feedback or need assistance with the MCP directory API, please join our Discord server