Codex to OpenCode MCP Server
Codex to OpenCode MCP Server
Un pequeño servidor local de MCP (Model Context Protocol) que permite a Codex delegar trabajo de programación en OpenCode. Usa el SDK oficial de MCP para Python, el transporte stdio y un subproceso asíncrono de OpenCode.
Herramientas
opencode_execute
opencode_execute(
task: str,
working_directory: str,
model: str | None = None,
reasoning_effort: str | None = None,
timeout: int = 1800,
)Ejecuta este comando sin shell:
opencode run --format json --dir <working_directory> --auto [--model <model>] [--variant <reasoning_effort>] <task>reasoning_effort se corresponde con la opción --variant específica del proveedor de OpenCode. Los valores comunes incluyen minimal, low, medium, high y max, pero las variantes disponibles las define el proveedor y el modelo seleccionados. El servidor MCP acepta a propósito cualquier valor no vacío, en lugar de imponer una enumeración específica del proveedor.
Ejemplo:
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,
)Devuelve una salida estructurada que contiene:
éxito, timeout, código de salida y tiempo transcurrido;
el ID de la sesión de OpenCode y el resumen final del asistente;
las llamadas a herramientas de OpenCode completadas y los errores de las llamadas;
capturas acotadas de stdout/stderr;
un
git status --shortfinal, ungit diff --staty un diff unificado acotado.
Los campos de Git son instantáneas posteriores a la ejecución. Pueden incluir cambios que ya existían antes de la llamada. El contenido de texto de los archivos sin seguimiento se representa como parches de archivo nuevo; los archivos binarios sin seguimiento se informan con su ruta y tamaño.
opencode_check
Resuelve el ejecutable de OpenCode configurado y ejecuta opencode --version sin modificar el entorno.
Related MCP server: BoundedRelay
Instalación
Requisitos: Python 3.11+, Git (opcional para informar diffs) y 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 debe instalarse y autenticarse de forma independiente. Verifícalo primero:
opencode --version
opencode auth listLa aplicación de escritorio de OpenCode y la CLI de OpenCode son puntos de entrada distintos en Windows. La invocación de OpenCode.exe --version que abre la GUI y no imprime nada no es una CLI utilizable. Instala la CLI oficial cuando sea necesario:
npm install -g opencode-aiSi opencode no está en PATH, define OPENCODE_MCP_COMMAND con la ruta absoluta del ejecutable. En las instalaciones npm de Windows, prefiere el binario nativo incluido en node_modules\opencode-ai\bin\opencode.exe; el servidor también detecta y omite automáticamente el envoltorio opencode.cmd.
Conectar Codex
Añade el servidor a través de la CLI de Codex, lo que evita tener que editar la configuración manualmente:
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.serverCuando OpenCode ya está en PATH, omite la opción --env:
codex mcp add opencode -- C:\path\to\opencode-mcp\.venv\Scripts\python.exe -m opencode_mcp.serverLuego verifica el registro:
codex mcp listReinicia Codex después de cambiar la configuración de MCP. El servidor escribe mensajes de protocolo únicamente en stdout y envía los logs a stderr, como requiere para los servidores MCP stdio.
Configuración
Variable de entorno | Valor por defecto | Significado |
|
| Nombre del ejecutable o ruta absoluta |
|
| Matriz JSON insertada después del ejecutable (útil para wrappers/pruebas) |
|
| Añade el indicador de permisos |
|
| Bytes finales que se conservan de forma independiente para stdout/stderr |
|
| Nivel de log del servidor escrito en stderr |
Si se establece la aprobación automática en false, OpenCode rechaza los permisos que no puede solicitar de forma interactiva:
$env:OPENCODE_MCP_AUTO_APPROVE = "false"Debug
Ejecuta las pruebas automatizadas:
.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 .Ejecuta el servidor con MCP Inspector:
uv run --python 3.11 --with-editable ".[dev]" mcp dev src\opencode_mcp\server.pyEl timeout de la herramienta MCP debe ser ligeramente superior al timeout pasado a opencode_execute; de lo contrario, Codex puede cancelar la solicitud MCP antes de que el servidor pueda terminar OpenCode y devolver los diagnósticos.
Modelo de seguridad
opencode_execute es una herramienta con capacidad de escritura y, a propósito, potencialmente destructiva. Concede a OpenCode los mismos permisos de sistema de archivos y procesos que tiene el servidor MCP. La implementación:
nunca invoca un shell para las tareas de OpenCode;
exige una ruta absoluta existente del directorio de trabajo;
limita la salida capturada para proteger el contexto de Codex;
termina el árbol de procesos de OpenCode en ejecución si se agota el timeout o si la petición MCP se cancela;
desactiva la actualización automática de OpenCode durante las ejecuciones delegadas;
marca la herramienta MCP como no idempotente y de forma potencialmente destructiva.
Usa una cuenta de sistema operativo con privilegios restringidos o un sandbox cuando delegues tareas o repositorios no confiables.
Available Tools
2 toolsopencode_checkCheck the local OpenCode installationARead-onlyIdempotent
Resolve the configured OpenCode executable and report its version.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
Output Schema
| Name | Required | Description |
|---|---|---|
| error | Yes | |
| command | Yes | |
| version | Yes | |
| available | Yes | |
| resolved_executable | Yes |
TDQS
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.
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.
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.
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.
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.
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 OpenCodeADestructive
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.
| Name | Required | Description | Default |
|---|---|---|---|
| task | Yes | Complete coding task and acceptance criteria for OpenCode. | |
| model | No | Optional OpenCode model in provider/model form; omit for its configured default. | |
| timeout | No | Maximum execution time in seconds (default 1800). | |
| reasoning_effort | No | Optional provider-specific reasoning effort passed to OpenCode as --variant, for example minimal, low, medium, high, or max. | |
| working_directory | Yes | Absolute path to the existing project directory OpenCode may modify. |
Output Schema
| Name | Required | Description |
|---|---|---|
| model | Yes | |
| errors | Yes | |
| stderr | Yes | |
| stdout | Yes | |
| success | Yes | |
| summary | Yes | |
| git_diff | Yes | |
| exit_code | Yes | |
| timed_out | Yes | |
| git_status | Yes | |
| session_id | Yes | |
| git_diff_stat | Yes | |
| elapsed_seconds | Yes | |
| output_truncated | Yes | |
| reasoning_effort | Yes | |
| tool_invocations | Yes | |
| working_directory | Yes | |
| git_diff_truncated | Yes |
TDQS
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.
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.
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.
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.
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.
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.
2 tool updates
v0.1.0- First observed
opencode_check - First observed
opencode_execute
TDQS
Scored across 2 tools
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.
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.
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.
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
Related MCP Connectors
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.
Source-checked CLI guides and model-aware planning for Claude Code, Codex, and Grok Build.
Operate Linux, macOS and Windows from your LLM. Every action runs through an auditable allowlist.
Related MCP Servers
- AlicenseNot gradedqualityAmaintenanceLets Codex delegate coding and repository work to an installed Claude Code CLI with permission-aware inspect/write access, model and effort selection, resumable and cloud-attached sessions, and durable synchronous or asynchronous jobs.MIT
- AlicenseNot gradedqualityBmaintenanceEnables Claude Code to delegate bounded, read-only analysis and isolated patch proposals to the locally installed Codex CLI over MCP, with sanitized live status, revision-aware polling, and reviewable results.1MIT
- AlicenseAqualityBmaintenanceEnables delegation of coding tasks to a locally installed MiniMax Code CLI, leveraging user's existing login, models, and configuration.7135 npmMIT
- AlicenseAqualityCmaintenanceEnables MCP-compatible coding agents to execute the local Codex CLI as a coding agent, including code reviews, session resume/fork, and CLI diagnostics.93 npmMIT