Skip to main content
Glama
cexll
by cexll

ask-codex

Execute code analysis and editing tasks using file references, model selection, and safety controls. Supports structured code changes for refactoring and documentation.

Instructions

Execute Codex CLI with file analysis (@syntax), model selection, and safety controls. Supports changeMode.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
promptYesTask or question. Use @ to include files (e.g., '@largefile.ts explain').
modelNoModel: gpt-5-codex, gpt-5, o3, o4-mini, codex-1, codex-mini-latest, gpt-4.1. Default: gpt-5-codex
sandboxNoQuick automation mode: enables workspace-write + on-failure approval. Alias for fullAuto.
fullAutoNoFull automation mode
approvalPolicyNoApproval: never, on-request, on-failure, untrusted
approvalNoApproval policy: untrusted, on-failure, on-request, never
sandboxModeNoAccess: read-only, workspace-write, danger-full-access
yoloNo⚠️ Bypass all safety (dangerous)
cdNoWorking directory
workingDirNoWorking directory for execution
changeModeNoReturn structured OLD/NEW edits for refactoring
chunkIndexNoChunk index (1-based)
chunkCacheKeyNoCache key for continuation
imageNoOptional image file path(s) to include with the prompt
configNoConfiguration overrides as 'key=value' string or object
profileNoConfiguration profile to use from ~/.codex/config.toml
timeoutNoMaximum execution time in milliseconds (optional)
includeThinkingNoInclude reasoning/thinking section in response
includeMetadataNoInclude configuration metadata in response
searchNoEnable web search by activating web_search_request feature flag. Requires network access - automatically sets sandbox to workspace-write if not specified.
ossNoUse local Ollama server (convenience for -c model_provider=oss). Requires Ollama running locally. Automatically sets sandbox to workspace-write if not specified.
enableFeaturesNoEnable feature flags (repeatable). Equivalent to -c features.<name>=true
disableFeaturesNoDisable feature flags (repeatable). Equivalent to -c features.<name>=false

Implementation Reference

  • The core handler function that destructures arguments, validates prompt, handles special changeMode with chunk continuation, executes the Codex CLI via executeCodex, processes output if in changeMode, formats response, and provides detailed error messages for common issues like installation, auth, quotas, timeouts, and permissions.
      execute: async (args, onProgress) => {
        const {
          prompt,
          model,
          sandbox,
          fullAuto,
          approvalPolicy,
          approval,
          sandboxMode,
          yolo,
          cd,
          workingDir,
          changeMode,
          chunkIndex,
          chunkCacheKey,
          image,
          config,
          profile,
          timeout,
          includeThinking,
          includeMetadata,
          search,
          oss,
          enableFeatures,
          disableFeatures,
        } = args;
    
        if (!prompt?.trim()) {
          throw new Error(ERROR_MESSAGES.NO_PROMPT_PROVIDED);
        }
    
        if (changeMode && chunkIndex && chunkCacheKey) {
          return processChangeModeOutput('', {
            chunkIndex: chunkIndex as number,
            cacheKey: chunkCacheKey as string,
            prompt: prompt as string,
          });
        }
    
        try {
          // Use enhanced executeCodex for better feature support
          const result = await executeCodex(
            prompt as string,
            {
              model: model as string,
              fullAuto: Boolean(fullAuto ?? sandbox),
              approvalPolicy: approvalPolicy as any,
              approval: approval as string,
              sandboxMode: sandboxMode as any,
              yolo: Boolean(yolo),
              cd: cd as string,
              workingDir: workingDir as string,
              image,
              config,
              profile: profile as string,
              timeout: timeout as number,
              search: search as boolean,
              oss: oss as boolean,
              enableFeatures: enableFeatures as string[],
              disableFeatures: disableFeatures as string[],
            },
            onProgress
          );
    
          if (changeMode) {
            return processChangeModeOutput(result, {
              chunkIndex: args.chunkIndex as number | undefined,
              prompt: prompt as string,
            });
          }
    
          // Format response with enhanced output parsing
          return formatCodexResponseForMCP(
            result,
            includeThinking as boolean,
            includeMetadata as boolean
          );
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : String(error);
    
          // Enhanced error handling with helpful context
          if (errorMessage.includes('not found') || errorMessage.includes('command not found')) {
            return `❌ **Codex CLI Not Found**: ${ERROR_MESSAGES.CODEX_NOT_FOUND}
    
    **Quick Fix:**
    \`\`\`bash
    npm install -g @openai/codex
    \`\`\`
    
    **Verification:** Run \`codex --version\` to confirm installation.`;
          }
    
          if (errorMessage.includes('authentication') || errorMessage.includes('unauthorized')) {
            return `❌ **Authentication Failed**: ${ERROR_MESSAGES.AUTHENTICATION_FAILED}
    
    **Setup Options:**
    1. **API Key:** \`export OPENAI_API_KEY=your-key\`
    2. **Login:** \`codex login\` (requires ChatGPT subscription)
    
    **Troubleshooting:** Verify key has Codex access in OpenAI dashboard.`;
          }
    
          if (errorMessage.includes('quota') || errorMessage.includes('rate limit')) {
            return `❌ **Usage Limit Reached**: ${ERROR_MESSAGES.QUOTA_EXCEEDED}
    
    **Solutions:**
    1. Wait and retry - rate limits reset periodically
    2. Check quota in OpenAI dashboard`;
          }
    
          if (errorMessage.includes('timeout')) {
            return `❌ **Request Timeout**: Operation took longer than expected
    
    **Solutions:**
    1. Increase timeout: Add \`timeout: 300000\` (5 minutes)
    2. Simplify request: Break complex queries into smaller parts`;
          }
    
          if (errorMessage.includes('sandbox') || errorMessage.includes('permission')) {
            // Enhanced debugging information
            const debugInfo = [
              `**Current Configuration:**`,
              `- yolo: ${yolo}`,
              `- fullAuto: ${fullAuto}`,
              `- sandbox: ${sandbox}`,
              `- sandboxMode: ${sandboxMode}`,
              `- approvalPolicy: ${approvalPolicy}`,
              `- search: ${search}`,
              `- oss: ${oss}`
            ].join('\n');
    
            return `❌ **Permission Error**: ${ERROR_MESSAGES.SANDBOX_VIOLATION}
    
    ${debugInfo}
    
    **Root Cause:**
    This error typically occurs when:
    1. \`approvalPolicy\` is set without \`sandboxMode\` (now auto-fixed in v1.2+)
    2. Explicit \`sandboxMode: "read-only"\` blocks file modifications
    3. Codex CLI defaults to restrictive permissions
    4. **YOLO mode not working**: If yolo is true but still blocked, there may be a configuration conflict
    
    **Solutions:**
    
    **Option A - Explicit Control (Recommended):**
    \`\`\`json
    {
      "approvalPolicy": "on-failure",
      "sandboxMode": "workspace-write",
      "model": "gpt-5-codex",
      "prompt": "your task..."
    }
    \`\`\`
    
    **Option B - Automated Mode:**
    \`\`\`json
    {
      "sandbox": true,  // Enables fullAuto (workspace-write + on-failure)
      "model": "gpt-5-codex",
      "prompt": "your task..."
    }
    \`\`\`
    
    **Option C - Full Bypass (⚠️ Use with caution):**
    \`\`\`json
    {
      "yolo": true,
      "model": "gpt-5-codex",
      "prompt": "your task..."
    }
    \`\`\`
    
    **Debug Steps:**
    1. Check if yolo mode is being overridden by other settings
    2. Verify Codex CLI version supports yolo flag
    3. Try using only yolo without other conflicting parameters
    
    **Sandbox Modes:**
    - \`read-only\`: Analysis only, no modifications
    - \`workspace-write\`: Can edit files in workspace (safe for most tasks)
    - \`danger-full-access\`: Full system access (use with caution)`;
          }
    
          // Generic error with context
          return `❌ **Codex Execution Error**: ${errorMessage}
    
    **Debug Steps:**
    1. Verify Codex CLI: \`codex --version\`
    2. Check authentication: \`codex login\`
    3. Try simpler query first`;
        }
      },
  • Comprehensive Zod schema defining all inputs for the tool: prompt, model selection, sandbox/approval policies, changeMode for edits, chunk handling, images, config overrides, and feature flags.
    const askCodexArgsSchema = z.object({
      prompt: z
        .string()
        .min(1)
        .describe("Task or question. Use @ to include files (e.g., '@largefile.ts explain')."),
      model: z
        .string()
        .optional()
        .describe(`Model: ${Object.values(MODELS).join(', ')}. Default: gpt-5-codex`),
      sandbox: z
        .boolean()
        .default(false)
        .describe(
          'Quick automation mode: enables workspace-write + on-failure approval. Alias for fullAuto.'
        ),
      fullAuto: z.boolean().optional().describe('Full automation mode'),
      approvalPolicy: z
        .enum(['never', 'on-request', 'on-failure', 'untrusted'])
        .optional()
        .describe('Approval: never, on-request, on-failure, untrusted'),
      approval: z
        .string()
        .optional()
        .describe(`Approval policy: ${Object.values(APPROVAL_POLICIES).join(', ')}`),
      sandboxMode: z
        .enum(['read-only', 'workspace-write', 'danger-full-access'])
        .optional()
        .describe('Access: read-only, workspace-write, danger-full-access'),
      yolo: z.boolean().optional().describe('⚠️ Bypass all safety (dangerous)'),
      cd: z.string().optional().describe('Working directory'),
      workingDir: z.string().optional().describe('Working directory for execution'),
      changeMode: z
        .boolean()
        .default(false)
        .describe('Return structured OLD/NEW edits for refactoring'),
      chunkIndex: z
        .preprocess(val => {
          if (typeof val === 'number') return val;
          if (typeof val === 'string') {
            const parsed = parseInt(val, 10);
            return isNaN(parsed) ? undefined : parsed;
          }
          return undefined;
        }, z.number().min(1).optional())
        .describe('Chunk index (1-based)'),
      chunkCacheKey: z.string().optional().describe('Cache key for continuation'),
      image: z
        .union([z.string(), z.array(z.string())])
        .optional()
        .describe('Optional image file path(s) to include with the prompt'),
      config: z
        .union([z.string(), z.record(z.any())])
        .optional()
        .describe("Configuration overrides as 'key=value' string or object"),
      profile: z.string().optional().describe('Configuration profile to use from ~/.codex/config.toml'),
      timeout: z.number().optional().describe('Maximum execution time in milliseconds (optional)'),
      includeThinking: z
        .boolean()
        .default(true)
        .describe('Include reasoning/thinking section in response'),
      includeMetadata: z.boolean().default(true).describe('Include configuration metadata in response'),
      search: z
        .boolean()
        .optional()
        .describe(
          'Enable web search by activating web_search_request feature flag. Requires network access - automatically sets sandbox to workspace-write if not specified.'
        ),
      oss: z
        .boolean()
        .optional()
        .describe(
          'Use local Ollama server (convenience for -c model_provider=oss). Requires Ollama running locally. Automatically sets sandbox to workspace-write if not specified.'
        ),
      enableFeatures: z
        .array(z.string())
        .optional()
        .describe('Enable feature flags (repeatable). Equivalent to -c features.<name>=true'),
      disableFeatures: z
        .array(z.string())
        .optional()
        .describe('Disable feature flags (repeatable). Equivalent to -c features.<name>=false'),
    });
  • Registers the askCodexTool (imported as askCodexTool) into the central toolRegistry alongside other tools.
    toolRegistry.push(
      askCodexTool,
      batchCodexTool,
      // reviewCodexTool,
      pingTool,
      helpTool,
      versionTool,
      brainstormTool,
      fetchChunkTool,
      timeoutTestTool
    );
  • src/tools/index.ts:3-3 (registration)
    Import statement that brings in the askCodexTool definition from its implementation file.
    import { askCodexTool } from './ask-codex.tool.js';
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions 'safety controls' and 'changeMode' but doesn't explain what safety controls exist, what risks are involved, what permissions are needed, or what the tool actually does behaviorally. The description is too vague about execution behavior, error handling, or output format to be helpful for an agent.

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 sentence that efficiently mentions key capabilities. It's appropriately sized for a complex tool, though it could be more front-loaded with the core purpose. There's no wasted verbiage, but the structure is basic without clear separation of concerns.

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

Completeness2/5

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

For a complex tool with 23 parameters, no annotations, and no output schema, the description is inadequate. It doesn't explain what the tool returns, what kind of execution occurs, what safety considerations exist, or how it differs from sibling tools. The description fails to compensate for the lack of structured metadata about this significant CLI execution tool.

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 description coverage is 100%, so the schema already documents all 23 parameters thoroughly. The description adds minimal value beyond what's in the schema - it mentions 'file analysis (@syntax), model selection, and safety controls' which correspond to some parameters, but doesn't provide additional semantic context or usage patterns. Baseline 3 is appropriate when schema does the heavy lifting.

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

Purpose3/5

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

The description states the tool 'Execute Codex CLI with file analysis (@syntax), model selection, and safety controls. Supports changeMode.' This provides a general purpose (executing Codex CLI) with some features mentioned, but it's vague about what Codex CLI actually does and doesn't distinguish it from sibling tools like 'batch-codex' or 'brainstorm'. The description mentions capabilities but lacks specificity about the core function.

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?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention when this tool is appropriate compared to 'batch-codex' (presumably for batch processing) or 'brainstorm' (presumably for ideation). There's no context about prerequisites, typical use cases, or exclusions for this tool.

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

Install Server

Other Tools

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/cexll/codex-mcp-server'

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