Skip to content

The agent that grows with you

fix(mcp): spend tally survives multiplex rekey and never evicts; budget prompts are serialized per chat

Tekniumc7993457bcd4
diff --git a/tests/tools/test_mcp_tool_costs.py b/tests/tools/test_mcp_tool_costs.py
index e232ab54a15..8d94cc6bebc 100644
--- a/tests/tools/test_mcp_tool_costs.py
+++ b/tests/tools/test_mcp_tool_costs.py
@@ -123,11 +123,14 @@ def test_chats_and_profiles_never_share_a_tally(session):
assert a is not None and b is not None
a.book()
assert a.spent() == 40 and b.spent() == 0
+ # A process that starts multiplexing moves bare-name policies under (scope, name); totals follow.
+ mcp_tool_costs.rekey_unscoped("launch")
+ assert mcp_tool_costs._spent[(("launch", "srv"), "chat-a")] == 120 # 40 + 40 + the approved 40
def test_declarations_validate_translate_and_survive_a_native_trust_override(tmp_path, caplog):
from hermes_cli.agent_plugins import AgentPluginError, load_agent_plugin
- from tools.mcp_tool_config import _filter_suspicious_mcp_servers, _portable_mcp_servers
+ from tools.mcp_tool_config import _filter_suspicious_mcp_servers, _load_mcp_config, _portable_mcp_servers
def package(server_decl):
root = tmp_path / "pkg"
@@ -155,5 +158,8 @@ def test_declarations_validate_translate_and_survive_a_native_trust_override(tmp
manager = SimpleNamespace(get_portable_mcp_servers=lambda: dict(pkg.mcp_servers))
with patch("hermes_cli.plugins.discover_plugins"), patch("hermes_cli.plugins.get_plugin_manager", return_value=manager):
_portable_mcp_servers(native)
- assert native["srv"]["trust"] == "full" and native["srv"]["spend_limit"] == 0
- assert native["srv"]["tool_costs"] == {"paid_render": [5, 20]}
+ assert native["srv"]["trust"] == "full" and native["srv"]["spend_limit"] == 0
+ assert native["srv"]["tool_costs"] == {"paid_render": [5, 20]}
+ # A native entry rejected for a malformed budget is not revived by the package's looser one.
+ with patch("hermes_cli.config.load_config", return_value={"mcp_servers": {"srv": {"command": "x", "spend_limit": -5}}}):
+ assert "srv" not in _load_mcp_config()
diff --git a/tools/mcp_tool_config.py b/tools/mcp_tool_config.py
index 8d42daa6551..0d5947682a1 100644
--- a/tools/mcp_tool_config.py
+++ b/tools/mcp_tool_config.py
@@ -659,7 +659,7 @@ def _filter_suspicious_mcp_servers(servers: dict[str, dict]) -> dict[str, dict]:
return safe_servers
-def _portable_mcp_servers(safe_servers: dict[str, dict]) -> None:
+def _portable_mcp_servers(safe_servers: dict[str, dict], rejected: frozenset[str] = frozenset()) -> None:
"""Merge plugin-provided (portable) MCP servers into *safe_servers*; native config wins on a clash. Never raises.
The package's declared costs are facts about its server, so a same-name native entry (the way a user widens
@@ -670,7 +670,9 @@ def _portable_mcp_servers(safe_servers: dict[str, dict]) -> None:
discover_plugins()
portable = get_plugin_manager().get_portable_mcp_servers()
for name, cfg in _filter_suspicious_mcp_servers(portable).items():
- if name in safe_servers:
+ if name in rejected: # the user's own entry for this name has a malformed budget: stay off
+ logger.warning("Portable MCP server '%s' skipped: the native entry of that name was rejected", name)
+ elif name in safe_servers:
native = safe_servers[name]
carried = {k: cfg[k] for k in CONFIG_KEYS if k in cfg and k not in native}
if carried:
@@ -702,12 +704,17 @@ def _load_mcp_config() -> dict[str, dict]:
except Exception:
pass
safe_servers: dict[str, dict] = {}
- for name, cfg in _filter_suspicious_mcp_servers(servers if isinstance(servers, dict) else {}).items():
+ servers = servers if isinstance(servers, dict) else {}
+ kept = _filter_suspicious_mcp_servers(servers)
+ for name, cfg in kept.items():
interpolated = _interpolate_env_vars(cfg)
if isinstance(interpolated, dict):
_warn_hidden_whitespace(name, interpolated)
safe_servers[name] = interpolated
- _portable_mcp_servers(safe_servers)
+ # A same-name package must not revive a server whose native budget was rejected (a mistyped
+ # tighter limit would fall back to the package's looser one while the server keeps spending).
+ rejected = frozenset(n for n in servers if n not in kept and _malformed_cost_table(n, servers[n]) is not None)
+ _portable_mcp_servers(safe_servers, rejected)
return safe_servers
except Exception as exc:
logger.debug("Failed to load MCP config: %s", exc)
diff --git a/tools/mcp_tool_costs.py b/tools/mcp_tool_costs.py
index b06fcac14a0..3c11ab0b63f 100644
--- a/tools/mcp_tool_costs.py
+++ b/tools/mcp_tool_costs.py
@@ -14,9 +14,9 @@ from __future__ import annotations
import math
import threading
-from collections import OrderedDict
from dataclasses import dataclass
-from typing import Any, Mapping, Optional
+from contextlib import contextmanager
+from typing import Any, Iterator, Mapping, Optional
DEFAULT_UNIT = "credits"
# Native ``mcp_servers.<name>`` keys; a portable package's ``costs`` maps to ``tool_costs``.
@@ -95,10 +95,23 @@ def _fmt(amount: float) -> str:
# Spend per (policy key, approval session key): the policy key carries the profile scope under a
-# multiplexer and the session key is the chat the approval system already isolates. In memory only.
+# multiplexer and the session key is the chat the approval system already isolates. In memory only and
+# never evicted: a forgotten total would hand a chat that already spent its limit a fresh budget.
_lock = threading.Lock()
-_spent: OrderedDict[tuple, float] = OrderedDict()
-_MAX_TALLIES = 16384 # bounds a long-lived gateway; the least recently charged chat falls off first
+_spent: dict[tuple, float] = {}
+# One budget prompt at a time per tally: a parallel call must see the total the previous approval booked,
+# and identical prompts would otherwise coalesce into one answer that releases several charges.
+_ask_locks: dict[tuple, threading.Lock] = {}
+
+
+def rekey_unscoped(scope: str) -> None:
+ """Follow ``mcp_tool_scope.rekey_unscoped_connections``: a process that starts multiplexing moves its
+ bare-name policies under ``(scope, name)``, and the chats' totals must move with them."""
+ with _lock:
+ for policy_key, session_key in [k for k in _spent if isinstance(k[0], str)]:
+ amount = _spent.pop((policy_key, session_key))
+ moved = ((scope, policy_key), session_key)
+ _spent[moved] = _spent.get(moved, 0.0) + amount
@dataclass(frozen=True)
@@ -137,9 +150,14 @@ class Charge:
def _add_locked(self, amount: float) -> None:
_spent[self.key] = max(0.0, _spent.get(self.key, 0.0) + amount)
- _spent.move_to_end(self.key)
- while len(_spent) > _MAX_TALLIES:
- _spent.popitem(last=False)
+
+ @contextmanager
+ def asking(self) -> Iterator[None]:
+ """Hold this chat's budget-prompt slot while asking and booking."""
+ with _lock:
+ slot = _ask_locks.setdefault(self.key, threading.Lock())
+ with slot:
+ yield
def cost_sentence(self) -> str:
unit, cost = self.policy.unit, self.cost
diff --git a/tools/mcp_tool_handlers.py b/tools/mcp_tool_handlers.py
index a1ec78c680c..fcde468db09 100644
--- a/tools/mcp_tool_handlers.py
+++ b/tools/mcp_tool_handlers.py
@@ -72,20 +72,31 @@ def _trust_gate_check(server_name: str, tool_name: str, booked: Optional[list] =
if key in _core._server_cost_policies: # no table: not even a session lookup, main's path byte for byte
from tools.approval_context import get_current_session_key
charge = _costs.pending_charge(key, server_name, tool_name, get_current_session_key())
- if charge is None and not gated:
+ if charge is None:
+ return _ask_for_call(server_name, tool_name, None, booked) if gated else None
+ if not gated and charge.reserve_within_limit()[0]:
+ if booked is not None:
+ booked.append(charge)
return None
+ with charge.asking(): # re-read under the slot: a call that asked first may have booked meanwhile
+ return _ask_for_call(server_name, tool_name, charge, booked, gated=gated)
+
+
+def _ask_for_call(server_name: str, tool_name: str, charge, booked: Optional[list], *,
+ gated: bool = True) -> Optional[str]:
+ """Ask the user about one gated and/or costed call; book the charge only on an explicit yes."""
spent, over = 0.0, False
if charge is not None:
- if not gated:
+ if gated:
+ spent = charge.spent()
+ over = charge.over_limit(spent)
+ else:
reserved, spent = charge.reserve_within_limit()
if reserved:
if booked is not None:
booked.append(charge)
return None
over = True
- else:
- spent = charge.spent()
- over = charge.over_limit(spent)
extra = charge.lines(spent) if charge is not None else []
if gated:
head = f"MCP tool '{tool_name}' on UNTRUSTED server '{server_name}' wants to run."
diff --git a/tools/mcp_tool_scope.py b/tools/mcp_tool_scope.py
index 81d7be4db18..8f8bf395396 100644
--- a/tools/mcp_tool_scope.py
+++ b/tools/mcp_tool_scope.py
@@ -99,4 +99,6 @@ def rekey_unscoped_connections(scope: str) -> None:
for key in set(_core._servers) | set(_core._lazy_server_tool_names):
if _key_scope(key) == scope:
_core._server_tool_scopes.setdefault(key, set()).add(scope)
+ from tools.mcp_tool_costs import rekey_unscoped
+ rekey_unscoped(scope) # chats' spend totals follow their server's policy key
registry.move_to_scope(tool_names, scope)