Flatten messages[] (in memory)
flatten_messagesReduce token usage by replacing large tool_result blocks in messages with compact markers, returning extracted data for separate storage and later restoration.
Instructions
Flatten a raw Anthropic Messages API messages[] array in memory: every bulky tool_result block (large text or base64 image) larger than min_size bytes is swapped for a compact [FLATTENED id=...] marker, and the originals are returned in "extracted". Persist "extracted" yourself — you are the store — and feed it back to unflatten_messages to restore the conversation byte-for-byte. Purely functional: no session file, no disk, no network; the input is never mutated. This is the same engine as the flatten-mcp library export; for production use inside your own process, prefer importing the library so the conversation does not travel over a transport.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| messages | Yes | The raw Messages API messages[] array ({ role, content } objects, verbatim). | |
| min_size | No | Only flatten tool_result blocks larger than N serialized bytes. |
Output Schema
| Name | Required | Description | Default |
|---|---|---|---|
| messages | Yes | The flattened messages[] array — safe to send — with every bulky tool_result replaced by a compact [FLATTENED id=...] marker. Deep-copied; the input is never mutated. | |
| extracted | Yes | The originals removed from the conversation. Persist this array yourself and pass it back to unflatten_messages to restore byte-for-byte. | |
| flattenedCount | Yes | How many tool_result blocks were flattened. | |
| contextTokensExact | Yes | Always false here — the in-memory tool never makes a network call; use the library flattenMessagesExact for an exact count. | |
| contextTokensSaved | Yes | Estimated context tokens removed from the conversation. | |
| imageBlocksFlattened | Yes | How many image blocks were among the flattened results. |