Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
258 changes: 258 additions & 0 deletions tests/tools/test_mcp_oauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,50 @@ def test_no_ssh_hint_when_port_not_set(self, monkeypatch, capsys):
err = capsys.readouterr().err
assert "ssh -N -L" not in err

def test_configured_redirect_uri_shows_proxy_hint_not_tunnel(self, monkeypatch, capsys):
"""With a proxy redirect_uri, the SSH hint must not push the loopback tunnel.

The Funnel/proxy callback reaches this machine on its own, so the
``ssh -N -L`` guidance would be actively misleading.
"""
import tools.mcp_oauth as mco
monkeypatch.setattr(mco, "_oauth_port", 49203)
monkeypatch.setenv("SSH_CLIENT", "1.2.3.4 1234 22")
monkeypatch.setattr(mco, "_can_open_browser", lambda: False)

self._run(
_redirect_handler(
"https://example.com/auth",
redirect_uri="https://oauth.example.ts.net/callback",
)
)

err = capsys.readouterr().err
assert "https://oauth.example.ts.net/callback" in err
assert "no SSH tunnel needed" in err
assert "ssh -N -L" not in err
assert "127.0.0.1" not in err

def test_configured_redirect_uri_no_hint_when_local(self, monkeypatch, capsys):
"""Off SSH, a configured redirect_uri prints no remote-session hint."""
import tools.mcp_oauth as mco
monkeypatch.setattr(mco, "_oauth_port", 49204)
monkeypatch.delenv("SSH_CLIENT", raising=False)
monkeypatch.delenv("SSH_TTY", raising=False)
monkeypatch.setattr(mco, "_can_open_browser", lambda: True)
monkeypatch.setattr("webbrowser.open", lambda url, **kw: True)

self._run(
_redirect_handler(
"https://example.com/auth",
redirect_uri="https://oauth.example.ts.net/callback",
)
)

err = capsys.readouterr().err
assert "Remote session detected" not in err
assert "no SSH tunnel needed" not in err


# ---------------------------------------------------------------------------
# Path traversal protection
Expand Down Expand Up @@ -587,6 +631,106 @@ def test_configure_callback_port_uses_explicit_port():
assert cfg["_resolved_port"] == 54321


_PROXY_REDIRECT = "https://oauth.example.ts.net/callback"


def test_resolve_redirect_uri_prefers_configured_value():
"""An explicit redirect_uri in cfg overrides the localhost default."""
from tools.mcp_oauth import _resolve_redirect_uri

assert _resolve_redirect_uri({"redirect_uri": _PROXY_REDIRECT}, 1234) == _PROXY_REDIRECT


def test_resolve_redirect_uri_falls_back_to_localhost():
"""No redirect_uri → the loopback callback derived from the port."""
from tools.mcp_oauth import _resolve_redirect_uri

assert _resolve_redirect_uri({}, 1234) == "http://127.0.0.1:1234/callback"


def test_resolve_redirect_uri_empty_string_falls_back():
"""An empty redirect_uri is treated as unset (YAML ``redirect_uri:``)."""
from tools.mcp_oauth import _resolve_redirect_uri

assert _resolve_redirect_uri({"redirect_uri": ""}, 5678) == "http://127.0.0.1:5678/callback"


def test_build_client_metadata_uses_configured_redirect_uri():
"""A proxied redirect_uri (e.g. Tailscale Funnel) flows into the metadata.

Without this the redirect_uri is pinned to ``http://127.0.0.1:<port>/callback``,
which a public HTTPS proxy cannot reach.
"""
pytest.importorskip("mcp")
from tools.mcp_oauth import _build_client_metadata, _configure_callback_port

cfg = {"redirect_uri": _PROXY_REDIRECT}
_configure_callback_port(cfg)
md = _build_client_metadata(cfg)

assert [str(u).rstrip("/") for u in md.redirect_uris] == [_PROXY_REDIRECT]


def test_build_client_metadata_redirect_uri_defaults_to_localhost():
"""Without redirect_uri, metadata keeps the loopback callback default."""
pytest.importorskip("mcp")
from tools.mcp_oauth import _build_client_metadata, _configure_callback_port

cfg: dict = {}
port = _configure_callback_port(cfg)
md = _build_client_metadata(cfg)

assert [str(u).rstrip("/") for u in md.redirect_uris] == [
f"http://127.0.0.1:{port}/callback"
]


def test_maybe_preregister_client_persists_configured_redirect_uri(tmp_path, monkeypatch):
"""Pre-registered client info records the configured redirect_uri verbatim.

The redirect_uri on the stored client_info MUST match the one in the
authorization request, or the provider rejects the callback.
"""
pytest.importorskip("mcp")
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
from tools.mcp_oauth import (
HermesTokenStorage,
_build_client_metadata,
_configure_callback_port,
_maybe_preregister_client,
)

cfg = {"client_id": "preset-client", "redirect_uri": _PROXY_REDIRECT}
_configure_callback_port(cfg)
storage = HermesTokenStorage("proxy-srv")
_maybe_preregister_client(storage, cfg, _build_client_metadata(cfg))

written = json.loads(storage._client_info_path().read_text())
assert [u.rstrip("/") for u in written["redirect_uris"]] == [_PROXY_REDIRECT]


def test_maybe_preregister_client_redirect_uri_defaults_to_localhost(tmp_path, monkeypatch):
"""Without redirect_uri, pre-registration falls back to the loopback callback."""
pytest.importorskip("mcp")
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
from tools.mcp_oauth import (
HermesTokenStorage,
_build_client_metadata,
_configure_callback_port,
_maybe_preregister_client,
)

cfg = {"client_id": "preset-client"}
port = _configure_callback_port(cfg)
storage = HermesTokenStorage("loopback-srv")
_maybe_preregister_client(storage, cfg, _build_client_metadata(cfg))

written = json.loads(storage._client_info_path().read_text())
assert [u.rstrip("/") for u in written["redirect_uris"]] == [
f"http://127.0.0.1:{port}/callback"
]


def test_build_oauth_auth_preserves_server_url_path():
"""server_url with path is forwarded to OAuthClientProvider unmodified.

Expand Down Expand Up @@ -620,6 +764,120 @@ def __init__(self, **kwargs):
assert captured["server_url"] == "https://mcp.notion.com/mcp"


def test_build_oauth_auth_wires_configured_redirect_uri_into_handler():
"""The configured redirect_uri is bound into the redirect_handler so the
remote-session hint can stay accurate for proxied callbacks."""
from tools import mcp_oauth

captured: dict = {}

class _FakeProvider:
def __init__(self, **kwargs):
captured.update(kwargs)

with patch.object(mcp_oauth, "_OAUTH_AVAILABLE", True), \
patch.object(mcp_oauth, "OAuthClientProvider", _FakeProvider), \
patch.object(mcp_oauth, "_is_interactive", return_value=True), \
patch.object(mcp_oauth, "_maybe_preregister_client"), \
patch.object(mcp_oauth, "HermesTokenStorage") as mock_storage_cls:
mock_storage_cls.return_value = MagicMock(has_cached_tokens=lambda: True)
build_oauth_auth(
server_name="proxy",
server_url="https://mcp.example.com/mcp",
oauth_config={"redirect_uri": _PROXY_REDIRECT},
)

assert captured["redirect_handler"].keywords["redirect_uri"] == _PROXY_REDIRECT


def test_build_oauth_auth_handler_redirect_uri_none_when_unset():
"""Without a configured redirect_uri, the handler is bound with None so it
falls back to the loopback SSH hint."""
from tools import mcp_oauth

captured: dict = {}

class _FakeProvider:
def __init__(self, **kwargs):
captured.update(kwargs)

with patch.object(mcp_oauth, "_OAUTH_AVAILABLE", True), \
patch.object(mcp_oauth, "OAuthClientProvider", _FakeProvider), \
patch.object(mcp_oauth, "_is_interactive", return_value=True), \
patch.object(mcp_oauth, "_maybe_preregister_client"), \
patch.object(mcp_oauth, "HermesTokenStorage") as mock_storage_cls:
mock_storage_cls.return_value = MagicMock(has_cached_tokens=lambda: True)
build_oauth_auth(
server_name="loopback",
server_url="https://mcp.example.com/mcp",
oauth_config={},
)

assert captured["redirect_handler"].keywords["redirect_uri"] is None


def test_build_client_metadata_redirect_uri_without_path_is_normalized():
"""pydantic AnyUrl appends a trailing slash to a bare-hostname redirect_uri.

Both _build_client_metadata and _maybe_preregister_client run the value
through AnyUrl, so they normalize identically and stay consistent — this
pins that behavior so a future pydantic change is caught.
"""
pytest.importorskip("mcp")
from tools.mcp_oauth import _build_client_metadata, _configure_callback_port

cfg = {"redirect_uri": "https://oauth.example.ts.net"}
_configure_callback_port(cfg)
md = _build_client_metadata(cfg)

assert str(md.redirect_uris[0]) == "https://oauth.example.ts.net/"


def test_maybe_preregister_client_skips_when_no_client_id(tmp_path, monkeypatch):
"""No client_id → pre-registration is a no-op even with a configured redirect_uri."""
pytest.importorskip("mcp")
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
from tools.mcp_oauth import (
HermesTokenStorage,
_build_client_metadata,
_configure_callback_port,
_maybe_preregister_client,
)

cfg = {"redirect_uri": _PROXY_REDIRECT} # no client_id
_configure_callback_port(cfg)
storage = HermesTokenStorage("no-client-id-srv")
_maybe_preregister_client(storage, cfg, _build_client_metadata(cfg))

assert not storage._client_info_path().exists()


def test_maybe_preregister_client_redirect_uri_with_secret(tmp_path, monkeypatch):
"""redirect_uri + client_secret: callback stored verbatim, auth method confidential."""
pytest.importorskip("mcp")
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
from tools.mcp_oauth import (
HermesTokenStorage,
_build_client_metadata,
_configure_callback_port,
_maybe_preregister_client,
)

cfg = {
"client_id": "my-client",
"client_secret": "shhh",
"redirect_uri": _PROXY_REDIRECT,
}
_configure_callback_port(cfg)
storage = HermesTokenStorage("secret-proxy-srv")
_maybe_preregister_client(storage, cfg, _build_client_metadata(cfg))

written = json.loads(storage._client_info_path().read_text())
assert [u.rstrip("/") for u in written["redirect_uris"]] == [_PROXY_REDIRECT]
assert written["client_secret"] == "shhh"
assert written["token_endpoint_auth_method"] == "client_secret_post"



class TestPasteCallbackReader:
"""_paste_callback_reader parses redirect URLs / query strings from stdin."""
Expand Down
56 changes: 45 additions & 11 deletions tools/mcp_oauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,12 @@
client_secret: "secret" # confidential clients only
scope: "read write" # default: server-provided
redirect_port: 0 # 0 = auto-pick free port
redirect_uri: "https://proxy/callback" # default: loopback callback
client_name: "My Custom Client" # default: "Hermes Agent"
"""

import asyncio
import functools
import json
import logging
import os
Expand Down Expand Up @@ -397,11 +399,18 @@ def log_message(self, fmt: str, *args: Any) -> None:
# ---------------------------------------------------------------------------


async def _redirect_handler(authorization_url: str) -> None:
async def _redirect_handler(
authorization_url: str, *, redirect_uri: str | None = None
) -> None:
"""Show the authorization URL to the user.

Opens the browser automatically when possible; always prints the URL
as a fallback for headless/SSH/gateway environments.

``redirect_uri`` is the configured proxy callback (e.g. a Tailscale Funnel
URL), or ``None`` for the loopback default. It tailors the remote-session
hint: a proxied callback reaches this machine on its own, so the loopback
SSH-tunnel guidance would be misleading.
"""
msg = (
f"\n MCP OAuth: authorization required.\n"
Expand All @@ -410,13 +419,23 @@ async def _redirect_handler(authorization_url: str) -> None:
)
print(msg, file=sys.stderr)

# On a remote SSH session the OAuth provider redirects to
# http://127.0.0.1:<port>/callback, which reaches the callback server on
# the *remote* machine — not the user's local machine where the browser
# opened. Two ways out: paste the redirect URL back (default fallback,
# offered by _wait_for_callback on interactive TTYs), or set up an SSH
# port forward so the redirect tunnels through.
if _oauth_port and (os.getenv("SSH_CLIENT") or os.getenv("SSH_TTY")):
on_ssh = bool(os.getenv("SSH_CLIENT") or os.getenv("SSH_TTY"))
if on_ssh and redirect_uri:
# A configured proxy callback (e.g. Tailscale Funnel) forwards the
# redirect to the listener on this machine, so no tunnel/paste is needed.
print(
f" Remote session detected. After you authorize, the provider redirects to\n"
f" {redirect_uri}\n"
f" which forwards to the callback listener on this machine — no SSH tunnel needed.\n",
file=sys.stderr,
)
elif on_ssh and _oauth_port:
# Loopback default: the provider redirects to
# http://127.0.0.1:<port>/callback, which reaches the callback server on
# the *remote* machine — not the user's local machine where the browser
# opened. Two ways out: paste the redirect URL back (default fallback,
# offered by _wait_for_callback on interactive TTYs), or set up an SSH
# port forward so the redirect tunnels through.
print(
f" Remote session detected. After you authorize, the provider redirects to\n"
f" http://127.0.0.1:{_oauth_port}/callback\n"
Expand Down Expand Up @@ -661,6 +680,19 @@ def _configure_callback_port(cfg: dict) -> int:
return port


def _resolve_redirect_uri(cfg: dict, port: int) -> str:
"""Resolve the OAuth callback URL: configured ``redirect_uri`` or loopback.

A configured ``redirect_uri`` lets the callback go through a proxy (e.g. a
Tailscale Funnel exposing a public HTTPS URL that forwards to localhost);
otherwise we default to ``http://127.0.0.1:<port>/callback``. An empty value
is treated as unset. Both the client metadata and any pre-registered client
info must derive the redirect_uri here so they stay identical — a mismatch
makes the authorization server reject the callback.
"""
return cfg.get("redirect_uri") or f"http://127.0.0.1:{port}/callback"


def _build_client_metadata(cfg: dict) -> "OAuthClientMetadata":
"""Build OAuthClientMetadata from the oauth config dict.

Expand All @@ -674,7 +706,7 @@ def _build_client_metadata(cfg: dict) -> "OAuthClientMetadata":
)
client_name = cfg.get("client_name", "Hermes Agent")
scope = cfg.get("scope")
redirect_uri = f"http://127.0.0.1:{port}/callback"
redirect_uri = _resolve_redirect_uri(cfg, port)

metadata_kwargs: dict[str, Any] = {
"client_name": client_name,
Expand All @@ -701,7 +733,7 @@ def _maybe_preregister_client(
if not client_id:
return
port = cfg["_resolved_port"]
redirect_uri = f"http://127.0.0.1:{port}/callback"
redirect_uri = _resolve_redirect_uri(cfg, port)

info_dict: dict[str, Any] = {
"client_id": client_id,
Expand Down Expand Up @@ -770,7 +802,9 @@ def build_oauth_auth(
server_url=server_url,
client_metadata=client_metadata,
storage=storage,
redirect_handler=_redirect_handler,
redirect_handler=functools.partial(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This binding only changes the legacy build_oauth_auth path. Runtime MCP connections use MCPOAuthManager._build_provider (tools/mcp_oauth_manager.py:548-556), which still passes _redirect_handler directly; mirror this partial there and add a manager-path regression test.

_redirect_handler, redirect_uri=cfg.get("redirect_uri") or None
),
callback_handler=_wait_for_callback,
timeout=float(cfg.get("timeout", 300)),
)