Skip to main content
Glama

session_discard

Discard Codex CLI sessions to manage workspace resources. Use force parameter to remove active sessions when needed.

Instructions

Discard Codex sessions. By default, refuses to discard sessions marked active unless force=true.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sessionIdsYesList of session IDs to discard
forceNoForce discard
workingDirectoryNoProject working directory (used to scope session tracking)

Implementation Reference

  • Main handler function codexSessionDiscard that validates session IDs, checks if sessions are active, deletes Codex session files from disk, and removes sessions from the tracking manager. Returns success status along with arrays of discarded and failed sessions.
    export async function codexSessionDiscard(
      params: CodexSessionDiscardParams
    ): Promise<CodexSessionDiscardResult> {
      const result: CodexSessionDiscardResult = {
        success: true,
        discarded: [],
        failed: [],
      };
    
      for (const sessionId of params.sessionIds) {
        try {
          // Validate sessionId format to prevent path traversal
          if (!SESSION_ID_RE.test(sessionId)) {
            result.failed.push({
              sessionId,
              reason: "Invalid session ID format (expected UUID).",
            });
            result.success = false;
            continue;
          }
          const tracked = await sessionManager.get(sessionId, {
            workingDirectory: params.workingDirectory,
          });
          if (tracked?.status === "active" && !params.force) {
            result.failed.push({
              sessionId,
              reason:
                "Session is still marked as active. Pass force=true to discard anyway.",
            });
            result.success = false;
            continue;
          }
    
          // Try to delete Codex session files
          const codexSessionPath = path.join(
            os.homedir(),
            ".codex",
            "sessions",
            sessionId
          );
    
          if (fs.existsSync(codexSessionPath)) {
            await fs.promises.rm(codexSessionPath, {
              recursive: true,
              force: params.force,
            });
          }
    
          // Remove from our tracking
          await sessionManager.remove(sessionId, {
            workingDirectory: params.workingDirectory,
          });
    
          result.discarded.push(sessionId);
        } catch (error) {
          result.failed.push({
            sessionId,
            reason: error instanceof Error ? error.message : String(error),
          });
          result.success = false;
        }
      }
    
      return result;
    }
  • Input validation schema (CodexSessionDiscardParamsSchema) using Zod that defines the parameters: sessionIds (array of strings), force (optional boolean), and workingDirectory (optional string).
    export const CodexSessionDiscardParamsSchema = z.object({
      sessionIds: z.array(z.string()).describe("List of session IDs to discard"),
      force: z.boolean().optional().default(false).describe("Force discard, ignore warnings"),
      workingDirectory: z
        .string()
        .optional()
        .describe("Project working directory (used to scope session tracking)"),
    });
    
    export type CodexSessionDiscardParams = z.infer<
      typeof CodexSessionDiscardParamsSchema
    >;
  • src/index.ts:198-229 (registration)
    MCP tool registration for 'session_discard' using server.tool() method, defining the tool name, description, input schema (repeated inline), and async handler that calls codexSessionDiscard and returns JSON-formatted results.
    // ─── session_discard ───────────────────────────────────────────────
    if (isToolEnabled(config, "session_discard")) {
      server.tool(
        "session_discard",
        "Discard Codex sessions. By default, refuses to discard sessions marked active unless force=true.",
        {
          sessionIds: z
            .array(z.string())
            .describe("List of session IDs to discard"),
          force: z
            .boolean()
            .optional()
            .default(false)
            .describe("Force discard"),
          workingDirectory: z
            .string()
            .optional()
            .describe("Project working directory (used to scope session tracking)"),
        },
        async (params) => {
          const result = await codexSessionDiscard(params);
          return {
            content: [
              {
                type: "text" as const,
                text: JSON.stringify(result, null, 2),
              },
            ],
          };
        }
      );
    }
  • Type definition for CodexSessionDiscardResult interface that defines the return structure: success (boolean), discarded (string[]), and failed (array of objects with sessionId and reason).
    export interface CodexSessionDiscardResult {
      success: boolean;
      discarded: string[];
      failed: Array<{ sessionId: string; reason: string }>;
    }

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