Skip to main content
Glama

health

Run environment and configuration checks for Codex CLI, Git, and filesystem to ensure proper setup before coding tasks.

Instructions

Run environment and configuration checks (Codex CLI, config, Git, filesystem).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
workingDirectoryNoDirectory to check (defaults to server process cwd)
checkGitNoCheck Git availability and repo status
ensureTrackingDirNoCreate tracking dirs if missing (~/.mcp/mcp-codex-dev and <project>/.mcp/mcp-codex-dev)

Implementation Reference

  • Main handler function codexHealth that performs environment and configuration checks including Node.js version, config validation, filesystem checks, Codex CLI availability, Git status, and session tracking stats.
    export async function codexHealth(params: CodexHealthParams): Promise<{
      ok: boolean;
      checks: Record<string, unknown>;
      suggestions: string[];
    }> {
      const suggestions: string[] = [];
      const checks: Record<string, unknown> = {};
    
      const workingDirectory = params.workingDirectory ?? process.cwd();
      checks.node = {
        version: process.version,
        platform: process.platform,
        arch: process.arch,
      };
    
      // Config (effective + diagnostics)
      const { config, diagnostics } = await loadConfigWithDiagnostics({
        workingDirectory,
      });
      checks.config = {
        effective: config,
        diagnostics,
      };
      if (diagnostics.warnings.length > 0) {
        suggestions.push("Fix config warnings (see checks.config.diagnostics.warnings).");
      }
    
      // Filesystem / tracking
      const codexHomeDir = path.join(os.homedir(), ".codex");
      const codexCliConfigToml = path.join(codexHomeDir, "config.toml");
      const mcpDataDir = MCP_DATA_DIR;
      const projectRoot = diagnostics.projectRoot ?? workingDirectory;
      const trackingDir = path.join(projectRoot, ".mcp", "mcp-codex-dev");
      const codexSessionsDir = path.join(codexHomeDir, "sessions");
    
      const mcpData: {
        dir: string;
        exists: boolean;
        writable?: boolean;
        error?: string;
      } = {
        dir: mcpDataDir,
        exists: fs.existsSync(mcpDataDir),
      };
    
      const tracking: {
        dir: string;
        exists: boolean;
        writable?: boolean;
        error?: string;
      } = {
        dir: trackingDir,
        exists: fs.existsSync(trackingDir),
      };
    
      if ((!tracking.exists || !mcpData.exists) && params.ensureTrackingDir) {
        try {
          await fs.promises.mkdir(mcpDataDir, { recursive: true });
          mcpData.exists = true;
          await fs.promises.mkdir(trackingDir, { recursive: true });
          tracking.exists = true;
        } catch (error) {
          tracking.error = error instanceof Error ? error.message : String(error);
          suggestions.push(`Fix filesystem permissions for ${trackingDir}.`);
        }
      }
    
      if (mcpData.exists) {
        try {
          await fs.promises.access(mcpDataDir, fs.constants.W_OK);
          mcpData.writable = true;
        } catch {
          mcpData.writable = false;
          suggestions.push(`Make ${mcpDataDir} writable (used for config.json).`);
        }
      }
    
      if (tracking.exists) {
        try {
          await fs.promises.access(trackingDir, fs.constants.W_OK);
          tracking.writable = true;
        } catch {
          tracking.writable = false;
          suggestions.push(`Make ${trackingDir} writable (used for sessions.json).`);
        }
      } else {
        suggestions.push(
          `Tracking dir missing: ${trackingDir} (it will be created on first run).`
        );
      }
    
      checks.filesystem = {
        workingDirectory,
        workingDirectoryExists: fs.existsSync(workingDirectory),
        codexHomeDir,
        codexCliConfig: readCodexTomlModelHint(codexCliConfigToml),
        mcpDataDir: mcpData,
        trackingDir: tracking,
        codexSessionsDir: {
          dir: codexSessionsDir,
          exists: fs.existsSync(codexSessionsDir),
        },
      };
    
      if (!fs.existsSync(workingDirectory)) {
        suggestions.push(`Set a valid workingDirectory (not found: ${workingDirectory}).`);
      }
    
      // Codex CLI
      const codexVersion = await runCommand("codex", ["--version"], {
        timeoutMs: 5000,
      });
      checks.codex = {
        installed: codexVersion.ok,
        version: codexVersion.stdout.trim() || undefined,
        error: codexVersion.error || (codexVersion.ok ? undefined : codexVersion.stderr.trim()),
      };
      if (!codexVersion.ok) {
        suggestions.push("Install Codex CLI (e.g. `npm install -g @openai/codex`) and ensure it is on PATH.");
      }
    
      // Git checks (optional)
      if (params.checkGit) {
        const gitVersion = await runCommand("git", ["--version"], {
          timeoutMs: 5000,
        });
        const git: Record<string, unknown> = {
          available: gitVersion.ok,
          version: gitVersion.stdout.trim() || undefined,
          error: gitVersion.error || (gitVersion.ok ? undefined : gitVersion.stderr.trim()),
        };
    
        if (gitVersion.ok && fs.existsSync(workingDirectory)) {
          const inside = await runCommand("git", ["rev-parse", "--is-inside-work-tree"], {
            cwd: workingDirectory,
            timeoutMs: 5000,
          });
          const isRepo = inside.ok && inside.stdout.trim() === "true";
          git.repo = {
            isGitRepo: isRepo,
          };
          if (isRepo) {
            const top = await runCommand("git", ["rev-parse", "--show-toplevel"], {
              cwd: workingDirectory,
              timeoutMs: 5000,
            });
            if (top.ok) {
              (git.repo as Record<string, unknown>).root = top.stdout.trim();
            }
          } else {
            suggestions.push("Run review in a Git repo (or set workingDirectory to a repo root).");
          }
        } else if (!gitVersion.ok) {
          suggestions.push("Install Git and ensure it is on PATH (required for review).");
        }
    
        checks.git = git;
      }
    
      // Session tracking stats
      await sessionManager.load({ workingDirectory });
      const sessions = await sessionManager.listAll({ workingDirectory });
      checks.sessions = {
        trackedCount: sessions.length,
        byStatus: {
          active: sessions.filter((s) => s.status === "active").length,
          completed: sessions.filter((s) => s.status === "completed").length,
          abandoned: sessions.filter((s) => s.status === "abandoned").length,
        },
      };
    
      if (config.sandbox === "danger-full-access") {
        suggestions.push(
          "Avoid sandbox.mode=danger-full-access unless absolutely necessary."
        );
      }
    
      const ok =
        (checks.codex as { installed: boolean }).installed &&
        (tracking.writable ?? true) &&
        fs.existsSync(workingDirectory);
    
      return { ok, checks, suggestions };
    }
  • Input parameter schema CodexHealthParamsSchema defining optional workingDirectory, checkGit, and ensureTrackingDir fields, along with the inferred type CodexHealthParams.
    export const CodexHealthParamsSchema = z.object({
      workingDirectory: z
        .string()
        .optional()
        .describe("Directory to check (defaults to process.cwd())"),
      checkGit: z
        .boolean()
        .optional()
        .default(true)
        .describe("Check Git availability and repo status"),
      ensureTrackingDir: z
        .boolean()
        .optional()
        .default(false)
        .describe("Create tracking dirs if missing (~/.mcp/mcp-codex-dev and <project>/.mcp/mcp-codex-dev)"),
    });
    
    export type CodexHealthParams = z.infer<typeof CodexHealthParamsSchema>;
  • src/index.ts:267-299 (registration)
    Tool registration code that registers the 'health' tool with the MCP server, including schema definition and handler invocation.
    if (isToolEnabled(config, "health")) {
      server.tool(
        "health",
        "Run environment and configuration checks (Codex CLI, config, Git, filesystem).",
        {
          workingDirectory: z
            .string()
            .optional()
            .describe("Directory to check (defaults to server process cwd)"),
          checkGit: z
            .boolean()
            .optional()
            .default(true)
            .describe("Check Git availability and repo status"),
          ensureTrackingDir: z
            .boolean()
            .optional()
            .default(false)
            .describe("Create tracking dirs if missing (~/.mcp/mcp-codex-dev and <project>/.mcp/mcp-codex-dev)"),
        },
        async (params) => {
          const result = await codexHealth(params);
          return {
            content: [
              {
                type: "text" as const,
                text: JSON.stringify(result, null, 2),
              },
            ],
          };
        }
      );
    }
  • Helper function runCommand that spawns child processes with timeout support, used to check Codex CLI and Git availability.
    async function runCommand(
      command: string,
      args: string[],
      options: { cwd?: string; timeoutMs: number }
    ): Promise<CommandResult> {
      return new Promise((resolve) => {
        const child = spawn(command, args, {
          cwd: options.cwd,
          shell: true,
          windowsHide: true,
        });
    
        let stdout = "";
        let stderr = "";
        let settled = false;
    
        const timer = setTimeout(() => {
          if (settled) return;
          settled = true;
          try {
            child.kill("SIGTERM");
          } catch {
            // ignore
          }
          resolve({
            ok: false,
            exitCode: null,
            stdout,
            stderr,
            error: `Timed out after ${options.timeoutMs}ms`,
          });
        }, options.timeoutMs);
    
        child.stdout?.on("data", (data: Buffer) => {
          stdout += data.toString();
        });
    
        child.stderr?.on("data", (data: Buffer) => {
          stderr += data.toString();
        });
    
        child.on("error", (error) => {
          if (settled) return;
          settled = true;
          clearTimeout(timer);
          resolve({
            ok: false,
            exitCode: null,
            stdout,
            stderr,
            error: error.message,
          });
        });
    
        child.on("exit", (code) => {
          if (settled) return;
          settled = true;
          clearTimeout(timer);
          resolve({
            ok: code === 0,
            exitCode: code,
            stdout,
            stderr,
          });
        });
      });
    }
  • Helper function readCodexTomlModelHint that parses the Codex CLI config.toml file to extract model hints.
    function readCodexTomlModelHint(filePath: string): {
      path: string;
      exists: boolean;
      model?: string;
      error?: string;
    } {
      const result: {
        path: string;
        exists: boolean;
        model?: string;
        error?: string;
      } = {
        path: filePath,
        exists: fs.existsSync(filePath),
      };
    
      if (!result.exists) return result;
    
      try {
        const content = fs.readFileSync(filePath, "utf-8");
        const match = content.match(/^\s*model\s*=\s*["']([^"']+)["']\s*$/m);
        if (match?.[1]) {
          result.model = match[1];
        }
      } catch (error) {
        result.error = error instanceof Error ? error.message : String(error);
      }
    
      return result;
    }
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 mentions 'checks' which implies a read-only diagnostic operation, but doesn't specify if it modifies anything (e.g., via 'ensureTrackingDir'), what permissions are needed, or how results are returned. For a tool with parameters that could affect system state, this is a significant gap in transparency.

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 front-loads the core purpose without any wasted words. It's appropriately sized for a diagnostic tool, making it easy to parse and understand 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 tool's complexity (3 parameters, no output schema, and no annotations), the description is insufficient. It doesn't explain what the checks entail, what output to expect, or behavioral traits like side effects from 'ensureTrackingDir'. For a diagnostic tool, more context is needed to guide effective use.

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 schema description coverage is 100%, meaning all parameters are well-documented in the input schema. The description adds no additional meaning beyond implying general checks, so it meets the baseline for adequate but not enhanced parameter semantics.

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 tool's purpose with specific verbs ('Run environment and configuration checks') and resources ('Codex CLI, config, Git, filesystem'), making it easy to understand what it does. However, it doesn't explicitly differentiate from sibling tools like 'exec' or 'review', which might also involve system operations, so it doesn't reach the highest 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 'exec' or 'review', nor does it mention any prerequisites or exclusions. It simply states what the tool does without context for its application, leaving the agent to infer usage scenarios.

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/FYZAFH/mcp-codex-dev'

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