Skip to main content
Glama

Flatten Claude Code or Codex session

flatten_session

Flatten a Claude Code or OpenAI Codex CLI session by moving large tool results into a backup, reducing context tokens while preserving conversation integrity. Resume with a lighter copy.

Instructions

Flatten a Claude Code or OpenAI Codex CLI session: move bulky tool results (large text output and, for Claude, base64 image/screenshot blocks) out of the session JSONL into a backup copy, leaving a compact [FLATTENED ...] marker. The conversation reads identically — every prompt and event stays verbatim — but resumes with far fewer context tokens. Crash-safe (atomic rewrite + a single backup holding the complete session) and reversible via unflatten_session. Choose the store with agent ("claude" default, or "codex"). Reports diskBytesSaved and contextTokensSaved out of contextTokensTotal. For claude these are estimated locally, or exact when FLATTEN_COUNT_EXACT=1 and ANTHROPIC_API_KEY are both set; for codex the token savings are ALWAYS a local estimate (Anthropic count_tokens does not measure the GPT-5 tokenizer) and contextTokensTotal comes from Codex's own token_count events. With no session_id, flattens the current live session (claude); under codex "current" falls back to "last" (Codex has no live-session linkage). Also accepts a UUID, "last", "last N", or "current"; under codex a UUID reaches any rollout in the tree, while "last"/"last N"/keyword are scoped to the project dir. After flattening, /resume the session (claude) or codex resume the rollout (codex) to load the lighter copy.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
agentNoWhich agent's session store to target: "claude" (default) or "codex".claude
dry_runNoReport what would be flattened without modifying files
min_sizeNoOnly flatten tool results larger than N bytes
breakdownNoInclude the per-tool/resource breakdown of what was flattened. false, true, or "summary" = the aggregated adaptive rows plus byKind/bySlot groupings; "deep" ALSO lists every individual block under its row (tool + arg summary + bytes + per-block token estimate), groups sorted by context tokens then blocks by bytes. Dry runs always include at least the summary; set true/"summary"/"deep" to also get it on a real flatten.
sessionIdNocamelCase alias for session_id (accepted so a camelCase call does not fail validation).
claude_dirNoAbsolute path (or ~/...) to the Claude config dir whose sessions to target — the dir holding projects/. Default: $CLAUDE_CONFIG_DIR if set, else ~/.claude. Applies to agent "claude" only.
codex_homeNoAbsolute path (or ~/...) to the Codex home whose sessions to target — the dir holding sessions/. Default: $CODEX_HOME if set, else ~/.codex. Applies to agent "codex" only.
session_idNoSession UUID, "last", "last N", or "current". Omit to flatten the current live session (claude); under codex "current" falls back to "last".
project_dirNoAbsolute path to project. Default: the project the CLI runs in (cwd). Under codex, scopes "last"/"last N"/keyword to rollouts whose cwd equals this dir.
include_tool_use_resultNoAlso flatten the top-level toolUseResult mirror Claude Code keeps per result line (roughly doubles disk savings; lossless & restorable). Set false to only touch message.content.

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
sessionsYesOne entry per session flattened (a single entry for one session_id, or several for "last N").

Schema Changelog

Changes observed during successful MCP inspections. Dates show when Glama detected each change.

  1. Changed12 schema fields changedv2.6.0
    • addedInput schema / properties / agent
      Added value: +{
      +  "default": "claude",
      +  "description": "Which agent's session store to target: \"claude\" (default) or \"codex\".",
      +  "enum": [
      +    "claude",
      +    "codex"
      +  ],
      +  "type": "string"
      +}
    • addedInput schema / properties / breakdown
      Added value: +{
      +  "anyOf": [
      +    {
      +      "type": "boolean"
      +    },
      +    {
      +      "enum": [
      +        "summary",
      +        "deep"
      +      ],
      +      "type": "string"
      +    }
      +  ],
      +  "default": false,
      +  "description": "Include the per-tool/resource breakdown of what was flattened. false, true, or \"summary\" = the aggregated adaptive rows plus byKind/bySlot groupings; \"deep\" ALSO lists every individual block under its row (tool + arg summary + bytes + per-block token estimate), groups sorted by context tokens then blocks by bytes. Dry runs always include at least the summary; set true/\"summary\"/\"deep\" to also get it on a real flatten."
      +}
    • changedInput schema / properties / claude_dir / description
      Previous value: -"Absolute path (or ~/...) to the Claude config dir whose sessions to target — the dir holding projects/. Default: $CLAUDE_CONFIG_DIR if set, else ~/.claude."New value: +"Absolute path (or ~/...) to the Claude config dir whose sessions to target — the dir holding projects/. Default: $CLAUDE_CONFIG_DIR if set, else ~/.claude. Applies to agent \"claude\" only."
    • addedInput schema / properties / codex_home
      Added value: +{
      +  "description": "Absolute path (or ~/...) to the Codex home whose sessions to target — the dir holding sessions/. Default: $CODEX_HOME if set, else ~/.codex. Applies to agent \"codex\" only.",
      +  "type": "string"
      +}
    • changedInput schema / properties / project_dir / description
      Previous value: -"Absolute path to project. Default: the project the CLI runs in (cwd)"New value: +"Absolute path to project. Default: the project the CLI runs in (cwd). Under codex, scopes \"last\"/\"last N\"/keyword to rollouts whose cwd equals this dir."
    • changedInput schema / properties / session_id / description
      Previous value: -"Session UUID, \"last\", \"last N\", or \"current\". Omit to flatten the current live session."New value: +"Session UUID, \"last\", \"last N\", or \"current\". Omit to flatten the current live session (claude); under codex \"current\" falls back to \"last\"."
    • addedOutput schema / properties / sessions / items / properties / breakdown
      Added value: +{
      +  "additionalProperties": false,
      +  "description": "X-ray of what was flattened: adaptive tool/resource rows plus byKind and bySlot groupings, each with the bytes and context tokens freed. Present on every dry run with at least one qualifying block, and on a real flatten only when breakdown=true. contextTokens are exact when tokensExact (per-group count_tokens, requiring the FLATTEN_COUNT_EXACT=1 + ANTHROPIC_API_KEY opt-in), otherwise a local estimate; they are always 0 for the toolUseResult slot (the mirror is disk-only and never in model context).",
      +  "properties": {
      +    "byKind": {
      +      "description": "Grouped by block kind.",
      +      "items": {
      +        "additionalProperties": false,
      +        "properties": {
      +          "bytes": {
      +            "description": "Disk bytes this group frees.",
      +            "type": "number"
      +          },
      +          "contextTokens": {
      +            "description": "Context tokens this group frees — exact when tokensExact, else estimated; 0 for toolUseResult-slot blocks.",
      +            "type": "number"
      +          },
      +          "count": {
      +            "description": "How many blocks this group holds.",
      +            "type": "number"
      +          },
      +          "key": {
      +            "description": "Block kind: \"text\", \"image\", or \"mixed\" (the group key).",
      +            "type": "string"
      +          }
      +        },
      +        "required": [
      +          "key",
      +          "count",
      +          "bytes",
      +          "contextTokens"
      +        ],
      +        "type": "object"
      +      },
      +      "type": "array"
      +    },
      +    "bySlot": {
      +      "description": "Grouped by storage slot.",
      +      "items": {
      +        "additionalProperties": false,
      +        "properties": {
      +          "bytes": {
      +            "description": "Disk bytes this group frees.",
      +            "type": "number"
      +          },
      +          "contextTokens": {
      +            "description": "Context tokens this group frees — the full contextTokensSaved on the content row, 0 on the disk-only toolUseResult row.",
      +            "type": "number"
      +          },
      +          "count": {
      +            "description": "How many blocks this group holds.",
      +            "type": "number"
      +          },
      +          "key": {
      +            "description": "Slot: \"content\" (message.content, in model context) or \"toolUseResult\" (the disk-only mirror).",
      +            "type": "string"
      +          }
      +        },
      +        "required": [
      +          "key",
      +          "count",
      +          "bytes",
      +          "contextTokens"
      +        ],
      +        "type": "object"
      +      },
      +      "type": "array"
      +    },
      +    "rows": {
      +      "description": "Adaptive tool/resource rows: MCP tools collapse per server, heavyweight resources get their own row, and the light tail folds into a single \"other\" row (at most 9 rows). Partitions the flattened blocks exactly. In deep mode each row also carries its individual blocks in .entries.",
      +      "items": {
      +        "additionalProperties": false,
      +        "properties": {
      +          "bytes": {
      +            "description": "Disk bytes this row frees.",
      +            "type": "number"
      +          },
      +          "contextTokens": {
      +            "description": "Context tokens this row frees — exact when tokensExact, else estimated; 0 for toolUseResult-slot blocks.",
      +            "type": "number"
      +          },
      +          "count": {
      +            "description": "How many blocks this row holds.",
      +            "type": "number"
      +          },
      +          "entries": {
      +            "description": "Deep mode only (breakdown=\"deep\"): the individual blocks this row aggregates, sorted by bytes desc — the per-command attribution. Absent in summary mode.",
      +            "items": {
      +              "additionalProperties": false,
      +              "properties": {
      +                "args": {
      +                  "description": "Short arg summary (command=…, file_path=…); \"\" when none.",
      +                  "type": "string"
      +                },
      +                "bytes": {
      +                  "description": "Disk bytes this block frees.",
      +                  "type": "number"
      +                },
      +                "contextTokens": {
      +                  "description": "Per-block net context-token estimate (local; never reconciled to the exact per-group total).",
      +                  "type": "number"
      +                },
      +                "kind": {
      +                  "description": "\"text\", \"image\", or \"mixed\".",
      +                  "type": "string"
      +                },
      +                "lineCount": {
      +                  "description": "Line count of the block's text projection.",
      +                  "type": "number"
      +                },
      +                "name": {
      +                  "description": "Originating tool name of this block.",
      +                  "type": "string"
      +                },
      +                "slot": {
      +                  "description": "\"content\" (in model context) or \"toolUseResult\" (disk-only mirror, 0 context tokens).",
      +                  "type": "string"
      +                }
      +              },
      +              "required": [
      +                "name",
      +                "args",
      +                "bytes",
      +                "kind",
      +                "slot",
      +                "contextTokens",
      +                "lineCount"
      +              ],
      +              "type": "object"
      +            },
      +            "type": "array"
      +          },
      +          "key": {
      +            "description": "Row key: a tool family (\"<server> (MCP)\" for MCP tools, else the built-in tool name), or \"other\" for the tail-collapsed row.",
      +            "type": "string"
      +          },
      +          "resource": {
      +            "description": "Present only on a resource-promoted row: the raw file_path/path/url value that earned this tool family its own line.",
      +            "type": "string"
      +          }
      +        },
      +        "required": [
      +          "key",
      +          "count",
      +          "bytes",
      +          "contextTokens"
      +        ],
      +        "type": "object"
      +      },
      +      "type": "array"
      +    },
      +    "tokensExact": {
      +      "description": "True when the rows' contextTokens are exact (per-group count_tokens), false when locally estimated.",
      +      "type": "boolean"
      +    }
      +  },
      +  "required": [
      +    "tokensExact",
      +    "rows",
      +    "byKind",
      +    "bySlot"
      +  ],
      +  "type": "object"
      +}
    • changedOutput schema / properties / sessions / items / properties / entries / description
      Previous value: -"One row per flattened block (id, originating tool name, size, kind, and slot)."New value: +"One row per flattened block — id, originating tool name, arg summary, size, kind, slot, per-block token estimate, and line count. The machine-readable per-command attribution the breakdown aggregates."
    • addedOutput schema / properties / sessions / items / properties / entries / items / properties / args
      Added value: +{
      +  "description": "Short arg summary of the originating call (e.g. command=…, file_path=…), same grammar as the marker; \"\" when none.",
      +  "type": "string"
      +}
    • addedOutput schema / properties / sessions / items / properties / entries / items / properties / contextTokens
      Added value: +{
      +  "description": "Per-block net context-token estimate (local; not reconciled to the exact per-group total).",
      +  "type": "number"
      +}
    • addedOutput schema / properties / sessions / items / properties / entries / items / properties / lineCount
      Added value: +{
      +  "description": "Line count of the block's text projection.",
      +  "type": "number"
      +}
    • changedOutput schema / properties / sessions / items / properties / entries / items / required
      Previous value: -[
      -  "id",
      -  "name",
      -  "size",
      -  "kind",
      -  "slot"
      -]New value: +[
      +  "id",
      +  "name",
      +  "args",
      +  "size",
      +  "kind",
      +  "slot",
      +  "contextTokens",
      +  "lineCount"
      +]
  2. Changed1 schema field changed
    • changedOutput schema / (root)
      Previous value: -nullNew value: +{
      +  "$schema": "http://json-schema.org/draft-07/schema#",
      +  "additionalProperties": false,
      +  "properties": {
      +    "sessions": {
      +      "description": "One entry per session flattened (a single entry for one session_id, or several for \"last N\").",
      +      "items": {
      +        "additionalProperties": false,
      +        "properties": {
      +          "backupPath": {
      +            "description": "Path to the single self-syncing backup holding the complete inlined session.",
      +            "type": "string"
      +          },
      +          "contextSavingsPercent": {
      +            "description": "contextTokensSaved as a percent of contextTokensTotal, or \"n/a\".",
      +            "type": "string"
      +          },
      +          "contextTokensExact": {
      +            "description": "True if counted via count_tokens, false if estimated locally.",
      +            "type": "boolean"
      +          },
      +          "contextTokensSaved": {
      +            "description": "Context tokens removed from the model context (the number that matters for --resume/compaction).",
      +            "type": "number"
      +          },
      +          "contextTokensTotal": {
      +            "description": "Real context size from the last turn API usage, or null if unknown.",
      +            "type": [
      +              "number",
      +              "null"
      +            ]
      +          },
      +          "diskBytesSaved": {
      +            "description": "Bytes removed from the .jsonl on disk (speeds --resume parsing).",
      +            "type": "number"
      +          },
      +          "diskSavingsPercent": {
      +            "description": "diskBytesSaved as a percent of the original file size.",
      +            "type": "string"
      +          },
      +          "dryRun": {
      +            "description": "True when dry_run was set — no files were modified.",
      +            "type": "boolean"
      +          },
      +          "entries": {
      +            "description": "One row per flattened block (id, originating tool name, size, kind, and slot).",
      +            "items": {
      +              "additionalProperties": false,
      +              "properties": {
      +                "id": {
      +                  "type": "string"
      +                },
      +                "kind": {
      +                  "type": "string"
      +                },
      +                "name": {
      +                  "type": "string"
      +                },
      +                "size": {
      +                  "type": "number"
      +                },
      +                "slot": {
      +                  "type": "string"
      +                }
      +              },
      +              "required": [
      +                "id",
      +                "name",
      +                "size",
      +                "kind",
      +                "slot"
      +              ],
      +              "type": "object"
      +            },
      +            "type": "array"
      +          },
      +          "flattenedCount": {
      +            "description": "How many tool results were flattened (0 on a no-op or dry run with nothing to do).",
      +            "type": "number"
      +          },
      +          "imageBlocksFlattened": {
      +            "description": "How many image/screenshot blocks were among them.",
      +            "type": "number"
      +          },
      +          "newSize": {
      +            "description": "Session file size after flattening, in bytes.",
      +            "type": "number"
      +          },
      +          "originalSize": {
      +            "description": "Session file size before flattening, in bytes.",
      +            "type": "number"
      +          },
      +          "resumeHint": {
      +            "description": "Present only when a live session was actually rewritten — reminds you to /resume to load the lighter copy.",
      +            "type": "string"
      +          },
      +          "sessionId": {
      +            "description": "The session UUID that was processed.",
      +            "type": "string"
      +          }
      +        },
      +        "required": [
      +          "sessionId",
      +          "dryRun",
      +          "flattenedCount",
      +          "imageBlocksFlattened",
      +          "diskBytesSaved",
      +          "diskSavingsPercent",
      +          "contextTokensTotal",
      +          "contextTokensSaved",
      +          "contextSavingsPercent",
      +          "contextTokensExact",
      +          "originalSize",
      +          "newSize",
      +          "backupPath",
      +          "entries"
      +        ],
      +        "type": "object"
      +      },
      +      "type": "array"
      +    }
      +  },
      +  "required": [
      +    "sessions"
      +  ],
      +  "type": "object"
      +}
  3. Changed4 schema fields changed
    • changedInput schema / properties / claude_dir / description
      Previous value: -"Absolute path (or ~/...) to the Claude config dir whose sessions to target — the dir holding projects/, e.g. ~/.claude-2 for a second profile. Default: $CLAUDE_CONFIG_DIR if set (so a server running inside an alternate profile targets it), else ~/.claude."New value: +"Absolute path (or ~/...) to the Claude config dir whose sessions to target — the dir holding projects/. Default: $CLAUDE_CONFIG_DIR if set, else ~/.claude."
    • removedInput schema / properties / force
      Removed value: -{
      -  "default": false,
      -  "description": "Flatten even if the session was modified seconds ago (may be live). Use only when the session is idle.",
      -  "type": "boolean"
      -}
    • changedInput schema / properties / sessionId / description
      Previous value: -"camelCase alias for session_id (the list_sessions output uses this name). Use session_id; this is accepted so a camelCase call does not fail validation."New value: +"camelCase alias for session_id (accepted so a camelCase call does not fail validation)."
    • changedInput schema / properties / session_id / description
      Previous value: -"Session UUID, \"last\", \"last N\", or \"current\" (most recent). Any other value is treated as a keyword matched against first messages and branch names, and may flatten MULTIPLE matching sessions — prefer a UUID here."New value: +"Session UUID, \"last\", \"last N\", or \"current\". Omit to flatten the current live session."
  4. Changed1 schema field changedv1.1.0
    • addedInput schema / properties / claude_dir
      Added value: +{
      +  "description": "Absolute path (or ~/...) to the Claude config dir whose sessions to target — the dir holding projects/, e.g. ~/.claude-2 for a second profile. Default: $CLAUDE_CONFIG_DIR if set (so a server running inside an alternate profile targets it), else ~/.claude.",
      +  "type": "string"
      +}
  5. First observedv1.0.3

TDQS

A4.8/5.0
Behavior5/5

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

Discloses crash-safe atomic rewrite, reversible nature, estimation vs exact token savings for each agent, and behavior with 'current' under codex. No contradiction with annotations (readOnlyHint=false, destructiveHint=false). Adds extensive behavioral context beyond annotations.

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?

Front-loaded with core purpose; but the description is long and includes many details that could be condensed. However, given the tool's complexity, the length is justified and well-structured.

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

Completeness5/5

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

Covers all aspects: agent differences, token calculation, session ID handling, directory paths, output fields mentioned. Comprehensive for a 10-parameter tool with output schema.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema has 100% description coverage, so baseline is 3. The description adds moderate extra context, e.g., explaining dry_run reports without modifying, breakdown options in detail, and behavior of session_id. But the schema descriptions are already good, so only slight improvement.

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?

Description clearly states the tool flattens Claude Code or Codex CLI sessions by moving bulky tool results to a backup copy and leaving compact markers. It distinguishes from siblings like unflatten_session and flatten_messages.

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

Usage Guidelines5/5

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

Provides explicit guidance on when to use (to reduce context tokens), how to choose agent, fallback behaviors for different session_id values, and mentions reversible via unflatten_session. Clearly states alternatives and context.

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

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/shayaShav/flatten-mcp'

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