codex
Analyze code for bugs, security issues, and architectural problems using deep AI-powered review. Specify scope and constraints to focus the analysis on specific files or functions.
Instructions
Invoke OpenAI Codex CLI agent for deep code analysis and critical review.
CAPABILITIES:
Strongest deep analysis and reflection abilities
Excellent at finding issues, edge cases, and potential bugs
Good at critical code review and architectural assessment
LIMITATIONS:
Tends to over-engineer solutions or over-simplify features
May suggest unnecessary abstractions
BEST PRACTICES:
Be explicit about scope: "Only fix X, don't refactor Y"
Specify constraints: "Keep it simple, no new abstractions"
Use for: Code review, bug hunting, security analysis
SUPPORTS: Image attachments for UI/screenshot analysis
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| prompt | Yes | Detailed task instruction for the agent. Include specific file paths, function names, or error messages when available. Be explicit about scope and constraints to avoid over-engineering. Example: 'Fix the TypeError in utils.py:42, only modify that function' | |
| workspace | Yes | Absolute path to the project directory. Use the path mentioned in conversation, or the current project root. Supports relative paths (resolved against server CWD). Example: '/Users/dev/my-project' or './src' | |
| permission | No | File system permission level: - 'read-only': Can only read files, safe for analysis tasks - 'workspace-write': Can modify files within workspace only (recommended for most tasks) - 'unlimited': (DANGER) Full system access, use only when explicitly needed | read-only |
| model | No | Model override. Only specify if user explicitly requests a specific model. | |
| save_file | No | Save agent output to a file at the specified path. The file will contain the agent's response without debug info. This saves the orchestrator from having to write files separately. Example: '/path/to/output.md' NOTE: This is intentionally exempt from permission restrictions. It serves as a convenience for persisting analysis results, not as a general file-write capability. The CLI agent's actual file operations are still governed by the 'permission' parameter. | |
| save_file_with_prompt | No | When true AND save_file is set, injects a note into the prompt asking the model to verbalize its analysis and insights. The model's detailed reasoning will be automatically saved to the file. Useful for generating comprehensive analysis reports. | |
| full_output | No | Return detailed output including reasoning and tool calls. Recommended for Gemini research/analysis tasks. Default: false (concise output) | |
| image | No | Absolute paths to image files for visual context. Use for: UI screenshots, error dialogs, design mockups. Example: ['/path/to/screenshot.png'] | |
| session_id | No | Session ID to continue a previous conversation. Reuse the ID from prior tool calls to maintain context. Leave empty for new conversations. | |
| task_note | No | Display label for GUI, e.g., '[Review] PR #123' | |
| debug | No | Override global debug setting for this call. When true, response includes execution stats (model, duration, tokens). When omitted, uses global CAM_DEBUG setting. |
Implementation Reference
- src/cli_agent_mcp/server.py:402-419 (registration)Registers the 'codex' MCP tool with description and input schema if enabled in config.async def list_tools() -> list[Tool]: """列出可用工具。""" tools = [] for cli_type in ["codex", "gemini", "claude", "opencode"]: if config.is_tool_allowed(cli_type): tools.append( Tool( name=cli_type, description=TOOL_DESCRIPTIONS[cli_type], inputSchema=create_tool_schema(cli_type), ) ) # DEBUG: 记录工具列表请求(通常是客户端初始化后的第一个调用) logger.debug( f"[MCP] list_tools called, returning {len(tools)} tools: " f"{[t.name for t in tools]}" ) return tools
- src/cli_agent_mcp/server.py:208-218 (schema)Defines the Codex-specific input schema properties (image array).CODEX_PROPERTIES = { "image": { "type": "array", "items": {"type": "string"}, "default": [], "description": ( "Absolute paths to image files for visual context. " "Use for: UI screenshots, error dialogs, design mockups. " "Example: ['/path/to/screenshot.png']" ), },
- src/cli_agent_mcp/server.py:63-79 (schema)Tool description for 'codex' used in MCP Tool registration."codex": """Invoke OpenAI Codex CLI agent for deep code analysis and critical review. CAPABILITIES: - Strongest deep analysis and reflection abilities - Excellent at finding issues, edge cases, and potential bugs - Good at critical code review and architectural assessment LIMITATIONS: - Tends to over-engineer solutions or over-simplify features - May suggest unnecessary abstractions BEST PRACTICES: - Be explicit about scope: "Only fix X, don't refactor Y" - Specify constraints: "Keep it simple, no new abstractions" - Use for: Code review, bug hunting, security analysis SUPPORTS: Image attachments for UI/screenshot analysis""",
- shared/invokers/codex.py:37-138 (handler)CodexInvoker class: core handler that builds and executes the 'codex' CLI command with parameters.class CodexInvoker(CLIInvoker): """Codex CLI 调用器。 封装 Codex CLI 的调用逻辑,包括: - 命令行参数构建 - Permission 到 --sandbox 参数映射 - 图片附件支持 Example: invoker = CodexInvoker() result = await invoker.execute(CodexParams( prompt="Review this code", workspace=Path("/path/to/repo"), image=[Path("screenshot.png")], )) """ def __init__( self, codex_path: str = "codex", event_callback: EventCallback | None = None, parser: Any | None = None, ) -> None: """初始化 Codex 调用器。 Args: codex_path: codex 可执行文件路径,默认 "codex" event_callback: 事件回调函数 parser: 自定义解析器 """ super().__init__(event_callback=event_callback, parser=parser) self._codex_path = codex_path @property def cli_type(self) -> CLIType: return CLIType.CODEX def validate_params(self, params: CommonParams) -> None: """验证 Codex 特有参数。""" super().validate_params(params) if isinstance(params, CodexParams): # 验证图片路径 for img_path in params.image: if not Path(img_path).exists(): raise ValueError(f"Image file does not exist: {img_path}") def build_command(self, params: CommonParams) -> list[str]: """构建 Codex CLI 命令。 Args: params: 调用参数 Returns: 命令行参数列表 """ cmd = [self._codex_path, "exec"] # 工作目录 cmd.extend(["--cd", str(params.workspace.absolute())]) # Permission 映射到 sandbox 参数 sandbox_value = PERMISSION_MAP_CODEX.get(params.permission, "read-only") cmd.extend(["--sandbox", sandbox_value]) # 硬编码参数 cmd.append("--skip-git-repo-check") cmd.append("--json") # 可选:模型 if params.model: cmd.extend(["--model", params.model]) # Codex 特有:图片附件 if isinstance(params, CodexParams): for img_path in params.image: cmd.extend(["--image", str(Path(img_path).absolute())]) # 会话恢复 if params.session_id: cmd.append("resume") cmd.append(params.session_id) # Prompt 通过 stdin 传递(使用 -- 分隔) cmd.append("--") return cmd def _process_event(self, event: Any, params: CommonParams) -> None: """处理 Codex 特有的事件。 Codex 的 session_id 可能在 thread.started 事件中。 """ super()._process_event(event, params) if not self._session_id: raw = event.raw if raw.get("type") == "thread.started": thread_id = raw.get("thread_id", "") if thread_id: self._session_id = thread_id
- shared/invokers/types.py:104-120 (schema)Dataclass defining CodexParams for input validation and typing.@dataclass class CodexParams(CommonParams): """Codex CLI 参数。 继承公共参数,增加 Codex 特有参数。 Attributes: image: 附加图片路径列表 """ image: list[Path] = field(default_factory=list) def __post_init__(self) -> None: super().__post_init__() # 确保 image 是 Path 列表 self.image = [Path(p) if isinstance(p, str) else p for p in self.image]