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 }>;
    }
Behavior4/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 effectively describes key behavioral traits: the tool discards sessions, has a default refusal mechanism for active sessions, and allows overriding with force=true. This covers destructive intent and conditional behavior, though it lacks details on permissions or error handling.

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 front-loaded with the core purpose and follows with a crucial behavioral detail in a single, efficient sentence. Every word earns its place, avoiding redundancy and maintaining clarity.

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

Completeness4/5

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

Given the tool's complexity as a destructive operation with no annotations or output schema, the description is reasonably complete. It covers the main action and a key behavioral constraint, but could benefit from mentioning prerequisites or potential side effects to be fully comprehensive.

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 parameters. The description adds some context by explaining the interaction between sessionIds and force, but does not provide additional meaning beyond what the schema specifies for parameters like workingDirectory.

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

Purpose5/5

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

The description clearly states the verb ('discard') and resource ('Codex sessions'), making the purpose specific and unambiguous. It distinguishes itself from sibling tools like 'session_list' by indicating a destructive operation rather than a read operation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context on when to use the tool by mentioning the default behavior of refusing to discard active sessions unless force=true. However, it does not explicitly state when not to use it or name alternatives, such as whether 'session_list' should be consulted first.

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