Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions cli-config.yaml.example
Original file line number Diff line number Diff line change
Expand Up @@ -1439,3 +1439,26 @@ updates:
# binary_path: "" # "" = resolve op via PATH; else absolute path
# cache_ttl_seconds: 300 # 0 disables BOTH cache layers
# override_existing: true # resolved values win over existing env

# =============================================================================
# Tool search (progressive tool disclosure)
# =============================================================================
# Replaces deferrable tool schemas in the model-facing tools array with three
# small bridge tools (tool_search / tool_describe / tool_call), cutting the
# schema "entry tax" every session pays on its first prefill. Deferred tools
# stay fully usable — the model finds them by search and calls them through
# the bridge, with guardrails/approvals/hooks firing identically.
#
# tools:
# tool_search:
# enabled: auto # auto | on | off. auto activates when deferrable
# # schemas would consume >= threshold_pct of context
# threshold_pct: 10.0 # auto-activation gate, % of context window
# search_default_limit: 5 # tool_search results when no limit is given
# max_search_limit: 20 # hard cap on requested results
# # By default only MCP and plugin tools are deferrable — built-in
# # ("core") toolsets always load. defer_toolsets opts named built-in
# # toolsets into deferral too, for installs where the built-in schemas
# # themselves are the bulk of the entry tax. Trade-off: turns that use
# # a deferred tool pay one extra bridge round-trip to discover it.
# # defer_toolsets: [session_search, delegation, skills, computer_use]
108 changes: 108 additions & 0 deletions tests/tools/test_tool_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,114 @@ def test_classify_keeps_unknown_in_visible(self):
assert deferrable == []


# ---------------------------------------------------------------------------
# defer_toolsets opt-in (built-in toolsets behind the bridge)
# ---------------------------------------------------------------------------


def _register_session_search():
"""Import a real built-in tool module so the registry holds its entry."""
import tools.session_search_tool # noqa: F401 — registers at import
from tools.registry import registry
entry = registry.get_entry("session_search")
assert entry is not None, "session_search must be registered for these tests"
return entry.toolset


class TestDeferToolsetsOptIn:
"""``defer_toolsets`` lets named BUILT-IN toolsets ride the bridge.

Core protection stays the default: everything here requires the explicit
per-toolset opt-in, and the bridge/dispatch paths must agree with the
assembly about what was deferred (an opted-in tool that assembly strips
but dispatch rejects would be unreachable).
"""

def test_config_parses_defer_toolsets(self):
from tools.tool_search import ToolSearchConfig
cfg = ToolSearchConfig.from_raw({
"enabled": "on",
"defer_toolsets": ["session_search", " delegation ", "", None, 7],
})
assert cfg.defer_toolsets == frozenset({"session_search", "delegation", "7"})

def test_config_defer_toolsets_defaults_empty(self):
from tools.tool_search import ToolSearchConfig
assert ToolSearchConfig.from_raw(None).defer_toolsets == frozenset()
assert ToolSearchConfig.from_raw(True).defer_toolsets == frozenset()
assert ToolSearchConfig.from_raw({"defer_toolsets": "not-a-list"}).defer_toolsets == frozenset()

def test_core_tool_defers_only_with_opt_in(self):
from tools.tool_search import is_deferrable_tool_name
toolset = _register_session_search()
assert not is_deferrable_tool_name("session_search", frozenset())
assert is_deferrable_tool_name("session_search", frozenset({toolset}))

def test_bridge_tools_never_defer_even_with_opt_in(self):
from tools.tool_search import is_deferrable_tool_name, BRIDGE_TOOL_NAMES
for name in BRIDGE_TOOL_NAMES:
assert not is_deferrable_tool_name(name, frozenset({"tool_search", "core"}))

def test_unknown_toolset_opt_in_is_harmless(self):
from tools.tool_search import is_deferrable_tool_name
_register_session_search()
assert not is_deferrable_tool_name(
"session_search", frozenset({"xx_no_such_toolset"})
)

def test_assemble_strips_opted_in_core_toolset(self):
from tools.tool_search import (
assemble_tool_defs, ToolSearchConfig, BRIDGE_TOOL_NAMES,
)
toolset = _register_session_search()
defs = [_td("terminal", "Run a command"),
_td("session_search", "Search past sessions")]
cfg = ToolSearchConfig.from_raw(
{"enabled": "on", "defer_toolsets": [toolset]}
)
result = assemble_tool_defs(defs, context_length=131072, config=cfg)
assert result.activated
names = {(td.get("function") or {}).get("name") for td in result.tool_defs}
assert "session_search" not in names # deferred
assert "terminal" in names # untouched core stays
assert BRIDGE_TOOL_NAMES <= names # bridge present

def test_dispatch_paths_accept_opted_in_tool(self, monkeypatch):
"""describe/tool_call must agree with assembly about the opt-in."""
import tools.tool_search as ts
toolset = _register_session_search()
cfg = ts.ToolSearchConfig.from_raw(
{"enabled": "on", "defer_toolsets": [toolset]}
)
monkeypatch.setattr(ts, "load_config", lambda: cfg)

td = _td("session_search", "Search past sessions")
described = json.loads(ts.dispatch_tool_describe(
{"name": "session_search"}, current_tool_defs=[td]))
assert described.get("name") == "session_search"
assert "error" not in described

name, args, err = ts.resolve_underlying_call(
{"name": "session_search", "arguments": {"query": "x"}})
assert err is None
assert name == "session_search"
assert args == {"query": "x"}

def test_dispatch_paths_reject_without_opt_in(self, monkeypatch):
import tools.tool_search as ts
_register_session_search()
cfg = ts.ToolSearchConfig.from_raw({"enabled": "on"})
monkeypatch.setattr(ts, "load_config", lambda: cfg)

described = json.loads(ts.dispatch_tool_describe(
{"name": "session_search"},
current_tool_defs=[_td("session_search", "Search past sessions")]))
assert "error" in described

_, _, err = ts.resolve_underlying_call({"name": "session_search", "arguments": {}})
assert err is not None


# ---------------------------------------------------------------------------
# Token estimation + threshold gate
# ---------------------------------------------------------------------------
Expand Down
91 changes: 65 additions & 26 deletions tools/tool_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,19 @@

When enabled, MCP and non-core plugin tools are replaced in the model-visible
tools array by three bridge tools — ``tool_search``, ``tool_describe``,
``tool_call`` — and surfaced on demand. Core Hermes tools never defer.
``tool_call`` — and surfaced on demand. Core Hermes tools never defer unless
their toolset is explicitly opted in via ``tools.tool_search.defer_toolsets``.

Design constraints this module is built around (see ``openclaw-tool-search-report``
for the full rationale):

* Core tools defined in ``toolsets._HERMES_CORE_TOOLS`` are *never* deferred.
Always-load means always-load. No exceptions.
* Core tools defined in ``toolsets._HERMES_CORE_TOOLS`` are *never* deferred
by default. The single exception is an explicit per-toolset opt-in:
``defer_toolsets: [session_search, ...]`` pushes every tool of the named
built-in toolsets behind the bridge. This exists because on schema-heavy
installs the built-in toolsets themselves are the entry tax (10k+ tokens
of every session's first prefill), and only the user knows which of them
their sessions actually lean on. Opt-in, never inferred.
* The threshold gate runs every assembly: when deferrable tools would consume
less than ``threshold_pct`` of the model's context window (default 10%),
tool search is a no-op and the tools array passes through unchanged.
Expand Down Expand Up @@ -68,6 +74,11 @@ class ToolSearchConfig:
threshold_pct: float # 0..100 — only used when enabled == "auto"
search_default_limit: int
max_search_limit: int
# Built-in toolsets explicitly opted in for deferral. Tools of these
# toolsets defer even when listed in ``_HERMES_CORE_TOOLS`` — the user
# is trading first-prefill size for an extra bridge round-trip on the
# turns that actually use them. Empty by default (no behavior change).
defer_toolsets: frozenset = frozenset()

@classmethod
def from_raw(cls, raw: Any) -> "ToolSearchConfig":
Expand Down Expand Up @@ -106,11 +117,20 @@ def from_raw(cls, raw: Any) -> "ToolSearchConfig":
search_default_limit = max(1, min(max_search_limit,
_safe_int(raw.get("search_default_limit"), 5)))

defer_raw = raw.get("defer_toolsets")
defer_toolsets: frozenset = frozenset()
if isinstance(defer_raw, (list, tuple, set)):
defer_toolsets = frozenset(
str(item).strip() for item in defer_raw
if isinstance(item, (str, int)) and str(item).strip()
)

return cls(
enabled=enabled,
threshold_pct=threshold_pct,
search_default_limit=search_default_limit,
max_search_limit=max_search_limit,
defer_toolsets=defer_toolsets,
)


Expand Down Expand Up @@ -160,39 +180,56 @@ def _core_tool_names() -> frozenset[str]:
return frozenset()


def is_deferrable_tool_name(name: str) -> bool:
def is_deferrable_tool_name(name: str,
defer_toolsets: Optional[frozenset] = None) -> bool:
"""Return True if a tool with this name is *eligible* for deferral.

A tool is deferrable iff it is registered with an MCP toolset prefix
OR it is not in ``_HERMES_CORE_TOOLS``. Core tools are never deferred
even when their toolset is technically plugin-provided (this protects
against accidental shadowing).
OR it is not in ``_HERMES_CORE_TOOLS`` OR its toolset is explicitly
opted in via ``defer_toolsets``. Outside the opt-in, core tools are
never deferred even when their toolset is technically plugin-provided
(this protects against accidental shadowing).

``defer_toolsets=None`` resolves the opt-in set from user config —
the dispatch paths (``tool_describe`` / ``tool_call`` / session
scoping) must accept whatever the assembly deferred, so both sides
read the same source. Pass the set explicitly in per-tool loops to
avoid a config read per tool.
"""
if name in BRIDGE_TOOL_NAMES:
return False
if name in _core_tool_names():
return False
# Check registry toolset for MCP prefix.
if defer_toolsets is None:
defer_toolsets = load_config().defer_toolsets
entry = None
try:
from tools.registry import registry
entry = registry.get_entry(name)
if entry is None:
return False
if entry.toolset.startswith("mcp-"):
return True
# Non-MCP, non-core → plugin tool, eligible.
return True
except Exception:
entry = None
if defer_toolsets and entry is not None and entry.toolset in defer_toolsets:
# Explicit per-toolset opt-in overrides core protection.
return True
if name in _core_tool_names():
return False
if entry is None:
return False
if entry.toolset.startswith("mcp-"):
return True
# Non-MCP, non-core → plugin tool, eligible.
return True


def classify_tools(tool_defs: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
def classify_tools(tool_defs: List[Dict[str, Any]],
defer_toolsets: Optional[frozenset] = None,
) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
"""Split a tool-defs list into (visible, deferrable).

``visible`` retains every tool that must stay in the model-facing array:
every core tool, plus any tool we can't classify. ``deferrable`` is the
candidate set for catalog entry.
every core tool (minus ``defer_toolsets`` opt-ins), plus any tool we
can't classify. ``deferrable`` is the candidate set for catalog entry.
"""
if defer_toolsets is None:
defer_toolsets = load_config().defer_toolsets
visible: List[Dict[str, Any]] = []
deferrable: List[Dict[str, Any]] = []
for td in tool_defs:
Expand All @@ -202,7 +239,7 @@ def classify_tools(tool_defs: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]
# Should never happen — bridge tools are added after classification —
# but be defensive.
continue
if is_deferrable_tool_name(name):
if is_deferrable_tool_name(name, defer_toolsets):
deferrable.append(td)
else:
visible.append(td)
Expand Down Expand Up @@ -535,9 +572,10 @@ def assemble_tool_defs(
"""Return the tool-defs list the model should actually see.

When tool search is inactive (off, no deferrable tools, or below
threshold), this is a passthrough. When active, MCP and plugin tools
are stripped from the visible list and replaced with the three bridge
tools. Core tools are *never* deferred regardless of config.
threshold), this is a passthrough. When active, MCP and plugin tools —
plus any built-in toolsets opted in via ``defer_toolsets`` — are
stripped from the visible list and replaced with the three bridge
tools. Outside that explicit opt-in, core tools are never deferred.

Idempotent: calling with bridge tools already in the input is a no-op
(they classify as non-core/non-deferrable but their names are reserved,
Expand All @@ -551,7 +589,7 @@ def assemble_tool_defs(
incoming = [td for td in tool_defs
Comment thread
lEWFkRAD marked this conversation as resolved.
Resolved
if (td.get("function") or {}).get("name") not in BRIDGE_TOOL_NAMES]

visible, deferrable = classify_tools(incoming)
visible, deferrable = classify_tools(incoming, config.defer_toolsets)
if not deferrable:
return AssemblyResult(tool_defs=incoming, activated=False)

Expand Down Expand Up @@ -619,7 +657,7 @@ def dispatch_tool_search(args: Dict[str, Any],
else:
limit = max(1, min(config.max_search_limit, _safe_int(raw_limit, config.search_default_limit)))

_, deferrable = classify_tools(current_tool_defs)
_, deferrable = classify_tools(current_tool_defs, config.defer_toolsets)
catalog = build_catalog(deferrable)
hits = search_catalog(catalog, query, limit=limit)
return json.dumps({
Expand Down Expand Up @@ -670,9 +708,10 @@ def scoped_deferrable_names(tool_defs: List[Dict[str, Any]]) -> frozenset[str]:
an out-of-scope tool via the bridge.
"""
names: set[str] = set()
defer_toolsets = load_config().defer_toolsets # resolve once, not per tool
for td in tool_defs:
name = (td.get("function") or {}).get("name", "")
if name and is_deferrable_tool_name(name):
if name and is_deferrable_tool_name(name, defer_toolsets):
names.add(name)
return frozenset(names)

Expand Down
Loading