Skip to main content
Glama

codex

Execute Codex CLI commands for AI-assisted coding tasks like code generation, analysis, and refactoring with session management and reasoning depth control.

Instructions

Execute Codex CLI in non-interactive mode for AI assistance

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
promptYesThe coding task, question, or analysis request
sessionIdNoOptional session ID for conversational context
resetSessionNoReset the session history before processing this request
modelNoSpecify which model to use (defaults to gpt-5.1-codex). Options: gpt-5.1-codex, gpt-5-codex, gpt-4, gpt-3.5-turbo
reasoningEffortNoControl reasoning depth (minimal < low < medium < high)

Implementation Reference

  • The primary handler class implementing the execution logic for the 'codex' tool, including session management and CLI command invocation.
    export class CodexToolHandler {
      constructor(private sessionStorage: SessionStorage) {}
    
      async execute(args: unknown): Promise<ToolResult> {
        try {
          const {
            prompt,
            sessionId,
            resetSession,
            model,
            reasoningEffort,
          }: CodexToolArgs = CodexToolSchema.parse(args);
    
          let activeSessionId = sessionId;
          let enhancedPrompt = prompt;
    
          // Only work with sessions if explicitly requested
          let useResume = false;
          let codexConversationId: string | undefined;
    
          if (sessionId) {
            if (resetSession) {
              this.sessionStorage.resetSession(sessionId);
            }
    
            codexConversationId =
              this.sessionStorage.getCodexConversationId(sessionId);
            if (codexConversationId) {
              useResume = true;
            } else {
              // Fallback to manual context building if no codex conversation ID
              const session = this.sessionStorage.getSession(sessionId);
              if (
                session &&
                Array.isArray(session.turns) &&
                session.turns.length > 0
              ) {
                enhancedPrompt = this.buildEnhancedPrompt(session.turns, prompt);
              }
            }
          }
    
          // Build command arguments with new v0.36.0 features
          const cmdArgs =
            useResume && codexConversationId
              ? ['resume', codexConversationId]
              : ['exec'];
    
          // Add model parameter (supported in both exec and resume)
          const selectedModel =
            model || process.env.CODEX_DEFAULT_MODEL || 'gpt-5-codex'; // Default to gpt-5-codex
          cmdArgs.push('--model', selectedModel);
    
          // Add reasoning effort via config parameter (v0.50.0+ uses -c instead of --reasoning-effort)
          if (reasoningEffort) {
            cmdArgs.push('-c', `model_reasoning_effort=${reasoningEffort}`);
          }
    
          // Skip git repo check for v0.50.0+
          cmdArgs.push('--skip-git-repo-check');
    
          // Use '-' to read prompt from stdin (avoids shell escaping issues)
          cmdArgs.push('-');
    
          const result = await executeCommand('codex', cmdArgs, enhancedPrompt);
          const response = result.stdout || 'No output from Codex';
    
          // Extract conversation ID from new conversations for future resume
          if (activeSessionId && !useResume) {
            const conversationIdMatch = result.stderr?.match(
              /conversation\s*id\s*:\s*([a-zA-Z0-9-]+)/i
            );
            if (conversationIdMatch) {
              this.sessionStorage.setCodexConversationId(
                activeSessionId,
                conversationIdMatch[1]
              );
            }
          }
    
          // Save turn only if using a session
          if (activeSessionId) {
            const turn: ConversationTurn = {
              prompt,
              response,
              timestamp: new Date(),
            };
            this.sessionStorage.addTurn(activeSessionId, turn);
          }
    
          return {
            content: [
              {
                type: 'text',
                text: response,
              },
            ],
            _meta: {
              ...(activeSessionId && { sessionId: activeSessionId }),
              model: selectedModel,
            },
          };
        } catch (error) {
          if (error instanceof ZodError) {
            throw new ValidationError(TOOLS.CODEX, error.message);
          }
          throw new ToolExecutionError(
            TOOLS.CODEX,
            'Failed to execute codex command',
            error
          );
        }
      }
    
      private buildEnhancedPrompt(
        turns: ConversationTurn[],
        newPrompt: string
      ): string {
        if (turns.length === 0) return newPrompt;
    
        // Get relevant context from recent turns
        const recentTurns = turns.slice(-2);
        const contextualInfo = recentTurns
          .map((turn) => {
            // Extract key information without conversational format
            if (
              turn.response.includes('function') ||
              turn.response.includes('def ')
            ) {
              return `Previous code context: ${turn.response.slice(0, 200)}...`;
            }
            return `Context: ${turn.prompt} -> ${turn.response.slice(0, 100)}...`;
          })
          .join('\n');
    
        // Build enhanced prompt that provides context without conversation format
        return `${contextualInfo}\n\nTask: ${newPrompt}`;
      }
    }
  • Registration of the codex tool handler within the tool registry.
    // Tool handler registry
    const sessionStorage = new InMemorySessionStorage();
    
    export const toolHandlers = {
      [TOOLS.CODEX]: new CodexToolHandler(sessionStorage),
      [TOOLS.PING]: new PingToolHandler(),
      [TOOLS.HELP]: new HelpToolHandler(),
      [TOOLS.LIST_SESSIONS]: new ListSessionsToolHandler(sessionStorage),
    } as const;
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states 'Execute Codex CLI in non-interactive mode' but doesn't explain what 'non-interactive' entails (e.g., single request vs. chat, no user input during execution), nor does it cover permissions, rate limits, or error handling, which are critical for an AI assistance tool.

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, efficient sentence that directly states the tool's function without unnecessary words. It's front-loaded with the core action, making it easy to parse quickly.

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?

Given the complexity of an AI assistance tool with 5 parameters and no annotations or output schema, the description is insufficient. It lacks details on behavior (e.g., response format, error cases), usage context, and how parameters interact with 'non-interactive mode', leaving significant gaps for the agent.

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?

The input schema has 100% description coverage, so the baseline is 3. The description adds no additional parameter information beyond what's in the schema (e.g., it doesn't clarify 'non-interactive mode' in relation to parameters like 'sessionId'), so it doesn't enhance the schema's documentation.

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 clearly states the action ('Execute Codex CLI') and the mode ('non-interactive mode for AI assistance'), making the purpose understandable. However, it doesn't differentiate from sibling tools like 'help' or 'listSessions' beyond the general AI assistance context, which prevents a perfect score.

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 like 'help' or 'listSessions'. It mentions 'non-interactive mode' but doesn't explain what that means or when it's appropriate, leaving the agent without clear usage context.

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

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