add mcp servers
This commit is contained in:
30 files changed
+8070
-21
No files matched your search
@@ -1,5 +1,6 @@
|
||||
"""Unit tests for agent factory."""
|
||||
|
||||
from homeagent.agent.antigravity import AntigravityAgent
|
||||
from homeagent.agent.factory import create_agent
|
||||
from homeagent.agent.gemini import GeminiAgent
|
||||
from homeagent.agent.openai_agent import OpenAIAgent
|
||||
@@ -39,3 +40,20 @@ def test_factory_creates_openai_compatible(tmp_path):
|
||||
assert agent.provider == "openai"
|
||||
assert agent.base_url == "https://openrouter.ai/api/v1"
|
||||
assert agent.model == "deepseek/deepseek-chat"
|
||||
|
||||
|
||||
def test_factory_creates_antigravity(tmp_path):
|
||||
settings = Settings(
|
||||
LLM_PROVIDER="antigravity",
|
||||
ANTIGRAVITY_MODEL="claude-sonnet-5-5-high",
|
||||
ANTIGRAVITY_SUBAGENT_MODEL="gemini-3.8-flash-medium",
|
||||
DATA_DIR=tmp_path,
|
||||
)
|
||||
agent = create_agent(settings=settings)
|
||||
assert isinstance(agent, AntigravityAgent)
|
||||
assert agent.provider == "antigravity"
|
||||
assert agent.model == "claude-sonnet-5-5-high"
|
||||
assert agent.subagent_model == "gemini-3.8-flash-medium"
|
||||
assert settings.get_active_provider_name() == "Antigravity"
|
||||
assert settings.get_active_model() == "claude-sonnet-5-5-high"
|
||||
assert settings.get_active_subagent_model() == "gemini-3.8-flash-medium"
|
||||
@@ -0,0 +1,500 @@
|
||||
"""Unit tests for AntigravityAgent, MCPToolBridge, and Antigravity SubagentRunner."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from typing import Any, Optional
|
||||
from unittest.mock import patch
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from homeagent.agent.antigravity import (
|
||||
AntigravityAgent,
|
||||
_format_cli_error,
|
||||
_parse_models_output,
|
||||
_strip_mcp_tool_prefix,
|
||||
)
|
||||
from homeagent.agent.conversation import ConversationManager
|
||||
from homeagent.agent.mcp_bridge import MCPToolBridge, normalize_mcp_schema
|
||||
from homeagent.agent.subagent import SubagentRunner
|
||||
from homeagent.config import Settings
|
||||
from homeagent.tools.base import tool
|
||||
from homeagent.tools.registry import ToolRegistry
|
||||
|
||||
|
||||
class FakeStreamReader:
|
||||
"""Async line reader mimicking asyncio.StreamReader for mocked subprocess stdout."""
|
||||
|
||||
def __init__(self, lines: list[bytes]) -> None:
|
||||
self._lines = list(lines)
|
||||
|
||||
async def readline(self) -> bytes:
|
||||
if not self._lines:
|
||||
return b""
|
||||
return self._lines.pop(0)
|
||||
|
||||
async def read(self) -> bytes:
|
||||
data = b"".join(self._lines)
|
||||
self._lines.clear()
|
||||
return data
|
||||
|
||||
|
||||
class FakeProcess:
|
||||
"""Minimal asyncio subprocess stub."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
stdout_lines: list[str],
|
||||
stderr_text: str = "",
|
||||
returncode: int = 0,
|
||||
) -> None:
|
||||
self.stdout = FakeStreamReader([(line + "\n").encode("utf-8") for line in stdout_lines])
|
||||
self.stderr = FakeStreamReader([stderr_text.encode("utf-8")] if stderr_text else [])
|
||||
self.returncode = returncode
|
||||
self._stdout_raw = "\n".join(stdout_lines).encode("utf-8")
|
||||
self._stderr_raw = stderr_text.encode("utf-8")
|
||||
self.killed = False
|
||||
|
||||
async def wait(self) -> int:
|
||||
return self.returncode
|
||||
|
||||
async def communicate(self) -> tuple[bytes, bytes]:
|
||||
return self._stdout_raw, self._stderr_raw
|
||||
|
||||
def kill(self) -> None:
|
||||
self.killed = True
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# MCPToolBridge tests
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_normalize_mcp_schema_strips_nullable_recursively():
|
||||
schema = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"category": {"type": "string", "nullable": True, "description": "Optional category"},
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": {"type": "string", "nullable": True},
|
||||
},
|
||||
},
|
||||
}
|
||||
normalized = normalize_mcp_schema(schema)
|
||||
assert "nullable" not in normalized["properties"]["category"]
|
||||
assert "nullable" not in normalized["properties"]["items"]["items"]
|
||||
assert normalized["properties"]["category"]["type"] == "string"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mcp_tool_bridge_protocol_and_auth(tmp_path):
|
||||
registry = ToolRegistry()
|
||||
|
||||
@tool(description="Add two numbers")
|
||||
async def add_numbers(a: int, b: int, label: Optional[str] = None) -> str:
|
||||
return f"{label or 'sum'}={a + b}"
|
||||
|
||||
@tool(description="Spawn subagent")
|
||||
async def spawn_subagent(task: str) -> str:
|
||||
return f"spawned:{task}"
|
||||
|
||||
registry.register(add_numbers)
|
||||
registry.register(spawn_subagent)
|
||||
|
||||
bridge = MCPToolBridge(registry)
|
||||
await bridge.ensure_started()
|
||||
try:
|
||||
url = bridge.get_endpoint_url(subagent=False)
|
||||
sub_url = bridge.get_endpoint_url(subagent=True)
|
||||
headers = {"Authorization": f"Bearer {bridge.token}"}
|
||||
|
||||
async with httpx.AsyncClient(trust_env=False) as client:
|
||||
# 1. Rejects missing/invalid auth
|
||||
unauth = await client.post(url, json={"jsonrpc": "2.0", "id": 1, "method": "ping"})
|
||||
assert unauth.status_code == 401
|
||||
|
||||
# 2. GET returns 405, DELETE returns 204
|
||||
assert (await client.get(url, headers=headers)).status_code == 405
|
||||
assert (await client.delete(url, headers=headers)).status_code == 204
|
||||
|
||||
# 3. initialize handshake
|
||||
init_resp = await client.post(
|
||||
url,
|
||||
headers=headers,
|
||||
json={
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "initialize",
|
||||
"params": {"protocolVersion": "2025-03-26"},
|
||||
},
|
||||
)
|
||||
assert init_resp.status_code == 200
|
||||
init_data = init_resp.json()["result"]
|
||||
assert init_data["protocolVersion"] == "2025-03-26"
|
||||
assert init_data["serverInfo"]["name"] == "homeagent"
|
||||
|
||||
# 4. notifications/initialized -> 202
|
||||
notif_resp = await client.post(
|
||||
url,
|
||||
headers=headers,
|
||||
json={"jsonrpc": "2.0", "method": "notifications/initialized"},
|
||||
)
|
||||
assert notif_resp.status_code == 202
|
||||
|
||||
# 5. tools/list on main includes both; subagent excludes spawn_subagent
|
||||
main_tools = (
|
||||
await client.post(url, headers=headers, json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
|
||||
).json()["result"]["tools"]
|
||||
assert {t["name"] for t in main_tools} == {"add_numbers", "spawn_subagent"}
|
||||
|
||||
sub_tools = (
|
||||
await client.post(sub_url, headers=headers, json={"jsonrpc": "2.0", "id": 3, "method": "tools/list"})
|
||||
).json()["result"]["tools"]
|
||||
assert {t["name"] for t in sub_tools} == {"add_numbers"}
|
||||
|
||||
# 6. tools/call executes registered tool
|
||||
call_resp = await client.post(
|
||||
url,
|
||||
headers=headers,
|
||||
json={
|
||||
"jsonrpc": "2.0",
|
||||
"id": 4,
|
||||
"method": "tools/call",
|
||||
"params": {"name": "add_numbers", "arguments": {"a": 19, "b": 23, "label": "ans"}},
|
||||
},
|
||||
)
|
||||
call_result = call_resp.json()["result"]
|
||||
assert call_result["isError"] is False
|
||||
assert call_result["content"][0]["text"] == "ans=42"
|
||||
|
||||
# 7. Calling excluded subagent tool on /mcp-subagent returns isError=True
|
||||
blocked = (
|
||||
await client.post(
|
||||
sub_url,
|
||||
headers=headers,
|
||||
json={
|
||||
"jsonrpc": "2.0",
|
||||
"id": 5,
|
||||
"method": "tools/call",
|
||||
"params": {"name": "spawn_subagent", "arguments": {"task": "recurse"}},
|
||||
},
|
||||
)
|
||||
).json()["result"]
|
||||
assert blocked["isError"] is True
|
||||
|
||||
# 8. write_mcp_config writes valid eager config
|
||||
cfg_path = bridge.write_mcp_config(tmp_path)
|
||||
cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
|
||||
server_cfg = cfg["mcpServers"]["homeagent"]
|
||||
assert server_cfg["serverUrl"] == url
|
||||
assert server_cfg["tools"]["add_numbers"] == {"eager": True}
|
||||
finally:
|
||||
await bridge.stop()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Helper parsing & formatting tests
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_parse_models_output_strips_spinner_and_ansi():
|
||||
raw = (
|
||||
"\r⠋ Fetching available models...\r⠙ Fetching available models...\r"
|
||||
"\x1b[32mgemini-4-neon-high\x1b[0m Gemini 4 Neon (High)\n"
|
||||
"claude-sonnet-5-5-high\tClaude Sonnet 5.5 (High)\n"
|
||||
"gpt-oss-120b-medium GPT-OSS 120B (Medium)\n"
|
||||
)
|
||||
parsed = _parse_models_output(raw)
|
||||
assert parsed == [
|
||||
("gemini-4-neon-high", "Gemini 4 Neon (High)"),
|
||||
("claude-sonnet-5-5-high", "Claude Sonnet 5.5 (High)"),
|
||||
("gpt-oss-120b-medium", "GPT-OSS 120B (Medium)"),
|
||||
]
|
||||
|
||||
|
||||
def test_strip_mcp_tool_prefix():
|
||||
assert _strip_mcp_tool_prefix("mcp_homeagent_calendar_today_schedule") == "calendar_today_schedule"
|
||||
assert _strip_mcp_tool_prefix("web_search") == "web_search"
|
||||
|
||||
|
||||
def test_format_cli_error_messages():
|
||||
assert "не авторизован" in _format_cli_error("authentication required", "gemini-4-neon-high")
|
||||
assert "Исчерпан лимит" in _format_cli_error("quota exceeded for model", "claude-opus-5-5-high")
|
||||
assert "недоступна" in _format_cli_error("invalid model selection", "bad-model")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# AntigravityAgent tests
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_antigravity_agent_missing_cli_returns_help(tmp_path):
|
||||
settings = Settings(
|
||||
LLM_PROVIDER="antigravity",
|
||||
ANTIGRAVITY_CLI_PATH="/nonexistent/agy-missing-bin",
|
||||
DATA_DIR=tmp_path,
|
||||
)
|
||||
agent = AntigravityAgent(settings=settings, registry=ToolRegistry(), conversation_manager=ConversationManager(tmp_path))
|
||||
reply = await agent.chat(chat_id=100, thread_id=None, user_message="Привет")
|
||||
assert "не найден" in reply
|
||||
await agent.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_antigravity_agent_chat_streams_progress_and_resumes_topic(tmp_path):
|
||||
settings = Settings(
|
||||
LLM_PROVIDER="antigravity",
|
||||
ANTIGRAVITY_MODEL="gemini-4-neon-high",
|
||||
ANTIGRAVITY_TIMEOUT_SECONDS=120,
|
||||
DATA_DIR=tmp_path,
|
||||
)
|
||||
registry = ToolRegistry()
|
||||
cm = ConversationManager(tmp_path)
|
||||
agent = AntigravityAgent(settings=settings, registry=registry, conversation_manager=cm)
|
||||
|
||||
captured_cmds: list[list[str]] = []
|
||||
turn1_events = [
|
||||
json.dumps({"event": "init", "conversation_id": "conv-aaa-111", "init": {"model": "gemini-4-neon-high"}}),
|
||||
json.dumps(
|
||||
{
|
||||
"event": "step_update",
|
||||
"step_update": {
|
||||
"conversation_id": "conv-aaa-111",
|
||||
"step_index": 1,
|
||||
"state": "ACTIVE",
|
||||
"step_type": "tool",
|
||||
"tool_name": "mcp_homeagent_calendar_today_schedule",
|
||||
"tool_info": {"name": "mcp_homeagent_calendar_today_schedule", "parameters": {}},
|
||||
},
|
||||
}
|
||||
),
|
||||
json.dumps(
|
||||
{
|
||||
"event": "step_update",
|
||||
"step_update": {
|
||||
"conversation_id": "conv-aaa-111",
|
||||
"step_index": 2,
|
||||
"state": "ACTIVE",
|
||||
"step_type": "agent_response",
|
||||
"text_delta": "Сегодня 2 встречи.",
|
||||
},
|
||||
}
|
||||
),
|
||||
json.dumps(
|
||||
{
|
||||
"event": "result",
|
||||
"result": {
|
||||
"conversation_id": "conv-aaa-111",
|
||||
"status": "SUCCESS",
|
||||
"response": "Сегодня 2 встречи.",
|
||||
"num_turns": 1,
|
||||
},
|
||||
}
|
||||
),
|
||||
]
|
||||
turn2_events = [
|
||||
json.dumps(
|
||||
{
|
||||
"event": "result",
|
||||
"result": {
|
||||
"conversation_id": "conv-aaa-111",
|
||||
"status": "SUCCESS",
|
||||
"response": "Первая в 10:00.",
|
||||
"num_turns": 2,
|
||||
},
|
||||
}
|
||||
)
|
||||
]
|
||||
turn3_after_reset_events = [
|
||||
json.dumps(
|
||||
{
|
||||
"event": "result",
|
||||
"result": {
|
||||
"conversation_id": "conv-bbb-222",
|
||||
"status": "SUCCESS",
|
||||
"response": "Новый диалог!",
|
||||
"num_turns": 1,
|
||||
},
|
||||
}
|
||||
)
|
||||
]
|
||||
procs = [
|
||||
FakeProcess(turn1_events),
|
||||
FakeProcess(turn2_events),
|
||||
FakeProcess(turn3_after_reset_events),
|
||||
]
|
||||
|
||||
async def fake_exec(*cmd: str, **kwargs: Any) -> FakeProcess:
|
||||
captured_cmds.append(list(cmd))
|
||||
return procs.pop(0)
|
||||
|
||||
progress_updates: list[str] = []
|
||||
|
||||
async def on_progress(text: str) -> None:
|
||||
progress_updates.append(text)
|
||||
|
||||
try:
|
||||
with (
|
||||
patch("homeagent.agent.antigravity._resolve_cli_binary", return_value="/usr/bin/agy"),
|
||||
patch("asyncio.create_subprocess_exec", side_effect=fake_exec),
|
||||
):
|
||||
# Turn 1: fresh session
|
||||
res1 = await agent.chat(chat_id=-1001, thread_id=5, user_message="Что сегодня?", on_progress=on_progress)
|
||||
assert res1 == "Сегодня 2 встречи."
|
||||
assert "--conversation" not in captured_cmds[0]
|
||||
assert "--model" in captured_cmds[0] and "gemini-4-neon-high" in captured_cmds[0]
|
||||
assert any("Проверяю расписание на сегодня" in p for p in progress_updates)
|
||||
|
||||
# Turn 2: resumes conversation_id conv-aaa-111
|
||||
res2 = await agent.chat(chat_id=-1001, thread_id=5, user_message="Во сколько первая?")
|
||||
assert res2 == "Первая в 10:00."
|
||||
assert "--conversation" in captured_cmds[1]
|
||||
cid_idx = captured_cmds[1].index("--conversation") + 1
|
||||
assert captured_cmds[1][cid_idx] == "conv-aaa-111"
|
||||
|
||||
# Verify ConversationManager also persisted messages
|
||||
msgs = cm.get_openai_messages(-1001, 5)
|
||||
assert len(msgs) == 4
|
||||
assert msgs[-1]["content"] == "Первая в 10:00."
|
||||
|
||||
# /reset via conversation_manager.clear() must reset Antigravity session too!
|
||||
cm.clear(-1001, 5)
|
||||
res3 = await agent.chat(chat_id=-1001, thread_id=5, user_message="Начнем сначала")
|
||||
assert res3 == "Новый диалог!"
|
||||
assert "--conversation" not in captured_cmds[2]
|
||||
finally:
|
||||
await agent.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_antigravity_agent_retries_when_saved_conversation_is_stale(tmp_path):
|
||||
settings = Settings(LLM_PROVIDER="antigravity", DATA_DIR=tmp_path)
|
||||
cm = ConversationManager(tmp_path)
|
||||
cm.append_openai_turn_sequence(
|
||||
10,
|
||||
None,
|
||||
[
|
||||
{"role": "user", "content": "Старый вопрос"},
|
||||
{"role": "assistant", "content": "Старый ответ"},
|
||||
],
|
||||
)
|
||||
agent = AntigravityAgent(settings=settings, registry=ToolRegistry(), conversation_manager=cm)
|
||||
agent._conversation_ids[agent._topic_key(10, None)] = "stale-conv-id"
|
||||
|
||||
cmds: list[list[str]] = []
|
||||
procs = [
|
||||
FakeProcess(
|
||||
[
|
||||
json.dumps(
|
||||
{
|
||||
"event": "result",
|
||||
"result": {
|
||||
"conversation_id": "",
|
||||
"status": "ERROR",
|
||||
"response": "",
|
||||
"error": "conversation not found: stale-conv-id",
|
||||
},
|
||||
}
|
||||
)
|
||||
],
|
||||
returncode=1,
|
||||
),
|
||||
FakeProcess(
|
||||
[
|
||||
json.dumps(
|
||||
{
|
||||
"event": "result",
|
||||
"result": {
|
||||
"conversation_id": "fresh-conv-id",
|
||||
"status": "SUCCESS",
|
||||
"response": "Восстановленный ответ",
|
||||
},
|
||||
}
|
||||
)
|
||||
],
|
||||
returncode=0,
|
||||
),
|
||||
]
|
||||
|
||||
async def fake_exec(*cmd: str, **kwargs: Any) -> FakeProcess:
|
||||
cmds.append(list(cmd))
|
||||
return procs.pop(0)
|
||||
|
||||
try:
|
||||
with (
|
||||
patch("homeagent.agent.antigravity._resolve_cli_binary", return_value="/usr/bin/agy"),
|
||||
patch("asyncio.create_subprocess_exec", side_effect=fake_exec),
|
||||
):
|
||||
res = await agent.chat(chat_id=10, thread_id=None, user_message="Продолжаем")
|
||||
assert res == "Восстановленный ответ"
|
||||
assert len(cmds) == 2
|
||||
assert "--conversation" in cmds[0]
|
||||
assert "--conversation" not in cmds[1]
|
||||
# Carryover history should be injected into retry prompt
|
||||
retry_prompt = cmds[1][cmds[1].index("-p") + 1]
|
||||
assert "Старый вопрос" in retry_prompt
|
||||
assert agent._conversation_ids[agent._topic_key(10, None)] == "fresh-conv-id"
|
||||
finally:
|
||||
await agent.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_antigravity_agent_set_model_updates_runtime_and_settings(tmp_path):
|
||||
settings = Settings(LLM_PROVIDER="antigravity", ANTIGRAVITY_MODEL="gemini-4-neon-high", DATA_DIR=tmp_path)
|
||||
agent = AntigravityAgent(settings=settings, registry=ToolRegistry(), conversation_manager=ConversationManager(tmp_path))
|
||||
|
||||
agent.set_model("claude-opus-5-5-high")
|
||||
assert agent.model == "claude-opus-5-5-high"
|
||||
assert settings.ANTIGRAVITY_MODEL == "claude-opus-5-5-high"
|
||||
assert settings.get_active_model() == "claude-opus-5-5-high"
|
||||
await agent.close()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# SubagentRunner with Antigravity provider
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_subagent_runner_antigravity_mocked(tmp_path):
|
||||
settings = Settings(
|
||||
LLM_PROVIDER="antigravity",
|
||||
ANTIGRAVITY_SUBAGENT_MODEL="gemini-3.8-flash-medium",
|
||||
DATA_DIR=tmp_path,
|
||||
)
|
||||
registry = ToolRegistry()
|
||||
runner = SubagentRunner(settings=settings, registry=registry)
|
||||
|
||||
captured_cmd: list[str] = []
|
||||
sub_proc = FakeProcess(
|
||||
[
|
||||
json.dumps(
|
||||
{
|
||||
"conversation_id": "sub-conv-1",
|
||||
"status": "SUCCESS",
|
||||
"response": "Найдено 3 активных тикета в Jira.",
|
||||
}
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
async def fake_exec(*cmd: str, **kwargs: Any) -> FakeProcess:
|
||||
captured_cmd.extend(cmd)
|
||||
return sub_proc
|
||||
|
||||
try:
|
||||
with (
|
||||
patch("homeagent.agent.antigravity._resolve_cli_binary", return_value="/usr/bin/agy"),
|
||||
patch("asyncio.create_subprocess_exec", side_effect=fake_exec),
|
||||
):
|
||||
res = await runner.run_task(task="Проверь задачи Jira", role="Jira Specialist")
|
||||
assert res == "Найдено 3 активных тикета в Jira."
|
||||
assert "--model" in captured_cmd
|
||||
assert captured_cmd[captured_cmd.index("--model") + 1] == "gemini-3.8-flash-medium"
|
||||
finally:
|
||||
if getattr(runner, "_mcp_bridge", None) is not None:
|
||||
await runner._mcp_bridge.stop()
|
||||
@@ -0,0 +1,281 @@
|
||||
"""Tests for MCP Connectors Telegram Bot interface: commands, inline callbacks, wizard, ghost mode, whitelist."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
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.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 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 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: MagicMock, 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
|
||||
|
||||
|
||||
@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. /mcp add with bearer token
|
||||
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
|
||||
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_interactive_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 wizard via /mcp add
|
||||
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)))
|
||||
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,
|
||||
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
|
||||
|
||||
# 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,
|
||||
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
|
||||
|
||||
# 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
|
||||
assert "подключён" in final_md
|
||||
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:
|
||||
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()
|
||||
@@ -0,0 +1,781 @@
|
||||
"""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()
|
||||
Reference in new issue
Block a user