Files
hermes-agent/tests/tools/test_mcp_client_cert.py
elphamale 11a9dcf567 feat(mcp): migrate to the mcp 2.x SDK
mcp 2.0.0 implements MCP revision 2026-07-28 and makes three breaking
changes Hermes sits on top of: `mcp.server.fastmcp` is gone, every model
field is renamed to snake_case (camelCase survives only as a
serialization alias, which pydantic does not expose to attribute
access), and the SDK's own HTTP stack moved from `httpx` to `httpx2`.

Bump the pin across the dev/mcp/computer-use extras and port the tree:

- `mcp_serve.py` and `agent/transports/hermes_tools_mcp_server.py` move
  from `FastMCP` to `mcp.server.MCPServer`, which has the same
  decorator/add_tool surface. The hermes-tools server already
  synthesised `__signature__` from Hermes' JSON Schema, which is exactly
  what 2.0's `add_tool` reads.
- SDK model reads go through `mcp_field(obj, snake, camel)`, which reads
  both spellings. A single-spelling read fails *silently* on the other
  generation — empty tool schemas, dropped structured content, tool
  results vanishing from sampling conversations — and `mcp` is an
  optional extra users install at their own version.
- `sdk_httpx()` resolves the httpx flavour from the SDK's own transport
  module, so objects handed to `streamable_http_client`, the `sse_client`
  factory, and the OAuth metadata helpers come from the module the
  installed SDK actually imports.
- HTTP support is gated on either streamable-HTTP entry point, not just
  the deprecated alias 2.0 removed.
- OAuth: `OAuthClientProvider` lost its `timeout` argument (the
  configured `oauth.timeout` now bounds the callback waiter's own poll
  loop, where the browser round-trip was always awaited), and
  `callback_handler` must return `AuthorizationCodeResult` rather than a
  tuple. 2.0 also validates the RFC 9207 `iss` parameter, so the
  callback handler and paste fallback capture it.

`mcp`/`mcp-types` 2.0.0 are inside the 14-day `exclude-newer` window, so
two narrow `exclude-newer-package` entries unblock `uv lock`, annotated
for removal on or after 2026-08-11. `httpx2` needs no exemption: 2.7.0 is
already outside the window and satisfies mcp's floor.

Refs #69931

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-16 23:26:10 -07:00

340 lines
12 KiB
Python

"""Tests for mTLS client certificate config on MCP HTTP/SSE transports.
Covers:
1. ``_resolve_client_cert`` helper — string, tuple, encrypted-key, validation
errors, missing-file errors.
2. HTTP (new SDK ``streamable_http_client``) path forwards ``cert=`` into the
user-owned ``httpx.AsyncClient``.
3. SSE path forwards ``cert`` and ``ssl_verify`` via an ``httpx_client_factory``
without breaking the OAuth/headers/timeout passthrough.
"""
from __future__ import annotations
import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
def _patch_sdk_async_client(dummy):
"""Patch ``AsyncClient`` on whichever httpx module the MCP SDK uses.
mcp 2.0 moved the SDK's HTTP stack to ``httpx2``, so patching
``httpx.AsyncClient`` no longer intercepts the client Hermes builds for
the SDK. Resolve the module the same way production does, via
``tools.mcp_tool.sdk_httpx``, so these tests follow the SDK rather than
hardcoding a distribution name.
"""
from tools.mcp_tool import sdk_httpx
return patch.object(sdk_httpx(), "AsyncClient", dummy)
# ---------------------------------------------------------------------------
# _resolve_client_cert helper
# ---------------------------------------------------------------------------
class TestResolveClientCert:
def test_returns_none_when_unset(self):
from tools.mcp_tool import _resolve_client_cert
assert _resolve_client_cert("srv", {}) is None
assert _resolve_client_cert("srv", {"url": "https://x"}) is None
def test_string_form_single_pem(self, tmp_path):
from tools.mcp_tool import _resolve_client_cert
pem = tmp_path / "combined.pem"
pem.write_text("dummy")
result = _resolve_client_cert("srv", {"client_cert": str(pem)})
assert result == str(pem)
def test_list_form_two_elements(self, tmp_path):
from tools.mcp_tool import _resolve_client_cert
cert = tmp_path / "client.crt"
key = tmp_path / "client.key"
cert.write_text("cert")
key.write_text("key")
result = _resolve_client_cert("srv", {
"client_cert": [str(cert), str(key)],
})
assert result == (str(cert), str(key))
def test_password_must_be_string(self, tmp_path):
from tools.mcp_tool import _resolve_client_cert
cert = tmp_path / "client.crt"
key = tmp_path / "client.key"
cert.write_text("cert")
key.write_text("key")
with pytest.raises(ValueError, match=r"key passphrase.*must be a string"):
_resolve_client_cert("srv", {
"client_cert": [str(cert), str(key), 42],
})
# ---------------------------------------------------------------------------
# HTTP transport — cert forwarded into httpx.AsyncClient
# ---------------------------------------------------------------------------
class TestHTTPClientCert:
def test_cert_forwarded_to_async_client(self, tmp_path):
"""When client_cert is set, the new-SDK HTTP path passes ``cert=``
into ``httpx.AsyncClient``."""
from tools.mcp_tool import MCPServerTask
cert = tmp_path / "client.pem"
cert.write_text("dummy")
server = MCPServerTask("remote")
captured: dict = {}
class DummyAsyncClient:
def __init__(self, **kwargs):
captured.update(kwargs)
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
class DummyTransportCtx:
async def __aenter__(self):
return MagicMock(), MagicMock(), (lambda: None)
async def __aexit__(self, *a):
return False
class DummySession:
def __init__(self, *args, **kwargs):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
async def initialize(self):
return None
async def _discover_tools(self):
self._shutdown_event.set()
async def _drive():
with patch("tools.mcp_tool._MCP_HTTP_AVAILABLE", True), \
patch("tools.mcp_tool._MCP_NEW_HTTP", True), \
_patch_sdk_async_client(DummyAsyncClient), \
patch("tools.mcp_tool.streamable_http_client",
return_value=DummyTransportCtx()), \
patch("tools.mcp_tool.ClientSession", DummySession), \
patch.object(MCPServerTask, "_discover_tools", _discover_tools):
await server._run_http({
"url": "https://example.com/mcp",
"client_cert": str(cert),
})
asyncio.run(_drive())
assert captured.get("cert") == str(cert)
def test_missing_cert_file_surfaces_clear_error(self, tmp_path):
"""A missing cert file fails fast with a server-scoped error message."""
from tools.mcp_tool import MCPServerTask
server = MCPServerTask("remote")
async def _drive():
with patch("tools.mcp_tool._MCP_HTTP_AVAILABLE", True), \
patch("tools.mcp_tool._MCP_NEW_HTTP", True):
await server._run_http({
"url": "https://example.com/mcp",
"client_cert": str(tmp_path / "nope.pem"),
})
with pytest.raises(FileNotFoundError, match=r"remote.*client_cert.*not found"):
asyncio.run(_drive())
# ---------------------------------------------------------------------------
# SSE transport — cert + verify routed via httpx_client_factory
# ---------------------------------------------------------------------------
@pytest.fixture
def patch_sse_client():
"""Replace ``sse_client`` with a MagicMock that records its kwargs.
Returns the captured kwargs dict so tests can assert how ``_run_http``
called it.
"""
captured_kwargs: dict = {}
class _FakeStream:
def __init__(self):
self._read = AsyncMock()
self._write = AsyncMock()
async def __aenter__(self):
return (self._read, self._write)
async def __aexit__(self, *a):
return False
def fake_sse_client(**kwargs):
captured_kwargs.clear()
captured_kwargs.update(kwargs)
return _FakeStream()
class _FakeSession:
def __init__(self, *args, **kwargs):
pass
async def __aenter__(self):
mock_session = MagicMock()
mock_session.initialize = AsyncMock()
return mock_session
async def __aexit__(self, *a):
return False
with patch("tools.mcp_tool.sse_client", new=fake_sse_client), \
patch("tools.mcp_tool.ClientSession", new=_FakeSession):
yield captured_kwargs
class TestSSEClientCert:
def test_no_factory_when_defaults(self, patch_sse_client):
"""With no cert and ssl_verify=True (default), the SDK's own factory is
used — we don't inject one."""
from tools.mcp_tool import MCPServerTask
server = MCPServerTask("sse-test")
server._auth_type = ""
server._sampling = None
async def drive():
with patch.object(MCPServerTask, "_wait_for_lifecycle_event",
new=AsyncMock(return_value="shutdown")), \
patch.object(MCPServerTask, "_discover_tools", new=AsyncMock()):
try:
await asyncio.wait_for(
server._run_http({
"url": "https://example.com/mcp/sse",
"transport": "sse",
}),
timeout=2.0,
)
except (asyncio.TimeoutError, StopAsyncIteration, Exception):
pass
asyncio.run(drive())
assert "httpx_client_factory" not in patch_sse_client
def test_factory_injected_when_cert_set(self, patch_sse_client, tmp_path):
"""With client_cert set, an httpx_client_factory is injected that
applies the cert (and follow_redirects=True to match the SDK)."""
from tools.mcp_tool import MCPServerTask
cert = tmp_path / "client.pem"
cert.write_text("dummy")
server = MCPServerTask("sse-test")
server._auth_type = ""
server._sampling = None
async def drive():
with patch.object(MCPServerTask, "_wait_for_lifecycle_event",
new=AsyncMock(return_value="shutdown")), \
patch.object(MCPServerTask, "_discover_tools", new=AsyncMock()):
try:
await asyncio.wait_for(
server._run_http({
"url": "https://example.com/mcp/sse",
"transport": "sse",
"client_cert": str(cert),
}),
timeout=2.0,
)
except (asyncio.TimeoutError, StopAsyncIteration, Exception):
pass
asyncio.run(drive())
factory = patch_sse_client.get("httpx_client_factory")
assert factory is not None, "expected httpx_client_factory to be injected"
# Invoke the factory the way the SDK would; capture the resulting
# httpx.AsyncClient kwargs.
captured_client_kwargs: dict = {}
class DummyAsyncClient:
def __init__(self, **kwargs):
captured_client_kwargs.update(kwargs)
from tools.mcp_tool import sdk_httpx
with _patch_sdk_async_client(DummyAsyncClient):
factory(headers={"x": "y"}, timeout=sdk_httpx().Timeout(30.0), auth=None)
assert captured_client_kwargs["cert"] == str(cert)
assert captured_client_kwargs["verify"] is True
assert captured_client_kwargs["follow_redirects"] is True
assert captured_client_kwargs["headers"] == {"x": "y"}
def test_factory_forwards_custom_ca_bundle(self, patch_sse_client, tmp_path):
"""ssl_verify as a path is forwarded to the factory's httpx client."""
from tools.mcp_tool import MCPServerTask
ca_bundle = tmp_path / "ca.pem"
ca_bundle.write_text("dummy")
server = MCPServerTask("sse-test")
server._auth_type = ""
server._sampling = None
async def drive():
with patch.object(MCPServerTask, "_wait_for_lifecycle_event",
new=AsyncMock(return_value="shutdown")), \
patch.object(MCPServerTask, "_discover_tools", new=AsyncMock()):
try:
await asyncio.wait_for(
server._run_http({
"url": "https://example.com/mcp/sse",
"transport": "sse",
"ssl_verify": str(ca_bundle),
}),
timeout=2.0,
)
except (asyncio.TimeoutError, StopAsyncIteration, Exception):
pass
asyncio.run(drive())
factory = patch_sse_client.get("httpx_client_factory")
assert factory is not None
captured_client_kwargs: dict = {}
class DummyAsyncClient:
def __init__(self, **kwargs):
captured_client_kwargs.update(kwargs)
with _patch_sdk_async_client(DummyAsyncClient):
factory(headers=None, timeout=None, auth=None)
assert captured_client_kwargs["verify"] == str(ca_bundle)
assert "cert" not in captured_client_kwargs