knowledge-platform/tests/integration/test_mcp_server.py
2026-09-02 16:39:26 +08:00

228 lines
8.4 KiB
Python

"""Protocol-level tests for authenticated WorkBuddy-compatible MCP search."""
import asyncio
from dataclasses import dataclass, field
from unittest.mock import patch
from uuid import uuid4
import httpx2
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client
from mcp_types import CallToolResult
from pydantic import AnyHttpUrl, SecretStr
from ekp_core.config import Settings
from ekp_mcp.auth import McpIdentity
from ekp_mcp.search import McpSearchResponse, McpSourceResponse
from ekp_mcp.server import McpConfigurationError, create_mcp_http_app, create_mcp_server
@dataclass(slots=True)
class RecordingSearchApplication:
"""Capture the authenticated identity observed at the business boundary."""
calls: list[tuple[McpIdentity, str, int]] = field(default_factory=list)
failure: Exception | None = None
empty: bool = False
def search(self, identity: McpIdentity, query: str, top_k: int) -> McpSearchResponse:
self.calls.append((identity, query, top_k))
if self.failure is not None:
raise self.failure
if self.empty:
return McpSearchResponse(results=[])
return McpSearchResponse(
results=[
McpSourceResponse(
document_id=uuid4(),
filename="退款政策.md",
page=2,
section="退款政策",
chunk_id=uuid4(),
content="产品A退款周期为七天。",
score=0.8,
rerank_score=0.9,
)
]
)
def _settings() -> Settings:
return Settings(
app_env="test",
database_url=SecretStr("sqlite+pysqlite:///:memory:"),
mcp_auth_token=SecretStr("workbuddy-test-token-at-least-32-chars"),
mcp_public_url=AnyHttpUrl("http://testserver/mcp"),
mcp_issuer_url=AnyHttpUrl("https://identity.example.test"),
mcp_service_identity="workbuddy-team-a",
)
async def _exercise_authenticated_gateway(
search_application: RecordingSearchApplication,
arguments: dict[str, object] | None = None,
) -> tuple[list[str], object]:
app = create_mcp_http_app(_settings(), search_application=search_application)
transport = httpx2.ASGITransport(app=app)
async with app.router.lifespan_context(app):
async with httpx2.AsyncClient(
transport=transport,
base_url="http://testserver",
headers={"Authorization": "Bearer workbuddy-test-token-at-least-32-chars"},
) as client:
async with streamable_http_client(
"http://testserver/mcp",
http_client=client,
) as (read_stream, write_stream):
async with ClientSession(read_stream, write_stream) as session:
await session.initialize()
tools = await session.list_tools()
result = await session.call_tool(
"search_knowledge",
arguments or {"query": "产品A退款周期", "top_k": 1},
)
return [tool.name for tool in tools.tools], result
def test_streamable_http_discovers_only_search_and_propagates_identity() -> None:
search_application = RecordingSearchApplication()
tool_names, result = asyncio.run(_exercise_authenticated_gateway(search_application))
assert tool_names == ["search_knowledge"]
assert isinstance(result, CallToolResult)
assert result.is_error is False
structured = result.structured_content
assert structured is not None
assert structured["results"][0]["filename"] == "退款政策.md"
assert set(structured["results"][0]) == {
"document_id",
"filename",
"page",
"section",
"chunk_id",
"content",
"score",
"rerank_score",
}
identity, query, top_k = search_application.calls[0]
assert identity.client_id == "workbuddy-enterprise"
assert identity.subject == "workbuddy-team-a"
assert identity.scopes == frozenset({"knowledge:search"})
assert (query, top_k) == ("产品A退款周期", 1)
def test_streamable_http_returns_an_empty_structured_result() -> None:
search_application = RecordingSearchApplication(empty=True)
_, result = asyncio.run(_exercise_authenticated_gateway(search_application))
assert isinstance(result, CallToolResult)
assert result.is_error is False
assert result.structured_content == {"results": []}
def test_streamable_http_rejects_boolean_top_k_before_search() -> None:
search_application = RecordingSearchApplication()
_, result = asyncio.run(
_exercise_authenticated_gateway(
search_application,
{"query": "退款周期", "top_k": True},
)
)
assert isinstance(result, CallToolResult)
assert result.is_error is True
assert search_application.calls == []
def test_streamable_http_rejects_missing_and_wrong_bearer_tokens() -> None:
async def exercise() -> None:
app = create_mcp_http_app(_settings(), search_application=RecordingSearchApplication())
request = {
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": {"name": "workbuddy-compatibility-test", "version": "1.0"},
},
}
async with app.router.lifespan_context(app):
async with httpx2.AsyncClient(
transport=httpx2.ASGITransport(app=app),
base_url="http://testserver",
) as client:
missing = await client.post(
"/mcp",
json=request,
headers={"Accept": "application/json, text/event-stream"},
)
wrong = await client.post(
"/mcp",
json=request,
headers={
"Accept": "application/json, text/event-stream",
"Authorization": "Bearer wrong-token",
},
)
assert missing.status_code == 401
assert wrong.status_code == 401
assert "workbuddy-test-token-at-least-32-chars" not in missing.text + wrong.text
asyncio.run(exercise())
def test_tool_failure_is_sanitized_for_client_and_logs() -> None:
search_application = RecordingSearchApplication(
failure=RuntimeError(
"provider https://internal.example.test failed with token secret-provider-token"
)
)
with patch("ekp_mcp.server.logger.error") as log_error:
_, result = asyncio.run(_exercise_authenticated_gateway(search_application))
assert isinstance(result, CallToolResult)
assert result.is_error is True
rendered = repr(result)
assert "knowledge search failed" in rendered
assert "internal.example.test" not in rendered
assert "secret-provider-token" not in rendered
log_error.assert_called_once_with("MCP knowledge search failed")
def test_transport_rejects_unapproved_origin() -> None:
async def exercise() -> None:
app = create_mcp_http_app(_settings(), search_application=RecordingSearchApplication())
async with app.router.lifespan_context(app):
async with httpx2.AsyncClient(
transport=httpx2.ASGITransport(app=app),
base_url="http://testserver",
) as client:
response = await client.post(
"/mcp",
json={"jsonrpc": "2.0", "id": 1, "method": "ping"},
headers={
"Accept": "application/json, text/event-stream",
"Authorization": "Bearer workbuddy-test-token-at-least-32-chars",
"Origin": "https://unapproved.example.test",
},
)
assert response.status_code == 403
asyncio.run(exercise())
def test_gateway_requires_a_strong_runtime_token() -> None:
settings = _settings().model_copy(update={"mcp_auth_token": SecretStr("short")})
try:
create_mcp_server(settings, search_application=RecordingSearchApplication())
except McpConfigurationError as error:
assert "32 characters" in str(error)
else: # pragma: no cover - defensive assertion for fail-open regressions.
raise AssertionError("MCP gateway accepted a weak runtime token")