Skip to content

feat(server): compact router — progressive-disclosure tool discovery (spec 085) - #853

Merged
github-actions[bot] merged 9 commits into
mainfrom
085-compact-router
Jul 15, 2026
Merged

github-actions[bot] merged 9 commits into
mainfrom
085-compact-router

Conversation

@Dumbris

@Dumbris Dumbris commented Jul 14, 2026

Copy link
Copy Markdown
Member

Summary

Implements spec 085 — Compact Router: retrieve_tools responses become compact signatures with full schemas on demand, addressing the community ask (#175, aolin480, armorer-labs) that discovery-phase costs eat the proxy's token savings. Live profiling (PR #851) measured the problem — median 8,640 tokens per discovery call, 77% raw inputSchema — and this is the measured winner: compact signatures at unchanged recall.

Behavior-neutral by default: tool_response_mode: "full" ships as default with retrieve_tools payloads byte-identical to pre-feature behavior (golden-gated against merge-base bytes). The default flip to compact is a separate future one-liner gated by profiler metrics.

What's new

  • internal/toolsig (leaf package, bench-importable): deterministic signature compiler per a normative EBNF grammar — (origin*:str, ttl:int=3600, account~:obj) — with atom escaping, (~) malformed-schema fallback, Lossy ⇔ ~ biconditional, never-elide-required-NAMES invariant, first-sentence extraction (CJK/ASCII terminator rules), and a hash-keyed memoized cache (single runtime-owned instance; stale hashes evicted on reconcile and unable to repopulate)
  • Compact mode: entries carry id/score/signature/first-sentence/lossy + one hint line; per-call detail override; existing retrieve_tools params preserved; ranked-ID identity between modes verified across the full 47-query golden set (release-blocking test) — serialization cannot touch ranking by construction
  • describe_tool (new built-in, retrieve_tools mode only): 1–5 ids → full definitions field-equal to full-mode rendering; per-id errors; same visibility resolver as search plus quarantine/pending gates (strictly narrower — never returns what search would not); definition ≤150 tokens (cl100k-verified)
  • Self-healing errors: pre-dispatch argument validation (new capability — calls previously dispatched unvalidated) via existing santhosh-tekuri/jsonschema/v6, fail-open on uncompilable schemas; invalid-params errors embed the failing tool's full schema + hint; narrow upstream-error classifier with auth/timeout deny patterns (a 401 … invalid parameters does not attach schemas)
  • Search semantics frozen: merge-base filter behavior (scope + callability) preserved exactly, with merge-base-cited table tests
  • bench: flip-gate metrics (ranked-ID identity, lossy rate) + MCP caller helpers for the profiler compact arm

Cross-branch note: bench-arm grammar migration + savings re-baseline (T040/T043) are explicitly blocked until #851 merges and this branch rebases.

Review

Spec: Codex-approved (3 rounds, 17 findings — incl. discovering mcpproxy had no pre-dispatch validation). Plan: Codex-approved (4 rounds, 16 findings). Implementation: Codex-approved (3 rounds, 6 findings — incl. a quoted-~ grammar hole, a code-exec-mode surface leak, and a search-semantics drift, all fixed with tests).

Testing

  • go test ./internal/{toolsig,runtime,config,server}/... ./bench/... -race: green (server suite 512s)
  • golangci-lint v2 on touched packages: 0 issues
  • ./scripts/test-api-e2e.sh: all passed
  • Full-mode byte-identity golden (from merge-base) + exact menu-surface delta test (describe_tool + detail param + description updates, nothing else)

Related #175

Comment thread internal/toolsig/signature.go Fixed
Comment thread internal/toolsig/signature.go Fixed
@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: cd2017c
Status: ✅  Deploy successful!
Preview URL: https://eff2c2cc.mcpproxy-docs.pages.dev
Branch Preview URL: https://085-compact-router.mcpproxy-docs.pages.dev

View logs

@codecov-commenter

codecov-commenter commented Jul 14, 2026 •

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

📦 Build Artifacts

Workflow Run: View Run
Branch: 085-compact-router

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 (20 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 29415571581 --repo smart-mcp-proxy/mcpproxy-go

Note: Artifacts expire in 14 days.

Dumbris and others added 8 commits July 15, 2026 14:43
Related #175

Compact-by-default retrieve_tools (signatures, never-elide-required-names,
lossy markers) + describe_tool (batch ≤5, search-identical visibility) +
pre-dispatch argument validation with self-healing full-schema errors.
tool_response_mode: full default (byte-identical payloads), Phase-2 flip
gated by profiler metrics (ranked-ID identity 100%, lossy rate <20%).
design.md = judge-panel synthesis record (rationale-only, spec normative).

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

Planning package: internal/toolsig leaf package (signature grammar EBNF
with escaping + (~) malformed fallback, shared by production and bench),
entry-builder extraction seam, shared visibility resolver
(toolVisibleToSession), pre-dispatch validation via existing
santhosh-tekuri/jsonschema/v6 with FR-013b fail-open, hot-reload via
DetectConfigChanges + currentConfig(), describe_tool field-equality
(spec FR-010/US2-AC1 clarified accordingly), 47-query ranked-ID identity
gate release-blocking in US1, 46 TDD-paired tasks with FR/SC coverage table.

Cross-branch note: bench-arm grammar migration + savings re-baseline
(T040/T043) blocked until PR #851 merges and this branch rebases.

Codex-reviewed: 4 rounds, 16 findings fixed, VERDICT: APPROVE.
…(spec 085)

Related #175

Implements specs/085-compact-router: compact retrieve_tools signatures,
describe_tool, pre-dispatch validation with self-healing errors.

- internal/toolsig: signature compiler per the normative grammar (EBNF,
  atom escaping, (~) malformed fallback, first-sentence extraction with
  CJK/ASCII terminator rules), hash-keyed memoized cache (single
  runtime-owned instance; compile-count test)
- internal/server: mode-aware entry-builder seam (full path byte-identical,
  golden-gated against pre-feature bytes from merge-base), compact entries
  (id/score/sig/desc/lossy, never-elide-required-names), per-call detail
  override, hint line; describe_tool (1-5 ids, per-id errors, field-equal
  definitions, canonical visibility via extracted toolVisibleToSession);
  pre-dispatch argument validation (santhosh-tekuri/jsonschema/v6,
  FR-013b fail-open) with schema-embedding invalid-params errors in both
  modes; menu-surface diff test (exactly describe_tool + detail param +
  description updates vs pre-feature golden)
- internal/config + runtime: tool_response_mode (full default) validation,
  DetectConfigChanges clause, effectiveToolResponseMode via currentConfig
- bench: flipgate metrics (ranked-ID identity, lossy rate) + MCP caller
  helpers for the profiler compact arm
- 47-query ranked-ID identity test (compact vs full) release-blocking
- T040/T043 (bench-arm grammar migration + re-baseline) cross-branch
  BLOCKED on PR #851 merge, marked in tasks.md

- go test ./internal/{toolsig,config,server}/... ./bench/... -race: green
  (server suite 512s)
- golangci-lint v2 on touched packages: 0 issues
- ./scripts/test-api-e2e.sh: all passed
- gofmt: branch-changed files clean
Related #175

- Lossy biconditional: tildes in quoted atoms escape to \u007E so a
  literal ~ never appears outside lossy markers (grammar §3.5 updated)
- code_execution mode: retrieve_tools always serializes full, detail
  param removed from that surface (describe_tool absent there in v1)
- Search semantics restored to merge-base exactly (scope + isToolCallable);
  quarantine + pending/changed gates are describe_tool-only additions —
  never-return-what-search-wouldnt holds by construction
- Path B invalid-params classifier: narrow allow phrases + deny patterns
  (auth/timeout/connection/HTTP shapes); 401-with-invalid-parameters no
  longer attaches schemas
- toolsig.Cache.RetainHashes + runtime reconciliation after differential
  updates and orphan cleanup — no stale-signature leak

## Testing
- go test ./internal/{toolsig,runtime,server}/... -race: green (server 514s)
- golangci-lint v2: 0 issues
Related #175

Get memoizes only live-set hashes post-reconcile (stale hashes
compute-through without storing); Warm — the authoritative indexing
path — always memoizes and admits its hash to the live set, so warming
a new hash before the post-update reconcile is never dropped.

## Testing
- go test ./internal/{toolsig,runtime,server}/... targeted -race: green
Equally-scored bleve hits came back in the engine's internal order,
which varies between otherwise-identical searches. Full- and compact-mode
retrieve_tools calls therefore returned the same tools in different order,
flaking the Spec 085 ranked-ID identity gate (SC-002) and the golden
byte-identity fixtures (platform-dependent on Windows). Add a deterministic
secondary sort by document ID (server:tool) via SortBy(["-_score","_id"]),
applied before the Size truncation so it also stabilizes which tied hits
survive the limit boundary.

Also fix two new CodeQL high-severity alerts in internal/toolsig:
- signature.go:503 \uXXXX is exactly 4 hex digits (<=0xFFFF); parse at
  bitSize 16 so rune(code) cannot overflow int32.
- signature.go:70 size the parts hint by len(properties) (a single map
  length) instead of an attacker-influenced len()+len() sum.

Related #175
With core.autocrlf=true (GitHub Windows runners) the committed *.golden.json
files check out with CRLF, so the fixture read back ends with a trailing \r
that the test's TrimRight(want,"\n") does not strip — failing the Spec 085
GoldenByteIdentity comparison on Windows only. Pin them to LF via .gitattributes,
matching the existing frontend/src/types/contracts.ts precedent.

Related #175
Rebasing 085-compact-router onto the new merge-base bf3f736 (which now
carries spec 084 adaptive TOON) surfaced two integration failures that
neither spec's own test suite caught in isolation:

- internal/server/toon_surface_isolation_test.go (a spec-084 test) called
  NewMCPProxyServer with the pre-085 arity; spec 085 appended a final
  *toolsig.Cache parameter. Pass nil, matching mcp_auth_scope_test.go.

- bench TestComputeReport_SavingsAreReal asserted the retrieve_tools menu
  is smaller than the frozen corpus_v1 baseline. That baseline is a terse,
  schema-LESS 45-tool snapshot (1730 tokens); the retrieve_tools menu
  carries FULL schemas for its built-in tools. On 084-base main the menu was
  1707 tokens (11 tools) — already only ~1% under the baseline. Spec 085 adds
  the describe_tool built-in (the 12th tool), taking the menu to 1856 tokens,
  which edges just past this micro-corpus. This is a fixture-scale artifact,
  not a regression: the retrieve_tools thesis holds at realistic scale via the
  corpus_v2 profiler path, and code_execution (1124 tokens) still guards the
  thesis strictly here. Keep every savings-ratio arithmetic check exact
  (sign included) and add the previously-missing code_execution ratio checks.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QyPrxW2Dkr8XkSnotnGFia
@Dumbris
Dumbris force-pushed the 085-compact-router branch from 6a827e7 to b8af0d3 Compare July 15, 2026 12:18
Related #175

GenerateKey stays pure (TestGenerateKey contract); the truncator now
derives its per-block timestamp from cache.NextUniqueTimestamp — a
process-wide atomic high-water mark that bumps same-tick readings by
1ns. Windows wall-clock granularity (~0.5-15.6ms) let two blocks
truncated in one tick share a key, so the second Store overwrote the
first (flaked TestForwardContentResult_MultipleTextBlocksDistinctKeys
on windows-latest).

## Testing
- internal/cache, internal/truncate, server ForwardContentResult
  suites green (-race -count=10)

@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 15458bd 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.

3 participants