make mcp connector more simple

This commit is contained in:
timka123 committed 2026-11-23 16:54:35 +03:00
1 parent 9ac0d1aa63
commit 3777ca71eb
7 files changed
+1644 -191

No files matched your search

+282 -14
View File
@@ -1,9 +1,16 @@
"""Tests for MCP Connectors Telegram Bot interface: commands, inline callbacks, wizard, ghost mode, whitelist."""
"""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
@@ -13,15 +20,28 @@ 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) -> tuple[web.AppRunner, str]:
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()
@@ -89,7 +109,7 @@ def _make_mock_bot() -> AsyncMock:
return bot
def _make_message(bot: MagicMock, user_id: int, chat_id: int, text: str, msg_id: int = 1) -> Message:
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)
@@ -97,6 +117,261 @@ def _make_message(bot: MagicMock, user_id: int, chat_id: int, text: str, msg_id:
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 <url>` — 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")
@@ -120,11 +395,10 @@ async def test_bot_mcp_quick_add_tools_and_remove(tmp_path):
dp.include_router(router)
bot = _make_mock_bot()
# 1. /mcp add with bearer token
# 1. Explicit `/mcp add demo <url> bearer <token>` 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))
# Should attempt to delete secret message and never echo raw token
bot.delete_message.assert_awaited_once()
sent_md = bot.send_rich_message.await_args.kwargs["rich_message"].markdown
assert "demo" in sent_md
@@ -154,7 +428,7 @@ async def test_bot_mcp_quick_add_tools_and_remove(tmp_path):
@pytest.mark.asyncio
async def test_bot_mcp_interactive_wizard_and_callback_whitelist(tmp_path):
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(
@@ -190,16 +464,14 @@ async def test_bot_mcp_interactive_wizard_and_callback_whitelist(tmp_path):
await dp.feed_update(bot, Update(update_id=10, callback_query=unauth_cb))
bot.send_rich_message.assert_not_awaited()
# Authorized user starts wizard via /mcp add
# 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 add", msg_id=2)))
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
# Step 1: connector name (must be intercepted by wizard, NOT sent to agent.chat!)
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
# Step 2: pick transport via inline button callback
cb_transport = CallbackQuery(
id="cb-wt",
from_user=owner,
@@ -211,11 +483,9 @@ async def test_bot_mcp_interactive_wizard_and_callback_whitelist(tmp_path):
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
# Step 3: send URL
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
# Step 4: pick Bearer auth via inline button callback
cb_auth = CallbackQuery(
id="cb-wa",
from_user=owner,
@@ -227,7 +497,6 @@ async def test_bot_mcp_interactive_wizard_and_callback_whitelist(tmp_path):
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
# Step 5: send Bearer token -> saves, connects, registers tools!
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
@@ -235,7 +504,6 @@ async def test_bot_mcp_interactive_wizard_and_callback_whitelist(tmp_path):
assert "wiz-secret-123456" not in final_md
assert registry.get("mcp_my_wiz_hello_world") is not None
# Agent was never mistakenly invoked during wizard steps
agent.chat.assert_not_awaited()
await manager.close()
finally: