Skip to content

feat(server): adaptive TOON output for tool results (spec 084) - #852

Merged
github-actions[bot] merged 11 commits into
mainfrom
084-toon-output
Jul 15, 2026
Merged

github-actions[bot] merged 11 commits into
mainfrom
084-toon-output

Conversation

@Dumbris

@Dumbris Dumbris commented Jul 14, 2026

Copy link
Copy Markdown
Member

Summary

Implements spec 084 — Adaptive TOON Output for Tool Results: opt-in, per-response-adaptive TOON serialization for call_tool_* result payloads. Encode only when the payload is tabular-uniform and the complete emission (marker + hint + body) beats the exact passthrough emission by ≥ threshold (default 15%) — never larger by construction. Off by default; byte-identical when off.

Grounded in spec-083 profiler measurements (PR #851): TOON is +23.9% worse on tool listings (excluded — retrieve_tools untouched) and wins only on uniform tabular results, hence adaptive instead of blanket.

What's new

  • internal/toonenc (leaf package, bench-importable): v1 tabular classifier (≥4 rows, scalar/null values, ≥90% key presence, single-key envelope), ordered-representation encoder (no map-iteration nondeterminism), complete-emission size comparison, ASCII marker + one-line decode hint, per-block Decision records, number-fidelity gate (any json.Number that toon-go would round through float64 — e.g. 2^53+1 — forces byte-identical passthrough)
  • Server seam (encodeToonBlocks): sanitise → encode → truncate ordering; contentTrust threaded; off ⇒ empty detection text + byte-identical path; retained-prefix-aware truncation guard; token metrics recount from the final response when encoding ran
  • Config: toon_output: off|adaptive|always (+ per-server override), toon_min_savings_pct (1–90), validation, hot-reload via DetectConfigChanges
  • Security parity: sensitive-data detection produces identical FINDINGS with the feature on/off (security corpus + over-limit fixtures); output sanitisation runs on the raw pre-encoding result
  • Scope isolation tests: code_execution, direct mode, and retrieve_tools byte-identical under every mode value
  • Activity audit: per-block encoding decisions with before/after byte sizes in tool_call metadata

Cross-branch note: the profiler adaptive-results arm (FR-012) is explicitly blocked on #851 merging; it lands as a follow-up after rebase.

Review

Spec: Codex-approved (3 rounds, 13 findings). Plan: Codex-approved (5 rounds, 14 findings). Implementation: Codex-approved (3 rounds — caught a real big-integer corruption bug and a token-metrics overreport, both fixed with tests).

Testing

  • go test ./internal/{toonenc,config,server}/... -race: green (server suite 502s)
  • golangci-lint v2 on touched packages: 0 issues
  • ./scripts/test-api-e2e.sh: all passed
  • Determinism: randomized key-order tests (non-vacuity asserted); golden fixtures newline-tolerant

Related #175

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 14, 2026 •

Copy link
Copy Markdown

Deploying mcpproxy-docs with  Cloudflare Pages  Cloudflare Pages

Latest commit: 5d7ab69
Status: ✅  Deploy successful!
Preview URL: https://bdbd68fd.mcpproxy-docs.pages.dev
Branch Preview URL: https://084-toon-output.mcpproxy-docs.pages.dev

View logs

@codecov-commenter

codecov-commenter commented Jul 14, 2026 •

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 89.03226% with 34 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
internal/server/toon_encode.go 85.86% 9 Missing and 4 partials ⚠️
internal/server/mcp.go 56.00% 10 Missing and 1 partial ⚠️
internal/runtime/event_bus.go 20.00% 2 Missing and 2 partials ⚠️
internal/server/mcp_routing.go 0.00% 2 Missing ⚠️
internal/toonenc/encoder.go 97.05% 1 Missing and 1 partial ⚠️
internal/truncate/truncator.go 80.00% 1 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

📦 Build Artifacts

Workflow Run: View Run
Branch: 084-toon-output

Available Artifacts

  • archive-darwin-amd64 (28 MB)
  • archive-darwin-arm64 (25 MB)
  • archive-linux-amd64 (16 MB)
  • archive-linux-arm64 (15 MB)
  • archive-windows-amd64 (28 MB)
  • archive-windows-arm64 (25 MB)
  • frontend-dist-pr (0 MB)
  • installer-dmg-darwin-amd64 (22 MB)
  • installer-dmg-darwin-arm64 (19 MB)

How to Download

Option 1: GitHub Web UI (easiest)

  1. Go to the workflow run page linked above
  2. Scroll to the bottom "Artifacts" section
  3. Click on the artifact you want to download

Option 2: GitHub CLI

gh run download 29398139119 --repo smart-mcp-proxy/mcpproxy-go

Note: Artifacts expire in 14 days.

Dumbris added 9 commits July 15, 2026 10:16
Related #175

Adaptive TOON encoding for call_tool_* result payloads: encode only when
tabular-uniform AND complete emission beats exact passthrough by >=15%
(never-larger by construction). Off by default, per-server override,
hot-reload. Security pipeline receives pre-encoding inputs; code_execution
and direct mode explicitly out of scope. Gated by spec-083 profiler
measurements (TOON listings measured +23.9% worse — excluded).

Codex-reviewed: 3 rounds, 13 findings fixed, VERDICT: APPROVE.
Related #175

Planning package: internal/toonenc leaf package (classifier + size-compared
encoder, ordered representation for determinism), server seam
encodeToonBlocks (contentTrust threaded; off ⇒ empty detection text),
truncation guard based on the truncator's actual retained-prefix budget,
detection FINDING-parity (spec US3 clarified accordingly), string-only
config resolution with per-server override, ASCII marker contract,
passthrough-error scoped to true encoder faults.

Codex-reviewed: 5 rounds, 14 findings fixed, VERDICT: APPROVE.
Related #175

Implements specs/084-toon-output: opt-in, measured, never-larger-by-construction.

- internal/toonenc: v1 tabular classifier (>=4 rows, scalar/null values,
  >=90% key presence, single-key envelope), ordered-representation encoder
  (no raw map iteration), complete-emission size comparison vs exact
  passthrough, ASCII marker + decode hint, Decision records
- internal/server: encodeToonBlocks seam (contentTrust + tool identity;
  off => byte-identical + empty detection text; sanitise before encode;
  encode before truncate with retained-prefix-aware guard), activity
  tool_call metadata per text-block, passthrough-error logging + counter
- internal/config: toon_output (off/adaptive/always) + per-server override,
  toon_min_savings_pct (1-90), validation, DetectConfigChanges wiring
- Detection FINDING-parity: same detections with feature on/off across the
  security corpus incl. over-limit fixtures
- Regression tests: code_execution, direct mode, retrieve_tools untouched
  under every mode value

- go test ./internal/{toonenc,config,server}/... -race: all green
- golangci-lint v2 on touched packages: 0 issues
- ./scripts/test-api-e2e.sh: all passed
- gofmt: branch-changed files clean (5 flagged files are pre-existing
  main drift, untouched)
…uous determinism test

Related #175

- Number fidelity gate: any json.Number that does not survive toon-go's
  exact float64 round-trip forces byte-identical passthrough
  (reason: non-roundtrippable-number) — 2^53+1 and max-uint64 corrupted
  before this fix; control test proves 2^53 still encodes
- FR-012 profiler-arm tasks marked CROSS-BRANCH-BLOCKED on PR #851
- Randomized-key determinism test now requires >=2 distinct serializations

## Testing
- go test ./internal/toonenc/... -race: green (incl. 8 new P1 subtests)
Related #175

OutputTokens/TotalTokens now recount from the final agent-facing response
whenever any block was TOON-encoded (previously only on truncation), so
tool-call history and session stats reflect the savings instead of
overreporting pre-encoding sizes. Adds toonEncodedAny helper + test.

## Testing
- go test ./internal/server -run 'Toon|TOON|TokenMetrics' -race: green
The Spec 084 FR-005 marker echo appended a verbose two-clause sentence
(64 tokens) to each call_tool_read|write|destructive description, pushing
the retrieve_tools proxy catalog past the frozen 45-tool corpus baseline
in bench.TestComputeReport_SavingsAreReal (1761 vs 1730 tokens), failing
unit tests on every platform plus the Windows/macOS binary builds.

Trim to the one-line footprint the spec asks for (§137), keeping
toonenc.Marker embedded verbatim so T037 / the single-source-of-truth
anti-drift guarantee still hold. The marker text is self-describing, so
the trailing explanatory clause was redundant.

Related #175
docs/features/toon-output.md is published on the Docusaurus site and its
links are validated (onBrokenLinks: throw). It linked to
../configuration.md#toon-output-adaptive-result-encoding, but the flat
docs/configuration.md is an orphan not in the sidebar, so it has no route
and the link 404s the docs build (Documentation + Cloudflare Pages
checks). Point at ../configuration/config-file.md, the routed canonical
config reference, matching the existing pattern in settings-page.md.

Related #175
Bleve returns search hits by score descending but leaves equally-scored
ties in an unstable, backend-dependent order. That order flows straight
into the retrieve_tools tools array and its JSON, so two otherwise-
identical calls could serialize differently. The Spec 084 surface-
isolation test (T031) compares retrieve_tools byte-for-byte across
toon_output modes and flaked on CI when a tie reordered between calls
(three github tools sharing an identical BM25 score).

Sort callable results by score desc then full tool name before building
the response, making the agent-facing output stable regardless of the
search backend. Full internal/index and internal/server suites pass.

Related #175
Dumbris added 2 commits July 15, 2026 10:28
…A5011

Related #175

CI lint upgraded to golangci-lint v2.6.2 whose staticcheck build no longer
models t.Fatal as no-return at these sites; explicit returns are
version-proof.
Related #175

CI-only SA5011 findings on t.Fatal no-return sites do not reproduce with
the identical golangci-lint v2.6.2 + config on a clean run; the action's
cross-run analysis cache is the remaining variable. Timeout raised to 10m
for cold runs.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved (Model B): Paperclip review verdicts = ACCEPT and qa-gate green at this head SHA. Arming auto-merge; GitHub merges when all required checks pass.

@github-actions
github-actions Bot merged commit bf3f736 into main Jul 15, 2026
52 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants