Skip to content

The agent that grows with you

refactor(tools): tool_search — drop dead build_catalog_listing/_describe_classification/_safe_int, fold describe classification into is_deferrable_tool_name, compact docstrings

Tekniumc7bae88fcee3
diff --git a/tools/tool_search.py b/tools/tool_search.py
index 64d1efaba4f..a10952f1e41 100644
--- a/tools/tool_search.py
+++ b/tools/tool_search.py
@@ -1,19 +1,14 @@
-"""Progressive tool disclosure ("tool search"): MCP/plugin tools (and a
-curated set of event-triggered core tools) are replaced in the model-visible
-array by three bridge tools — tool_search / tool_describe / tool_call.
-
-Invariants:
-* Working-set core tools (``toolsets._HERMES_CORE_TOOLS``) and session-gated GUI
- toolsets never defer unless named in the ``defer`` list.
-* Tiered disclosure: ANY deferrable tool activates the bridge (tier 1 = bridge +
- listing that fits ``min(threshold_pct% of context, listing_max_tokens)``,
- tier 2 = bare bridge + per-server summary). The listing scales, not activation.
-* The catalog is stateless — rebuilt from the live tool-defs list on every
- assembly. A session-keyed catalog drifts from the registry and silently
- drops tools.
-* Bridge calls route through ``model_tools.handle_function_call`` so guardrails,
- hooks, approvals, and truncation fire identically; display/trajectory unwrap
- always shows the underlying tool.
+"""Progressive tool disclosure ("tool search"): MCP/plugin tools and a curated set
+of event-triggered core tools are replaced in the model-visible array by three
+bridge tools — tool_search / tool_describe / tool_call.
+
+Invariants: working-set core tools (``toolsets._HERMES_CORE_TOOLS``) and
+session-gated GUI toolsets never defer unless named in ``defer``; ANY deferrable
+tool activates the bridge (the listing scales with budget, not activation); the
+catalog is stateless — rebuilt from the live tool-defs on every assembly (a
+session-keyed catalog drifts from the registry and silently drops tools); bridge
+calls route through ``model_tools.handle_function_call`` so guardrails, hooks,
+approvals and truncation fire identically.
"""
from __future__ import annotations
@@ -23,7 +18,7 @@ import logging
import math
from collections import Counter
from dataclasses import dataclass
-from typing import Any, Dict, Iterable, List, Literal, Optional, Tuple
+from typing import Any, Dict, Iterable, List, Optional, Tuple
from tools.registry import tool_error
from tools.tool_search_names import ( # noqa: F401 — re-exported public names
@@ -35,7 +30,6 @@ from tools.tool_search_names import ( # noqa: F401 — re-exported public names
from tools.tool_search_catalog import ( # noqa: F401 — re-exported public/test names
CHARS_PER_TOKEN,
CatalogEntry,
- _classify_source,
_corpus_stats,
_entry_search_text,
_fn,
@@ -45,30 +39,18 @@ from tools.tool_search_catalog import ( # noqa: F401 — re-exported public/tes
_stem,
_tokenize,
build_catalog,
- build_catalog_listing,
build_catalog_listing_with_form,
search_catalog,
)
-
-from tools.tool_search_validation import ( # noqa: F401 — re-exported public/test names
- _schema_for_local_validation,
- _schema_has_external_ref,
- validate_deferred_call_args,
-)
+from tools.tool_search_validation import validate_deferred_call_args # noqa: F401
logger = logging.getLogger("tools.tool_search")
-# Bound the work one tool_search bridge call can request.
+# Bound the work one bridge call can request.
_MAX_QUERIES_PER_CALL = 10
-# Bound the work one tool_describe bridge call can request.
_MAX_DESCRIBE_NAMES_PER_CALL = 10
-# ---------------------------------------------------------------------------
-# Configuration plumbing
-# ---------------------------------------------------------------------------
-
-
@dataclass(frozen=True)
class ToolSearchConfig:
"""Resolved, validated tool-search configuration for a single assembly."""
@@ -79,9 +61,8 @@ class ToolSearchConfig:
threshold_pct: float # 0..100
search_default_limit: int
max_search_limit: int
- # Embedded name + short-description manifest so deferred tools stay
- # DISCOVERABLE (like the skills listing) while full schemas stay deferred.
- # "auto"/"on" = include when it fits (names-only, then bare); "off" = bare bridge.
+ # Embedded name + short-description manifest keeping deferred tools
+ # DISCOVERABLE. "auto"/"on" = include when it fits; "off" = bare bridge.
listing: str = "auto" # "auto" | "on" | "off"
# Effective budget = min(listing_max_tokens, threshold_pct% of context).
listing_max_tokens: int = 4000
@@ -95,13 +76,11 @@ class ToolSearchConfig:
@classmethod
def from_raw(cls, raw: Any) -> "ToolSearchConfig":
- """Build a config from a raw dict / legacy bool / None. Every field is
- validated and clamped; unknown values fall back to safe defaults rather
- than raising, so a typo in user config cannot break the agent."""
+ """Build from a raw dict / legacy bool / None. Every field is clamped and
+ unknown values fall back to safe defaults — a config typo must not break the agent."""
if not isinstance(raw, dict):
return cls(enabled="off" if raw is False else "auto", threshold_pct=5.0,
search_default_limit=5, max_search_limit=25)
-
max_search_limit = _clamped_int(raw.get("max_search_limit"), 25, 1, 50)
defer_raw = raw.get("defer")
return cls(
@@ -130,16 +109,13 @@ def _tri_state(value: Any) -> str:
return text if text in ("auto", "on", "off") else "auto"
-def _safe_int(value: Any, fallback: int) -> int:
+def _clamped_int(value: Any, fallback: int, lo: int, hi: int) -> int:
+ """``int(value)`` (or ``fallback`` when unparseable) clamped to ``[lo, hi]``."""
try:
- return int(value)
+ value = int(value)
except (TypeError, ValueError):
- return fallback
-
-
-def _clamped_int(value: Any, fallback: int, lo: int, hi: int) -> int:
- """``_safe_int`` clamped to ``[lo, hi]`` (the fallback is clamped too)."""
- return max(lo, min(hi, _safe_int(value, fallback)))
+ value = fallback
+ return max(lo, min(hi, value))
def _safe_float(value: Any, fallback: float) -> float:
@@ -170,11 +146,6 @@ def load_config_readonly() -> ToolSearchConfig:
return _config_from_loader("load_config_readonly")
-# ---------------------------------------------------------------------------
-# Tool classification
-# ---------------------------------------------------------------------------
-
-
def _core_tool_names() -> frozenset[str]:
"""Tool names that never defer by default (lazy import: ``toolsets`` imports
``tools.registry``, so a module-level import would be a cycle)."""
@@ -190,9 +161,8 @@ def _core_tool_names() -> frozenset[str]:
_DIRECT_SURFACE_TOOLSETS = frozenset({"desktop_ui", "project"})
# Curated event-triggered core tools deferred BY DEFAULT — reached for when
-# something specific happens, not every-turn working-set tools, so a catalog
-# stub suffices. ``tools.tool_search.defer`` replaces this list wholesale
-# ([] = legacy everything-eager). Names are POST-rename.
+# something specific happens, so a catalog stub suffices. ``tools.tool_search.defer``
+# replaces this list wholesale ([] = legacy everything-eager). Names are POST-rename.
# ``clarify`` is deliberately NOT here: A/B showed deferring it collapsed
# structured-clarify usage (18/18 -> 7/18) — the ask-the-user affordance must
# be ambient to fire; a stub is not enough.
@@ -225,25 +195,6 @@ def is_deferrable_tool_name(name: str, defer_tools: Optional[frozenset] = None)
return False
-def _describe_classification(
- name: str,
- defer_tools: Optional[frozenset] = None,
-) -> Literal["available", "not_found", "not_deferrable"]:
- """Classify a describe name without treating unknown names as errors."""
- entry = _registry_entry(name)
- if entry is None:
- return "not_found"
- if defer_tools is not None and name in defer_tools:
- return "available"
- if (
- name in BRIDGE_TOOL_NAMES
- or name in _core_tool_names()
- or entry.toolset in _DIRECT_SURFACE_TOOLSETS
- ):
- return "not_deferrable"
- return "available"
-
-
def _tool_def_names(tool_defs: Iterable[Dict[str, Any]]) -> Iterable[str]:
"""Function names of a tool-defs list (``""`` for a nameless def)."""
return (_fn(td).get("name", "") for td in tool_defs)
@@ -270,11 +221,6 @@ def _deferrable_in(tool_defs: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
return classify_tools(tool_defs, load_config_readonly().effective_defer_tools)[1]
-# ---------------------------------------------------------------------------
-# Token estimation and threshold gate
-# ---------------------------------------------------------------------------
-
-
def estimate_tokens_from_schemas(tool_defs: Iterable[Dict[str, Any]]) -> int:
"""Token cost of a tool-defs list via the chars/4 rule (order-of-magnitude
precision is all the activation gate needs)."""
@@ -295,15 +241,12 @@ def should_activate(
"""``"off"`` never activates; ``"on"``/``"auto"`` activate whenever any
deferrable tool exists. ``"auto"`` is an alias of ``"on"`` reserved for a
future budget-gated mode — do not distinguish them without that design.
- ``context_length`` is kept in the signature for caller compatibility; the
+ ``context_length`` stays in the signature for caller compatibility; the
threshold governs the listing budget, not activation."""
return config.enabled != "off" and deferrable_tokens > 0
-def listing_token_budget(
- config: ToolSearchConfig,
- context_length: Optional[int],
-) -> int:
+def listing_token_budget(config: ToolSearchConfig, context_length: Optional[int]) -> int:
"""``min(listing_max_tokens, threshold_pct% of context)``; unknown context
uses a 10K percentage leg (5% of a typical 200K window)."""
if context_length and context_length > 0:
@@ -313,11 +256,6 @@ def listing_token_budget(
return max(0, min(config.listing_max_tokens, pct_leg))
-# ---------------------------------------------------------------------------
-# Catalog + BM25 retrieval
-# ---------------------------------------------------------------------------
-
-
def _bridge_schema(name: str, description: str, properties: Dict[str, Any],
required: List[str]) -> Dict[str, Any]:
"""One OpenAI-style function schema (key order is part of the frozen bytes)."""
@@ -375,10 +313,10 @@ def bridge_tool_schemas(
listing_form: str = "",
) -> List[Dict[str, Any]]:
"""Bridge tool schemas injected in place of deferred tools. Kept short —
- every byte is paid on every turn. ``listing`` is embedded in the
- tool_search description; ``listing_form`` picks the framing (per-tool forms
- say "skip search when you see the exact name", the "groups" summary says
- which domains exist and that search is mandatory)."""
+ every byte is paid on every turn. ``listing`` is embedded in the tool_search
+ description; ``listing_form`` picks the framing (per-tool forms say "skip
+ search when you see the exact name", "groups" says which domains exist and
+ that search is mandatory)."""
return [
_bridge_schema(
TOOL_SEARCH_NAME,
@@ -427,14 +365,9 @@ def bridge_tool_schemas(
]
-# ---------------------------------------------------------------------------
-# Public entry point: assemble tool-defs with optional tool search
-# ---------------------------------------------------------------------------
-
-
@dataclass
class AssemblyResult:
- """Outcome of one assembly. Useful for tests and observability."""
+ """Outcome of one assembly (tests and observability)."""
tool_defs: List[Dict[str, Any]]
activated: bool
@@ -442,8 +375,7 @@ class AssemblyResult:
deferred_tokens: int = 0
threshold_tokens: int = 0
# 0 = passthrough; 1 = bridge + per-tool listing (full/names/mixed);
- # 2 = bare bridge / server-summary only — domains stay visible but
- # individual tools are reachable only via tool_search.
+ # 2 = bare bridge / server-summary only (tools reachable only via tool_search).
tier: int = 0
listing_form: str = "none" # "full" | "names" | "mixed" | "groups" | "none"
@@ -459,10 +391,8 @@ def assemble_tool_defs(
tools. Idempotent — bridge tools already present are stripped first."""
if config is None:
config = load_config()
-
incoming = [td for td, name in zip(tool_defs, _tool_def_names(tool_defs))
if name not in BRIDGE_TOOL_NAMES]
-
visible, deferrable = classify_tools(incoming, config.effective_defer_tools)
if not deferrable:
return AssemblyResult(tool_defs=incoming, activated=False)
@@ -470,9 +400,7 @@ def assemble_tool_defs(
deferrable_tokens = estimate_tokens_from_schemas(deferrable)
if not should_activate(config, deferrable_tokens, context_length):
return AssemblyResult(
- tool_defs=incoming,
- activated=False,
- deferred_count=len(deferrable),
+ tool_defs=incoming, activated=False, deferred_count=len(deferrable),
deferred_tokens=deferrable_tokens,
threshold_tokens=int((context_length or 0) * (config.threshold_pct / 100.0)),
tier=0,
@@ -483,33 +411,20 @@ def assemble_tool_defs(
if config.listing != "off":
listing, listing_form = build_catalog_listing_with_form(
deferrable, max_tokens=listing_budget)
- bridge = bridge_tool_schemas(len(deferrable), listing=listing,
- listing_form=listing_form)
+ bridge = bridge_tool_schemas(len(deferrable), listing=listing, listing_form=listing_form)
tier = 1 if listing_form in ("full", "names", "mixed") else 2
-
logger.info(
"tool_search activated (tier %d): %d core/visible tools kept, %d deferred "
"(~%d tokens), listing %s (budget ~%d tokens)",
- tier, len(visible), len(deferrable), deferrable_tokens,
- listing_form, listing_budget,
+ tier, len(visible), len(deferrable), deferrable_tokens, listing_form, listing_budget,
)
-
return AssemblyResult(
- tool_defs=visible + bridge,
- activated=True,
- deferred_count=len(deferrable),
- deferred_tokens=deferrable_tokens,
- threshold_tokens=listing_budget,
- tier=tier,
- listing_form=listing_form,
+ tool_defs=visible + bridge, activated=True, deferred_count=len(deferrable),
+ deferred_tokens=deferrable_tokens, threshold_tokens=listing_budget,
+ tier=tier, listing_form=listing_form,
)
-# ---------------------------------------------------------------------------
-# Bridge tool dispatch
-# ---------------------------------------------------------------------------
-
-
def is_bridge_tool(name: str) -> bool:
return name in BRIDGE_TOOL_NAMES
@@ -534,8 +449,7 @@ def _shared_tool_record(entry: CatalogEntry) -> Dict[str, Any]:
def _available_source_summary(catalog: List[CatalogEntry]) -> List[Dict[str, Any]]:
"""Deterministic ``[{name, tool_count}]`` of connected sources, attached to
- empty query groups so a lexical miss is not read as a missing capability
- (adds nothing to the fixed per-turn prompt)."""
+ empty query groups so a lexical miss is not read as a missing capability."""
counts = Counter(_listing_group_label(entry.source_name) for entry in catalog)
return [{"name": name, "tool_count": counts[name]} for name in sorted(counts)]
@@ -545,8 +459,7 @@ def _string_list_arg(
) -> Tuple[Optional[List[str]], Optional[str]]:
"""Read a list-of-strings bridge argument -> ``(items, error_json)``. A bare
string (a common model slip) counts as a one-item list. Rejects non-list
- input, an empty list (after stripping blanks), and more than ``max_items``
- (bounds the work one bridge call can request)."""
+ input, an empty list (after stripping blanks), and more than ``max_items``."""
raw = args.get(key)
if isinstance(raw, str):
raw = [raw]
@@ -581,21 +494,16 @@ def dispatch_tool_search(args: Dict[str, Any],
"""
if config is None:
config = load_config()
-
queries, err = _string_list_arg(
args, "queries", dedupe=False, max_items=_MAX_QUERIES_PER_CALL,
retry_hint="Retry with fewer, more targeted queries.")
if err:
return err
-
raw_limit = args.get("limit")
- if raw_limit is None:
- limit = config.search_default_limit
- else:
- limit = _clamped_int(raw_limit, config.search_default_limit, 1, config.max_search_limit)
+ limit = (config.search_default_limit if raw_limit is None
+ else _clamped_int(raw_limit, config.search_default_limit, 1, config.max_search_limit))
catalog = build_catalog(_deferrable_in(current_tool_defs))
-
results: List[Dict[str, Any]] = []
tools_map: Dict[str, Dict[str, Any]] = {}
corpus_stats = _corpus_stats(catalog)
@@ -614,7 +522,6 @@ def dispatch_tool_search(args: Dict[str, Any],
"object before concluding the capability is unavailable."
)
results.append(group)
-
return json.dumps({
"queries": queries,
"total_available": len(catalog),
@@ -637,7 +544,6 @@ def dispatch_tool_describe(args: Dict[str, Any],
"""
if config is None:
config = load_config_readonly()
-
names, err = _string_list_arg(
args, "names", dedupe=True, max_items=_MAX_DESCRIBE_NAMES_PER_CALL,
retry_hint="Retry with fewer names per call.")
@@ -646,7 +552,6 @@ def dispatch_tool_describe(args: Dict[str, Any],
deferrable = _deferrable_in(current_tool_defs)
by_name = {name: _fn(td) for td, name in zip(deferrable, _tool_def_names(deferrable)) if name}
-
tools: Dict[str, Dict[str, Any]] = {}
not_found: List[str] = []
errors: Dict[str, str] = {}
@@ -657,9 +562,10 @@ def dispatch_tool_describe(args: Dict[str, Any],
"description": fn.get("description", ""),
"parameters": fn.get("parameters", {}),
}
- elif _describe_classification(
+ elif _registry_entry(name) is not None and not is_deferrable_tool_name(
name, load_config_readonly().effective_defer_tools
- ) == "not_deferrable":
+ ):
+ # Registered but bridge/core/GUI-surface: a real name, wrong door.
errors[name] = (
f"'{name}' is not a deferrable tool. If you see it in the tools list "
"already, call it directly; otherwise check the spelling against tool_search."
@@ -729,7 +635,6 @@ __all__ = [
"estimate_tokens_from_schemas",
"should_activate",
"build_catalog",
- "build_catalog_listing",
"build_catalog_listing_with_form",
"listing_token_budget",
"search_catalog",
diff --git a/tools/tool_search_catalog.py b/tools/tool_search_catalog.py
index d745fd2bedb..f371d047f93 100644
--- a/tools/tool_search_catalog.py
+++ b/tools/tool_search_catalog.py
@@ -42,8 +42,7 @@ _thread_local = threading.local()
def _stemmer() -> Any:
st = getattr(_thread_local, "stemmer", None)
if st is None:
- st = snowballstemmer.stemmer("english")
- _thread_local.stemmer = st
+ st = _thread_local.stemmer = snowballstemmer.stemmer("english")
return st
@@ -54,10 +53,8 @@ def _stem(token: str) -> str:
def _tokenize(text: str) -> List[str]:
- """Lowercase alphanumeric tokens, Snowball-stemmed (English).
-
- Shared by the index path and the query path so "issues" matches ``create_issue``.
- """
+ """Lowercase alphanumeric tokens, Snowball-stemmed (English). Shared by the
+ index and query paths so "issues" matches ``create_issue``."""
if not text:
return []
return [_stem(token.lower()) for token in _TOKEN_RE.findall(text)]
@@ -84,8 +81,7 @@ def _entry_search_text(td: Dict[str, Any], source_label: str = "") -> str:
top-level parameter names. Schema bodies are excluded (noise, no recall
gain). The ``mcp__`` prefix is dropped — it is in every MCP document, so
its IDF is ~0. The source label lets a service-name query ("linear") reach
- a tool whose own name omits the vendor.
- """
+ a tool whose own name omits the vendor."""
fn = _fn(td)
name = fn.get("name", "")
if name.startswith("mcp__"):
@@ -135,8 +131,8 @@ def _bm25_score(query_tokens: List[str], doc_tokens: List[str],
doc_lengths: List[int], avg_dl: float,
doc_freq: Dict[str, int], n_docs: int,
k1: float = 1.5, b: float = 0.75) -> float:
- """Standard BM25 score for one query against one document (inlined; the
- catalog is bounded — typically < 500 tools — so a dependency is not worth it)."""
+ """Standard BM25 for one query against one document (inlined; the catalog
+ is bounded — typically < 500 tools — so a dependency is not worth it)."""
if not doc_tokens:
return 0.0
score = 0.0
@@ -144,12 +140,10 @@ def _bm25_score(query_tokens: List[str], doc_tokens: List[str],
doc_tf = Counter(doc_tokens)
for q in query_tokens:
df = doc_freq.get(q, 0)
- if df == 0:
- continue
- idf = math.log(1 + (n_docs - df + 0.5) / (df + 0.5))
tf = doc_tf.get(q, 0)
- if tf == 0:
+ if df == 0 or tf == 0:
continue
+ idf = math.log(1 + (n_docs - df + 0.5) / (df + 0.5))
norm = tf * (k1 + 1) / (tf + k1 * (1 - b + b * dl / max(avg_dl, 1.0)))
score += idf * norm
return score
@@ -178,17 +172,14 @@ def search_catalog(
"""Top-``limit`` catalog entries for ``query`` by BM25 (exact name match
ranks first). Falls back to a name-substring match only when NO query
token appears in any document (e.g. "hub" vs ``github_*``); the IDF
- variant is strictly positive, so a hit anywhere suppresses the fallback.
- """
+ variant is strictly positive, so a hit anywhere suppresses the fallback."""
if not catalog or limit <= 0:
return []
query_tokens = _tokenize(query)
if not query_tokens:
return []
-
if corpus_stats is None:
corpus_stats = _corpus_stats(catalog)
- doc_lengths, avg_dl, doc_freq, n_docs = corpus_stats
scored: List[Tuple[float, CatalogEntry]] = []
exact_name = query.strip().lower()
@@ -196,17 +187,12 @@ def search_catalog(
if entry.name.lower() == exact_name:
scored.append((float("inf"), entry))
continue
- s = _bm25_score(query_tokens, entry._tokens, doc_lengths, avg_dl,
- doc_freq, n_docs)
+ s = _bm25_score(query_tokens, entry._tokens, *corpus_stats)
if s > 0:
scored.append((s, entry))
-
if not scored:
ql = query.lower()
- for entry in catalog:
- if ql in entry.name.lower():
- scored.append((0.1, entry))
-
+ scored = [(0.1, entry) for entry in catalog if ql in entry.name.lower()]
scored.sort(key=lambda x: x[0], reverse=True)
return [e for _, e in scored[:limit]]
@@ -239,16 +225,6 @@ def _listing_group_label(source_name: str) -> str:
return label[4:] if label.startswith("mcp-") else label
-def build_catalog_listing(
- deferrable: List[Dict[str, Any]],
- *,
- max_tokens: int = 4000,
-) -> Optional[str]:
- """Render the deferred-catalog manifest; text only (see
- :func:`build_catalog_listing_with_form` for the degradation ladder)."""
- return build_catalog_listing_with_form(deferrable, max_tokens=max_tokens)[0]
-
-
def build_catalog_listing_with_form(
deferrable: List[Dict[str, Any]],
*,
@@ -267,9 +243,6 @@ def build_catalog_listing_with_form(
Degradation is PER SERVER (largest first): one huge server must not cost
a small co-attached server its listing.
"""
- if not deferrable:
- return None, "none"
-
groups: Dict[str, List[Tuple[str, str]]] = {}
for td in deferrable:
fn = _fn(td)
@@ -280,7 +253,6 @@ def build_catalog_listing_with_form(
# ``_listing_group_label("")`` is "other", so one call covers both.
label = _listing_group_label(_classify_source(name)[1])
groups.setdefault(label, []).append((name, _short_desc(fn.get("description", ""))))
-
if not groups:
return None, "none"
@@ -310,10 +282,8 @@ def build_catalog_listing_with_form(
text = assemble_if_fits(modes)
if text is not None:
return text, mode
-
# 3. Per-server degradation: collapse the LARGEST rendered groups first
- # (deterministic: size then label) so one oversized server does not
- # cost a small co-attached server its per-tool names.
+ # (deterministic: size then label).
by_size = sorted(groups, key=lambda lbl: (-len(render_group(lbl, "names")), lbl))
for lbl in by_size:
modes[lbl] = "summary"
@@ -321,5 +291,4 @@ def build_catalog_listing_with_form(
if text is not None:
form = "groups" if all(m == "summary" for m in modes.values()) else "mixed"
return text, form
-
return None, "none"
diff --git a/tools/tool_search_validation.py b/tools/tool_search_validation.py
index c5ee9ba401f..39d86582530 100644
--- a/tools/tool_search_validation.py
+++ b/tools/tool_search_validation.py
@@ -22,20 +22,13 @@ def _schema_for_local_validation(node: Any) -> Any:
return [_schema_for_local_validation(item) for item in node]
if not isinstance(node, dict):
return node
-
- normalized = {}
- for key, value in node.items():
- if key == "nullable":
- continue
- # Literal keywords hold instance data, not schemas: copy byte-for-byte.
- normalized[key] = (
- copy.deepcopy(value)
- if key in _SCHEMA_LITERAL_KEYS
- else _schema_for_local_validation(value)
- )
+ # Literal keywords hold instance data, not schemas: copy byte-for-byte.
+ normalized = {
+ key: copy.deepcopy(value) if key in _SCHEMA_LITERAL_KEYS else _schema_for_local_validation(value)
+ for key, value in node.items() if key != "nullable"
+ }
if node.get("nullable") is not True:
return normalized
-
schema_type = normalized.get("type")
if isinstance(schema_type, str):
if schema_type != "null":
@@ -45,7 +38,6 @@ def _schema_for_local_validation(node: Any) -> Any:
if "null" not in schema_type:
normalized["type"] = [*schema_type, "null"]
return normalized
-
# No ``type`` to extend ($ref/combinator): wrap so local refs still resolve
# from the root while null stays an explicit alternative.
return {"anyOf": [normalized, {"type": "null"}]}
@@ -83,10 +75,7 @@ def _validation_path(error: Any) -> str:
def _validation_error(message: str, *, path: str, constraint: str, parameters: Any) -> str:
return tool_error(
- message,
- path=path,
- constraint=constraint,
- parameters=parameters,
+ message, path=path, constraint=constraint, parameters=parameters,
hint="Retry tool_call with 'arguments' matching the parameters schema above.",
)
@@ -122,18 +111,14 @@ def validate_deferred_call_args(name: str, args: Dict[str, Any]) -> Optional[str
validation_schema = _schema_for_local_validation(params)
if _schema_has_external_ref(validation_schema):
- logger.debug(
- "Skipping local deferred-argument validation for %s: external $ref",
- name,
- )
+ logger.debug("Skipping local deferred-argument validation for %s: external $ref", name)
return None
# Validate the repaired shape dispatch will see; copy because
# coerce_tool_args may normalize in place (dispatch re-coerces canonically).
- candidate_args = dict(args)
try:
from model_tools import coerce_tool_args
- candidate_args = coerce_tool_args(name, candidate_args)
+ candidate_args = coerce_tool_args(name, dict(args))
except Exception:
logger.debug("Deferred-argument coercion failed for %s", name, exc_info=True)
candidate_args = dict(args)
@@ -142,20 +127,14 @@ def validate_deferred_call_args(name: str, args: Dict[str, Any]) -> Optional[str
from jsonschema.exceptions import best_match
from jsonschema.validators import validator_for
except ImportError:
- logger.debug(
- "jsonschema unavailable; keeping required-only validation for %s",
- name,
- )
+ logger.debug("jsonschema unavailable; keeping required-only validation for %s", name)
return None
validator_cls = validator_for(validation_schema)
validator_cls.check_schema(validation_schema)
- validation_error = best_match(
- validator_cls(validation_schema).iter_errors(candidate_args)
- )
+ validation_error = best_match(validator_cls(validation_schema).iter_errors(candidate_args))
if validation_error is None:
return None
-
path = _validation_path(validation_error)
constraint = str(getattr(validation_error, "validator", None) or "schema")
detail = re.sub(r"\s+", " ", str(validation_error.message)).strip()