Compression Strategies
New here? Start with the STM Overview to see the full pipeline in context first.
Every MCP tool response routed through STM passes through its compression gate before it reaches your agent. Direct upstream calls bypass STM. When a routed response exceeds its configured budget, STM compresses it — and the method depends on the content type.
Exception — annotated multi-block responses: when a successful (non-isError) response has more than one text block and any text block carries metadata (annotations or _meta), STM keeps the block boundaries instead of compressing the response as one string. Each text block is cleaned on its own, the raw text is capped at max_upstream_chars, and the cleaned text is cut to the tool’s character budget (max_result_chars, or max_result_tokens when a token budget is set) with no retention floor. Block metadata, non-text content, structuredContent and _meta are kept, and the response is returned without compression, surfacing or caching (metrics strategy none→metadata_bypass). To receive more, raise the tool’s budget, and max_upstream_chars if that is the lower limit. Under structured delivery, the same path also takes any successful response that carries upstream structuredContent or non-text content.
memtomem-stm automatically compresses MCP tool responses by content type to save tokens. It ships 10 strategies in total — 8 content-type reducers plus the auto selector and the none passthrough — reducing response size while preserving the information the agent needs. If you’re not sure which to pick, leave the setting on auto — it chooses the right reducer per response from the immediate-response strategies. The STM pages describe the default legacy delivery; the experimental structured format is covered in Structured chunk delivery.
Compression Strategies
Section titled “Compression Strategies”| Strategy | Target content | Behavior |
|---|---|---|
| truncate | Small text | Length-limited truncation (default fallback) |
| hybrid | Markdown | Preserve structure + abbreviate non-essential sections |
| selective | Large structured data | Two-phase TOC first, then retrieve selected sections on demand |
| progressive | Large content | Cursor-based sequential delivery of the retained source |
| extract_fields | JSON dictionaries | Preserve top-level shape with representative nested values |
| schema_pruning | JSON arrays | Recursive schema-preserving sampling |
| skeleton | API docs | Preserve headings and first content lines |
| llm_summary | Complex text | LLM-based summarization (OpenAI/Anthropic/Ollama) — timeout-bound (default 60s) |
| auto | All types | Analyze content and auto-select optimal strategy |
| none | — | Pass through original without compression |
In a selective TOC, each Markdown section keeps its heading line. Headings follow Markdown rules: a # line inside a code fence is not a heading, a heading may be indented up to three spaces, and a closing # sequence is not part of the key (## Title ## is keyed Title). JSON TOC entries report each value’s real type, such as number, boolean or null.
Auto-Selection Logic
Section titled “Auto-Selection Logic”The auto strategy (default) analyzes content to pick the optimal strategy:
| Content type | Selected strategy |
|---|---|
| Already within budget | none |
| Large JSON array, or dict containing large arrays | schema_pruning |
| Nested JSON dictionary | extract_fields |
| API docs with HTTP endpoints | skeleton |
| Large structured Markdown / code-heavy text | hybrid |
| Other text or simple JSON | truncate |
selective, progressive, and llm_summary are opt-in only. auto never chooses them because they change the interaction pattern or add external latency.
JSON nested more than 512 levels deep is not treated as JSON. The JSON-aware compression paths fall back to their text handling, so such a response is compressed like any other text instead of failing the call.
Query-Aware Budget Allocation
Section titled “Query-Aware Budget Allocation”During compression, the agent’s current query is taken into account — relevant sections receive a larger token budget. The selective / hybrid / schema_pruning / skeleton strategies also rank table-of-contents entries by BM25 relevance to the active query. The deterministic BM25 score used here is recorded by selection telemetry for offline analysis (see Configuration).
Budgets can be expressed as max_result_chars or max_result_tokens. Token budgets use chars_per_token plus token_estimation_mode (static or Unicode-aware unicode), while consumer_model and context_budget_ratio can cap a result against the receiving model’s context window. Per-upstream and per-tool values override proxy defaults.
JSON Safety
Section titled “JSON Safety”JSON-aware tiers re-serialize strict JSON after compression. Non-finite values such as NaN, Infinity, and -Infinity are mapped to null before JSON output so downstream parsers do not receive Python extension tokens. The JSON tiers degrade monotonically as budgets shrink. Under legacy delivery, the documented exception is standalone selective: it shrinks per-entry previews first, but a zero-preview TOC envelope can still exceed budget at very high section counts because dropping entries would break the selection contract.
Progressive Delivery
Section titled “Progressive Delivery”The progressive strategy delivers retained content sequentially, subject to the recovery boundaries below:
- First response delivers a table of contents (TOC) and the first chunk
- Agent calls
stm_proxy_read_more(key, offset)→ cursor-based delivery of subsequent chunks - Full content can be inspected sequentially
Under legacy delivery, every progressive chunk ends with the canonical footer \n---\n[progressive: chars=<n>] — agents must split on the full PROGRESSIVE_FOOTER_TOKEN string (exported from memtomem_stm.proxy.progressive). Splitting on \n---\n alone silently drops bytes when content contains Markdown horizontal rules or YAML fences.
Per-response follow-up rate and coverage for progressive delivery — along with degradation to passthrough when the primary store fails — are reported by stm_admin(action="progressive_stats") (see MCP Tools). mms stats reads the same telemetry from disk and adds a Progressive delivery block that compares the characters produced with the characters delivered (--json: progressive).
The response cache uses key schema 8 and preserves the canonical MCP envelope, including content, structuredContent, and _meta. An incompatible older cache is reset once instead of mixing envelope versions. An upstream result that quotes STM’s progressive footer (\n---\n[progressive: chars=) is cached unless it also carries the stm_proxy_read_more(key="…") call.
Structured chunk delivery
Section titled “Structured chunk delivery”Set delivery_format: "structured" globally (MEMTOMEM_STM_PROXY__DELIVERY_FORMAT), on an upstream, or in a tool_overrides entry; the closest setting wins. A progressive, selective or hybrid key keeps the format it was published with, and the continuation tools can override it per call with response_format (legacy or structured).
- Payload: for an eligible text-only response, STM puts a versioned JSON envelope in the text block, and continuations return it both in text and in
structuredContent. Read content and control fields fromstm.payload. For progressive reads, concatenate thecontentfields exactly and pass eachnext_offsetback unchanged; the footer rule above applies only to legacy delivery, and body text may contain the footer token. Offsets and limits count Unicode code points. - Native payloads: a successful (non-
isError) response that carries upstreamstructuredContentor non-text content keeps it as is. Each text block is cleaned on its own, their total text is capped at the tool’s character budget, and the response skips compression, surfacing, indexing and caching and gets no continuation key. - Budget: the character budget covers the serialized MCP result, including JSON escapes and, on continuations, both representations. Optional surfacing and index supplements are added after that check, so the final result can be larger.
selectiveandhybridalso hold passthrough responses to this serialized result budget (returning a TOC, progressive delivery, orbudget_exceededrather than an over-budget success). A TOC that cannot fit with all its keys falls back to progressive delivery, and a budget too small to deliver even one character of content returnsbudget_exceeded. If the pending store fails,selectiveandhybriddegrade to a shorter budget-fitting truncation orbudget_exceeded, andprogressivedegrades to a boundary-aware truncation with no continuation key (orbudget_exceededwhen none fits) instead of a full-text passthrough;legacydelivery is unchanged. Structured selective and TOC-mode hybrid delivery do not widen the budget to meet aretention_floor, because their keys keep the source recoverable. - Selection: a chosen section is never truncated; if the selected keys exceed the stored budget, ask for fewer keys or for
response_format: "legacy". - Surfacing: memories arrive in
stm.supplements.surfacinginstead of the response text, so everyinjection_modeworks, includingprepend. - Cache and stats: the response-cache key includes the delivery format.
mms statsreports structured calls on a separateStructured delivery:line (--json:compression.structured_delivery), apart from the legacy saved ratio, and the tuner’s retention ratios leave them out.
The upstream structured chunk delivery reference lists the envelope fields and error codes.
Fallback Ladder
Section titled “Fallback Ladder”The retention floor (MEMTOMEM_STM_PROXY__MIN_RESULT_RETENTION, default 0.65) guards against over-compression. When an output drops below the floor, a 3-tier fallback activates automatically:
progressive → hybrid → truncateEach tier checks the floor — if satisfied, that strategy’s output is used. The char budget is raised to len(response) * min_result_retention before truncation when per-tool max_result_chars would otherwise drop more than the floor allows.
- Rounding the minimum: the minimum is rounded up to a whole character and passed to plain-text truncation. Truncation picks a sentence or word boundary only at or above it, and otherwise cuts at the budget. This covers the
truncatestrategy,llm_summarywithout an LLM configured, the schema-pruning and skeleton plain-text fallbacks, store-error degradation and the terminal truncate tier.- A plain-text cut that used to fall a few characters short of the floor, and switch to progressive delivery, now arrives as one truncated result of at least the floor.
- A result that still falls short, such as a structural cut, takes its fallback as before.
- Explicit
retention_floor: a toolretention_flooroverrides a server one, which overrides the global ladder;nullinherits and an explicit0opts that level out. An explicitretention_floorapplies even withmin_result_retention: 0(but not to the annotated multi-block exception above). A tool set to1.0, for example, is preserved in full rather than cut to its character budget.
The llm_summary strategy has its own timeout guard: the llm_timeout_seconds field (default 60s) on the per-server / per-tool llm block. A slow or stuck LLM endpoint no longer blocks the proxy — on timeout, STM falls back to truncate so the agent still receives a bounded response. An empty or whitespace-only summary makes the compressor fall back to the truncated original, recorded as llm_summary→llm_empty_fallback when that result clears the retention floor; if it does not, the retention guard replaces it as for any other result (for example llm_summary→progressive_fallback). Because the endpoint answered, an empty summary does not count as a circuit-breaker failure. Anthropic responses are read from every text block, not only the first.
Compression Budget Tuning
Section titled “Compression Budget Tuning”Agent feedback automatically adjusts per-tool compression budgets:
- Agent reports information loss → Increase preservation ratio for that tool
- Agent reports response too long → Decrease preservation ratio
This feedback loop is driven by the stm_compression_feedback tool; accumulated feedback and per-tool adjustments are visible via stm_admin(action="compression_stats") (see MCP Tools).
Recovery boundaries
Section titled “Recovery boundaries”Progressive delivery retains the cleaned source after upstream limits, not an unlimited byte-for-byte copy of the original response. Pending selections are memory-backed by default; SQLite persistence is opt-in. With pending_store: "sqlite", a SELECTIVE, HYBRID or PROGRESSIVE response that would be stored there and matches STM’s credential patterns is not written to pending_selections.db: it comes back uncached as a boundary-aware truncation (SELECTIVE/HYBRID, truncate_on_sensitive) or as the full cleaned response (PROGRESSIVE, passthrough_on_sensitive). Email addresses do not trigger it. Entries expire under their TTL; progressive.ttl_seconds: 0 expires immediately, delivering the first chunk with an expiry notice. An expired ID returns an error, not an automatic upstream refetch. Repeating an original read-only call is a separate, explicit action; do not replay a write just to recover content.
Cache key schema 8 uses length-prefixed key framing and Unicode serialization, binds a cached reply to the upstream’s connection settings (URL, headers, transport, command), so editing them no longer replays the old connection’s reply, and keys each row with an HMAC under a key file beside the database (its path plus .key, proxy_cache.db.key by default). Older cache rows are discarded on initialization (metrics and feedback are kept), so the response cache and the tool-graph consult cache start empty once after upgrading to 0.7.9; restart running proxies so no process from the previous release keeps writing unkeyed rows. This is separate from deleting LTM memories.