782 lines
32 KiB
Python
782 lines
32 KiB
Python
"""Comprehensive tests for MCP connectors: models, transports, auth methods, and manager."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import sys
|
|
import textwrap
|
|
from pathlib import Path
|
|
from typing import Any
|
|
from urllib.parse import parse_qs, urlparse
|
|
|
|
from aiohttp import web
|
|
import pytest
|
|
|
|
from homeagent.agent.mcp_bridge import MCPToolBridge
|
|
from homeagent.config import Settings
|
|
from homeagent.mcp.auth import (
|
|
MCPAuthManager,
|
|
MCPAuthRequiredError,
|
|
OAuthTokenStore,
|
|
parse_www_authenticate,
|
|
)
|
|
from homeagent.mcp.manager import MCPConnectorManager
|
|
from homeagent.mcp.models import (
|
|
MCPAuthConfig,
|
|
MCPConnectorConfig,
|
|
expand_env_vars,
|
|
mask_secret,
|
|
parse_connectors_payload,
|
|
sanitize_mcp_input_schema,
|
|
sanitize_tool_name,
|
|
)
|
|
from homeagent.tools.registry import ToolRegistry
|
|
|
|
|
|
# ------------------------------------------------------------------------------
|
|
# Helpers: real local aiohttp test servers (Streamable HTTP, Legacy SSE, OAuth)
|
|
# ------------------------------------------------------------------------------
|
|
|
|
|
|
async def _start_aiohttp_app(app: web.Application) -> tuple[web.AppRunner, str]:
|
|
runner = web.AppRunner(app, access_log=None)
|
|
await runner.setup()
|
|
site = web.TCPSite(runner, "127.0.0.1", 0)
|
|
await site.start()
|
|
sockets = getattr(site._server, "sockets", None) # type: ignore[union-attr]
|
|
assert sockets
|
|
port = int(sockets[0].getsockname()[1])
|
|
return runner, f"http://127.0.0.1:{port}"
|
|
|
|
|
|
# ------------------------------------------------------------------------------
|
|
# 1. Models, parsing, env expansion, and schema sanitization tests
|
|
# ------------------------------------------------------------------------------
|
|
|
|
|
|
def test_parse_connectors_payload_supports_mcp_servers_and_connectors(monkeypatch):
|
|
monkeypatch.setenv("TEST_GH_TOKEN", "ghp_secret_123456")
|
|
|
|
raw_claude_format = {
|
|
"mcpServers": {
|
|
"github": {
|
|
"serverUrl": "https://api.githubcopilot.com/mcp/",
|
|
"headers": {"Authorization": "Bearer ${TEST_GH_TOKEN}"},
|
|
},
|
|
"local-fs": {
|
|
"command": "npx",
|
|
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
|
|
"env": {"NODE_ENV": "test"},
|
|
},
|
|
}
|
|
}
|
|
conns = parse_connectors_payload(raw_claude_format, source="config")
|
|
assert len(conns) == 2
|
|
by_name = {c.name: c for c in conns}
|
|
assert by_name["github"].url == "https://api.githubcopilot.com/mcp/"
|
|
assert by_name["github"].transport == "auto"
|
|
assert by_name["github"].resolved().headers["Authorization"] == "Bearer ghp_secret_123456"
|
|
# Unresolved original preserves placeholder (does not leak expanded env)
|
|
assert by_name["github"].headers["Authorization"] == "Bearer ${TEST_GH_TOKEN}"
|
|
assert by_name["local-fs"].transport == "stdio"
|
|
assert by_name["local-fs"].command == "npx"
|
|
assert by_name["local-fs"].args == ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
|
|
|
|
assert expand_env_vars("${UNSET_VAR_XYZ:-fallback_val}") == "fallback_val"
|
|
assert mask_secret("sk-1234567890abcdef") == "sk-1••••cdef"
|
|
assert mask_secret("${TEST_GH_TOKEN}") == "`${TEST_GH_TOKEN}` (env)"
|
|
|
|
|
|
def test_sanitize_mcp_input_schema_compatible_with_gemini_and_openai():
|
|
complex_schema = {
|
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
|
"$defs": {
|
|
"Filter": {
|
|
"type": "object",
|
|
"properties": {
|
|
"field": {"type": "string"},
|
|
"values": {"type": "array"},
|
|
},
|
|
"required": ["field"],
|
|
"additionalProperties": False,
|
|
}
|
|
},
|
|
"type": "object",
|
|
"additionalProperties": False,
|
|
"properties": {
|
|
"query": {"type": "string", "description": "Search query", "default": ""},
|
|
"limit": {"type": ["integer", "null"], "minimum": 1, "maximum": 100},
|
|
"mode": {"const": "fast"},
|
|
"tag": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "Optional tag"},
|
|
"filter": {"$ref": "#/$defs/Filter"},
|
|
},
|
|
"required": ["query", "nonexistent_required"],
|
|
}
|
|
|
|
sanitized = sanitize_mcp_input_schema(complex_schema)
|
|
assert "$schema" not in sanitized
|
|
assert "additionalProperties" not in sanitized
|
|
assert sanitized["required"] == ["query"]
|
|
assert sanitized["properties"]["limit"]["type"] == "integer"
|
|
assert sanitized["properties"]["limit"]["nullable"] is True
|
|
assert sanitized["properties"]["tag"]["type"] == "string"
|
|
assert sanitized["properties"]["tag"]["nullable"] is True
|
|
assert sanitized["properties"]["mode"]["enum"] == ["fast"]
|
|
assert sanitized["properties"]["filter"]["type"] == "object"
|
|
assert sanitized["properties"]["filter"]["properties"]["values"]["items"] == {"type": "string"}
|
|
|
|
# Verify Gemini FunctionDeclaration accepts sanitized schema cleanly!
|
|
from homeagent.tools.base import ToolDefinition
|
|
|
|
registry = ToolRegistry()
|
|
registry.register_definition(
|
|
ToolDefinition(
|
|
name=sanitize_tool_name("linear", "search/issues.v2"),
|
|
description="[MCP:linear] Search issues",
|
|
func=lambda **kw: "ok",
|
|
parameters_schema=sanitized,
|
|
is_async=False,
|
|
)
|
|
)
|
|
decls = registry.get_function_declarations()
|
|
assert len(decls) == 1
|
|
assert decls[0].name == "mcp_linear_search_issues_v2"
|
|
openai_tools = registry.get_openai_tools()
|
|
assert openai_tools[0]["function"]["name"] == "mcp_linear_search_issues_v2"
|
|
|
|
|
|
def test_sanitize_tool_name_length_and_collision():
|
|
long_name = sanitize_tool_name("very_long_connector_name_12345", "extremely_long_remote_tool_name_that_exceeds_limit_xyz")
|
|
assert len(long_name) <= 64
|
|
|
|
existing = {"mcp_demo_ping"}
|
|
alt = sanitize_tool_name("demo", "ping", existing_names=existing)
|
|
assert alt == "mcp_demo_ping_2"
|
|
|
|
|
|
def test_parse_www_authenticate():
|
|
hdr = 'Bearer realm="mcp", resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource", scope="read write"'
|
|
parsed = parse_www_authenticate(hdr)
|
|
assert parsed["realm"] == "mcp"
|
|
assert parsed["resource_metadata"] == "https://mcp.example.com/.well-known/oauth-protected-resource"
|
|
assert parsed["scope"] == "read write"
|
|
|
|
|
|
# ------------------------------------------------------------------------------
|
|
# 2. Streamable HTTP transport + Bearer / API Key / Basic / Headers / SSE response
|
|
# ------------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_streamable_http_all_static_auth_methods_and_sse_response(tmp_path):
|
|
captured_requests: list[dict[str, Any]] = []
|
|
expected_mode = {"mode": "bearer"}
|
|
|
|
async def handle_mcp(request: web.Request) -> web.Response:
|
|
captured_requests.append(
|
|
{
|
|
"headers": dict(request.headers),
|
|
"query": dict(request.query),
|
|
}
|
|
)
|
|
mode = expected_mode["mode"]
|
|
if mode == "bearer" and request.headers.get("Authorization") != "Bearer tok-secret-1":
|
|
return web.Response(status=401, text="Unauthorized")
|
|
if mode == "api_key_header" and request.headers.get("X-Custom-Key") != "Prefix key-999":
|
|
return web.Response(status=401, text="Unauthorized")
|
|
if mode == "api_key_query" and request.query.get("token_param") != "qkey-888":
|
|
return web.Response(status=401, text="Unauthorized")
|
|
if mode == "basic":
|
|
expected_b64 = base64.b64encode(b"alice:wonderland").decode("ascii")
|
|
if request.headers.get("Authorization") != f"Basic {expected_b64}":
|
|
return web.Response(status=401, text="Unauthorized")
|
|
if mode == "headers":
|
|
if request.headers.get("X-Tenant") != "acme" or request.headers.get("X-Secret") != "s3cr3t":
|
|
return web.Response(status=401, text="Unauthorized")
|
|
|
|
if request.method == "DELETE":
|
|
return web.Response(status=204)
|
|
|
|
body = await request.json()
|
|
method = body.get("method")
|
|
req_id = body.get("id")
|
|
if req_id is None:
|
|
return web.Response(status=202)
|
|
|
|
if method == "initialize":
|
|
return web.json_response(
|
|
{
|
|
"jsonrpc": "2.0",
|
|
"id": req_id,
|
|
"result": {
|
|
"protocolVersion": "2025-03-26",
|
|
"capabilities": {"tools": {}},
|
|
"serverInfo": {"name": "mock-http-mcp", "version": "1.2.3"},
|
|
},
|
|
},
|
|
headers={"Mcp-Session-Id": "sess-42"},
|
|
)
|
|
if method == "tools/list":
|
|
cursor = (body.get("params") or {}).get("cursor")
|
|
if not cursor:
|
|
return web.json_response(
|
|
{
|
|
"jsonrpc": "2.0",
|
|
"id": req_id,
|
|
"result": {
|
|
"tools": [
|
|
{
|
|
"name": "echo",
|
|
"description": "Echo text back",
|
|
"inputSchema": {
|
|
"type": "object",
|
|
"properties": {"text": {"type": "string"}},
|
|
"required": ["text"],
|
|
},
|
|
}
|
|
],
|
|
"nextCursor": "page2",
|
|
},
|
|
}
|
|
)
|
|
return web.json_response(
|
|
{
|
|
"jsonrpc": "2.0",
|
|
"id": req_id,
|
|
"result": {
|
|
"tools": [
|
|
{
|
|
"name": "secret_admin",
|
|
"description": "Should be excluded when filtered",
|
|
"inputSchema": {"type": "object", "properties": {}},
|
|
}
|
|
]
|
|
},
|
|
}
|
|
)
|
|
if method == "tools/call":
|
|
# Respond using text/event-stream (Streamable HTTP SSE response mode!)
|
|
args = (body.get("params") or {}).get("arguments") or {}
|
|
sse_payload = json.dumps(
|
|
{
|
|
"jsonrpc": "2.0",
|
|
"id": req_id,
|
|
"result": {
|
|
"content": [{"type": "text", "text": f"ECHO:{args.get('text', '')}"}],
|
|
"isError": False,
|
|
},
|
|
}
|
|
)
|
|
return web.Response(
|
|
text=f": keepalive\nevent: message\ndata: {sse_payload}\n\n",
|
|
content_type="text/event-stream",
|
|
)
|
|
return web.json_response({"jsonrpc": "2.0", "id": req_id, "result": {}})
|
|
|
|
app = web.Application()
|
|
app.router.add_route("*", "/mcp", handle_mcp)
|
|
runner, base_url = await _start_aiohttp_app(app)
|
|
|
|
try:
|
|
registry = ToolRegistry()
|
|
settings = Settings(DATA_DIR=tmp_path, MCP_CONFIG_FILE=tmp_path / "nonexistent.json")
|
|
manager = MCPConnectorManager(settings=settings, registry=registry)
|
|
|
|
auth_cases = [
|
|
("bearer", MCPAuthConfig(type="bearer", token="tok-secret-1")),
|
|
(
|
|
"api_key_header",
|
|
MCPAuthConfig(
|
|
type="api_key",
|
|
api_key="key-999",
|
|
api_key_in="header",
|
|
header_name="X-Custom-Key",
|
|
api_key_prefix="Prefix ",
|
|
),
|
|
),
|
|
(
|
|
"api_key_query",
|
|
MCPAuthConfig(
|
|
type="api_key",
|
|
api_key="qkey-888",
|
|
api_key_in="query",
|
|
query_param="token_param",
|
|
),
|
|
),
|
|
("basic", MCPAuthConfig(type="basic", username="alice", password="wonderland")),
|
|
("headers", MCPAuthConfig(type="headers", headers={"X-Tenant": "acme", "X-Secret": "s3cr3t"})),
|
|
]
|
|
|
|
for mode, auth_cfg in auth_cases:
|
|
expected_mode["mode"] = mode
|
|
cfg = MCPConnectorConfig(
|
|
name=f"srv_{mode}",
|
|
transport="streamable_http",
|
|
url=f"{base_url}/mcp",
|
|
auth=auth_cfg,
|
|
exclude_tools=["secret_admin"],
|
|
source="bot",
|
|
)
|
|
state = await manager.add_or_update_connector(cfg, connect_now=True, persist=True)
|
|
assert state.status == "connected", f"Failed for {mode}: {state.last_error}"
|
|
assert state.resolved_transport == "streamable_http"
|
|
assert [t.remote_name for t in state.tools] == ["echo"]
|
|
|
|
tool_name = f"mcp_srv_{mode}_echo"
|
|
out = await registry.execute(tool_name, {"text": f"hi-{mode}"})
|
|
assert out == f"ECHO:hi-{mode}"
|
|
|
|
# Also verify MCPToolBridge exposes connected MCP tools to Antigravity CLI automatically!
|
|
bridge = MCPToolBridge(registry)
|
|
await bridge.ensure_started()
|
|
try:
|
|
mcp_cfg = bridge.build_mcp_config()
|
|
assert "mcp_srv_bearer_echo" in mcp_cfg["mcpServers"]["homeagent"]["tools"]
|
|
finally:
|
|
await bridge.stop()
|
|
|
|
# Disconnecting unregisters its tools cleanly
|
|
await manager.disconnect("srv_bearer")
|
|
assert registry.get("mcp_srv_bearer_echo") is None
|
|
|
|
await manager.close()
|
|
finally:
|
|
await runner.cleanup()
|
|
|
|
|
|
# ------------------------------------------------------------------------------
|
|
# 3. Legacy SSE transport + Auto-detect fallback (Streamable HTTP -> SSE)
|
|
# ------------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_legacy_sse_and_auto_transport_fallback(tmp_path):
|
|
sse_queue: asyncio.Queue[str | None] = asyncio.Queue()
|
|
|
|
async def handle_sse_get(request: web.Request) -> web.StreamResponse:
|
|
if request.method != "GET":
|
|
# Force Streamable HTTP POST to get 405 so `auto` falls back to SSE!
|
|
return web.Response(status=405, text="Method Not Allowed")
|
|
resp = web.StreamResponse(
|
|
status=200,
|
|
headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"},
|
|
)
|
|
await resp.prepare(request)
|
|
await resp.write(b"event: endpoint\ndata: /messages?sid=1\n\n")
|
|
try:
|
|
while True:
|
|
msg = await sse_queue.get()
|
|
if msg is None:
|
|
break
|
|
await resp.write(f"event: message\ndata: {msg}\n\n".encode("utf-8"))
|
|
except (asyncio.CancelledError, ConnectionResetError):
|
|
pass
|
|
return resp
|
|
|
|
async def handle_messages_post(request: web.Request) -> web.Response:
|
|
body = await request.json()
|
|
req_id = body.get("id")
|
|
method = body.get("method")
|
|
if req_id is None:
|
|
return web.Response(status=202)
|
|
if method == "initialize":
|
|
res = {"protocolVersion": "2024-11-05", "capabilities": {"tools": {}}, "serverInfo": {"name": "sse-srv"}}
|
|
elif method == "tools/list":
|
|
res = {
|
|
"tools": [
|
|
{
|
|
"name": "ping_sse",
|
|
"description": "SSE ping",
|
|
"inputSchema": {"type": "object", "properties": {}},
|
|
}
|
|
]
|
|
}
|
|
elif method == "tools/call":
|
|
res = {"content": [{"type": "text", "text": "pong-over-sse"}], "isError": False}
|
|
else:
|
|
res = {}
|
|
await sse_queue.put(json.dumps({"jsonrpc": "2.0", "id": req_id, "result": res}))
|
|
return web.Response(status=202)
|
|
|
|
app = web.Application()
|
|
app.router.add_route("*", "/stream", handle_sse_get)
|
|
app.router.add_post("/messages", handle_messages_post)
|
|
runner, base_url = await _start_aiohttp_app(app)
|
|
|
|
try:
|
|
registry = ToolRegistry()
|
|
settings = Settings(DATA_DIR=tmp_path, MCP_CONFIG_FILE=tmp_path / "none.json")
|
|
manager = MCPConnectorManager(settings=settings, registry=registry)
|
|
|
|
# Notice URL does NOT end with /sse, so `auto` tries Streamable HTTP first, gets 405, and falls back to SSE!
|
|
cfg = MCPConnectorConfig(
|
|
name="legacy",
|
|
transport="auto",
|
|
url=f"{base_url}/stream",
|
|
source="bot",
|
|
)
|
|
state = await manager.add_or_update_connector(cfg, connect_now=True, persist=True)
|
|
assert state.status == "connected", state.last_error
|
|
assert state.resolved_transport == "sse"
|
|
assert await registry.execute("mcp_legacy_ping_sse", {}) == "pong-over-sse"
|
|
await manager.close()
|
|
finally:
|
|
await sse_queue.put(None)
|
|
await runner.cleanup()
|
|
|
|
|
|
# ------------------------------------------------------------------------------
|
|
# 4. Stdio transport (real Python subprocess with ENV auth)
|
|
# ------------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_stdio_transport_real_subprocess_with_env_auth(tmp_path):
|
|
script = tmp_path / "fake_stdio_mcp.py"
|
|
script.write_text(
|
|
textwrap.dedent(
|
|
"""
|
|
import json, os, sys
|
|
|
|
for line in sys.stdin:
|
|
line = line.strip()
|
|
if not line:
|
|
continue
|
|
msg = json.loads(line)
|
|
if "id" not in msg or msg["id"] is None:
|
|
continue
|
|
req_id = msg["id"]
|
|
method = msg.get("method")
|
|
if method == "initialize":
|
|
res = {"protocolVersion": "2025-03-26", "capabilities": {"tools": {}}, "serverInfo": {"name": "stdio-demo"}}
|
|
elif method == "tools/list":
|
|
res = {
|
|
"tools": [
|
|
{
|
|
"name": "whoami",
|
|
"description": "Return env secret tag",
|
|
"inputSchema": {"type": "object", "properties": {"prefix": {"type": "string"}}},
|
|
}
|
|
]
|
|
}
|
|
elif method == "tools/call":
|
|
args = (msg.get("params") or {}).get("arguments") or {}
|
|
secret = os.environ.get("MCP_DEMO_SECRET", "missing")
|
|
res = {"content": [{"type": "text", "text": f"{args.get('prefix', '')}:{secret}"}], "isError": False}
|
|
else:
|
|
res = {}
|
|
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": req_id, "result": res}) + "\\n")
|
|
sys.stdout.flush()
|
|
"""
|
|
).strip()
|
|
+ "\n",
|
|
encoding="utf-8",
|
|
)
|
|
|
|
registry = ToolRegistry()
|
|
settings = Settings(DATA_DIR=tmp_path, MCP_CONFIG_FILE=tmp_path / "none.json")
|
|
manager = MCPConnectorManager(settings=settings, registry=registry)
|
|
|
|
cfg = MCPConnectorConfig(
|
|
name="local_py",
|
|
transport="stdio",
|
|
command=sys.executable,
|
|
args=[str(script)],
|
|
env={"MCP_DEMO_SECRET": "env-pass-777"},
|
|
source="bot",
|
|
)
|
|
state = await manager.add_or_update_connector(cfg, connect_now=True, persist=True)
|
|
assert state.status == "connected", state.last_error
|
|
assert state.resolved_transport == "stdio"
|
|
assert await registry.execute("mcp_local_py_whoami", {"prefix": "ok"}) == "ok:env-pass-777"
|
|
await manager.close()
|
|
|
|
|
|
# ------------------------------------------------------------------------------
|
|
# 5. OAuth 2.1 PKCE (RFC 9728 + RFC 8414 + RFC 7591 DCR + 401 auto-upgrade + Refresh)
|
|
# AND OAuth 2.0 Client Credentials + Device Flow + Refresh Token
|
|
# ------------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_oauth2_pkce_discovery_dcr_and_refresh_end_to_end(tmp_path):
|
|
oauth_state: dict[str, Any] = {
|
|
"valid_tokens": set(),
|
|
"registered_clients": {},
|
|
"issued_codes": {},
|
|
"refresh_count": 0,
|
|
}
|
|
base_url_holder = {"url": ""}
|
|
|
|
async def handle_prm(request: web.Request) -> web.Response:
|
|
return web.json_response(
|
|
{
|
|
"resource": f"{base_url_holder['url']}/mcp",
|
|
"authorization_servers": [base_url_holder["url"]],
|
|
"scopes_supported": ["mcp:read", "mcp:write"],
|
|
}
|
|
)
|
|
|
|
async def handle_as_meta(request: web.Request) -> web.Response:
|
|
u = base_url_holder["url"]
|
|
return web.json_response(
|
|
{
|
|
"issuer": u,
|
|
"authorization_endpoint": f"{u}/oauth/authorize",
|
|
"token_endpoint": f"{u}/oauth/token",
|
|
"registration_endpoint": f"{u}/oauth/register",
|
|
"device_authorization_endpoint": f"{u}/oauth/device",
|
|
}
|
|
)
|
|
|
|
async def handle_dcr(request: web.Request) -> web.Response:
|
|
data = await request.json()
|
|
cid = "dcr-client-42"
|
|
oauth_state["registered_clients"][cid] = data
|
|
return web.json_response({"client_id": cid}, status=201)
|
|
|
|
async def handle_token(request: web.Request) -> web.Response:
|
|
form = await request.post()
|
|
grant = form.get("grant_type")
|
|
if grant == "authorization_code":
|
|
code = form.get("code")
|
|
verifier = form.get("code_verifier", "")
|
|
expected_challenge = oauth_state["issued_codes"].get(code)
|
|
actual_challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode("ascii")).digest()).rstrip(b"=").decode("ascii")
|
|
if not expected_challenge or actual_challenge != expected_challenge:
|
|
return web.json_response({"error": "invalid_grant"}, status=400)
|
|
tok = "pkce-access-1"
|
|
oauth_state["valid_tokens"].add(tok)
|
|
return web.json_response(
|
|
{
|
|
"access_token": tok,
|
|
"token_type": "Bearer",
|
|
"expires_in": 3600,
|
|
"refresh_token": "pkce-refresh-1",
|
|
}
|
|
)
|
|
if grant == "refresh_token":
|
|
if form.get("refresh_token") not in ("pkce-refresh-1", "preset-refresh-99"):
|
|
return web.json_response({"error": "invalid_grant"}, status=400)
|
|
oauth_state["refresh_count"] += 1
|
|
tok = f"refreshed-access-{oauth_state['refresh_count']}"
|
|
oauth_state["valid_tokens"].add(tok)
|
|
return web.json_response(
|
|
{
|
|
"access_token": tok,
|
|
"token_type": "Bearer",
|
|
"expires_in": 3600,
|
|
"refresh_token": form.get("refresh_token"),
|
|
}
|
|
)
|
|
if grant == "client_credentials":
|
|
if form.get("client_id") == "m2m-id" and form.get("client_secret") == "m2m-secret":
|
|
tok = "m2m-access-1"
|
|
oauth_state["valid_tokens"].add(tok)
|
|
return web.json_response({"access_token": tok, "token_type": "Bearer", "expires_in": 3600})
|
|
return web.json_response({"error": "invalid_client"}, status=401)
|
|
if grant == "urn:ietf:params:oauth:grant-type:device_code":
|
|
polls = oauth_state.setdefault("device_polls", 0) + 1
|
|
oauth_state["device_polls"] = polls
|
|
if polls == 1:
|
|
return web.json_response({"error": "authorization_pending"}, status=400)
|
|
tok = "device-access-1"
|
|
oauth_state["valid_tokens"].add(tok)
|
|
return web.json_response({"access_token": tok, "token_type": "Bearer", "expires_in": 3600})
|
|
return web.json_response({"error": "unsupported_grant_type"}, status=400)
|
|
|
|
async def handle_device_auth(request: web.Request) -> web.Response:
|
|
return web.json_response(
|
|
{
|
|
"device_code": "dev-code-123",
|
|
"user_code": "ABCD-EFGH",
|
|
"verification_uri": f"{base_url_holder['url']}/activate",
|
|
"expires_in": 300,
|
|
"interval": 1,
|
|
}
|
|
)
|
|
|
|
async def handle_mcp(request: web.Request) -> web.Response:
|
|
auth_hdr = request.headers.get("Authorization", "")
|
|
token = auth_hdr[7:] if auth_hdr.startswith("Bearer ") else ""
|
|
if token not in oauth_state["valid_tokens"]:
|
|
return web.Response(
|
|
status=401,
|
|
headers={
|
|
"WWW-Authenticate": f'Bearer resource_metadata="{base_url_holder["url"]}/.well-known/oauth-protected-resource", scope="mcp:read"'
|
|
},
|
|
)
|
|
body = await request.json()
|
|
req_id = body.get("id")
|
|
method = body.get("method")
|
|
if req_id is None:
|
|
return web.Response(status=202)
|
|
if method == "initialize":
|
|
return web.json_response(
|
|
{"jsonrpc": "2.0", "id": req_id, "result": {"protocolVersion": "2025-03-26", "capabilities": {"tools": {}}, "serverInfo": {"name": "oauth-mcp"}}}
|
|
)
|
|
if method == "tools/list":
|
|
return web.json_response(
|
|
{
|
|
"jsonrpc": "2.0",
|
|
"id": req_id,
|
|
"result": {
|
|
"tools": [{"name": "status", "description": "Get protected status", "inputSchema": {"type": "object", "properties": {}}}]
|
|
},
|
|
}
|
|
)
|
|
if method == "tools/call":
|
|
return web.json_response(
|
|
{"jsonrpc": "2.0", "id": req_id, "result": {"content": [{"type": "text", "text": f"authed-as:{token}"}], "isError": False}}
|
|
)
|
|
return web.json_response({"jsonrpc": "2.0", "id": req_id, "result": {}})
|
|
|
|
app = web.Application()
|
|
app.router.add_get("/.well-known/oauth-protected-resource", handle_prm)
|
|
app.router.add_get("/.well-known/oauth-authorization-server", handle_as_meta)
|
|
app.router.add_post("/oauth/register", handle_dcr)
|
|
app.router.add_post("/oauth/token", handle_token)
|
|
app.router.add_post("/oauth/device", handle_device_auth)
|
|
app.router.add_route("*", "/mcp", handle_mcp)
|
|
runner, base_url = await _start_aiohttp_app(app)
|
|
base_url_holder["url"] = base_url
|
|
|
|
try:
|
|
registry = ToolRegistry()
|
|
settings = Settings(DATA_DIR=tmp_path, MCP_CONFIG_FILE=tmp_path / "none.json")
|
|
manager = MCPConnectorManager(settings=settings, registry=registry)
|
|
|
|
# A) Connect with auth=none -> hits 401 -> status becomes auth_required with challenge metadata!
|
|
pkce_cfg = MCPConnectorConfig(name="saas", transport="streamable_http", url=f"{base_url}/mcp", source="bot")
|
|
st = await manager.add_or_update_connector(pkce_cfg, connect_now=True, persist=True)
|
|
assert st.status == "auth_required"
|
|
assert st.oauth_challenge and "oauth-protected-resource" in (st.oauth_challenge.get("resource_metadata_url") or "")
|
|
|
|
# Start OAuth -> auto-upgrades to oauth2_pkce, discovers metadata, runs DCR!
|
|
oauth_info = await manager.start_oauth("saas")
|
|
assert oauth_info["flow"] == "pkce"
|
|
assert "dcr-client-42" in oauth_state["registered_clients"]
|
|
|
|
parsed_auth_url = urlparse(oauth_info["authorize_url"])
|
|
qs = parse_qs(parsed_auth_url.query)
|
|
assert qs["client_id"] == ["dcr-client-42"]
|
|
assert qs["code_challenge_method"] == ["S256"]
|
|
oauth_state["issued_codes"]["auth-code-xyz"] = qs["code_challenge"][0]
|
|
|
|
# Complete PKCE by pasting full redirect URL!
|
|
redirect_paste = f"{oauth_info['redirect_uri']}?code=auth-code-xyz&state={qs['state'][0]}"
|
|
st2 = await manager.complete_oauth_code("saas", redirect_paste)
|
|
assert st2.status == "connected", st2.last_error
|
|
assert await registry.execute("mcp_saas_status", {}) == "authed-as:pkce-access-1"
|
|
|
|
# Simulate token invalidation on server -> client transparently refreshes via refresh_token on 401!
|
|
oauth_state["valid_tokens"].discard("pkce-access-1")
|
|
out_after_refresh = await registry.execute("mcp_saas_status", {})
|
|
assert out_after_refresh == "authed-as:refreshed-access-1"
|
|
|
|
# Verify token file permissions are 0600
|
|
mode = os.stat(manager.tokens_path).st_mode & 0o777
|
|
assert mode == 0o600
|
|
|
|
# B) OAuth 2.0 Client Credentials (auto-discovers token_url!)
|
|
m2m_cfg = MCPConnectorConfig(
|
|
name="m2m",
|
|
transport="streamable_http",
|
|
url=f"{base_url}/mcp",
|
|
auth=MCPAuthConfig(type="oauth2_client_credentials", client_id="m2m-id", client_secret="m2m-secret"),
|
|
source="bot",
|
|
)
|
|
m2m_st = await manager.add_or_update_connector(m2m_cfg, connect_now=True, persist=True)
|
|
assert m2m_st.status == "connected", m2m_st.last_error
|
|
assert await registry.execute("mcp_m2m_status", {}) == "authed-as:m2m-access-1"
|
|
|
|
# C) OAuth 2.0 Device Flow (auto-discovers endpoints + polls pending -> token!)
|
|
dev_cfg = MCPConnectorConfig(
|
|
name="devflow",
|
|
transport="streamable_http",
|
|
url=f"{base_url}/mcp",
|
|
auth=MCPAuthConfig(type="oauth2_device", client_id="dev-client"),
|
|
source="bot",
|
|
)
|
|
await manager.add_or_update_connector(dev_cfg, connect_now=False, persist=True)
|
|
dev_info = await manager.start_oauth("devflow")
|
|
assert dev_info["flow"] == "device"
|
|
assert dev_info["user_code"] == "ABCD-EFGH"
|
|
dev_st = await manager.wait_for_device_oauth("devflow", timeout_seconds=10)
|
|
assert dev_st.status == "connected", dev_st.last_error
|
|
assert await registry.execute("mcp_devflow_status", {}) == "authed-as:device-access-1"
|
|
|
|
# D) OAuth 2.0 Refresh Token grant
|
|
rt_cfg = MCPConnectorConfig(
|
|
name="rtgrant",
|
|
transport="streamable_http",
|
|
url=f"{base_url}/mcp",
|
|
auth=MCPAuthConfig(type="oauth2_refresh_token", refresh_token="preset-refresh-99", client_id="rt-client"),
|
|
source="bot",
|
|
)
|
|
rt_st = await manager.add_or_update_connector(rt_cfg, connect_now=True, persist=True)
|
|
assert rt_st.status == "connected", rt_st.last_error
|
|
assert "authed-as:refreshed-access-" in await registry.execute("mcp_rtgrant_status", {})
|
|
|
|
await manager.close()
|
|
finally:
|
|
await runner.cleanup()
|
|
|
|
|
|
# ------------------------------------------------------------------------------
|
|
# 6. Config loading (JSON + YAML + MCP_CONNECTORS_JSON + persistence + stdio policy)
|
|
# ------------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_config_loading_yaml_and_env_json_and_stdio_restriction(tmp_path):
|
|
yaml_cfg = tmp_path / "mcp_connectors.yaml"
|
|
yaml_cfg.write_text(
|
|
textwrap.dedent(
|
|
"""
|
|
connectors:
|
|
yaml_srv:
|
|
url: https://yaml.example.com/mcp
|
|
enabled: false
|
|
auth:
|
|
type: bearer
|
|
token: yaml-tok
|
|
"""
|
|
).strip()
|
|
+ "\n",
|
|
encoding="utf-8",
|
|
)
|
|
|
|
inline = json.dumps({"mcpServers": {"env_srv": {"url": "https://env.example.com/mcp", "disabled": True}}})
|
|
settings = Settings(
|
|
DATA_DIR=tmp_path / "data",
|
|
MCP_CONFIG_FILE=yaml_cfg,
|
|
MCP_CONNECTORS_JSON=inline,
|
|
MCP_ALLOW_STDIO_FROM_BOT=False,
|
|
)
|
|
registry = ToolRegistry()
|
|
manager = MCPConnectorManager(settings=settings, registry=registry)
|
|
|
|
names = {s.config.name for s in manager.list_connectors()}
|
|
assert names == {"yaml_srv", "env_srv"}
|
|
assert manager.get_connector("yaml_srv").status == "disabled"
|
|
|
|
# Bot stdio creation blocked when MCP_ALLOW_STDIO_FROM_BOT=False
|
|
stdio_cfg = MCPConnectorConfig(name="blocked_stdio", transport="stdio", command="echo", source="bot")
|
|
with pytest.raises(PermissionError):
|
|
await manager.add_or_update_connector(stdio_cfg, connect_now=False, persist=True)
|
|
|
|
# Import JSON with markdown fences persists across fresh manager instance
|
|
fenced = '```json\n{"mcpServers": {"imported": {"url": "https://imp.example.com/mcp", "disabled": true}}}\n```'
|
|
states = await manager.import_from_json(fenced, connect_now=False)
|
|
assert len(states) == 1 and states[0].config.name == "imported"
|
|
|
|
manager2 = MCPConnectorManager(settings=settings, registry=ToolRegistry())
|
|
assert manager2.get_connector("imported") is not None
|
|
await manager.close()
|
|
await manager2.close()
|