b4d04eb8fd
* feat: add session-scoped connector access for onboarding
* fix(connectors): availability is the config flag AND the portal entitlement — no free-tier leg
The port carried a third availability leg from hermes-magic: a stored guest
(free-tier) identity short-circuits the managed-tool entitlement check. That
leg reads hermes_cli.anon_auth, which does not exist on hermes-agent main, so
connectors_available() raised ImportError inside its fail-closed try and the
whole connector surface was silently dark on a plain upstream checkout.
On this tree availability is the two-leg AND the design started with:
tools.connectors.enabled AND managed_nous_tools_enabled(). The free-tier leg
is a hermes-magic concern and belongs in hermes-magic's own delta over this
branch, next to the identity it depends on. Its integration test goes with it.
* docs(tool-search): connectors section — remote tools through the bridge
The squashed port carried the code but not the user-facing docs. Restores the
Connectors section of the Tool Search page and the connector-gateway host /
CONNECTOR_GATEWAY_URL override on the Tool Gateway page, updated for the
manage_connections tool and the pure-connector batch rule.
* fix(tool-search): connector tools rank with local tools in one pass instead of taking leftover slots
dispatch_tool_search ran BM25 over the local catalog, filled `limit` slots,
then appended connector hits only into slots left empty. On a 300-tool
catalog no slot was ever empty, so with Gmail and Google Calendar connected
"send gmail email" returned five betterstack tools and zero connector tools.
The gateway's hits for a query now become catalog entries (connector name,
slug words, description as the search text) and join the local catalog for
that query's BM25 pass. One ranking, one rarest-token admission rule for both
sources, `limit` as the total per query. The merge loop and the separate
record builder for connector hits are gone; `_shared_tool_record` serves both
sources.
The gateway search timeout rises from 8 s to 30 s. One request with six
use_cases measured 7 s, so 8 s sat on the edge and cut real answers off; the
failure path is unchanged (local-only results, no error to the model).
Live, 311 local tools + gateway, before -> after:
"send gmail email": 5 betterstack tools -> gmail SEND_EMAIL, CREATE_EMAIL_DRAFT
"read google calendar events": 5 betterstack tools -> googlecalendar EVENTS_LIST_ALL_CALENDARS
"linear create issue", "betterstack incident": unchanged
Benchmark (25 labelled queries): connector recall 0.09 -> 0.82, precision@5
0.18 -> 0.59, false positives on absent intents 17 -> 2.
* refactor(tool-search): connector leg into tools/connector_search.py
tools/tool_search.py is a facade. The connector leg (gateway hits as catalog
entries for tool_search, remote schemas for tool_describe, the
connections_in_scope gate) was appended to it by the port. It now lives in
its own sibling, tools/connector_search.py, and the facade imports the three
entry points: connections_in_scope, connector_entries_by_group,
remote_schemas_for.
No behaviour change. The tool_describe remote block became
remote_schemas_for(names, current_tool_defs, connector_describe) with the
same inputs, the same silent-degradation contract and the same injection
seam the tests already use.
* fix(tool-search): at most 7 queries per call, the gateway's search limit
One tool_search call sends all its queries to the connector gateway as one
search request. The gateway answers 7 use_cases per request and returns
HTTP 502 for 8 or more (measured 2026-09-09, re-measured with one-word
use_cases: it is a count limit, not a size limit). With the client cap at
10, a model sending 8 to 10 queries lost every connector hit for that call
and saw local-only results with no error.
The shared constant splits: _MAX_QUERIES_PER_CALL = 7 for search,
_MAX_DESCRIBE_NAMES_PER_CALL = 10 for describe, which has no remote count
limit. Eight or more queries now get the existing "too many queries" retry
hint before any request is made. No chunking: one call, one request.
* fix(tool-search): the model is told that connectors__ names are manage_connections accounts
tool_search results carry names like connectors__gmail__CREATE_EMAIL_DRAFT and
manage_connections is the tool that checks and connects those accounts, but
nothing told the model the two are the same thing. A model that hit
CONNECTION_REQUIRED had to infer the fix on its own.
The tool_search description gains one sentence making the link, added at
assembly only when manage_connections is in the session's tools. Signed out
or with connectors off the tool is absent and the description is unchanged,
so it never names a tool the model cannot call. This follows the existing
rule for cross-tool references (tools/AGENTS.md): they are added dynamically
from the session's actual tool set, never hardcoded in a schema.
Tool defs are fixed for the life of a conversation, so the description is
byte-stable per conversation; this is a one-time prefix change.
Live, real get_tool_definitions() against a signed-in home: sentence present.
Same home with auth.json removed: manage_connections absent, sentence absent.
* fix(connectors): /stop halts a connector batch before the next remote call
dispatch_connector_batch runs every remote entry of a tool_call batch in
sequence. The executor only checks the interrupt flag between tools, and
the whole batch is one tool to it, so a /stop landing during entry 1 of
20 still sent the other 19 to the gateway.
The loop now reads tools.interrupt.is_interrupted before each dispatch.
Once set, it stops calling handle_function_call and fills every unstarted
slot with the loop's existing error-slot shape, code INTERRUPTED and the
message "Stopped by the user before this call was made.", so the result
envelope stays valid and the counts stay honest. Entries already
dispatched keep their real results.
Test: three connector calls where the fake client sets the interrupt on
the first execute. The client sees exactly one call and slots 2 and 3
carry INTERRUPTED. Red on the base branch, green with the fix.
* test(connections): schema assertions become dispatch contracts
test_schema_documents_wait_and_its_timeout froze description fragments
("REQUIRED", "can NOT disconnect", "Nous Portal"). A wording edit fails
it while a real regression (a disconnect that reaches the gateway) does
not. That is a snapshot of prose, not a behaviour contract.
Delete it. The requirement that wait needs connectors is already covered
by test_wait_requires_connectors. The user-only disconnect boundary is
now asserted as behaviour: action disconnect with a connector returns an
error and the fake client records no call. That replaces the earlier
de-authenticate test, which only checked that the word "dashboard"
appeared in the error text.
Test count in the file goes from 26 to 25.
* docs(tool-search): connector batches are one gateway request per entry
The user guide said a connector batch travels as one gateway request. It
does not: model_tools_connectors.dispatch_connector_batch re-enters core
dispatch per entry, and each entry becomes its own execute request in
bridge._run_remote (plus at most one literal-slug retry when the gateway
reports TOOL_NOT_FOUND under the conventional slug). The docstrings in
tools/tool_gateway/bridge.py and tools/tool_gateway/__init__.py still
described the abandoned V1 plan and claimed nothing outside the package
imports it.
Rewrite those sentences to match the code: one request per entry, in
input order, dispatched from model_tools_connectors.py, with the per-entry
approval and interrupt behaviour that motivated the split. The guide also
still showed the single-call shape tool_call(name, arguments); both
places now show the `calls: [{name, arguments}]` array the schema
advertises and note that a single local call is an array of one.
Docs only, no test.
* fix(tools): the between-turns refresh never rewrites the bridge tools
The per-turn MCP refresh folds a fresh tool snapshot into the live array
with preserve_prefix: order and membership stay, but a name present in both
takes the fresh schema. That is right for ordinary tools, whose schema is a
constant. tool_search is the one tool whose description is derived from the
session: the deferred-tool count, the embedded listing, and, on this branch,
whether manage_connections was present. A late MCP server or one failed
portal lookup (manage_connections' check_fn fails closed) changed those bytes
on the next turn, and every byte after tool_search in the cached prefix was
re-prefilled. The array also contradicted itself in that case: the flapping
manage_connections was carried forward while the description lost its hint.
The bridge entries now keep the bytes they were built with for the life of
the conversation. Nothing is lost: tool_search reads the live catalog at
dispatch, so tools that arrived late are still found; connector availability
is checked at dispatch too. The compaction-boundary rebuild (content_aware,
the one sanctioned cache break) still refreshes the description.
Consequence: connector exposure in the prompt is decided once, at agent
build, by whether the user was signed in then. That is the intended
contract.
* refactor(tool-search): normalize_tool_call_entries lives with the other argument validation
The port appended the tool_call argument parser to the tool_search facade.
The family already has tools/tool_search_validation.py for exactly this
work (schema validation of deferred call arguments), so the parser moves
there and the facade imports it. No behaviour change; the one test that
imported it now imports from the defining module.
* refactor(connectors): delete the unused batch dispatcher; _run_remote becomes run_remote
bridge.dispatch_calls and its helpers (_dispatch_calls_inner, _run_pre_dispatch,
_run_local, _error_slot, _maybe_parse_json) and the LocalDispatch / PreDispatch
seams had no production caller. Connector dispatch runs through
model_tools_connectors: dispatch_connector_batch re-enters handle_function_call
once per entry, so scope, hook, approval and middleware policy fire against each
composed name inside core dispatch, and dispatch_connector_call hands the single
planned entry to the bridge's transport function. Only tests called the batch
dispatcher, and they exercised policy seams that production never wires.
The transport function is the module's real entry point, so it drops the
underscore: _run_remote becomes run_remote, body unchanged. The module
docstring now describes the two legs that exist (availability with D32 silent
degradation, and run_remote) instead of the injected seams. Imports that only
the deleted code used are gone; merge.py is untouched because every export
still has a caller.
Tests that drove dispatch_calls are deleted where they covered the removed
seams (pre_dispatch blocks and rewrites, local_dispatch classification, mixed
batches). The literal-slug fallback, the per-entry transport failure, and the
hook rewrite reaching the gateway request body are re-targeted at
handle_function_call('tool_call', ...) with the fake client swapped in at
bridge._default_client_factory, the same seam test_connector_dispatch_policy
uses. Each re-targeted test fails when the retry is disabled in run_remote.
* fix(connectors): search keeps the twin a colliding name reaches, and says so
format_connector_name strips the toolkit prefix, so GMAIL_FETCH_PROFILE and a
literal FETCH_PROFILE on gmail both compose to connectors__gmail__FETCH_PROFILE.
describe and execute decode that name to the prefixed slug first, so the
literal twin is unreachable under it. If a vendor ever shipped both, search
could describe the literal under a name that runs the prefixed tool.
Search is the one place that sees both twins in one response. It now keeps
the twin the name reaches and drops the other with a WARNING that names both
slugs, whichever the gateway listed first. Short names stay; no marker, no
per-process map, no change to describe or execute. No such pair exists in the
live catalog today; the guard turns a silent alias into a logged one.
484 lines
18 KiB
Python
484 lines
18 KiB
Python
"""Tests for the shared MCP agent-tool refresh helper and discovery-wait bound.
|
|
|
|
``refresh_agent_mcp_tools`` is the single rebuild path used by the TUI
|
|
``reload.mcp`` RPC, the gateway reload, and the late-binding refresh thread —
|
|
so a slow MCP server that connects after the agent's one-time tool snapshot is
|
|
picked up everywhere identically. These assert the *contracts* those callers
|
|
rely on (name-based diff, in-place mutation, agent-scoped filtering) rather than
|
|
freezing any particular tool list.
|
|
"""
|
|
|
|
import json
|
|
import threading
|
|
import types
|
|
|
|
import pytest
|
|
|
|
from tools import mcp_tool
|
|
from tools import mcp_tool_agent as _mcp_agent
|
|
|
|
|
|
def _tool(name):
|
|
return {"type": "function", "function": {"name": name, "description": "", "parameters": {}}}
|
|
|
|
|
|
def _agent(tool_names, *, enabled=None, disabled=None):
|
|
a = types.SimpleNamespace()
|
|
a.tools = [_tool(n) for n in tool_names]
|
|
a.valid_tool_names = set(tool_names)
|
|
a.enabled_toolsets = enabled
|
|
a.disabled_toolsets = disabled
|
|
return a
|
|
|
|
|
|
def test_refresh_adds_late_landing_tools(monkeypatch):
|
|
"""A server that registers after build → its tools land in the snapshot."""
|
|
agent = _agent(["read_file", "terminal"])
|
|
|
|
new_defs = [_tool(n) for n in ("read_file", "terminal", "mcp_granola_get_account_info")]
|
|
monkeypatch.setattr(mcp_tool, "get_tool_definitions", lambda **kw: new_defs, raising=False)
|
|
# get_tool_definitions is imported inside the helper from model_tools, so patch there too.
|
|
import model_tools
|
|
monkeypatch.setattr(model_tools, "get_tool_definitions", lambda **kw: new_defs)
|
|
|
|
added = _mcp_agent.refresh_agent_mcp_tools(agent)
|
|
|
|
assert added == {"mcp_granola_get_account_info"}
|
|
assert "mcp_granola_get_account_info" in agent.valid_tool_names
|
|
assert len(agent.tools) == 3
|
|
|
|
|
|
def test_refresh_preserves_memory_provider_and_context_engine_tools(monkeypatch):
|
|
"""B1 regression: a rebuild must NOT drop post-build-injected tools.
|
|
|
|
get_tool_definitions() returns only the registry-derived tools. agent_init
|
|
appends memory-provider tools (mem0/honcho/…) and context-engine tools
|
|
(lcm_*) directly onto agent.tools AFTER that. A naive
|
|
`agent.tools = get_tool_definitions()` would silently delete them on every
|
|
refresh. The helper must re-inject them.
|
|
"""
|
|
# Agent already carries: a built-in, a memory-provider tool, a context tool.
|
|
agent = _agent(["read_file", "memory_search", "lcm_grep"])
|
|
|
|
# Provider exposes its schemas; context compressor exposes lcm_*.
|
|
agent._memory_manager = types.SimpleNamespace(
|
|
get_all_tool_schemas=lambda: [
|
|
{"name": "memory_search", "description": "", "parameters": {}}
|
|
]
|
|
)
|
|
agent.context_compressor = types.SimpleNamespace(
|
|
get_tool_schemas=lambda: [
|
|
{"name": "lcm_grep", "description": "", "parameters": {}}
|
|
]
|
|
)
|
|
agent._context_engine_tool_names = {"lcm_grep"}
|
|
|
|
import model_tools
|
|
# The registry now ALSO has a newly-connected MCP tool, but does NOT contain
|
|
# the memory/context tools (they're never in get_tool_definitions output).
|
|
monkeypatch.setattr(
|
|
model_tools, "get_tool_definitions",
|
|
lambda **kw: [_tool("read_file"), _tool("mcp_new_server_tool")],
|
|
)
|
|
|
|
added = _mcp_agent.refresh_agent_mcp_tools(agent)
|
|
|
|
# The new MCP tool landed AND the injected families survived.
|
|
assert "mcp_new_server_tool" in agent.valid_tool_names
|
|
assert "memory_search" in agent.valid_tool_names # not clobbered
|
|
assert "lcm_grep" in agent.valid_tool_names # not clobbered
|
|
assert added == {"mcp_new_server_tool"}
|
|
|
|
|
|
def test_refresh_does_not_reinject_disabled_memory_provider_tools(monkeypatch):
|
|
"""A refresh removes stale provider tools when memory becomes disabled."""
|
|
agent = _agent(
|
|
["read_file", "memory_search"],
|
|
enabled=["all"],
|
|
disabled=["memory"],
|
|
)
|
|
agent._memory_manager = types.SimpleNamespace(
|
|
get_all_tool_schemas=lambda: [
|
|
{"name": "memory_search", "description": "", "parameters": {}}
|
|
]
|
|
)
|
|
|
|
import model_tools
|
|
monkeypatch.setattr(
|
|
model_tools,
|
|
"get_tool_definitions",
|
|
lambda **kw: [_tool("read_file")],
|
|
)
|
|
|
|
_mcp_agent.refresh_agent_mcp_tools(agent)
|
|
|
|
assert "memory_search" not in agent.valid_tool_names
|
|
assert all(t["function"]["name"] != "memory_search" for t in agent.tools)
|
|
|
|
|
|
def test_refresh_respects_context_engine_toolset_gate(monkeypatch):
|
|
"""#5544: context-engine tools must NOT be re-injected on a restricted
|
|
toolset. A platform with enabled_toolsets that excludes context_engine
|
|
must not get lcm_* leaked back in by a refresh."""
|
|
agent = _agent(["read_file"], enabled=["coding"]) # context_engine NOT enabled
|
|
agent.context_compressor = types.SimpleNamespace(
|
|
get_tool_schemas=lambda: [{"name": "lcm_grep", "description": "", "parameters": {}}]
|
|
)
|
|
agent._context_engine_tool_names = set()
|
|
|
|
import model_tools
|
|
monkeypatch.setattr(
|
|
model_tools, "get_tool_definitions",
|
|
lambda **kw: [_tool("read_file"), _tool("mcp_new_tool")],
|
|
)
|
|
|
|
_mcp_agent.refresh_agent_mcp_tools(agent)
|
|
|
|
assert "mcp_new_tool" in agent.valid_tool_names # MCP tool still lands
|
|
assert "lcm_grep" not in agent.valid_tool_names # gated out (#5544)
|
|
|
|
|
|
def test_refreshed_tool_is_callable_through_valid_tool_names_guard(monkeypatch):
|
|
"""The whole point: a late tool, once refreshed, passes the name guard the
|
|
run loop uses to accept/reject tool calls (agent.valid_tool_names)."""
|
|
agent = _agent(["read_file"])
|
|
|
|
import model_tools
|
|
monkeypatch.setattr(
|
|
model_tools, "get_tool_definitions",
|
|
lambda **kw: [_tool("read_file"), _tool("mcp_granola_list_meetings")],
|
|
)
|
|
|
|
# Before refresh the run loop would reject the call ("Tool does not exist").
|
|
assert "mcp_granola_list_meetings" not in agent.valid_tool_names
|
|
|
|
_mcp_agent.refresh_agent_mcp_tools(agent)
|
|
|
|
# After refresh the same guard accepts it AND it's in the tools= payload.
|
|
assert "mcp_granola_list_meetings" in agent.valid_tool_names
|
|
assert any(t["function"]["name"] == "mcp_granola_list_meetings" for t in agent.tools)
|
|
|
|
|
|
def test_refresh_is_thread_safe_under_concurrent_calls(monkeypatch):
|
|
"""Concurrent refreshes keep tools / valid_tool_names coherent.
|
|
|
|
The registry alternates between two DIFFERENT tool sets every call, so the
|
|
write path (publish) runs repeatedly rather than short-circuiting on the
|
|
no-change early return — this actually exercises the lock. The invariant:
|
|
a reader of ``valid_tool_names`` must always match ``agent.tools``, and the
|
|
final published pair must be one of the two valid sets (never a mix).
|
|
"""
|
|
agent = _agent(["a"])
|
|
|
|
import itertools
|
|
set_a = [_tool("a"), _tool("b")]
|
|
set_b = [_tool("a"), _tool("c")]
|
|
flip = itertools.cycle([set_a, set_b])
|
|
flip_lock = threading.Lock()
|
|
|
|
def _gtd(**kw):
|
|
with flip_lock:
|
|
return list(next(flip))
|
|
|
|
import model_tools
|
|
monkeypatch.setattr(model_tools, "get_tool_definitions", _gtd)
|
|
|
|
errors = []
|
|
|
|
def _worker():
|
|
try:
|
|
for _ in range(50):
|
|
_mcp_agent.refresh_agent_mcp_tools(agent)
|
|
# Coherence invariant: the name set must match the tool list
|
|
# at every observation, never a torn cross-attribute state.
|
|
names = {t["function"]["name"] for t in agent.tools}
|
|
assert agent.valid_tool_names == names
|
|
assert names in ({"a", "b"}, {"a", "c"})
|
|
except Exception as exc: # pragma: no cover - failure path
|
|
errors.append(exc)
|
|
|
|
threads = [threading.Thread(target=_worker) for _ in range(4)]
|
|
for t in threads:
|
|
t.start()
|
|
for t in threads:
|
|
t.join(timeout=10)
|
|
|
|
assert not errors
|
|
assert agent.valid_tool_names in ({"a", "b"}, {"a", "c"})
|
|
|
|
|
|
# ── discovery-wait bound (mcp_discovery_timeout config) ──────────────────────
|
|
|
|
|
|
def test_resolve_discovery_timeout_explicit_wins(monkeypatch):
|
|
from hermes_cli import mcp_startup
|
|
|
|
assert mcp_startup._resolve_discovery_timeout(2.5) == 2.5
|
|
|
|
|
|
def test_wait_returns_instantly_when_no_discovery_thread(monkeypatch):
|
|
"""The common case (no MCP / discovery done) pays ~0s regardless of bound."""
|
|
import time
|
|
from hermes_cli import mcp_startup
|
|
|
|
monkeypatch.setattr(mcp_startup, "_mcp_discovery_thread", None)
|
|
import hermes_cli.config as cfg
|
|
monkeypatch.setattr(cfg, "load_config", lambda: {"mcp_discovery_timeout": 999.0})
|
|
|
|
t0 = time.time()
|
|
mcp_startup.wait_for_mcp_discovery()
|
|
assert time.time() - t0 < 0.2 # never blocks on the bound when nothing's pending
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# preserve_prefix: the tool array is a cached request prefix (#100336)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _registered(monkeypatch, names):
|
|
"""Make the registry report exactly *names* as still registered."""
|
|
from tools import registry as registry_mod
|
|
|
|
entries = [types.SimpleNamespace(name=n) for n in names]
|
|
monkeypatch.setattr(
|
|
registry_mod.registry, "get_all_entries", lambda: entries, raising=False
|
|
)
|
|
|
|
|
|
def _serve(monkeypatch, defs):
|
|
import model_tools
|
|
|
|
monkeypatch.setattr(model_tools, "get_tool_definitions", lambda **kw: list(defs))
|
|
|
|
|
|
def test_preserve_prefix_carries_a_flapping_tool_forward(monkeypatch):
|
|
"""A check_fn flip must not shrink a live session's tool prefix.
|
|
|
|
``browser_navigate``'s availability probe fails this turn (headless box,
|
|
expired credential, docker blip) so ``get_tool_definitions`` omits it. The
|
|
tool is still *registered* — only its probe flapped — so the snapshot must
|
|
keep it, byte-for-byte, instead of forking the cached prefix.
|
|
"""
|
|
agent = _agent(["read_file", "browser_navigate", "terminal"])
|
|
before = list(agent.tools)
|
|
|
|
_serve(monkeypatch, [_tool("read_file"), _tool("terminal")])
|
|
_registered(monkeypatch, ["read_file", "browser_navigate", "terminal"])
|
|
|
|
added = _mcp_agent.refresh_agent_mcp_tools(agent, preserve_prefix=True)
|
|
|
|
assert added == set()
|
|
assert agent.tools == before
|
|
assert "browser_navigate" in agent.valid_tool_names
|
|
|
|
|
|
def test_preserve_prefix_appends_late_arrivals_at_the_tail(monkeypatch):
|
|
"""``get_definitions`` sorts by name, so a late tool can splice in at 0.
|
|
|
|
Under ``preserve_prefix`` the live order is authoritative and the new tool
|
|
extends the array, leaving every earlier byte where the provider cached it.
|
|
"""
|
|
agent = _agent(["read_file", "terminal"])
|
|
|
|
# Sorted order would put the new tool first.
|
|
_serve(monkeypatch, [_tool("aaa_mcp_late"), _tool("read_file"), _tool("terminal")])
|
|
_registered(monkeypatch, ["aaa_mcp_late", "read_file", "terminal"])
|
|
|
|
added = _mcp_agent.refresh_agent_mcp_tools(agent, preserve_prefix=True)
|
|
|
|
assert added == {"aaa_mcp_late"}
|
|
assert [t["function"]["name"] for t in agent.tools] == [
|
|
"read_file", "terminal", "aaa_mcp_late",
|
|
]
|
|
|
|
|
|
def test_preserve_prefix_keeps_the_bridge_tools_byte_identical(monkeypatch):
|
|
"""``tool_search``'s description is derived from the session at build time: the
|
|
deferred-tool count, the embedded listing, and whether ``manage_connections`` was
|
|
present. Every one of those inputs can move between turns (a late MCP server, a
|
|
``check_fn`` flap on a portal blip), and a moved byte in the tool array re-prefills
|
|
the whole cached history. The refresh must leave the bridge entries exactly as
|
|
built; a search still reads the live catalog at dispatch."""
|
|
from tools.tool_search_catalog import BRIDGE_TOOL_NAMES
|
|
|
|
built = _tool("tool_search")
|
|
built["function"]["description"] = "Search 21 additional tools. connectors__ hint present."
|
|
agent = _agent(["read_file", "manage_connections"])
|
|
agent.tools.append(built)
|
|
agent.valid_tool_names.add("tool_search")
|
|
before = json.dumps(agent.tools, sort_keys=True)
|
|
|
|
fresh_bridge = _tool("tool_search")
|
|
fresh_bridge["function"]["description"] = "Search 33 additional tools."
|
|
# manage_connections flapped out (portal blip); a late server grew the count.
|
|
_serve(monkeypatch, [_tool("read_file"), fresh_bridge, _tool("mcp_late_tool")])
|
|
_registered(monkeypatch, ["read_file", "manage_connections", "mcp_late_tool", *BRIDGE_TOOL_NAMES])
|
|
|
|
added = _mcp_agent.refresh_agent_mcp_tools(agent, preserve_prefix=True)
|
|
|
|
assert added == {"mcp_late_tool"}
|
|
assert json.dumps(agent.tools[:3], sort_keys=True) == before
|
|
assert [t["function"]["name"] for t in agent.tools][-1] == "mcp_late_tool"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# tools[] freeze: eviction rebuild + the /reload-mcp re-probe hatch
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_eviction_rebuild_restores_the_sessions_saved_tool_order(monkeypatch):
|
|
"""A fresh AIAgent for an EXISTING session must keep the saved tools[] pin.
|
|
|
|
Gateway agent-cache eviction rebuilds the agent; ``agent_init`` re-probes
|
|
every ``check_fn`` and ``browser_navigate``'s flips false. The persisted
|
|
name list stands in for the missing predecessor: the tool is carried
|
|
forward from the registry schema, byte-for-byte in its old slot.
|
|
"""
|
|
from tools import registry as registry_mod
|
|
|
|
saved = ["read_file", "browser_navigate", "terminal"]
|
|
entries = {n: types.SimpleNamespace(name=n, schema=_tool(n)["function"]) for n in saved}
|
|
monkeypatch.setattr(registry_mod.registry, "get_all_entries", lambda: list(entries.values()), raising=False)
|
|
monkeypatch.setattr(registry_mod.registry, "get_entry", lambda name, **kw: entries.get(name), raising=False)
|
|
|
|
rebuilt = _agent(["read_file", "terminal"]) # probe flipped: browser_navigate gone
|
|
changed = _mcp_agent.restore_agent_tool_prefix(rebuilt, saved)
|
|
|
|
assert changed is True
|
|
assert [t["function"]["name"] for t in rebuilt.tools] == saved
|
|
assert rebuilt.valid_tool_names == set(saved)
|
|
|
|
|
|
def test_reprobe_tool_availability_drops_cached_check_fn_verdicts(monkeypatch):
|
|
"""/reload-mcp is the explicit hatch: a cached False must be re-probed."""
|
|
from tools import registry as registry_mod
|
|
import model_tools
|
|
|
|
verdict = {"ok": False}
|
|
|
|
def probe():
|
|
return verdict["ok"]
|
|
|
|
monkeypatch.setattr(registry_mod, "check_fn_cache_scope", lambda: "test-scope")
|
|
assert registry_mod._check_fn_cached(probe) is False
|
|
verdict["ok"] = True
|
|
assert registry_mod._check_fn_cached(probe) is False # TTL cache replays stale verdict
|
|
with model_tools._tool_defs_cache_lock:
|
|
model_tools._tool_defs_cache[("sentinel",)] = []
|
|
|
|
_mcp_agent.reprobe_tool_availability()
|
|
|
|
assert registry_mod._check_fn_cached(probe) is True
|
|
assert ("sentinel",) not in model_tools._tool_defs_cache
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Bot Mode dynamic capability: every snapshot rebuild re-runs its auth gate
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class _BotModeDB:
|
|
def __init__(self, home, title):
|
|
self.db_path = str(home / "state.db")
|
|
self._title = title
|
|
|
|
def get_session_title(self, _session_id):
|
|
return self._title
|
|
|
|
|
|
@pytest.fixture
|
|
def managed_bot_home(tmp_path):
|
|
home = tmp_path / ".hermes"
|
|
profile = home / "profiles" / "researcher"
|
|
profile.mkdir(parents=True)
|
|
(profile / "profile.yaml").write_text(
|
|
"ui_meta:\n hermes-bots:\n shape: cloud\n",
|
|
encoding="utf-8",
|
|
)
|
|
return home
|
|
|
|
|
|
def _bot_mode_agent(home, *, title="Bot Chat"):
|
|
agent = _agent(["read_file"])
|
|
agent._session_db = _BotModeDB(home, title)
|
|
agent.session_id = "session-1"
|
|
agent._session_title_hint = None
|
|
agent._bot_mode_protocol = True
|
|
return agent
|
|
|
|
|
|
def _message_agent_schema_count(agent):
|
|
return sum(
|
|
t.get("function", {}).get("name") == "message_agent"
|
|
for t in agent.tools
|
|
if isinstance(t, dict)
|
|
)
|
|
|
|
|
|
def _assert_tool_snapshot_coherent(agent):
|
|
names = {t["function"]["name"] for t in agent.tools}
|
|
assert agent.valid_tool_names == names
|
|
|
|
|
|
@pytest.mark.parametrize("rebuild", ["compaction", "reload", "between_turns", "resume"])
|
|
def test_authorized_message_agent_survives_every_snapshot_rebuild(
|
|
managed_bot_home, monkeypatch, rebuild
|
|
):
|
|
"""Compaction, live refreshes and eviction/resume all preserve the guarded tool."""
|
|
from tools.bot_mode_dm import ensure_message_agent_tool
|
|
from tools import registry as registry_mod
|
|
|
|
agent = _bot_mode_agent(managed_bot_home)
|
|
_serve(monkeypatch, [_tool("read_file")])
|
|
entry = types.SimpleNamespace(name="read_file", schema=_tool("read_file")["function"])
|
|
monkeypatch.setattr(registry_mod.registry, "get_all_entries", lambda: [entry], raising=False)
|
|
monkeypatch.setattr(
|
|
registry_mod.registry,
|
|
"get_entry",
|
|
lambda name, **_kw: entry if name == "read_file" else None,
|
|
raising=False,
|
|
)
|
|
|
|
assert ensure_message_agent_tool(agent) is True
|
|
|
|
def rebuild_snapshot():
|
|
if rebuild == "resume":
|
|
agent.tools = [_tool("read_file")]
|
|
agent.valid_tool_names = {"read_file"}
|
|
_mcp_agent.restore_agent_tool_prefix(agent, ["read_file", "message_agent"])
|
|
else:
|
|
_mcp_agent.refresh_agent_mcp_tools(
|
|
agent,
|
|
content_aware=rebuild == "compaction",
|
|
preserve_prefix=rebuild == "between_turns",
|
|
)
|
|
|
|
for _ in range(2):
|
|
rebuild_snapshot()
|
|
assert _message_agent_schema_count(agent) == 1
|
|
assert "message_agent" in agent.valid_tool_names
|
|
_assert_tool_snapshot_coherent(agent)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("title", "managed"),
|
|
[("Ordinary chat", True), ("Bot Chat", False)],
|
|
)
|
|
def test_snapshot_rebuild_never_grants_message_agent_to_unauthorized_sessions(
|
|
tmp_path, managed_bot_home, monkeypatch, title, managed
|
|
):
|
|
"""Ordinary and unmanaged chats remain fail-closed across repeated rebuilds."""
|
|
home = managed_bot_home if managed else tmp_path / "unmanaged"
|
|
home.mkdir(exist_ok=True)
|
|
agent = _bot_mode_agent(home, title=title)
|
|
# Even a stale/leaked dynamic capability is scrubbed unless the live gate re-authorizes it.
|
|
agent.tools.append(_tool("message_agent"))
|
|
agent.valid_tool_names.add("message_agent")
|
|
_serve(monkeypatch, [_tool("read_file")])
|
|
|
|
for _ in range(2):
|
|
_mcp_agent.refresh_agent_mcp_tools(agent, content_aware=True)
|
|
assert _message_agent_schema_count(agent) == 0
|
|
assert "message_agent" not in agent.valid_tool_names
|
|
_assert_tool_snapshot_coherent(agent)
|