Skip to content

The agent that grows with you

fix(mcp): make sampling.tools capability opt-in via expose_client_tools

nikkoxgonzalesffe73c37f0a0
diff --git a/cli-config.yaml.example b/cli-config.yaml.example
index f2f487e448c..8d02c25bd41 100644
--- a/cli-config.yaml.example
+++ b/cli-config.yaml.example
@@ -1607,6 +1607,7 @@ platform_toolsets:
# max_rpm: 10 # max requests per minute
# allowed_models: [] # model whitelist (empty = all)
# max_tool_rounds: 5 # tool loop limit (0 = disable)
+# expose_client_tools: false # advertise extended sampling.tools capability
# log_level: "info" # audit verbosity
# =============================================================================
diff --git a/skills/autonomous-ai-agents/hermes-agent/references/native-mcp.md b/skills/autonomous-ai-agents/hermes-agent/references/native-mcp.md
index 13ccd204c10..0fed2652193 100644
--- a/skills/autonomous-ai-agents/hermes-agent/references/native-mcp.md
+++ b/skills/autonomous-ai-agents/hermes-agent/references/native-mcp.md
@@ -326,10 +326,11 @@ mcp_servers:
max_rpm: 10 # max requests per minute
allowed_models: [] # model whitelist (empty = all)
max_tool_rounds: 5 # tool loop limit (0 = disable)
+ expose_client_tools: false # advertise extended sampling.tools capability
log_level: "info" # audit verbosity
```
-Servers can also include `tools` in sampling requests for multi-turn tool-augmented workflows. The `max_tool_rounds` config prevents infinite tool loops. Per-server audit metrics (requests, errors, tokens, tool use count) are tracked via `get_mcp_status()`.
+Servers can also include `tools` in sampling requests for multi-turn tool-augmented workflows. The `max_tool_rounds` config prevents infinite tool loops. Hermes does not advertise the extended `sampling.tools` client capability unless `expose_client_tools: true` is set, because some strict MCP servers reject unknown sampling sub-capabilities during initialization. Most servers only need normal sampling; enable `expose_client_tools` only for servers that explicitly support sampling tool callbacks. Per-server audit metrics (requests, errors, tokens, tool use count) are tracked via `get_mcp_status()`.
Disable sampling for untrusted servers with `sampling: { enabled: false }`.
diff --git a/tests/tools/test_mcp_tool.py b/tests/tools/test_mcp_tool.py
index 96e1c6c7305..3fc063b5794 100644
--- a/tests/tools/test_mcp_tool.py
+++ b/tests/tools/test_mcp_tool.py
@@ -1997,12 +1997,14 @@ class _CompatType:
try:
from mcp.types import (
+ ClientCapabilities,
CreateMessageResult,
ErrorData,
SamplingCapability,
TextContent,
)
except ImportError:
+ ClientCapabilities = _CompatType
CreateMessageResult = _CompatType
ErrorData = _CompatType
SamplingCapability = _CompatType
@@ -2495,6 +2497,58 @@ class TestMetricsTracking:
# ---------------------------------------------------------------------------
+ @staticmethod
+ def _capability_payload(capability):
+ if hasattr(capability, "model_dump"):
+ return capability.model_dump(exclude_none=True)
+ return {k: v for k, v in vars(capability).items() if v is not None}
+
+ @classmethod
+ def _client_capability_payload(cls, sampling_capability):
+ capabilities = ClientCapabilities(sampling=sampling_capability)
+ return cls._capability_payload(capabilities)
+
+ def test_default_omits_tools_capability(self):
+ """Strict servers reject unknown sampling.tools, so it stays off by default (#5468)."""
+ handler = SamplingHandler("sk", {})
+ assert handler.expose_client_tools is False
+ cap = handler.session_kwargs()["sampling_capabilities"]
+ assert isinstance(cap, SamplingCapability)
+ assert cap.tools is None
+ assert "tools" not in self._capability_payload(cap)
+ assert self._client_capability_payload(cap) == {"sampling": {}}
+
+ def test_sampling_tools_capability_is_opt_in(self):
+ handler = SamplingHandler("sk3", {"expose_client_tools": True})
+ cap = handler.session_kwargs()["sampling_capabilities"]
+ assert isinstance(cap.tools, SamplingToolsCapability)
+ assert "tools" in self._capability_payload(cap)
+ assert self._client_capability_payload(cap) == {"sampling": {"tools": {}}}
+
+ @pytest.mark.parametrize(
+ "raw_value, expected",
+ [
+ (False, False),
+ ("false", False),
+ ("0", False),
+ ("off", False),
+ (True, True),
+ ("true", True),
+ ("1", True),
+ ("yes", True),
+ ],
+ )
+ def test_sampling_tools_capability_parses_bool_flags(self, raw_value, expected):
+ handler = SamplingHandler("sk4", {"expose_client_tools": raw_value})
+ cap = handler.session_kwargs()["sampling_capabilities"]
+ payload = self._capability_payload(cap)
+ if expected:
+ assert isinstance(cap.tools, SamplingToolsCapability)
+ assert "tools" in payload
+ else:
+ assert cap.tools is None
+ assert "tools" not in payload
+
# ---------------------------------------------------------------------------
# 14. MCPServerTask integration
# ---------------------------------------------------------------------------
diff --git a/tools/mcp_tool_sampling.py b/tools/mcp_tool_sampling.py
index b343dd44e8e..02f5ccdce78 100644
--- a/tools/mcp_tool_sampling.py
+++ b/tools/mcp_tool_sampling.py
@@ -8,6 +8,7 @@ import logging
import time
from contextvars import Context
from typing import TYPE_CHECKING, Callable, List, Optional
+from utils import is_truthy_value
from tools.mcp_tool_common import _MISSING, _exc_str, _safe_numeric, _sanitize_error, mcp_field, _core
from tools.mcp_tool_schema import _normalize_mcp_input_schema
@@ -101,6 +102,9 @@ class SamplingHandler:
self.timeout = _safe_numeric(config.get("timeout", 30), 30, float)
self.max_tokens_cap = _safe_numeric(config.get("max_tokens_cap", 4096), 4096, int)
self.max_tool_rounds = _safe_numeric(config.get("max_tool_rounds", 5), 5, int, minimum=0)
+ # Strict MCP servers reject the unknown sampling.tools sub-capability during
+ # initialization, so it is opt-in per server (default: plain sampling). (#5468)
+ self.expose_client_tools = is_truthy_value(config.get("expose_client_tools"), default=False)
self.model_override = config.get("model")
self.allowed_models = config.get("allowed_models", [])
self.audit_level = self._LOG_LEVELS.get(str(config.get("log_level", "info")).lower(), logging.INFO)
@@ -171,8 +175,13 @@ class SamplingHandler:
def session_kwargs(self) -> dict:
"""Kwargs to pass to ClientSession for sampling support."""
+ sampling_capabilities = (
+ _core.SamplingCapability(tools=_core.SamplingToolsCapability())
+ if self.expose_client_tools
+ else _core.SamplingCapability()
+ )
return {"sampling_callback": self,
- "sampling_capabilities": _core.SamplingCapability(tools=_core.SamplingToolsCapability())}
+ "sampling_capabilities": sampling_capabilities}
def _admit(self, params):
"""Rate-limit + allowed_models gate. Returns ``(resolved_model, None)`` or ``(None, ErrorData)``."""