"""Tests for MCP Connectors Telegram Bot interface: zero-config Smart Connect, manual wizard, commands, ghost mode, whitelist.""" from __future__ import annotations import base64 import hashlib import json import sys import textwrap from datetime import datetime from typing import Any from unittest.mock import AsyncMock, MagicMock from urllib.parse import parse_qs, urlparse from aiohttp import web from aiogram import Bot, Dispatcher from aiogram.types import CallbackQuery, Chat, Message, Update, User import pytest from homeagent.bot.handlers import create_bot_router from homeagent.bot.middlewares import WhitelistMiddleware from homeagent.config import Settings from homeagent.mcp.autodiscover import ( derive_connector_name_from_command, derive_connector_name_from_url, parse_smart_input, ) from homeagent.mcp.manager import MCPConnectorManager from homeagent.skills.manager import SkillManager from homeagent.tools.registry import ToolRegistry async def _start_mock_mcp_server( *, expected_bearer: str | None = None, expected_api_key_header: tuple[str, str] | None = None, ) -> tuple[web.AppRunner, str]: async def handle_mcp(request: web.Request) -> web.Response: if expected_bearer and request.headers.get("Authorization") != f"Bearer {expected_bearer}": return web.Response(status=401) if expected_api_key_header: hdr_name, hdr_val = expected_api_key_header if request.headers.get(hdr_name) != hdr_val: return web.Response(status=401) if request.method == "DELETE": return web.Response(status=204) 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": "bot-test-mcp", "version": "1.0"}, }, } ) if method == "tools/list": return web.json_response( { "jsonrpc": "2.0", "id": req_id, "result": { "tools": [ { "name": "hello_world", "description": "Say hello", "inputSchema": {"type": "object", "properties": {"who": {"type": "string"}}}, } ] }, } ) if method == "tools/call": who = ((body.get("params") or {}).get("arguments") or {}).get("who", "world") return web.json_response( { "jsonrpc": "2.0", "id": req_id, "result": {"content": [{"type": "text", "text": f"Hello, {who}!"}], "isError": False}, } ) return web.json_response({"jsonrpc": "2.0", "id": req_id, "result": {}}) app = web.Application() app.router.add_route("*", "/mcp", handle_mcp) runner = web.AppRunner(app, access_log=None) await runner.setup() site = web.TCPSite(runner, "127.0.0.1", 0) await site.start() port = int(site._server.sockets[0].getsockname()[1]) # type: ignore[union-attr] return runner, f"http://127.0.0.1:{port}/mcp" def _make_mock_bot() -> AsyncMock: bot = AsyncMock(spec=Bot) bot.send_rich_message = AsyncMock() bot.send_message = AsyncMock() bot.delete_message = AsyncMock() bot.answer_callback_query = AsyncMock() bot.answer_guest_query = AsyncMock() bot.get_me = AsyncMock(return_value=MagicMock(username="homeagent_bot")) return bot def _make_message(bot: AsyncMock, user_id: int, chat_id: int, text: str, msg_id: int = 1) -> Message: user = User(id=user_id, is_bot=False, first_name="Owner", username="owner") chat = Chat(id=chat_id, type="private") msg = Message(message_id=msg_id, date=datetime.now(), chat=chat, from_user=user, text=text) msg._bot = bot return msg # ------------------------------------------------------------------------------ # Smart name derivation & free-form parsing tests # ------------------------------------------------------------------------------ def test_smart_name_derivation_and_input_parsing(): assert derive_connector_name_from_url("https://mcp.linear.app/mcp") == "linear" assert derive_connector_name_from_url("https://mcp.notion.com/sse", {"notion"}) == "notion_2" assert derive_connector_name_from_url("http://127.0.0.1:8080/weather/mcp") == "weather" assert derive_connector_name_from_url("http://127.0.0.1:8080/mcp") == "local_8080" assert derive_connector_name_from_command("npx", ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]) == "filesystem" assert derive_connector_name_from_command("uvx", ["mcp-server-git"]) == "git" assert derive_connector_name_from_command("python3", ["/opt/my_weather.py"]) == "my_weather" # Embedded URL Basic Auth cfgs, cred = parse_smart_input("https://bob:s3cr3t@mcp.acme.io/mcp") assert cred is None and len(cfgs) == 1 assert cfgs[0].name == "acme" assert cfgs[0].url == "https://mcp.acme.io/mcp" assert cfgs[0].auth.type == "basic" and cfgs[0].auth.username == "bob" and cfgs[0].auth.password == "s3cr3t" # Embedded query API key cfgs_q, _ = parse_smart_input("https://mcp.example.com/mcp?api_key=k123&other=1") assert cfgs_q[0].auth.type == "api_key" and cfgs_q[0].auth.api_key_in == "query" and cfgs_q[0].auth.api_key == "k123" assert "api_key" not in (cfgs_q[0].url or "") and "other=1" in (cfgs_q[0].url or "") # curl snippet cfgs_curl, _ = parse_smart_input('curl -H "Authorization: Bearer tok_abc" https://mcp.github.com/mcp') assert cfgs_curl[0].name == "github" assert cfgs_curl[0].auth.type == "bearer" and cfgs_curl[0].auth.token == "tok_abc" # Bare JSON without name or mcpServers wrapper cfgs_json, _ = parse_smart_input('{"url": "https://mcp.stripe.com/mcp", "headers": {"X-Api": "1"}}') assert cfgs_json[0].name == "stripe" # Stdio command with leading ENV vars cfgs_stdio, _ = parse_smart_input("GITHUB_TOKEN=ghp_1 npx -y @modelcontextprotocol/server-github") assert cfgs_stdio[0].transport == "stdio" assert cfgs_stdio[0].name == "github" assert cfgs_stdio[0].env == {"GITHUB_TOKEN": "ghp_1"} # ------------------------------------------------------------------------------ # Zero-Config Smart Connect E2E tests (user pastes ONLY URL + raw key, or ONLY URL for OAuth!) # ------------------------------------------------------------------------------ @pytest.mark.asyncio async def test_smart_connect_auto_probes_x_api_key_without_user_knowing_auth_type(tmp_path): """User clicks Add -> pastes JUST a URL -> bot detects 401 -> user pastes JUST the raw key -> bot auto-detects X-API-Key!""" runner, mcp_url = await _start_mock_mcp_server(expected_api_key_header=("X-API-Key", "raw-secret-key-777")) try: settings = Settings( ALLOWED_TELEGRAM_USER_IDS=[101], DATA_DIR=tmp_path, MCP_CONFIG_FILE=tmp_path / "none.json", ) registry = ToolRegistry() manager = MCPConnectorManager(settings=settings, registry=registry) agent = MagicMock() agent.chat = AsyncMock() skill_manager = SkillManager(tmp_path / "skills") router = create_bot_router(settings, agent, skill_manager, registry, mcp_manager=manager) dp = Dispatcher() wl = WhitelistMiddleware(settings) dp.message.middleware(wl) dp.callback_query.middleware(wl) dp.include_router(router) bot = _make_mock_bot() # 1. User simply sends `/mcp ` — no name, no transport, no auth type! await dp.feed_update(bot, Update(update_id=1, message=_make_message(bot, 101, 101, f"/mcp {mcp_url}", msg_id=1))) prompt_md = bot.send_rich_message.await_args.kwargs["rich_message"].markdown assert "требует авторизацию" in prompt_md # 2. User simply replies with the raw API key string (without knowing it goes into X-API-Key!) await dp.feed_update(bot, Update(update_id=2, message=_make_message(bot, 101, 101, "raw-secret-key-777", msg_id=2))) # Secret message deleted, never echoed, auth auto-detected as api_key (X-API-Key), tools registered! bot.delete_message.assert_awaited_once() reply_md = bot.send_rich_message.await_args.kwargs["rich_message"].markdown assert "подключён" in reply_md assert "X-API-Key" in reply_md assert "raw-secret-key-777" not in reply_md connectors = manager.list_connectors() assert len(connectors) == 1 conn = connectors[0] assert conn.status == "connected" assert conn.config.auth.type == "api_key" assert conn.config.auth.header_name == "X-API-Key" assert await registry.execute(conn.tools[0].registered_name, {"who": "Magic"}) == "Hello, Magic!" agent.chat.assert_not_awaited() await manager.close() finally: await runner.cleanup() @pytest.mark.asyncio async def test_smart_connect_auto_discovers_and_completes_oauth_pkce_from_url_alone(tmp_path): """User pastes ONLY a URL -> bot hits 401 -> auto-discovers OAuth + DCR -> sends login link -> user pastes redirect URL -> connected!""" oauth_state: dict[str, Any] = {"valid_tokens": set(), "issued_codes": {}} 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"]]} ) async def handle_as(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", } ) async def handle_dcr(request: web.Request) -> web.Response: return web.json_response({"client_id": "auto-dcr-client"}, status=201) async def handle_token(request: web.Request) -> web.Response: form = await request.post() verifier = form.get("code_verifier", "") challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode("ascii")).digest()).rstrip(b"=").decode("ascii") if oauth_state["issued_codes"].get(form.get("code")) != challenge: return web.json_response({"error": "invalid_grant"}, status=400) oauth_state["valid_tokens"].add("smart-oauth-tok") return web.json_response({"access_token": "smart-oauth-tok", "token_type": "Bearer", "expires_in": 3600}) async def handle_mcp(request: web.Request) -> web.Response: if request.headers.get("Authorization") != "Bearer smart-oauth-tok": return web.Response( status=401, headers={"WWW-Authenticate": f'Bearer resource_metadata="{base_url_holder["url"]}/.well-known/oauth-protected-resource"'}, ) body = await request.json() req_id = body.get("id") if req_id is None: return web.Response(status=202) if body.get("method") == "initialize": return web.json_response({"jsonrpc": "2.0", "id": req_id, "result": {"protocolVersion": "2025-03-26", "capabilities": {"tools": {}}, "serverInfo": {"name": "smart-oauth"}}}) if body.get("method") == "tools/list": return web.json_response({"jsonrpc": "2.0", "id": req_id, "result": {"tools": [{"name": "ping", "description": "Ping", "inputSchema": {"type": "object", "properties": {}}}]}}) return web.json_response({"jsonrpc": "2.0", "id": req_id, "result": {"content": [{"type": "text", "text": "oauth-ok"}], "isError": False}}) 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) app.router.add_post("/oauth/register", handle_dcr) app.router.add_post("/oauth/token", handle_token) app.router.add_route("*", "/mcp", handle_mcp) runner = web.AppRunner(app, access_log=None) await runner.setup() site = web.TCPSite(runner, "127.0.0.1", 0) await site.start() port = int(site._server.sockets[0].getsockname()[1]) # type: ignore[union-attr] base_url = f"http://127.0.0.1:{port}" base_url_holder["url"] = base_url try: settings = Settings(ALLOWED_TELEGRAM_USER_IDS=[102], DATA_DIR=tmp_path, MCP_CONFIG_FILE=tmp_path / "none.json") registry = ToolRegistry() manager = MCPConnectorManager(settings=settings, registry=registry) agent = MagicMock() agent.chat = AsyncMock() router = create_bot_router(settings, agent, SkillManager(tmp_path / "skills"), registry, mcp_manager=manager) dp = Dispatcher() dp.include_router(router) bot = _make_mock_bot() # Step 1: User taps Add (/mcp add) then pastes ONLY the URL await dp.feed_update(bot, Update(update_id=1, message=_make_message(bot, 102, 102, "/mcp add", msg_id=1))) assert "Быстрое подключение MCP" in bot.send_rich_message.await_args.kwargs["rich_message"].markdown await dp.feed_update(bot, Update(update_id=2, message=_make_message(bot, 102, 102, f"{base_url}/mcp", msg_id=2))) oauth_md = bot.send_rich_message.await_args.kwargs["rich_message"].markdown assert "OAuth-вход" in oauth_md assert "/oauth/authorize" in oauth_md # Extract authorize URL from bot reply and simulate browser redirect auth_line = [ln for ln in oauth_md.splitlines() if "/oauth/authorize" in ln][0].strip() qs = parse_qs(urlparse(auth_line).query) oauth_state["issued_codes"]["code-999"] = qs["code_challenge"][0] redirect_url = f"{qs['redirect_uri'][0]}?code=code-999&state={qs['state'][0]}" # Step 2: User simply pastes the redirect URL back in chat! await dp.feed_update(bot, Update(update_id=3, message=_make_message(bot, 102, 102, redirect_url, msg_id=3))) done_md = bot.send_rich_message.await_args.kwargs["rich_message"].markdown assert "подключён" in done_md conn = manager.list_connectors()[0] assert conn.status == "connected" assert await registry.execute(conn.tools[0].registered_name, {}) == "oauth-ok" agent.chat.assert_not_awaited() await manager.close() finally: await runner.cleanup() @pytest.mark.asyncio async def test_smart_connect_stdio_command_directly(tmp_path): """User sends `/mcp python script.py` directly without knowing about stdio transport.""" script = tmp_path / "echo_mcp.py" script.write_text( textwrap.dedent( """ import json, sys for line in sys.stdin: msg = json.loads(line) if "id" not in msg or msg["id"] is None: continue m = msg.get("method") if m == "initialize": res = {"protocolVersion": "2025-03-26", "capabilities": {"tools": {}}, "serverInfo": {"name": "echo"}} elif m == "tools/list": res = {"tools": [{"name": "hi", "description": "Hi", "inputSchema": {"type": "object", "properties": {}}}]} else: res = {"content": [{"type": "text", "text": "stdio-magic"}], "isError": False} sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": res}) + "\\n") sys.stdout.flush() """ ).strip() + "\n", encoding="utf-8", ) settings = Settings(ALLOWED_TELEGRAM_USER_IDS=[103], DATA_DIR=tmp_path, MCP_CONFIG_FILE=tmp_path / "none.json") registry = ToolRegistry() manager = MCPConnectorManager(settings=settings, registry=registry) agent = MagicMock() agent.chat = AsyncMock() router = create_bot_router(settings, agent, SkillManager(tmp_path / "skills"), registry, mcp_manager=manager) dp = Dispatcher() dp.include_router(router) bot = _make_mock_bot() await dp.feed_update(bot, Update(update_id=1, message=_make_message(bot, 103, 103, f"/mcp {sys.executable} {script}", msg_id=1))) md = bot.send_rich_message.await_args.kwargs["rich_message"].markdown assert "подключён" in md assert registry.get("mcp_echo_mcp_hi") is not None assert await registry.execute("mcp_echo_mcp_hi", {}) == "stdio-magic" await manager.close() # ------------------------------------------------------------------------------ # Explicit CLI, Manual Wizard, Callback Whitelist, and Ghost Mode tests # ------------------------------------------------------------------------------ @pytest.mark.asyncio async def test_bot_mcp_quick_add_tools_and_remove(tmp_path): runner, mcp_url = await _start_mock_mcp_server(expected_bearer="super-secret-token-999") try: settings = Settings( ALLOWED_TELEGRAM_USER_IDS=[111], DATA_DIR=tmp_path, MCP_CONFIG_FILE=tmp_path / "none.json", ) registry = ToolRegistry() manager = MCPConnectorManager(settings=settings, registry=registry) agent = MagicMock() agent.chat = AsyncMock(return_value="should not be called") skill_manager = SkillManager(tmp_path / "skills") router = create_bot_router(settings, agent, skill_manager, registry, mcp_manager=manager) dp = Dispatcher() wl = WhitelistMiddleware(settings) dp.message.middleware(wl) dp.callback_query.middleware(wl) dp.include_router(router) bot = _make_mock_bot() # 1. Explicit `/mcp add demo bearer ` still works msg = _make_message(bot, 111, 111, f"/mcp add demo {mcp_url} bearer super-secret-token-999", msg_id=10) await dp.feed_update(bot, Update(update_id=1, message=msg)) bot.delete_message.assert_awaited_once() sent_md = bot.send_rich_message.await_args.kwargs["rich_message"].markdown assert "demo" in sent_md assert "подключён" in sent_md assert "super-secret-token-999" not in sent_md assert registry.get("mcp_demo_hello_world") is not None assert await registry.execute("mcp_demo_hello_world", {"who": "Telegram"}) == "Hello, Telegram!" # 2. /mcp tools demo bot.send_rich_message.reset_mock() msg_tools = _make_message(bot, 111, 111, "/mcp tools demo", msg_id=11) await dp.feed_update(bot, Update(update_id=2, message=msg_tools)) tools_md = bot.send_rich_message.await_args.kwargs["rich_message"].markdown assert "mcp_demo_hello_world" in tools_md # 3. /mcp remove demo bot.send_rich_message.reset_mock() msg_rm = _make_message(bot, 111, 111, "/mcp remove demo", msg_id=12) await dp.feed_update(bot, Update(update_id=3, message=msg_rm)) assert registry.get("mcp_demo_hello_world") is None assert manager.get_connector("demo") is None agent.chat.assert_not_awaited() await manager.close() finally: await runner.cleanup() @pytest.mark.asyncio async def test_bot_mcp_manual_wizard_and_callback_whitelist(tmp_path): runner, mcp_url = await _start_mock_mcp_server(expected_bearer="wiz-secret-123456") try: settings = Settings( ALLOWED_TELEGRAM_USER_IDS=[222], DATA_DIR=tmp_path, MCP_CONFIG_FILE=tmp_path / "none.json", ) registry = ToolRegistry() manager = MCPConnectorManager(settings=settings, registry=registry) agent = MagicMock() agent.chat = AsyncMock(return_value="agent reply") skill_manager = SkillManager(tmp_path / "skills") router = create_bot_router(settings, agent, skill_manager, registry, mcp_manager=manager) dp = Dispatcher() wl = WhitelistMiddleware(settings) dp.message.middleware(wl) dp.callback_query.middleware(wl) dp.include_router(router) bot = _make_mock_bot() # Unauthorized callback query must be silently blocked by WhitelistMiddleware! stranger = User(id=999, is_bot=False, first_name="Stranger") base_msg = _make_message(bot, 222, 222, "/mcp", msg_id=1) unauth_cb = CallbackQuery( id="cb-unauth", from_user=stranger, chat_instance="inst", message=base_msg, data="mcp:add", ) unauth_cb._bot = bot await dp.feed_update(bot, Update(update_id=10, callback_query=unauth_cb)) bot.send_rich_message.assert_not_awaited() # Authorized user starts manual wizard via /mcp wizard owner = User(id=222, is_bot=False, first_name="Owner") await dp.feed_update(bot, Update(update_id=11, message=_make_message(bot, 222, 222, "/mcp wizard", msg_id=2))) assert "Шаг 1/5" in bot.send_rich_message.await_args.kwargs["rich_message"].markdown await dp.feed_update(bot, Update(update_id=12, message=_make_message(bot, 222, 222, "my_wiz", msg_id=3))) assert "Шаг 2/5" in bot.send_rich_message.await_args.kwargs["rich_message"].markdown cb_transport = CallbackQuery( id="cb-wt", from_user=owner, chat_instance="inst", message=base_msg, data="mcp:wt:streamable_http", ) cb_transport._bot = bot await dp.feed_update(bot, Update(update_id=13, callback_query=cb_transport)) assert "Шаг 3/5" in bot.send_rich_message.await_args.kwargs["rich_message"].markdown await dp.feed_update(bot, Update(update_id=14, message=_make_message(bot, 222, 222, mcp_url, msg_id=4))) assert "Шаг 4/5" in bot.send_rich_message.await_args.kwargs["rich_message"].markdown cb_auth = CallbackQuery( id="cb-wa", from_user=owner, chat_instance="inst", message=base_msg, data="mcp:wa:bearer", ) cb_auth._bot = bot await dp.feed_update(bot, Update(update_id=15, callback_query=cb_auth)) assert "Шаг 5/5" in bot.send_rich_message.await_args.kwargs["rich_message"].markdown await dp.feed_update(bot, Update(update_id=16, message=_make_message(bot, 222, 222, "wiz-secret-123456", msg_id=5))) final_md = bot.send_rich_message.await_args.kwargs["rich_message"].markdown assert "my_wiz" in final_md assert "подключён" in final_md assert "wiz-secret-123456" not in final_md assert registry.get("mcp_my_wiz_hello_world") is not None agent.chat.assert_not_awaited() await manager.close() finally: await runner.cleanup() @pytest.mark.asyncio async def test_bot_mcp_ghost_mode_command(tmp_path): settings = Settings( GHOST_MODE_ENABLED=True, ALLOWED_TELEGRAM_USER_IDS=[333], DATA_DIR=tmp_path, MCP_CONFIG_FILE=tmp_path / "none.json", ) registry = ToolRegistry() manager = MCPConnectorManager(settings=settings, registry=registry) agent = MagicMock() agent.chat = AsyncMock() skill_manager = SkillManager(tmp_path / "skills") router = create_bot_router(settings, agent, skill_manager, registry, mcp_manager=manager) dp = Dispatcher() dp.include_router(router) bot = _make_mock_bot() caller = User(id=333, is_bot=False, first_name="Owner") guest_msg = Message( message_id=1, date=datetime.now(), chat=Chat(id=-100555, type="group"), from_user=caller, text="@homeagent_bot /mcp list", guest_query_id="gq_mcp_list", guest_bot_caller_user=caller, ) guest_msg._bot = bot await dp.feed_update(bot, Update(update_id=20, guest_message=guest_msg)) bot.answer_guest_query.assert_awaited_once() sent = bot.answer_guest_query.await_args.kwargs["result"].input_message_content.rich_message.markdown assert "MCP Коннекторы" in sent agent.chat.assert_not_awaited() await manager.close() @pytest.mark.asyncio async def test_agent_builtin_mcp_tools_and_cimd_oauth_flow(tmp_path): """LLM agent can connect & authenticate MCP servers via built-in mcp_connect/mcp_provide_auth tools (including CIMD OAuth like Zenmoney).""" base_url_holder = {"url": ""} valid_tokens: set[str] = set() 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": ["all"], } ) async def handle_as(request: web.Request) -> web.Response: u = base_url_holder["url"] return web.json_response( { "issuer": u, "authorization_endpoint": f"{u}/oauth2/authorize/", "token_endpoint": f"{u}/oauth2/token/", "client_id_metadata_document_supported": True, "code_challenge_methods_supported": ["S256"], } ) async def handle_mcp(request: web.Request) -> web.Response: auth_hdr = request.headers.get("Authorization", "") if auth_hdr not in {f"Bearer {t}" for t in valid_tokens}: return web.Response( status=401, headers={ "WWW-Authenticate": f'Bearer resource_metadata="{base_url_holder["url"]}/.well-known/oauth-protected-resource/mcp", scope="all"' }, ) body = await request.json() req_id = body.get("id") if req_id is None: return web.Response(status=202) if body.get("method") == "initialize": return web.json_response( {"jsonrpc": "2.0", "id": req_id, "result": {"protocolVersion": "2025-03-26", "capabilities": {"tools": {}}, "serverInfo": {"name": "zen-mock"}}} ) if body.get("method") == "tools/list": return web.json_response( {"jsonrpc": "2.0", "id": req_id, "result": {"tools": [{"name": "get_balance", "description": "Get balance", "inputSchema": {"type": "object", "properties": {}}}]}} ) return web.json_response( {"jsonrpc": "2.0", "id": req_id, "result": {"content": [{"type": "text", "text": "1000 RUB"}], "isError": False}} ) app = web.Application() app.router.add_get("/.well-known/oauth-protected-resource/mcp", handle_prm) app.router.add_get("/.well-known/oauth-authorization-server", handle_as) app.router.add_route("*", "/mcp", handle_mcp) runner = web.AppRunner(app, access_log=None) await runner.setup() site = web.TCPSite(runner, "127.0.0.1", 0) await site.start() port = int(site._server.sockets[0].getsockname()[1]) # type: ignore[union-attr] base_url = f"http://127.0.0.1:{port}" base_url_holder["url"] = base_url try: # Case 1: Without MCP_OAUTH_CLIENT_METADATA_URL -> agent gets clear CIMD/token instructions, then authenticates with token registry = ToolRegistry() settings = Settings(DATA_DIR=tmp_path / "case1", MCP_CONFIG_FILE=tmp_path / "none.json") manager = MCPConnectorManager(settings=settings, registry=registry) assert registry.get("mcp_connect") is not None assert registry.get("mcp_provide_auth") is not None res1 = await registry.execute("mcp_connect", {"source": f"zenmoney {base_url}/mcp"}) assert "Client ID Metadata Document" in res1 assert "mcp_provide_auth" in res1 valid_tokens.add("zen-personal-tok") res2 = await registry.execute("mcp_provide_auth", {"connector_name": "zenmoney", "credential_or_url": "zen-personal-tok"}) assert "авторизован и подключён" in res2 assert await registry.execute("mcp_zenmoney_get_balance", {}) == "1000 RUB" list_out = await registry.execute("mcp_list_connectors", {}) assert "zenmoney" in list_out and "connected" in list_out await registry.execute("mcp_remove_connector", {"connector_name": "zenmoney"}) assert registry.get("mcp_zenmoney_get_balance") is None await manager.close() # Case 2: With MCP_OAUTH_CLIENT_METADATA_URL -> auto-starts OAuth 2.1 PKCE using CIMD URL as client_id! registry2 = ToolRegistry() settings2 = Settings( DATA_DIR=tmp_path / "case2", MCP_CONFIG_FILE=tmp_path / "none.json", MCP_OAUTH_CLIENT_METADATA_URL="https://example.org/homeagent-client.json", ) manager2 = MCPConnectorManager(settings=settings2, registry=registry2) res_cimd = await registry2.execute("mcp_connect", {"source": f"zenmoney {base_url}/mcp"}) assert "oauth2/authorize/" in res_cimd assert "client_id=https%3A%2F%2Fexample.org%2Fhomeagent-client.json" in res_cimd assert "scope=all" in res_cimd # Case 3: Persisting default_client_metadata_url via set_default_client_metadata_url survives restart manager2.set_default_client_metadata_url("https://example.org/custom-client.json") settings3 = Settings(DATA_DIR=tmp_path / "case2", MCP_CONFIG_FILE=tmp_path / "none.json") manager3 = MCPConnectorManager(settings=settings3, registry=ToolRegistry()) assert manager3.auth_manager.default_client_metadata_url == "https://example.org/custom-client.json" await manager2.close() await manager3.close() finally: await runner.cleanup()