feat(mcp): warn on hidden whitespace in MCP config values
Inspired by Claude Code v2.1.219: MCP config string values with hidden
leading/trailing whitespace (pasted tokens with trailing newlines, URLs
with leading spaces) now trigger a startup warning naming the server and
the dotted key path, instead of failing later as an opaque auth/connect
error.
Advisory only: values are never mutated, secrets are never logged (only
key paths), and warnings dedupe to once per process per (server, path).
Checked after ${VAR} interpolation so whitespace inside referenced env
vars is caught too.
This commit is contained in:
@@ -0,0 +1,125 @@
|
||||
"""Tests for MCP config hidden-whitespace warnings.
|
||||
|
||||
Inspired by Claude Code v2.1.219: warn when MCP config values carry hidden
|
||||
leading/trailing whitespace (pasted tokens with trailing newlines, URLs with
|
||||
leading spaces), which otherwise surfaces as opaque auth/connect failures.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
import pytest
|
||||
|
||||
from tools import mcp_tool
|
||||
from tools.mcp_tool import _warn_hidden_whitespace
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_dedupe():
|
||||
mcp_tool._whitespace_warned.clear()
|
||||
yield
|
||||
mcp_tool._whitespace_warned.clear()
|
||||
|
||||
|
||||
def test_clean_config_no_warnings(caplog):
|
||||
config = {
|
||||
"url": "https://example.com/mcp",
|
||||
"headers": {"Authorization": "Bearer abc123"},
|
||||
"args": ["--flag", "value"],
|
||||
}
|
||||
with caplog.at_level(logging.WARNING, logger="tools.mcp_tool"):
|
||||
flagged = _warn_hidden_whitespace("clean", config)
|
||||
assert flagged == []
|
||||
assert not [r for r in caplog.records if "hidden" in r.getMessage()]
|
||||
|
||||
|
||||
def test_trailing_newline_in_header_flagged(caplog):
|
||||
config = {"url": "https://example.com/mcp",
|
||||
"headers": {"Authorization": "Bearer abc123\n"}}
|
||||
with caplog.at_level(logging.WARNING, logger="tools.mcp_tool"):
|
||||
flagged = _warn_hidden_whitespace("srv", config)
|
||||
assert flagged == ["headers.Authorization"]
|
||||
messages = [r.getMessage() for r in caplog.records]
|
||||
assert any("srv" in m and "headers.Authorization" in m for m in messages)
|
||||
# The secret value itself must never appear in the log.
|
||||
assert not any("abc123" in m for m in messages)
|
||||
|
||||
|
||||
def test_leading_space_in_url_flagged():
|
||||
flagged = _warn_hidden_whitespace("srv", {"url": " https://example.com"})
|
||||
assert flagged == ["url"]
|
||||
|
||||
|
||||
def test_whitespace_in_list_item_flagged_with_index():
|
||||
flagged = _warn_hidden_whitespace(
|
||||
"srv", {"command": "npx", "args": ["-y", "some-pkg "]}
|
||||
)
|
||||
assert flagged == ["args[1]"]
|
||||
|
||||
|
||||
def test_nested_env_dict_flagged():
|
||||
flagged = _warn_hidden_whitespace(
|
||||
"srv", {"command": "npx", "env": {"API_KEY": "secret\t"}}
|
||||
)
|
||||
assert flagged == ["env.API_KEY"]
|
||||
|
||||
|
||||
def test_multiple_flags_all_reported():
|
||||
flagged = _warn_hidden_whitespace(
|
||||
"srv", {"url": "https://x.com ", "headers": {"X-Key": " k"}}
|
||||
)
|
||||
assert set(flagged) == {"url", "headers.X-Key"}
|
||||
|
||||
|
||||
def test_non_string_values_ignored():
|
||||
flagged = _warn_hidden_whitespace(
|
||||
"srv", {"timeout": 30, "enabled": True, "retries": None}
|
||||
)
|
||||
assert flagged == []
|
||||
|
||||
|
||||
def test_values_never_mutated():
|
||||
config = {"headers": {"Authorization": "Bearer tok\n"}}
|
||||
_warn_hidden_whitespace("srv", config)
|
||||
assert config["headers"]["Authorization"] == "Bearer tok\n"
|
||||
|
||||
|
||||
def test_warning_deduped_per_process(caplog):
|
||||
config = {"url": "https://x.com "}
|
||||
with caplog.at_level(logging.WARNING, logger="tools.mcp_tool"):
|
||||
first = _warn_hidden_whitespace("srv", config)
|
||||
second = _warn_hidden_whitespace("srv", config)
|
||||
# Both calls still report the flagged path (return value is for callers)...
|
||||
assert first == second == ["url"]
|
||||
# ...but only one warning record is emitted.
|
||||
warn_records = [r for r in caplog.records if "hidden" in r.getMessage()]
|
||||
assert len(warn_records) == 1
|
||||
|
||||
|
||||
def test_distinct_servers_warned_separately(caplog):
|
||||
with caplog.at_level(logging.WARNING, logger="tools.mcp_tool"):
|
||||
_warn_hidden_whitespace("a", {"url": "https://x.com "})
|
||||
_warn_hidden_whitespace("b", {"url": "https://x.com "})
|
||||
warn_records = [r for r in caplog.records if "hidden" in r.getMessage()]
|
||||
assert len(warn_records) == 2
|
||||
|
||||
|
||||
def test_load_mcp_config_emits_warning(tmp_path, monkeypatch, caplog):
|
||||
"""E2E through _load_mcp_config with a real config load path."""
|
||||
from unittest.mock import patch as mock_patch
|
||||
|
||||
servers = {
|
||||
"pasted": {
|
||||
"url": "https://example.com/mcp",
|
||||
"headers": {"Authorization": "Bearer tok\n"},
|
||||
}
|
||||
}
|
||||
with mock_patch("hermes_cli.config.load_config",
|
||||
return_value={"mcp_servers": servers}), \
|
||||
caplog.at_level(logging.WARNING, logger="tools.mcp_tool"):
|
||||
result = mcp_tool._load_mcp_config()
|
||||
|
||||
assert "pasted" in result
|
||||
# Value passes through unmutated.
|
||||
assert result["pasted"]["headers"]["Authorization"] == "Bearer tok\n"
|
||||
messages = [r.getMessage() for r in caplog.records]
|
||||
assert any("headers.Authorization" in m for m in messages)
|
||||
+53
-1
@@ -108,7 +108,7 @@ import time
|
||||
from types import SimpleNamespace
|
||||
from typing import Callable
|
||||
from datetime import datetime
|
||||
from typing import Any, Coroutine, Dict, List, Optional
|
||||
from typing import Any, Coroutine, Dict, List, Optional, Set, Tuple
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from tools.registry import tool_error
|
||||
@@ -4553,6 +4553,57 @@ def _interpolate_env_vars(value):
|
||||
return value
|
||||
|
||||
|
||||
# (server_name, dotted key path) pairs already warned about — see
|
||||
# _warn_hidden_whitespace(); config loads happen on every discovery pass.
|
||||
_whitespace_warned: Set[Tuple[str, str]] = set()
|
||||
|
||||
|
||||
def _warn_hidden_whitespace(server_name: str, config: dict) -> List[str]:
|
||||
"""Warn about MCP config string values with hidden leading/trailing whitespace.
|
||||
|
||||
A token pasted with a trailing newline or a URL copied with a leading
|
||||
space produces opaque auth/connect failures (the server rejects the
|
||||
credential, TLS/DNS fails on ``"example.com "``), and the whitespace is
|
||||
invisible when eyeballing config.yaml. Inspired by Claude Code v2.1.219,
|
||||
which added the same startup warning for its MCP config values.
|
||||
|
||||
Advisory only — values are never mutated (whitespace could theoretically
|
||||
be intentional in an arg). Returns the list of dotted key paths flagged,
|
||||
for testability. Values themselves are never logged (they are often
|
||||
secrets); only the key path is named. Each (server, key path) is warned
|
||||
about once per process — ``_load_mcp_config()`` runs on every discovery/
|
||||
status call and repeating the warning would be noise.
|
||||
"""
|
||||
flagged: List[str] = []
|
||||
|
||||
def _walk(value: Any, path: str) -> None:
|
||||
if isinstance(value, str):
|
||||
if value != value.strip():
|
||||
flagged.append(path)
|
||||
elif isinstance(value, dict):
|
||||
for k, v in value.items():
|
||||
_walk(v, f"{path}.{k}" if path else str(k))
|
||||
elif isinstance(value, list):
|
||||
for i, v in enumerate(value):
|
||||
_walk(v, f"{path}[{i}]")
|
||||
|
||||
_walk(config, "")
|
||||
for key_path in flagged:
|
||||
dedupe_key = (server_name, key_path)
|
||||
if dedupe_key in _whitespace_warned:
|
||||
continue
|
||||
_whitespace_warned.add(dedupe_key)
|
||||
logger.warning(
|
||||
"MCP server '%s': config value '%s' has hidden leading or "
|
||||
"trailing whitespace — this often causes authentication or "
|
||||
"connection failures. Check for stray spaces/newlines in "
|
||||
"config.yaml (or the referenced env var).",
|
||||
server_name,
|
||||
key_path,
|
||||
)
|
||||
return flagged
|
||||
|
||||
|
||||
def _filter_suspicious_mcp_servers(servers: Dict[str, dict]) -> Dict[str, dict]:
|
||||
"""Drop exfiltration-shaped MCP configs before any stdio spawn path."""
|
||||
try:
|
||||
@@ -4611,6 +4662,7 @@ def _load_mcp_config() -> Dict[str, dict]:
|
||||
for name, cfg in _filter_suspicious_mcp_servers(servers).items():
|
||||
interpolated = _interpolate_env_vars(cfg)
|
||||
if isinstance(interpolated, dict):
|
||||
_warn_hidden_whitespace(name, interpolated)
|
||||
safe_servers[name] = interpolated
|
||||
return safe_servers
|
||||
except Exception as exc:
|
||||
|
||||
Reference in New Issue
Block a user