Skip to content

The agent that grows with you

feat(mcp): declared per-tool costs and a per-chat spend limit for MCP servers

Teknium4baddd2606d0
diff --git a/hermes_cli/agent_plugins.py b/hermes_cli/agent_plugins.py
index f983c39060c..b2b5081fef3 100644
--- a/hermes_cli/agent_plugins.py
+++ b/hermes_cli/agent_plugins.py
@@ -90,7 +90,9 @@ class AgentPluginPackage:
diagnostics: tuple[AgentPluginDiagnostic, ...]
-_SERVER_DECLARATION_KEYS = frozenset({"app", "requires", "liveness", "trust", "timeout"})
+_SERVER_DECLARATION_KEYS = frozenset({"app", "requires", "liveness", "trust", "timeout", "costs", "spend_limit", "cost_unit"})
+# Hermes call-policy keys: alone they configure a server, they do not declare an application.
+_SERVER_POLICY_KEYS = frozenset({"trust", "timeout", "costs", "spend_limit", "cost_unit"})
def _server_declarations(
@@ -120,8 +122,8 @@ def _server_declarations(
continue
if "liveness" in raw and "app" not in raw and "requires" not in raw:
raise AgentPluginError(f"server declaration '{name}' has liveness without app or requires")
- if raw and set(raw) <= {"trust", "timeout"}:
- continue # transport settings alone do not declare an application
+ if raw and set(raw) <= _SERVER_POLICY_KEYS:
+ continue # transport/policy settings alone do not declare an application
try:
declaration = parse_declaration(
name, raw.get("app"), raw.get("requires"),
@@ -174,6 +176,30 @@ def _server_timeouts(manifest: Mapping[str, Any], mcp_servers: Mapping[str, dict
return timeouts
+def _server_costs(manifest: Mapping[str, Any], mcp_servers: Mapping[str, dict[str, Any]]) -> dict[str, dict[str, Any]]:
+ """Translate ``costs``/``spend_limit``/``cost_unit`` into the native ``tool_costs``/``spend_limit``/``cost_unit``
+ keys (``tools.mcp_tool_costs``). A malformed table disables the package: a budget the author declared must
+ never be dropped while the server still spends."""
+ from tools.mcp_tool_costs import parse_cost_policy
+ raw_servers = manifest.get("extensions", {}).get(_HERMES_EXTENSION, {}).get("servers", {})
+ translated: dict[str, dict[str, Any]] = {}
+ for name, raw in (raw_servers.items() if isinstance(raw_servers, dict) else ()):
+ if not isinstance(raw, dict) or name not in mcp_servers:
+ continue
+ declared = {key: raw[key] for key in ("costs", "spend_limit", "cost_unit") if key in raw}
+ if not declared:
+ continue
+ try:
+ parse_cost_policy(declared.get("costs"), declared.get("spend_limit"), declared.get("cost_unit"),
+ where=f"server declaration '{name}'")
+ except ValueError as exc:
+ raise AgentPluginError(str(exc)) from exc
+ if "costs" in declared:
+ declared["tool_costs"] = declared.pop("costs")
+ translated[name] = declared
+ return translated
+
+
def _inside(path: Path, root: Path) -> bool:
try:
return path.resolve(strict=False).is_relative_to(root.resolve(strict=True))
@@ -480,6 +506,8 @@ def load_agent_plugin(plugin_root: Path, data_root: Path) -> AgentPluginPackage:
mcp_servers[name] = {**mcp_servers[name], "trust": tier}
for name, timeout in _server_timeouts(manifest, mcp_servers).items():
mcp_servers[name] = {**mcp_servers[name], "timeout": timeout}
+ for name, costs in _server_costs(manifest, mcp_servers).items():
+ mcp_servers[name] = {**mcp_servers[name], **costs}
server_declarations = _server_declarations(manifest, mcp_servers, diagnostics)
return AgentPluginPackage(
name=manifest["name"], version=manifest.get("version", ""),
diff --git a/hermes_cli/plugin_validate.py b/hermes_cli/plugin_validate.py
index 916a4834789..ea88f7ce2a7 100644
--- a/hermes_cli/plugin_validate.py
+++ b/hermes_cli/plugin_validate.py
@@ -667,6 +667,12 @@ def _validate_portable_plugin(report: ValidationReport, plugin_dir: Path) -> Val
if config.get("trust") == "untrusted":
report.add(f"server trust: {server_name}", True,
"untrusted (Hermes asks before every write-capable tool call)")
+ if config.get("tool_costs"):
+ limit = config.get("spend_limit") or 0
+ report.add(f"server costs: {server_name}", True,
+ f"{len(config['tool_costs'])} costed tool(s), "
+ + (f"spend limit {limit} {config.get('cost_unit') or 'credits'} per chat" if limit
+ else "no spend limit"))
for server_name, server_decl in package.server_declarations.items():
result = availability(server_decl.declaration)
detail = result.state
diff --git a/tests/tools/test_mcp_tool_costs.py b/tests/tools/test_mcp_tool_costs.py
new file mode 100644
index 00000000000..e232ab54a15
--- /dev/null
+++ b/tests/tools/test_mcp_tool_costs.py
@@ -0,0 +1,159 @@
+"""Declared MCP tool costs and the per-chat spend limit (``tools.mcp_tool_costs``).
+
+Invariants: a costed call's prompt names the cost and the chat's running total; only dispatched
+calls count; a call that would cross ``spend_limit`` asks even on a ``trust: full`` server and is
+refused unattended without dispatching; chats and profiles never share a tally; malformed
+declarations fail with a named error (package and config.yaml) while unknown keys only warn.
+"""
+
+import asyncio
+import json
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from tools import mcp_tool, mcp_tool_costs
+from tools import mcp_tool_handlers as handlers
+from tools import mcp_tool_registration as registration
+from tools.approval_context import reset_current_session_key, set_current_session_key
+
+COSTED = {"trust": "full", "tool_costs": {"paid_render": 40, "batch": {"credits": [5, 20], "note": "per item"}},
+ "spend_limit": 100}
+
+
+def _run_on_loop(coro_or_factory, timeout=30):
+ coro = coro_or_factory() if callable(coro_or_factory) else coro_or_factory
+ loop = asyncio.new_event_loop()
+ try:
+ async def _run():
+ for srv in list(mcp_tool._servers.values()):
+ if getattr(srv, "_rpc_lock", None) is None:
+ srv._rpc_lock = asyncio.Lock()
+ return await coro
+ return loop.run_until_complete(_run())
+ finally:
+ loop.close()
+
+
+def session():
+ result = SimpleNamespace(content=[SimpleNamespace(type="text", text="ok")], isError=False, structuredContent=None)
+ session = MagicMock()
+ session.call_tool = AsyncMock(return_value=result)
+ with patch.dict(mcp_tool._servers, {"srv": SimpleNamespace(session=session, _rpc_lock=None)}), \
+ patch("tools.mcp_tool_loop._run_on_mcp_loop", side_effect=_run_on_loop), \
+ patch.dict(mcp_tool._server_error_counts, {}, clear=True), \
+ patch.dict(mcp_tool._server_trust_levels, {}, clear=True), \
+ patch.dict(mcp_tool._tool_read_only_hints, {}, clear=True), \
+ patch.dict(mcp_tool._server_cost_policies, {}, clear=True), \
+ patch.dict(mcp_tool_costs._spent, {}, clear=True):
+ yield session
+
+
+def _register(config, name="srv", tools=("paid_render", "batch", "free_status")):
+ registration._record_tool_trust_metadata(name, config, [SimpleNamespace(name=t, annotations=None) for t in tools])
+
+
+def _call(tool, chat="chat-a", answer="accept"):
+ asked = []
+ token = set_current_session_key(chat)
+ try:
+ with patch("tools.approval_prompt.request_elicitation_consent",
+ side_effect=lambda msg, desc, **kw: asked.append(msg) or answer):
+ raw = handlers._make_tool_handler("srv", tool, 30.0)({})
+ finally:
+ reset_current_session_key(token)
+ return json.loads(raw), asked
+
+
+def test_untrusted_prompt_names_cost_and_running_total_and_declines_add_nothing(session):
+ _register(dict(COSTED, trust="untrusted"))
+ _, asked = _call("paid_render", answer="decline")
+ assert "Costs about 40 credits." in asked[0] and "used about" not in asked[0]
+ result, asked = _call("paid_render") # the declined call added nothing
+ assert result == {"result": "ok"} and "used about" not in asked[0]
+ _, asked = _call("batch")
+ assert "Costs 5-20 credits (per item). This chat has used about 40 credits on 'srv' (limit 100)." in asked[0]
+ # An undeclared tool on a costed server keeps main's exact prompt.
+ _, asked = _call("free_status")
+ assert asked == ["MCP tool 'free_status' on UNTRUSTED server 'srv' wants to run. This tool is write-capable "
+ "(no readOnlyHint=true annotation) and may modify external state."]
+ assert session.call_tool.await_count == 3
+
+
+def test_full_trust_asks_only_past_the_limit_and_unattended_refuses_without_dispatch(session):
+ from gateway.session_context import clear_session_vars, set_session_vars
+ _register(COSTED)
+ for _ in range(2): # 80 of 100: trust: full stays silent below the limit
+ result, asked = _call("paid_render")
+ assert result == {"result": "ok"} and asked == []
+ _, asked = _call("free_status")
+ assert asked == []
+ result, asked = _call("paid_render", answer="decline") # 80 + 40 > 100
+ assert "would take this chat past its spend limit" in asked[0]
+ assert "This chat has used about 80 credits on 'srv' (limit 100)." in asked[0]
+ assert "spend limit is 100 credits" in result["error"] and "Do not retry" in result["error"]
+ result, asked = _call("paid_render") # approved past the limit: runs, and the next one asks again
+ assert result == {"result": "ok"}
+ _, asked = _call("batch")
+ assert "used about 120 credits" in asked[0]
+ dispatched = session.call_tool.await_count
+ tokens = set_session_vars(cron_session="1") # cron: nobody can answer, the real consent path declines
+ token = set_current_session_key("chat-a")
+ try:
+ result = json.loads(handlers._make_tool_handler("srv", "paid_render", 30.0)({}))
+ finally:
+ reset_current_session_key(token)
+ clear_session_vars(tokens)
+ assert "used about 140 credits" in result["error"] and session.call_tool.await_count == dispatched
+
+
+def test_chats_and_profiles_never_share_a_tally(session):
+ _register(COSTED)
+ for _ in range(2):
+ _call("paid_render", chat="chat-a")
+ assert _call("paid_render", chat="chat-a")[1] # chat-a is at its limit
+ assert _call("paid_render", chat="chat-b")[1] == [] # chat-b is not
+ # Two profiles in one multiplexed process: the policy key carries the profile scope.
+ policy = mcp_tool._server_cost_policies["srv"]
+ mcp_tool._server_cost_policies[("profile-a", "srv")] = mcp_tool._server_cost_policies[("profile-b", "srv")] = policy
+ a = mcp_tool_costs.pending_charge(("profile-a", "srv"), "srv", "paid_render", "chat-a")
+ b = mcp_tool_costs.pending_charge(("profile-b", "srv"), "srv", "paid_render", "chat-a")
+ assert a is not None and b is not None
+ a.book()
+ assert a.spent() == 40 and b.spent() == 0
+
+
+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
+
+ def package(server_decl):
+ root = tmp_path / "pkg"
+ root.mkdir(exist_ok=True)
+ (root / "plugin.json").write_text(json.dumps({
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", "name": "pkg",
+ "extensions": {"com.nousresearch.hermes": {"servers": {"srv": server_decl}}}}))
+ (root / "mcp.json").write_text(json.dumps({
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
+ "mcpServers": {"srv": {"type": "stdio", "command": "python3", "args": ["s.py"]}}}))
+ return load_agent_plugin(root, tmp_path / "data")
+
+ pkg = package({"trust": "untrusted", "costs": {"paid_render": [5, 20]}, "spend_limit": 50, "future": 1})
+ assert pkg.mcp_servers["srv"]["tool_costs"] == {"paid_render": [5, 20]}
+ assert pkg.mcp_servers["srv"]["spend_limit"] == 50
+ assert any("future" in d.message for d in pkg.diagnostics) # unknown keys still only warn
+ with pytest.raises(AgentPluginError, match="cost of 'paid_render' must be a non-negative number"):
+ package({"costs": {"paid_render": -1}})
+ with caplog.at_level("ERROR"):
+ kept = _filter_suspicious_mcp_servers({"bad": {"command": "x", "spend_limit": "lots"}, "ok": {"command": "x"}})
+ assert list(kept) == ["ok"] and "spend_limit must be a non-negative number" in caplog.text
+
+ # A same-name native entry widening trust keeps the package's costs; its own spend_limit (0 = off) wins.
+ native = {"srv": {"command": "python3", "trust": "full", "spend_limit": 0}}
+ 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]}
diff --git a/tools/mcp_tool.py b/tools/mcp_tool.py
index 5cb72c1d979..bd29e0f88dd 100644
--- a/tools/mcp_tool.py
+++ b/tools/mcp_tool.py
@@ -526,6 +526,9 @@ _CIRCUIT_BREAKER_THRESHOLD, _CIRCUIT_BREAKER_COOLDOWN_SEC = 3, 60.0
# ``_tool_read_only_hints`` by the connection key (the server's own tool annotations).
_server_trust_levels: dict[Any, str] = {}
_tool_read_only_hints: dict[Any, dict[str, bool]] = {}
+# Declared per-tool costs + per-chat spend limit (``tools.mcp_tool_costs.CostPolicy``), keyed like
+# ``_server_trust_levels``: the consuming profile's policy. Absent = no costs, behaviour unchanged.
+_server_cost_policies: dict[Any, Any] = {}
_TRUST_FULL, _TRUST_UNTRUSTED = "full", "untrusted"
diff --git a/tools/mcp_tool_config.py b/tools/mcp_tool_config.py
index 4bcb2ba8d82..912d410bb80 100644
--- a/tools/mcp_tool_config.py
+++ b/tools/mcp_tool_config.py
@@ -629,24 +629,42 @@ def _warn_hidden_whitespace(server_name: str, config: dict) -> list[str]:
return flagged
+def _malformed_cost_table(name: str, cfg: Any) -> Optional[str]:
+ """Why a server's ``tool_costs``/``spend_limit``/``cost_unit`` is unusable, else None. A budget the
+ user declared must never be silently dropped while its server keeps spending, so the server is skipped."""
+ from tools.mcp_tool_costs import config_cost_policy
+ try:
+ config_cost_policy(name, cfg if isinstance(cfg, dict) else None)
+ except ValueError as exc:
+ return str(exc)
+ return None
+
+
def _filter_suspicious_mcp_servers(servers: dict[str, dict]) -> dict[str, dict]:
- """Drop exfiltration-shaped MCP configs before any stdio spawn path."""
+ """Drop exfiltration-shaped MCP configs, and servers with a malformed cost table, before any stdio spawn path."""
try:
from hermes_cli.mcp_security import validate_mcp_server_entry
except Exception:
- return servers
+ validate_mcp_server_entry = None
safe_servers = {}
for name, cfg in servers.items():
- issues = validate_mcp_server_entry(name, cfg) if isinstance(cfg, dict) else None
+ issues = validate_mcp_server_entry(name, cfg) if validate_mcp_server_entry and isinstance(cfg, dict) else None
if issues:
logger.warning("Skipping suspicious MCP server '%s': %s", name, "; ".join(issues))
+ elif (bad_costs := _malformed_cost_table(name, cfg)) is not None:
+ logger.error("Skipping MCP server '%s': %s (fix tool_costs/spend_limit/cost_unit in config.yaml)",
+ name, bad_costs)
else:
safe_servers[name] = cfg
return safe_servers
def _portable_mcp_servers(safe_servers: dict[str, dict]) -> None:
- """Merge plugin-provided (portable) MCP servers into *safe_servers*; native config wins on a clash. Never raises."""
+ """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
+ a package server's trust) keeps them unless it sets the cost key itself; ``spend_limit: 0`` turns the limit off."""
+ from tools.mcp_tool_costs import CONFIG_KEYS
try:
from hermes_cli.plugins import discover_plugins, get_plugin_manager
discover_plugins()
@@ -654,6 +672,10 @@ def _portable_mcp_servers(safe_servers: dict[str, dict]) -> None:
for name, cfg in _filter_suspicious_mcp_servers(portable).items():
if name in safe_servers:
logger.warning("Portable MCP server '%s' conflicts with native config; skipping", name)
+ native = safe_servers[name]
+ carried = {k: cfg[k] for k in CONFIG_KEYS if k in cfg and k not in native}
+ if carried:
+ safe_servers[name] = {**native, **carried}
else:
safe_servers[name] = dict(cfg)
except Exception:
diff --git a/tools/mcp_tool_costs.py b/tools/mcp_tool_costs.py
new file mode 100644
index 00000000000..b06fcac14a0
--- /dev/null
+++ b/tools/mcp_tool_costs.py
@@ -0,0 +1,177 @@
+"""Declared per-tool MCP costs and the per-chat spend tally behind the budget gate.
+
+A server may declare what its tools spend (``tool_costs`` in config.yaml, ``costs`` in a portable
+package) and a ``spend_limit`` per chat. The approval prompt then names the cost and the chat's
+running total, and a call that would take the chat past the limit needs an explicit yes even on a
+``trust: full`` server. Figures are the server's own declared estimates: Hermes counts the declared
+figure (the top of a range) for every call it dispatched, never a vendor's bill.
+
+Undeclared and zero-cost tools never reach any of this, so a server without a table behaves
+exactly as before.
+"""
+
+from __future__ import annotations
+
+import math
+import threading
+from collections import OrderedDict
+from dataclasses import dataclass
+from typing import Any, Mapping, Optional
+
+DEFAULT_UNIT = "credits"
+# Native ``mcp_servers.<name>`` keys; a portable package's ``costs`` maps to ``tool_costs``.
+CONFIG_KEYS = ("tool_costs", "spend_limit", "cost_unit")
+
+
+@dataclass(frozen=True)
+class ToolCost:
+ low: float
+ high: float
+ note: str = ""
+
+
+@dataclass(frozen=True)
+class CostPolicy:
+ costs: Mapping[str, ToolCost]
+ limit: float # 0 = no limit
+ unit: str
+
+
+def _number(value: Any, where: str) -> float:
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value < 0:
+ raise ValueError(f"{where} must be a non-negative number, not {value!r}")
+ return float(value)
+
+
+def _parse_cost(value: Any, where: str) -> ToolCost:
+ note = ""
+ if isinstance(value, dict):
+ if "credits" not in value or set(value) - {"credits", "note"}:
+ raise ValueError(f"{where} must be a number, [min, max], or {{\"credits\": ..., \"note\": \"...\"}}")
+ note = value.get("note", "")
+ if not isinstance(note, str):
+ raise ValueError(f"{where} note must be a string")
+ value = value["credits"]
+ if isinstance(value, (list, tuple)):
+ if len(value) != 2:
+ raise ValueError(f"{where} range must be [min, max]")
+ low, high = _number(value[0], where), _number(value[1], where)
+ if low > high:
+ raise ValueError(f"{where} range must be [min, max] with min <= max")
+ return ToolCost(low, high, note.strip())
+ amount = _number(value, where)
+ return ToolCost(amount, amount, note.strip())
+
+
+def parse_cost_policy(costs: Any = None, spend_limit: Any = None, cost_unit: Any = None, *,
+ where: str) -> Optional[CostPolicy]:
+ """Validate one server's declaration. None when it declares no tool cost (a limit alone has
+ nothing to count); raises ValueError naming the bad key otherwise, never a silent pass."""
+ if costs is not None and not isinstance(costs, dict):
+ raise ValueError(f"{where} costs must be an object mapping MCP tool names to costs")
+ table: dict[str, ToolCost] = {}
+ for tool, value in (costs or {}).items():
+ if not isinstance(tool, str) or not tool:
+ raise ValueError(f"{where} costs keys must be non-empty MCP tool names")
+ table[tool] = _parse_cost(value, f"{where} cost of '{tool}'")
+ limit = 0.0 if spend_limit is None else _number(spend_limit, f"{where} spend_limit")
+ unit = DEFAULT_UNIT if cost_unit is None else cost_unit
+ if not isinstance(unit, str) or not unit.strip() or len(unit) > 32:
+ raise ValueError(f"{where} cost_unit must be a short non-empty label, not {cost_unit!r}")
+ if not any(cost.high > 0 for cost in table.values()):
+ return None
+ return CostPolicy(table, limit, unit.strip())
+
+
+def config_cost_policy(server_name: str, config: Mapping[str, Any] | None) -> Optional[CostPolicy]:
+ """Policy of a native/translated ``mcp_servers`` entry (raises ValueError when malformed)."""
+ config = config or {}
+ return parse_cost_policy(config.get("tool_costs"), config.get("spend_limit"), config.get("cost_unit"),
+ where=f"MCP server '{server_name}'")
+
+
+def _fmt(amount: float) -> str:
+ return f"{int(amount):,}" if float(amount).is_integer() else f"{amount:,.2f}".rstrip("0").rstrip(".")
+
+
+# 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.
+_lock = threading.Lock()
+_spent: OrderedDict[tuple, float] = OrderedDict()
+_MAX_TALLIES = 16384 # bounds a long-lived gateway; the least recently charged chat falls off first
+
+
+@dataclass(frozen=True)
+class Charge:
+ """One costed call about to be admitted: what it costs and whose tally it lands on."""
+ key: tuple
+ server: str
+ tool: str
+ cost: ToolCost
+ policy: CostPolicy
+
+ def spent(self) -> float:
+ with _lock:
+ return _spent.get(self.key, 0.0)
+
+ def over_limit(self, spent: float) -> bool:
+ return self.policy.limit > 0 and spent + self.cost.high > self.policy.limit
+
+ def reserve_within_limit(self) -> tuple[bool, float]:
+ """Book the estimate when it keeps the chat within its limit; ``(booked, spent before)``.
+ Check and book share the lock, so parallel calls cannot both slip under the limit."""
+ with _lock:
+ spent = _spent.get(self.key, 0.0)
+ if self.over_limit(spent):
+ return False, spent
+ self._add_locked(self.cost.high)
+ return True, spent
+
+ def book(self) -> None:
+ with _lock:
+ self._add_locked(self.cost.high)
+
+ def refund(self) -> None:
+ with _lock:
+ self._add_locked(-self.cost.high)
+
+ 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)
+
+ def cost_sentence(self) -> str:
+ unit, cost = self.policy.unit, self.cost
+ text = (f"Costs about {_fmt(cost.high)} {unit}" if cost.low == cost.high
+ else f"Costs {_fmt(cost.low)}-{_fmt(cost.high)} {unit}")
+ return f"{text} ({cost.note})." if cost.note else f"{text}."
+
+ def spend_sentence(self, spent: float) -> str:
+ unit, limit = self.policy.unit, self.policy.limit
+ if spent > 0:
+ cap = f" (limit {_fmt(limit)})" if limit > 0 else ""
+ return f"This chat has used about {_fmt(spent)} {unit} on '{self.server}'{cap}."
+ return f"Spend limit for this chat on '{self.server}': {_fmt(limit)} {unit}." if limit > 0 else ""
+
+ def lines(self, spent: float) -> list[str]:
+ return [s for s in (self.cost_sentence(), self.spend_sentence(spent)) if s]
+
+ def refusal(self, spent: float) -> str:
+ unit = self.policy.unit
+ return (f"MCP tool '{self.tool}' on server '{self.server}' was NOT run: this chat has used about "
+ f"{_fmt(spent)} {unit} on '{self.server}' and its spend limit is {_fmt(self.policy.limit)} {unit}. "
+ f"This call (about {_fmt(self.cost.high)} {unit}) needed an explicit approval and did not get "
+ f"one. Do not retry; tell the user the spend limit was reached.")
+
+
+def pending_charge(policy_key: Any, server_name: str, tool_name: str, session_key: str) -> Optional[Charge]:
+ """The charge a call to *tool_name* would add, or None for an undeclared/zero-cost tool."""
+ from tools.mcp_tool_common import _core
+ policy = _core._server_cost_policies.get(policy_key)
+ if policy is None:
+ return None
+ cost = policy.costs.get(tool_name)
+ if cost is None or cost.high <= 0:
+ return None
+ return Charge((policy_key, session_key), server_name, tool_name, cost, policy)
diff --git a/tools/mcp_tool_handlers.py b/tools/mcp_tool_handlers.py
index 3723e119183..a1ec78c680c 100644
--- a/tools/mcp_tool_handlers.py
+++ b/tools/mcp_tool_handlers.py
@@ -57,30 +57,68 @@ def _tool_is_read_only(server_name: str, tool_name: str) -> bool:
return _core._tool_read_only_hints.get(_resolve_server_key(server_name), {}).get(tool_name) is True
-def _trust_gate_check(server_name: str, tool_name: str) -> Optional[str]:
- """Approval gate for write-capable tools on ``trust: untrusted`` servers. None to proceed,
- else a ``tool_error``. Fail-closed: approval-system errors block."""
+def _trust_gate_check(server_name: str, tool_name: str, booked: Optional[list] = None) -> Optional[str]:
+ """Approval gate for write-capable tools on ``trust: untrusted`` servers, plus the declared spend
+ limit on any server. None to proceed, else a ``tool_error``. Fail-closed: approval-system errors
+ block. An admitted costed call is charged to the chat's tally and appended to *booked* so the
+ caller can refund it when the call never reaches the server."""
from tools.mcp_tool_scope import _server_key
- # Trust is the calling profile's own policy (an adopter of a shared connection keeps its own tier).
- trust = _core._server_trust_levels.get(_server_key(server_name), _core._TRUST_FULL)
- if trust != _core._TRUST_UNTRUSTED or _tool_is_read_only(server_name, tool_name):
+ from tools import mcp_tool_costs as _costs
+ # Trust and costs are the calling profile's own policy (an adopter of a shared connection keeps its own).
+ key = _server_key(server_name)
+ trust = _core._server_trust_levels.get(key, _core._TRUST_FULL)
+ gated = trust == _core._TRUST_UNTRUSTED and not _tool_is_read_only(server_name, tool_name)
+ charge = None
+ 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:
return None
+ spent, over = 0.0, False
+ if charge is not None:
+ if not gated:
+ 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."
+ tail = "This tool is write-capable (no readOnlyHint=true annotation) and may modify external state."
+ message = " ".join([head, *extra, *(["This call goes past the chat's spend limit."] if over else []), tail])
+ description = (f"Server '{server_name}' is configured 'trust: untrusted'. "
+ f"Approve to run '{tool_name}' once, or deny to block it.")
+ title = f"MCP server '{server_name}' is asking"
+ else:
+ message = " ".join([f"MCP tool '{tool_name}' on server '{server_name}' would take this chat past its "
+ f"spend limit.", *extra])
+ description = (f"Server '{server_name}' declares a spend limit per chat. Approve to run '{tool_name}' "
+ f"once (every further paid call in this chat asks again), or deny to block it.")
+ title = f"MCP server '{server_name}' spend limit"
try: # lazy: tools.approval routes the prompt to whichever surface owns the session
from tools.approval_prompt import request_elicitation_consent
- answer = request_elicitation_consent(
- f"MCP tool '{tool_name}' on UNTRUSTED server '{server_name}' wants to run. This tool is write-capable "
- f"(no readOnlyHint=true annotation) and may modify external state.",
- f"Server '{server_name}' is configured 'trust: untrusted'. "
- f"Approve to run '{tool_name}' once, or deny to block it.",
- surface=f"mcp-trust/{server_name}", title=f"MCP server '{server_name}' is asking")
+ answer = request_elicitation_consent(message, description, surface=f"mcp-trust/{server_name}", title=title)
except Exception as exc:
logger.error("MCP trust gate: approval check failed for %s.%s: %s", server_name, tool_name, exc, exc_info=True)
+ if over and charge is not None:
+ return tool_error(charge.refusal(spent))
return tool_error(f"MCP tool '{tool_name}' on untrusted server '{server_name}' was blocked: the approval "
f"system was unavailable (fail-closed).")
if answer == "accept":
+ if charge is not None:
+ charge.book()
+ if booked is not None:
+ booked.append(charge)
return None
- logger.info("MCP trust gate: user %s '%s' on untrusted server '%s'",
- "cancelled" if answer == "cancel" else "denied", tool_name, server_name)
+ logger.info("MCP trust gate: user %s '%s' on %s server '%s'", "cancelled" if answer == "cancel" else "denied",
+ tool_name, "untrusted" if gated else "spend-limited", server_name)
+ if over and charge is not None:
+ return tool_error(charge.refusal(spent))
return tool_error(f"The user did not approve running write-capable MCP tool '{tool_name}' on untrusted server "
f"'{server_name}'. The command was NOT run. Do not retry without explicit user direction.")
@@ -575,11 +613,16 @@ def _make_tool_handler(server_name: str, tool_name: str, tool_timeout: float, *,
def _handler(args: dict, **kwargs) -> Any:
# Security boundary: untrusted-server write tools need approval before ANY transport work (incl. lazy spawn).
- error = _trust_gate_check(server_name, tool_name) or _check_circuit_breaker(server_name)
+ booked: list = [] # a costed call's charge; refunded when the call never reaches the server
+ error = _trust_gate_check(server_name, tool_name, booked)
if error is not None:
return error
- server, error = _acquire_call_server(server_name, tool_timeout)
+ server, error = None, _check_circuit_breaker(server_name)
+ if error is None:
+ server, error = _acquire_call_server(server_name, tool_timeout)
if server is None:
+ for charge in booked:
+ charge.refund()
return error
# Only a tool annotated readOnlyHint=True is replayed after session expiry; a 401 is always
# pre-dispatch so the auth recoverer keeps its retry for every tool.
diff --git a/tools/mcp_tool_registration.py b/tools/mcp_tool_registration.py
index 9591c446b8c..f7b6ec9a608 100644
--- a/tools/mcp_tool_registration.py
+++ b/tools/mcp_tool_registration.py
@@ -58,6 +58,18 @@ def _annotation_read_only_hint(mcp_tool: Any) -> bool:
return hint is True
+def _record_cost_policy(server_name: str, config: dict, key) -> None:
+ """Declared ``tool_costs``/``spend_limit`` for *key*. Load-time validation already dropped malformed
+ entries (``_filter_suspicious_mcp_servers``); a direct caller's bad table still fails loudly. Caller holds
+ ``_core._lock``."""
+ from tools.mcp_tool_costs import config_cost_policy
+ policy = config_cost_policy(server_name, config)
+ if policy is None:
+ _core._server_cost_policies.pop(key, None)
+ else:
+ _core._server_cost_policies[key] = policy
+
+
def _record_tool_trust_metadata(server_name: str, config: dict, tools: list[Any], key=None) -> None:
"""Capture per-server trust and per-tool readOnlyHint at discovery — the security boundary: the call-time gate
classifies from data we control, never re-read server-supplied state. *key* is the connection (default: the
@@ -67,16 +79,19 @@ def _record_tool_trust_metadata(server_name: str, config: dict, tools: list[Any]
if key is None:
key = _server_key(server_name)
_core._server_trust_levels[key] = _normalize_server_trust((config or {}).get("trust"))
+ _record_cost_policy(server_name, config, key)
hints = _core._tool_read_only_hints.setdefault(key, {})
hints.update({t.name: _annotation_read_only_hint(t) for t in tools if getattr(t, "name", None)})
def _record_scope_trust(server_name: str, config: dict, scope: str) -> None:
- """``trust`` is the CONSUMING profile's policy, never the connection's: an ``untrusted`` profile that
- adopts a ``full`` profile's live connection must still be asked before every write-capable call."""
+ """``trust`` (and the cost policy) is the CONSUMING profile's policy, never the connection's: an
+ ``untrusted`` profile that adopts a ``full`` profile's live connection must still be asked before every
+ write-capable call."""
with _core._lock:
- _core._server_trust_levels[_server_key(server_name, scope, current=False)] = _normalize_server_trust(
- (config or {}).get("trust"))
+ key = _server_key(server_name, scope, current=False)
+ _core._server_trust_levels[key] = _normalize_server_trust((config or {}).get("trust"))
+ _record_cost_policy(server_name, config, key)
def _track_mcp_tool_server(tool_name: str, server_name: str) -> None:
@@ -150,6 +165,7 @@ def _remove_server_scope(key, scope: str) -> None:
else:
_core._server_tool_scopes.pop(key, None)
_core._server_trust_levels.pop(_server_key(server_name, scope, current=False), None)
+ _core._server_cost_policies.pop(_server_key(server_name, scope, current=False), None)
_restore_server_toolset_alias(key)
diff --git a/tools/mcp_tool_scope.py b/tools/mcp_tool_scope.py
index ede54b2d076..81d7be4db18 100644
--- a/tools/mcp_tool_scope.py
+++ b/tools/mcp_tool_scope.py
@@ -69,7 +69,7 @@ _KEYED_LEDGERS = (
"_lazy_server_configs", "_lazy_server_fingerprints", "_lazy_server_tool_names",
"_server_connect_retry_after", "_server_connect_failures", "_server_error_counts",
"_server_breaker_opened_at", "_server_errors_all_application", "_server_trust_levels",
- "_tool_read_only_hints")
+ "_tool_read_only_hints", "_server_cost_policies")
_KEYED_SETS = ("_server_connecting", "_parallel_safe_servers")