Skip to main content
Glama
NealZhi
by NealZhi

Instrucciones de integración de Codex JetBrains HUD + Hooks

Antecedentes del proyecto: Esta solución de adaptación se basa en el análisis del código fuente filtrado de Claude Code v2.1.88. El objetivo es dotar a Codex de capacidades similares a las de Claude Code, permitiéndole detectar el archivo, el número de línea y el rango de código seleccionados actualmente en la serie de IDE de JetBrains.

Autor: nealzhi

Este documento solo conserva una ruta de integración: HUD + hooks.

Este repositorio ha eliminado la antigua solución de "servidor MCP local + prompts globales", y ya no se recomienda ni se proporciona dicha configuración.

Captura de pantalla exitosa

1. Requisitos previos

Cumple primero con las siguientes dos condiciones:

  1. Utilizas la serie de IDE de JetBrains Por ejemplo: IntelliJ IDEA, PyCharm, WebStorm, GoLand, Android Studio

  2. Tu IDE tiene instalado el plugin oficial de Claude Code para JetBrains Este es el requisito previo para la vinculación. Sin este plugin, no existirán los archivos ~/.claude/ide/*.lock locales ni las interfaces locales correspondientes, por lo que Codex no podrá leer el archivo seleccionado actualmente ni el rango de código.

Related MCP server: Claude Code Control MCP

2. Instalación de dependencias

Ejecuta en la raíz del repositorio:

cd codex-jetbrains-mcp
npm install
brew install tmux

Explicación:

  • npm install: Instala las dependencias de HUD y hooks

  • tmux: Dependencia del HUD

3. Integración del HUD

Ejecuta en la raíz del repositorio:

chmod +x codex-jetbrains-mcp/bin/codex-jetbrains-hud

Si deseas que al ejecutar codex se inicie automáticamente con el HUD, añade la siguiente línea a tu ~/.zshrc o ~/.bashrc:

alias codex='$(pwd)/codex-jetbrains-mcp/bin/codex-jetbrains-hud'

Recarga el shell:

source ~/.zshrc

Si usas bash, ejecuta:

source ~/.bashrc

Si descubres que la rueda del ratón no puede desplazar la ventana de Codex en la terminal integrada de macOS o en la terminal Warp, puedes ejecutar el siguiente comando para activar el soporte de ratón de tmux:

tmux set -g mouse on

Una vez iniciado el HUD, se mostrará una línea:

JetBrains PyCharm 已连接 | test_main.py:2140-2147 (8 lines)

4. Configuración de hooks

El núcleo de esta solución es:

  1. Iniciar el HUD al mismo tiempo que se inicia codex

  2. El HUD escribe automáticamente el archivo/número de línea actual de JetBrains en .codex/jetbrains-selection-state.json

  3. El hook UserPromptSubmit lee este estado cuando envías un mensaje

  4. Cuando hay contexto de JetBrains, solo se inyecta la "ruta del archivo" o "ruta del archivo + número de línea"

  5. No se inyecta el texto seleccionado, permitiendo que Codex lea el archivo según sea necesario

4.1 Método de inicio recomendado

Ejecuta en la raíz del repositorio:

chmod +x codex-jetbrains-mcp/bin/codex-jetbrains-hud
alias codex='$(pwd)/codex-jetbrains-mcp/bin/codex-jetbrains-hud'

Después, puedes ejecutar codex normalmente.

Ahora, codex-jetbrains-hud no solo muestra el HUD, sino que también sincroniza automáticamente el estado necesario para los hooks. Esta es la única ruta recomendada; no se proporciona ni se necesita un proceso de sincronización independiente.

El archivo de estado se escribirá en:

.codex/jetbrains-selection-state.json

4.2 Configuración de hooks

El repositorio ya incluye:

  • .codex/config.toml

  • .codex/hooks/selection-state.mjs

  • .codex/hooks.json

  • .codex/hooks/user-prompt-submit-jetbrains-selection.mjs

Existen dos formas de integración:

  1. Si inicias codex en este directorio del repositorio Codex leerá directamente el .codex/config.toml y .codex/hooks.json del repositorio, sin necesidad de especificar rutas adicionales.

  2. Si ya tienes tu propio ~/.codex/hooks.json global No lo sobrescribas, simplemente fusiona la configuración de UserPromptSubmit del repositorio. Si vas a copiarlo a ~/.codex/hooks/, copia todo el directorio .codex/hooks/, no solo el archivo de entrada.

La función de .codex/config.toml es activar la funcionalidad de hooks requerida oficialmente:

[features]
codex_hooks = true

Según la documentación oficial, los hooks están desactivados por defecto y deben habilitarse en config.toml, o pasando codex --enable codex_hooks al iniciar. Además, la capa de configuración de Codex leerá tanto ~/.codex/config.toml como el .codex/config.toml del repositorio; si el proyecto no está marcado como confiable, el .codex/config.toml a nivel de repositorio no tendrá efecto.

El contenido de la configuración incluida en el repositorio es:

{
  "hooks": {
    "UserPromptSubmit": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "node \"$(git rev-parse --show-toplevel)/.codex/hooks/user-prompt-submit-jetbrains-selection.mjs\"",
            "statusMessage": "Loading JetBrains selection"
          }
        ]
      }
    ]
  }
}

Este hook leerá el archivo de estado local cada vez que se ejecute UserPromptSubmit:

  • Si solo se ha seleccionado un archivo, inyecta a Codex "cuál es el archivo actual"

  • Si se ha seleccionado un rango de código, inyecta a Codex "archivo actual + número de línea"

  • Si no hay contexto de JetBrains o el estado ha caducado, no se inyecta nada

No inyecta el texto del código, solo proporciona la referencia de ubicación.

4.3 Limpieza de configuraciones antiguas

Si anteriormente utilizaste la versión antigua, elimina lo siguiente:

  1. Elimina la configuración de MCP local

codex mcp remove jetbrains-selection
  1. Elimina este tipo de contenido de tus prompts globales

每次用户请求时,先调用 MCP 工具 jetbrains-selection.jetbrains_get_selection 获取 JetBrains 当前选区

Este paso es obligatorio, de lo contrario, el modelo podría intentar seguir llamando a una herramienta MCP que ya no existe.

4.4 Contenido inyectado por el hook

Cuando solo se selecciona un archivo, se inyecta algo como:

JetBrains 当前选中文件:/path/to/file.ts
这只是文件指引,没有附带文件内容。
如果本轮问题和这个文件相关,请先自行读取该文件;如果无关,请忽略这条上下文。

Cuando se selecciona un rango de código, se inyecta algo como:

JetBrains 当前选中位置:/path/to/file.ts:120-146
这只是位置指引,没有附带代码内容。
如果本轮问题和这个位置相关,请先自行读取对应文件和行号;如果无关,请忽略这条上下文。

El estado predeterminado es válido por 20s. Mientras el HUD esté en ejecución, actualizará el estado cada 5s; si el HUD se cierra, el hook dejará de inyectar el estado antiguo rápidamente. También puedes ajustar este tiempo mediante la variable de entorno CODEX_JB_HOOK_MAX_AGE_MS.

5. ¿Por qué no mantener la solución MCP local?

Los problemas de la solución antigua eran principalmente:

  • Requería ejecutar codex mcp add adicionalmente, aumentando el coste de instalación y mantenimiento.

  • El modelo solía depender de prompts globales para "llamar a una MCP en cada turno", incluso si la pregunta no tenía nada que ver con la selección de JetBrains, lo cual era un paso innecesario.

  • La relevancia de la selección debería decidirse según la pregunta actual; ponerlo en un prompt global hacía que el comportamiento fuera demasiado mecánico.

  • El servidor MCP local era solo una capa de tránsito; en realidad, seguía conectándose al plugin de Claude Code para JetBrains. Mantener esta capa por separado no aportaba mucho valor y aumentaba la complejidad.

  • La configuración antigua no era fácil de limpiar, y tras la migración era fácil que quedaran nombres de herramientas inválidos o prompts antiguos.

Tras cambiar a HUD + hooks, los beneficios son más directos:

  • Solo se lee el estado local al enviar un mensaje, sin necesidad de invocar una capa MCP adicional en cada turno.

  • El contenido inyectado solo contiene la ruta del archivo o el número de línea, lo que hace que la información sea más limpia y permite que el modelo decida por sí mismo si necesita leer el archivo.

  • El archivo de estado está aislado por directorio raíz del proyecto; cada proyecto escribe su propio .codex/jetbrains-selection-state.json.

  • El HUD actualiza el estado continuamente mientras está activo; si el HUD se detiene, el estado antiguo caducará automáticamente.

  • La ruta de integración es más sencilla; el usuario solo necesita mantener el HUD y los hooks, sin necesidad de mantener configuraciones de MCP.

6. ¿Cómo funciona esta solución?

El flujo de datos es el siguiente:

  1. El plugin oficial de Claude Code para JetBrains expone la información de conexión local y los eventos de selección.

  2. El HUD coincide con la ventana del proyecto de JetBrains correcta según el directorio de trabajo actual.

  3. Una vez que el HUD recibe un cambio en la selección, escribe la ruta del archivo, el número de línea y el tiempo de latido en el .codex/jetbrains-selection-state.json del proyecto actual.

  4. El hook UserPromptSubmit lee este estado cuando envías un mensaje.

  5. Si el estado es válido, inyecta un prompt ligero con el "archivo actual" o "archivo actual + número de línea" a Codex.

En este flujo no hay servidor MCP local ni se necesitan prompts globales adicionales.

7. Verificación

Una vez completados los pasos anteriores:

  1. Abre el IDE de JetBrains.

  2. Inicia codex.

  3. Si utilizaste el envoltorio del HUD para iniciar, el HUD sincronizará automáticamente el estado del hook.

  4. Vuelve al IDE de JetBrains con el plugin oficial de Claude Code instalado y selecciona un archivo o un fragmento de código.

  5. Confirma que el HUD muestra el archivo y el número de línea actuales.

  6. Haz preguntas normalmente en Codex.

Si el HUD no se actualiza, lo más seguro es:

  • Volver al IDE y hacer clic de nuevo en el archivo.

  • O volver a arrastrar la selección.

En condiciones normales:

  • Cuando solo se selecciona un archivo, Codex recibirá la guía de la ruta del archivo.

  • Cuando se selecciona un rango de código, Codex recibirá la guía de la ruta del archivo y el número de línea.

  • Cuando no hay contexto de JetBrains, no se inyectará ninguna sugerencia de JetBrains.

Available Tools

5 tools
jetbrains_get_selectionC

Return the current file path and selected lines forwarded by the Claude JetBrains plugin.

ParametersJSON Schema
NameRequiredDescriptionDefault
maxCharsNo
includeTextNo

TDQS

C2.9/5.0
Behavior2/5

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

No annotations are present, so the description must fully disclose behavioral traits. It fails to indicate whether the operation is read-only, destructive, or requires authentication. Mentioning 'forwarded by the Claude JetBrains plugin' weakly implies a read operation but is insufficient.

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

Conciseness4/5

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

The description is a single concise sentence that front-loads the main purpose. However, it is slightly under-specified for a tool with multiple parameters, but still efficient.

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

Completeness3/5

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

Given the tool's complexity (2 parameters, no output schema), the description provides a high-level overview of the return value ('file path and selected lines') but lacks details about the format, structure, or behavior (e.g., what happens if no selection exists). It is minimally adequate but not comprehensive.

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

Parameters1/5

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

Schema coverage is 0%, and the description does not explain any parameters (maxChars, includeText) or their purpose. The schema provides defaults and constraints, but the description adds no value beyond that, leaving the agent uninformed about how to use the parameters effectively.

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 clearly states that the tool returns the current file path and selected lines from the JetBrains plugin. This verb-resource combination is specific and distinct from sibling tools like jetbrains_list_instances or jetbrains_status.

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

Usage Guidelines2/5

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

No guidance is provided on when to use this tool versus alternatives, nor are there any exclusions or prerequisites mentioned. The description only states what it does, not the context for usage.

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

jetbrains_list_instancesA

List discovered JetBrains plugin instances and show which one matches the current project.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

A3.6/5.0
Behavior2/5

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

No annotations are provided, so the description must carry the full burden of behavioral disclosure. It mentions listing and matching but does not discuss side effects (likely none, read-only), authorization requirements, or potential limitations. This is a significant gap.

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

Conciseness4/5

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

The description is a single, front-loaded sentence that conveys the core functionality with no unnecessary words. It is concise, though could be slightly more structured.

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

Completeness3/5

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

Given there are no parameters, no output schema, and no annotations, the description provides minimal context. It lacks details about the output format, the definition of 'matches', and any behavior beyond listing. While acceptable for a simple list tool, it leaves gaps for an AI agent.

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?

The input schema has zero properties, so there are no parameters to describe. Per guidelines, a baseline of 4 is appropriate since the description does not need to add parameter semantics.

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 clearly states the verb 'List' and the resource 'JetBrains plugin instances', and adds the specific behavior of showing which instance matches the current project. This distinctly differentiates it from sibling tools like jetbrains_get_selection or jetbrains_status.

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 description implies that the tool is for listing instances and identifying the project-matched one, but it does not explicitly state when to use it over alternatives or when to avoid using it. No usage context or exclusions are provided.

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

jetbrains_list_upstream_toolsA

List the upstream MCP tools exposed by the Claude JetBrains plugin connection for debugging and extension work.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

A3.9/5.0
Behavior3/5

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

The description indicates a read operation by 'list', but with no annotations, it does not disclose any additional behavioral traits such as permissions, side effects, or limitations. Basic transparency is adequate but minimal.

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 a single sentence with no superfluous words, clearly stating the tool's function and context.

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

Completeness3/5

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

The description covers purpose and use-case but does not specify output format (e.g., list of tool names or details). For a simple list tool without output schema, this is adequate but could be more informative.

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?

The tool has zero parameters; the empty schema is fully described. The description does not need to add parameter information beyond what the schema already provides.

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 explicitly states 'List the upstream MCP tools' with a clear verb and resource, and distinguishes from siblings like jetbrains_get_selection by specifying 'upstream MCP tools'.

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 description mentions 'for debugging and extension work' which gives context, but lacks explicit when-to-use or alternatives guidance. No comparison with sibling tools is provided.

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

jetbrains_refresh_connectionA

Force a fresh scan of lockfiles and reconnect to the matching JetBrains plugin instance.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

A3.7/5.0
Behavior2/5

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

No annotations are provided, so the description must disclose behavioral traits. It mentions 'force a fresh scan' and 'reconnect' but does not explain side effects (e.g., whether current state is disrupted, auth requirements) or what happens to existing connections.

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 with no wasted words. Every part delivers essential information.

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

Completeness3/5

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

Given no output schema and no annotations, the description is minimal but covers the core action. However, it lacks details on side effects, prerequisites, or postconditions, leaving some gaps for a complete understanding.

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?

No parameters exist, so baseline is 4. The description adds meaning by explaining the tool's actions (scan lockfiles, reconnect) beyond the empty schema.

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?

Description clearly states it forces a fresh scan of lockfiles and reconnects to the matching JetBrains plugin instance. This specific verb-resource pair distinguishes it from siblings like get_selection or list_instances.

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?

No explicit when-to-use or when-not-to-use guidance is given. The description implies it's for refreshing a stale connection or lockfiles, but alternatives are not mentioned.

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

jetbrains_statusA

Show connection status for the Claude JetBrains plugin adapter.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

A3.9/5.0
Behavior2/5

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

No annotations provided, and the description only says 'Show connection status'. Does not disclose whether it performs a live check or returns cached state, or any side effects. Minimal disclosure.

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?

Single sentence, no fluff, perfectly sized for the tool's simplicity.

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?

Given zero complexity, no parameters, no output schema, and no annotations, the description fully covers what the tool does.

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?

Zero parameters, so the description naturally adds no param info. According to calibration rules, 0 params = baseline 4.

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?

Clearly states verb 'Show' and resource 'connection status for the Claude JetBrains plugin adapter'. Distinguishes from sibling tools like jetbrains_refresh_connection which implies a different action.

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?

No explicit when or when-not to use, but the simplicity of a zero-parameter status check makes usage obvious. No alternatives mentioned, but siblings indicate other connection-related tools.

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.

  1. 5 tool updatesv0.1.0
    • First observedjetbrains_get_selection
    • First observedjetbrains_list_instances
    • First observedjetbrains_list_upstream_tools
    • First observedjetbrains_refresh_connection
    • First observedjetbrains_status

TDQS

A3.7/5.0

Scored across 5 tools

Disambiguation5/5

Each tool has a clearly distinct purpose: getting selection, listing instances, listing upstream tools, refreshing connection, and showing status. No two tools could be confused.

Naming Consistency5/5

All tools follow a consistent 'jetbrains_' prefix with verb_noun pattern (get_selection, list_instances, list_upstream_tools, refresh_connection, status). No mixing of conventions.

Tool Count5/5

With 5 tools, the set is well-scoped for a connection adapter that manages plugin instances and retrieves selections. Each tool earns its place without unnecessary bloat.

Completeness4/5

The tool surface covers the core operations: get current selection, list/manage instances, refresh connection, and check status. Minor gaps like setting selection or executing actions are absent, but the stated purpose is well-covered.

Maintenance

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers