Skip to content

mcp: Hermes-style progressive disclosure + Claude Code-style tool_search - #315

Merged
FMXExpress merged 3 commits into
mainfrom
claude/mcp-progressive-disclosure
Jun 21, 2026
Merged

FMXExpress merged 3 commits into
mainfrom
claude/mcp-progressive-disclosure

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

Adds opt-in lazy reveal for MCP tools so PasClaw stops paying the prompt-cost of every MCP tool's JSON schema on turns that touch zero MCP tools.

Mirrors two prior-art patterns:

  • Hermes-agent's Level 0 / Level 1 — same shape PasClaw already uses for skills (PasClaw.Skills.Disclosure: skills_list / skills_view).
  • Claude Code's ToolSearch — the deferred-tools-by-name + schema-fetch surface you're sitting inside right now in any Claude Code session.

Both are surfaces for the same problem (don't materialize the full tool catalog up front); this PR brings the pattern to MCP.

Problem

PasClaw registers every MCP tool from every configured server into TToolRegistry and dumps all their JSON schemas into the per-request tools array on every turn. Two servers is cheap; the GitHub MCP alone ships 50+ tools and stacking 3-4 servers pushes the tools-array token bill into the regime where it dominates turns that don't actually use an MCP tool.

Design

Cfg.MCPProgressiveDisclosure: Boolean (default False). When True:

  1. PasClaw.MCP.Bridge passes the flag through to RegisterToolViaDispatch as a Deferred parameter. The TTool's new IsDeferred field is set; the dispatcher still finds the tool (RunTool / Find unchanged), but ToProviderDefs filters the schema out of the per-request tools array.

  2. TToolRegistry gains an FRevealed string set + Reveal(name) method. ToProviderDefs strips IsDeferred-and-not-revealed entries; once Reveal is called, the next ToProviderDefs pass surfaces the schema. Reveal is idempotent and silently no-ops on stale names (a model with names from a previous session can't wedge the registry).

  3. PasClaw.MCP.Disclosure registers a single new tool, tool_search, modelled on Claude Code's ToolSearch. Three query forms:

    Query Behavior
    select:Name1,Name2 Exact-name fetch
    +required keyword1 keyword2 Require substring in name, rank rest
    keyword1 keyword2 Ranked keyword search across name + description

    Returns matched tools as <function>{"name":..,"description":..,"parameters":{...}}</function> blocks and calls Reveal so the model can invoke them on the very next iteration — no second search needed.

  4. PasClaw.Agent.Prompt.BuildDeferredToolsSection adds a ## Deferred Tools section listing the deferred tool names so the model knows what exists. Pulled from PasClaw.MCP.Disclosure (which captures the registry pointer at registration time). Emits empty when disclosure is off or zero tools deferred.

  5. PasClaw.Tools.ToolLoop re-snapshots Tools := Registry.ToProviderDefs at the top of every iter loop's provider call (was: snapshot once, reuse). A reveal at iter N becomes visible at iter N+1 without waiting a full user turn.

Onboarding

PromptMCPProgressiveDisclosure asks only when at least one MCP server is configured — a fresh install without MCP gets no confusing question about a feature that has no effect. The question explains the tradeoff (smaller prompt vs +1 turn per unfamiliar tool) and recommends Y for fat catalogs.

Save / load

Round-trips through SaveConfig (emit-if-True; default False stays silent in fresh config.json) / LoadConfig (default-preserving GetBool). Tested.

Tests

New test program src/tests/mcp_disclosure_tests.pas (make test-mcp-disclosure). Nine cases:

  • TToolRegistry strips IsDeferred entries from ToProviderDefs
  • Reveal moves a deferred tool back into ToProviderDefs
  • Reveal of unknown / empty name is a no-op (stale-name safety)
  • tool_search select: query loads + reveals
  • tool_search keyword query ranks and caps at max_results
  • tool_search +required filters by name substring
  • tool_search with no deferred tools returns clean text result
  • RegisterMCPDisclosureTools skips registration when disclosure is False
  • Cfg.MCPProgressiveDisclosure round-trips save / load

Hermetic — no MCP server started, just synthetic TTool records. make clean && make passes; make test-mcp-disclosure passes all 9.

Test plan

  • Default-off path: MCPProgressiveDisclosure := False on fresh install, behavior identical to pre-PR
  • Default-off save: fresh config.json does not gain a mcp_progressive_disclosure key
  • On path: registry filters deferred entries from ToProviderDefs
  • On path: tool_search registers and is callable
  • On path: Reveal makes a deferred tool visible to the next ToProviderDefs
  • Reveal stale-name safety: silently no-ops
  • Onboarding skips the question when no MCP servers are configured
  • Manual: real GitHub MCP catalog with disclosure on, verify a tool_search round-trip end-to-end (followup — needs an operator with GitHub MCP wired up)
  • Manual: verify the ## Deferred Tools section renders in the system prompt as expected on a real run

Build wiring

Added PasClaw.MCP.Disclosure.pas to src/pasclaw/PasClaw.dproj's DCCReference list and a test-mcp-disclosure target to the Makefile alongside test-config-profile.

Defaults preserved

MCPProgressiveDisclosure := False on fresh install — the historical "every MCP tool schema in every turn's tools array" behavior is unchanged for anyone who doesn't flip the flag on.


Generated by Claude Code

claude added 2 commits June 21, 2026 00:56
Adds opt-in lazy reveal for MCP tools. Mirrors the Skills.Disclosure
pattern (Hermes-agent's Level 0 / Level 1) and Claude Code's
ToolSearch deferred-tool pattern -- two complementary surfaces for
the same problem: don't pay the prompt-cost of every MCP tool schema
on turns that touch zero MCP tools.

Problem
=======

PasClaw registers every MCP tool from every configured server into
TToolRegistry and dumps ALL their JSON schemas into the per-request
`tools` array on every turn. Two MCP servers is cheap; the GitHub
MCP alone ships 50+ tools and stacking 3-4 servers pushes the
tools-array token bill into a regime where it dominates turns that
don't actually USE an MCP tool.

Design
======

Cfg.MCPProgressiveDisclosure (Boolean, default False). When True:

  1. PasClaw.MCP.Bridge passes Cfg.MCPProgressiveDisclosure through
     to RegisterToolViaDispatch as a `Deferred` flag. The TTool's
     new IsDeferred field is set; the dispatcher still finds the
     tool (RunTool / Find unchanged), but ToProviderDefs filters
     the schema out of the per-request tools array.

  2. TToolRegistry gains a FRevealed string set + Reveal(name)
     method. ToProviderDefs strips IsDeferred-and-not-revealed
     entries; once Reveal is called, the next ToProviderDefs pass
     surfaces the schema. Reveal is idempotent and silently no-ops
     on stale names (a model with names from a previous session
     can't wedge the registry).

  3. PasClaw.MCP.Disclosure registers a single new tool,
     `tool_search`, modelled on Claude Code's ToolSearch. Three
     query forms:

       select:Name1,Name2     exact-name fetch
       +required keyword ...  require substring in name, rank rest
       keyword1 keyword2 ...  ranked keyword search

     Returns matched tools as <function>{"name":..,"description":..,
     "parameters":{...}}</function> blocks AND calls Reveal so the
     model can invoke them on the very next iteration (no second
     search needed).

  4. PasClaw.Agent.Prompt.BuildDeferredToolsSection adds a
     "## Deferred Tools" section listing the deferred tool NAMES so
     the model knows what exists. Pulled from
     PasClaw.MCP.Disclosure (which captures the registry pointer at
     RegisterMCPDisclosureTools time). Emits empty when disclosure
     is off or zero tools deferred.

  5. PasClaw.Tools.ToolLoop re-snapshots Tools := Registry.
     ToProviderDefs at the top of every iter loop's provider call
     (was: snapshot once, reuse). A reveal at iter N becomes
     visible at iter N+1 without waiting a full user turn.

Onboarding
==========

PromptMCPProgressiveDisclosure asks only when at least one MCP
server is configured -- a fresh install without MCP gets no
confusing question about a feature that has no effect. The
question explains the tradeoff (smaller prompt vs +1 turn per
unfamiliar tool) and recommends Y for fat catalogs.

Save / load
===========

Round-trips through SaveConfig (emit-if-True; default False stays
silent in fresh config.json) / LoadConfig (default-preserving
GetBool). Tested in TestConfigRoundTrip.

Tests
=====

New test program src/tests/mcp_disclosure_tests.pas (make
test-mcp-disclosure). Nine cases:

  - TToolRegistry strips IsDeferred entries from ToProviderDefs.
  - Reveal moves a deferred tool back into ToProviderDefs.
  - Reveal of unknown / empty name is a no-op (stale-name safety).
  - tool_search select: query loads + reveals.
  - tool_search keyword query ranks and caps at max_results.
  - tool_search +required filters by name substring.
  - tool_search with no deferred tools returns clean text result.
  - RegisterMCPDisclosureTools skips registration when disclosure
    is False.
  - Cfg.MCPProgressiveDisclosure round-trips save / load.

Hermetic -- no MCP server started, just synthetic TTool records.

Build wiring
============

Added PasClaw.MCP.Disclosure.pas to src/pasclaw/PasClaw.dproj's
DCCReference list and a `test-mcp-disclosure` target to the
Makefile alongside `test-config-profile`. make clean && make
passes; make test-mcp-disclosure passes all 9 cases.

Defaults preserved
==================

MCPProgressiveDisclosure := False on fresh install -- the
historical "every MCP tool schema in every turn's tools array"
behaviour is unchanged for anyone who doesn't flip the flag on.
The previous commit landed Cfg.MCPProgressiveDisclosure := False as
the floor, on the theory that "off preserves historical behaviour."
That ordering is wrong for the actual operator population:

  - Replicate MCP ships ~50 tools
  - GitHub MCP ships ~50+ tools
  - Stacks of 2-3 servers easily hit 100+

For any operator running a fat catalog (which is most of them once
they've wired any of the big public MCP servers), the prompt cost
of every schema every turn dominates the bill on turns that touch
zero MCP tools. The +1 turn cost per first-use of an unfamiliar
tool is dramatically cheaper than the per-turn schema overhead.
Lazy-reveal IS the right floor; eager-reveal is the special case.

Changes
=======

  - TConfig.Create sets MCPProgressiveDisclosure := True.
  - SaveConfig emit-rule flipped from opt-in (emit-if-True) to
    opt-out (emit-if-False) so on-keepers don't get a redundant
    "mcp_progressive_disclosure": true in their config.json.
  - PromptMCPProgressiveDisclosure default flipped from N to Y;
    copy updated to "recommended for fat catalogs (Replicate /
    GitHub MCP), answer N for one or two tiny servers."
  - PromptMCPProgressiveDisclosure no longer force-resets the field
    to False when there are zero MCP servers configured -- the
    flag is inert at runtime in that case (tool_search registers
    but DeferredNames is empty), and force-resetting fought the
    True default on fresh installs without MCP.
  - TestConfigRoundTrip exercises BOTH the default and the
    round-trip: asserts MCPProgressiveDisclosure is True on a
    fresh install, then sets it to False, saves, loads, and
    asserts the opt-out persisted. (Previous test set True and
    asserted True came back, which after this commit would be
    a no-op since True is the default.)

Tests
=====

make clean && make passes. make test-mcp-disclosure passes all 9
cases including the rewritten TestConfigRoundTrip. make
test-config-profile passes.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 28a875aa88

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

deferred unless tool_search has since revealed the name. This
keeps the provider's per-request `tools` array small (and the
token bill low) while leaving the dispatcher unchanged. }
if FTools[i].IsDeferred and (not IsRevealedLocked(FTools[i].Name)) then

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Initialize deferred flag before filtering tools

This filter makes IsDeferred authoritative for every registered tool, but most existing non-MCP registrations build a stack TTool and never assign the new field (for example RegisterFSTools and RegisterShellTool set Name/Schema/Handler/Category only). The registry already has a defensive cleanup for another stack-garbage field (HandlerObj), so an uninitialized nonzero byte here can cause core tools to be omitted from the provider tools array even when MCP progressive disclosure is disabled. Please initialize IsDeferred := False for legacy registrations, or clear it in Register without overriding the MCP path that explicitly sets it.

Useful? React with 👍 / 👎.

…iew fix)

P1 reviewer concern: TTool's new IsDeferred field is authoritative
for ToProviderDefs filtering, but most existing registrations
(RegisterFSTools, RegisterShellTool, every TPasClawTool subclass)
build T: TTool on the stack and never assign IsDeferred. FPC /
Delphi don't zero-init local records; stack garbage with a non-
zero byte there could cause core tools to be silently omitted from
the per-request tools array even when MCPProgressiveDisclosure is
off. The reviewer noted the registry already has a defensive clear
for the same risk shape on HandlerObj.

Fix
===

Split TToolRegistry.Register into two entry points sharing a
private RegisterImpl:

  Register(const T)
    Defensively zeroes T.IsDeferred before storing. All legacy
    callers go through here; their stack-garbage IsDeferred can no
    longer leak into the registry.

  RegisterDeferred(const T; Deferred: Boolean)
    Sets T.IsDeferred from the explicit Deferred parameter. The
    only legitimate IsDeferred=True path -- MCP.Bridge when
    Cfg.MCPProgressiveDisclosure is on -- goes through this entry
    point instead. T.IsDeferred from the caller is overridden;
    callers must NOT also set it.

Both call RegisterImpl, which does the HandlerObj clear + lock +
upsert. No duplicated body.

Callers updated
===============

  PasClaw.MCP.Bridge.RegisterToolViaDispatch
    Dropped `Entry.IsDeferred := Deferred` and switched to
    Reg.RegisterDeferred(Entry, Deferred). Comment updated to
    explain that the parameter is authoritative and the plain
    Register would clear the field defensively.

  PasClaw.MCP.Disclosure.RegisterMCPDisclosureTools
    Dropped the redundant T.IsDeferred := False on tool_search
    (the plain Register now guarantees this). Comment notes the
    discovery tool itself is always visible -- the defensive
    clear is what makes that true.

  src/tests/mcp_disclosure_tests.pas
    Test helper RegisterDeferred -> RegisterDeferredTool (avoids
    shadowing the new registry method) and now routes through
    Reg.RegisterDeferred(T, True) instead of setting T.IsDeferred
    := True then calling Register (which would silently get False
    now and turn the registry-filtering tests into no-ops).

New test
========

TestLegacyRegisterClearsIsDeferred simulates the bug shape the
reviewer was worried about: builds a TTool with IsDeferred := True
to simulate stack garbage, registers via plain Register, and
asserts the tool nevertheless shows up in ToProviderDefs (because
Register zeroed the field) and does NOT appear in DeferredNames.
A regression that drops the defensive clear would fail here.

Tests
=====

make clean && make passes. make test-mcp-disclosure passes all 10
cases (was 9; added TestLegacyRegisterClearsIsDeferred). make
test-config-profile passes.
@FMXExpress
FMXExpress merged commit a1f3ff2 into main Jun 21, 2026
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
The README + docs/changelog.md last entry was 2026-06-13 (FMXExpress#244). Five
substantial PRs (FMXExpress#314 FMXExpress#315 FMXExpress#316 FMXExpress#317 FMXExpress#318) and ten more feature PRs
between them and that entry shipped without changelog entries. This
brings both files current through today.

Twenty new entries (newest first, matching the existing style):

  2026-06-21
    FMXExpress#318  Relay pull-worker provider (queue + provider + /v1/relay/* HTTP)

  2026-06-20
    FMXExpress#317  pasclaw plan + build PLAN.md pickup + build --goal + cog mode
    FMXExpress#316  Cloudflare AI Gateway provider catalog rows
    FMXExpress#315  MCP progressive disclosure + tool_search
    FMXExpress#314  Stock defaults adopt lean-edit shape; fs_grep split-gate

  2026-06-18
    FMXExpress#312  Web UI workspace.zip export + import
    FMXExpress#310  Model-callable cron tool
    FMXExpress#309  FTS5 snippet window widened 24 -> 60
    FMXExpress#307  Windows cmd.exe quoting fix

  2026-06-17
    FMXExpress#306  cog-build honours profile=security sandbox
    FMXExpress#304  cog-build default profile = max-build
    FMXExpress#303  cog-build list[Path] outputs + Secret inputs + -q

  2026-06-16
    FMXExpress#302  cog-build optional workspace_in
    FMXExpress#300  pasclaw build cmd + cog-build/ predictor (parent feature)
    FMXExpress#299  Checkpoints zpaq backend + /redo
    FMXExpress#298  AGENTS.md + pasclaw init + /init
    FMXExpress#297  tool_choice force-a-specific-tool form
    FMXExpress#296  Delphi ExtraEnv injection fix
    FMXExpress#295  KB native PDF ingest

  2026-06-15
    FMXExpress#292  pasclaw profile diff + bench

Skipped per the changelog's stated convention ("Bug fixes and review
follow-ups are in the full git log"):

  FMXExpress#293  cmd/profile dcc64 fix
  FMXExpress#294  skills_manage gemini empty-enum fix
  FMXExpress#301  cmd.build dcc64 fix
  FMXExpress#311  cron dcc64 fix

Files updated identically (the docs/changelog.md note at the top says
"This file mirrors the changelog section at the top of the root
README.md"):

  M README.md           20 entries + 20 link refs added
  M docs/changelog.md   same

The link-ref block at the bottom of each file gained 20 [#NNN] entries
keeping the existing one-per-line / sorted-numerically format.
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