Open-source personal finance manager. Self-hosted, privacy-first.
feat(mcp): speak MCP 2026-07-28 Streamable HTTP, dual-era (#1308)
Luqmana67303b6f100
diff --git a/backend/app/agents/config.py b/backend/app/agents/config.pyindex e84c2147..4ad1c7ec 100644--- a/backend/app/agents/config.py+++ b/backend/app/agents/config.py@@ -36,6 +36,14 @@ class AgentSettings(BaseSettings):# mcp-server container publishes port 8765.mcp_external_ttl_days: int = 90+ # Browser origins allowed to call the MCP server, comma-separated. The+ # MCP spec requires servers to validate `Origin` (a DNS-rebinding guard)+ # and refuse an invalid one with 403. Legitimate callers — the agent+ # runtime, MCP gateways, desktop clients — send no `Origin` at all, so+ # the default admits no browser page. Set only for a browser-based MCP+ # client you deliberately want to allow, e.g. "https://app.example.com".+ mcp_allowed_origins: str = ""+# Embedding dimension for the knowledge_chunks vector column. Locked at# migration time. 1536 covers OpenAI text-embedding-3-small (default) and# nomic-embed-text via Matryoshka padding/truncation.diff --git a/backend/app/agents/mcp/client.py b/backend/app/agents/mcp/client.pyindex 8d4e276b..0e8c8e9c 100644--- a/backend/app/agents/mcp/client.py+++ b/backend/app/agents/mcp/client.py@@ -5,7 +5,10 @@ Per call, mints a short-lived JWT scoped to (user_id, conversation_id)."""from __future__ import annotations+import base64+import jsonimport logging+import reimport uuidfrom dataclasses import dataclassfrom typing import Any, Optional@@ -52,34 +55,178 @@ def _parse_servers() -> list[_ServerSpec]:return out+MODERN_PROTOCOL_VERSION = "2026-07-28"+CLIENT_INFO = {"name": "securo-agent-runtime", "version": "0.2.0"}+# `_meta` key the built-in server puts its per-tool extras under. Mirrors+# mcp_server.protocol.TOOL_META_KEY; not imported, because this module also+# talks to third-party servers and must not depend on the server package.+_SECURO_TOOL_META_KEY = "com.usesecuro/tool"++# JSON-RPC error codes a *modern* (2026-07-28+) server uses to refuse a+# request it did understand. Seeing one means "fix the request", never+# "fall back to the legacy protocol".+_MODERN_REFUSAL_CODES = frozenset({-32020, -32021, -32022})++_HEADER_SAFE = re.compile(r"^[\x20-\x7e\t]*$")+++def _encode_header_value(value: str) -> str:+ """The spec's `=?base64?…?=` sentinel for values unsafe as a header."""+ if _HEADER_SAFE.match(value) and value == value.strip() and not (+ value.startswith("=?base64?") and value.endswith("?=")+ ):+ return value+ return "=?base64?" + base64.b64encode(value.encode("utf-8")).decode("ascii") + "?="+++def _is_modern_refusal(status: int, data: Any) -> bool:+ """Whether a 4xx body identifies a modern MCP server.++ Per the 2026-07-28 backward-compatibility rules, a dual-era client that+ gets 400/404/405 inspects the body: a recognised modern JSON-RPC error+ means the server is modern and the request should be corrected; anything+ else — an empty body, HTML, a bare framework error — means a legacy+ server, and the client falls back.+ """+ if not isinstance(data, dict) or not isinstance(data.get("error"), dict):+ return False+ code = data["error"].get("code")+ if code in _MODERN_REFUSAL_CODES:+ return True+ # 404 + Method not found, and 400 + Invalid params (missing `_meta`),+ # are how a modern server answers; a legacy server does not send them.+ return (status == 404 and code == -32601) or (status == 400 and code == -32602)+++def _parse_sse(text: str, request_id: Any) -> Any:+ """Pull the JSON-RPC response for `request_id` out of an SSE body.++ A modern server may answer any request with a request-scoped event+ stream: optional notifications, then the response. The built-in server+ never streams, but a user-supplied one can.+ """+ data_lines: list[str] = []+ found: Any = None++ def flush() -> None:+ nonlocal found+ if not data_lines:+ return+ try:+ message = json.loads("\n".join(data_lines))+ except ValueError:+ message = None+ data_lines.clear()+ if isinstance(message, dict) and message.get("id") == request_id and (+ "result" in message or "error" in message+ ):+ found = message++ for line in text.splitlines():+ if line == "":+ flush()+ elif line.startswith("data:"):+ data_lines.append(line[5:].lstrip(" "))+ flush()+ return found++class MCPClient:- """Single-server JSON-RPC client. One instance per server URL."""+ """Single-server JSON-RPC client. One instance per server URL.++ Dual-era, as the 2026-07-28 spec recommends for clients that must work+ with servers of either generation: every request is first sent in the+ modern shape (`_meta` protocol fields plus the mirrored `MCP-Protocol-+ Version`, `Mcp-Method` and `Mcp-Name` headers). A 4xx that is not a+ modern refusal marks the server legacy, and the request is resent in the+ original plain shape. The era is remembered per instance so the probe+ happens once, not on every call.+ """def __init__(self, *, name: str, url: str):self.name = nameself.url = urlself._next_id = 0+ # None until the first exchange settles which protocol era the+ # server speaks; then "modern" or "legacy".+ self._era: Optional[str] = Nonedef _id(self) -> int:self._next_id += 1return self._next_idasync def _post(self, method: str, params: dict[str, Any], *, token: str) -> Any:+ if self._era != "legacy":+ status, data = await self._send_modern(method, params, token=token)+ if status < 400:+ self._era = "modern"+ return self._unwrap(data, modern=True)+ if _is_modern_refusal(status, data):+ self._era = "modern"+ raise RuntimeError(f"MCP {self.name} error: {data['error']}")+ if status not in (400, 404, 405):+ # Auth failures, server errors: not an era signal.+ raise RuntimeError(f"MCP {self.name} HTTP {status}")+ self._era = "legacy"+ return await self._send_legacy(method, params, token=token)++ async def _send_modern(self, method: str, params: dict[str, Any], *, token: str) -> tuple[int, Any]:+ request_id = self._id()+ body_params = dict(params)+ body_params["_meta"] = {+ **(params.get("_meta") or {}),+ "io.modelcontextprotocol/protocolVersion": MODERN_PROTOCOL_VERSION,+ "io.modelcontextprotocol/clientInfo": CLIENT_INFO,+ "io.modelcontextprotocol/clientCapabilities": {},+ }+ payload = {"jsonrpc": "2.0", "id": request_id, "method": method, "params": body_params}+ headers = {+ "Authorization": f"Bearer {token}",+ "Content-Type": "application/json",+ "Accept": "application/json, text/event-stream",+ "MCP-Protocol-Version": MODERN_PROTOCOL_VERSION,+ "Mcp-Method": method,+ }+ if method == "tools/call" and isinstance(params.get("name"), str):+ headers["Mcp-Name"] = _encode_header_value(params["name"])+ async with httpx.AsyncClient(timeout=httpx.Timeout(60.0, connect=10.0)) as client:+ resp = await client.post(self.url, json=payload, headers=headers)+ content_type = (getattr(resp, "headers", None) or {}).get("content-type", "")+ if "text/event-stream" in content_type:+ return resp.status_code, _parse_sse(resp.text, request_id)+ try:+ data = resp.json()+ except ValueError:+ data = None+ return resp.status_code, data++ async def _send_legacy(self, method: str, params: dict[str, Any], *, token: str) -> Any:payload = {"jsonrpc": "2.0", "id": self._id(), "method": method, "params": params}headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}async with httpx.AsyncClient(timeout=httpx.Timeout(60.0, connect=10.0)) as client:resp = await client.post(self.url, json=payload, headers=headers)resp.raise_for_status()data = resp.json()+ return self._unwrap(data, modern=False)++ def _unwrap(self, data: Any, *, modern: bool) -> Any:+ if not isinstance(data, dict):+ raise RuntimeError(f"MCP {self.name} returned no JSON-RPC response")if "error" in data and data["error"]:raise RuntimeError(f"MCP {self.name} error: {data['error']}")- return data.get("result")+ result = data.get("result")+ if modern and isinstance(result, dict) and result.get("resultType") == "input_required":+ # Multi round-trip requests (the server asking the client for+ # input mid-call) are not something the agent runtime can answer.+ raise RuntimeError(f"MCP {self.name} asked for client input, which is not supported")+ return resultasync def list_tools(self, *, token: str) -> list[ToolHandle]:result = await self._post("tools/list", {}, token=token)out: list[ToolHandle] = []for t in (result or {}).get("tools", []):- extras = t.get("_securo") or {}+ meta = t.get("_meta") if isinstance(t.get("_meta"), dict) else {}+ extras = meta.get(_SECURO_TOOL_META_KEY) or t.get("_securo") or {}out.append(ToolHandle(server=self.name,name=t.get("name") or "",diff --git a/backend/mcp_server/main.py b/backend/mcp_server/main.pyindex 5ce5b6a9..384e60bf 100644--- a/backend/mcp_server/main.py+++ b/backend/mcp_server/main.py@@ -1,20 +1,31 @@-"""MCP server FastAPI app. JSON-RPC 2.0 over HTTP POST /mcp.+"""MCP server FastAPI app: Streamable HTTP on a single `POST /mcp` endpoint.Exposes Securo's built-in tools (read-only + propose-mutations) over theModel Context Protocol. Runs as a separate container; gated by the`agents` profile in docker-compose.++Dual-era per the 2026-07-28 specification (see `mcp_server/protocol.py`):+modern requests carry their protocol version in `params._meta` and are+served statelessly; requests without it follow the legacy `initialize`+lifecycle. Responses are always single JSON objects — the spec lets a server+choose JSON over a per-request SSE stream, and no tool here streams progress.+There is no GET stream and no session: both were removed in 2026-07-28, so+GET/DELETE get 405 and no `Mcp-Session-Id` is ever issued."""from __future__ import annotations+import jsonimport loggingfrom typing import Any-from fastapi import FastAPI, Request+from fastapi import FastAPI, Request, Responsefrom fastapi.responses import JSONResponse+from app.agents.config import get_agent_settingsfrom app.core.database import async_session_maker+from mcp_server import protocol as pfrom mcp_server import tools as _tools_pkg # noqa: F401 triggers tool registration-from mcp_server.auth import verify_request+from mcp_server.auth import CallContext, verify_requestfrom mcp_server.registry import REGISTRY, call_tool, list_toolslogger = logging.getLogger(__name__)@@ -24,9 +35,11 @@ app = FastAPI(title="Securo MCP Server", openapi_url=None, docs_url=None)SERVER_INFO = {"name": "securo-builtin",- "version": "0.1.0",+ "version": "0.2.0",}-PROTOCOL_VERSION = "2024-11-05"+# The capability set is the same in both eras: tools, and no list-changed+# notifications (the tool set only changes with a deploy).+CAPABILITIES = {"tools": {"listChanged": False}}def _err(req_id: Any, code: int, message: str, data: Any = None) -> dict:@@ -45,9 +58,24 @@ async def health():return {"status": "ok", "tools": len(REGISTRY)}[email protected]_route("/mcp", methods=["GET", "DELETE"])+async def mcp_no_stream() -> Response:+ """2026-07-28 removed the standalone GET stream and session termination+ by DELETE. The spec asks a server that receives either to answer 405."""+ return Response(status_code=405, headers={"Allow": "POST"})++@app.post("/mcp")-async def mcp(request: Request) -> JSONResponse:- # Auth first — never accept unauthenticated calls.+async def mcp(request: Request) -> Response:+ # DNS-rebinding guard before anything else, as the transport requires.+ allowed = p.parse_allowed_origins(get_agent_settings().mcp_allowed_origins)+ if not p.origin_allowed(request.headers.get("origin"), allowed):+ return JSONResponse(+ status_code=403,+ content={"jsonrpc": "2.0", "error": {"code": p.INVALID_REQUEST, "message": "Origin not allowed"}},+ )++ # Auth next — never accept unauthenticated calls.try:ctx = verify_request(request)except Exception as exc: # HTTPException from verify_request@@ -61,59 +89,215 @@ async def mcp(request: Request) -> JSONResponse:try:body = await request.json()except Exception:- return JSONResponse(status_code=400, content=_err(None, -32700, "parse error"))+ return JSONResponse(status_code=400, content=_err(None, p.PARSE_ERROR, "parse error"))+ # One message per POST. JSON-RPC batching is not part of MCP.if not isinstance(body, dict):- return JSONResponse(status_code=400, content=_err(None, -32600, "invalid request"))+ return JSONResponse(status_code=400, content=_err(None, p.INVALID_REQUEST, "invalid request"))- req_id = body.get("id")method = body.get("method")- params = body.get("params") or {}-if body.get("jsonrpc") != "2.0" or not isinstance(method, str):- return JSONResponse(status_code=400, content=_err(req_id, -32600, "invalid request"))+ # Also catches a JSON-RPC *response*, which clients must not send.+ return JSONResponse(status_code=400, content=_err(body.get("id"), p.INVALID_REQUEST, "invalid request"))- if method == "initialize":- return JSONResponse(- content=_ok(req_id, {- "protocolVersion": PROTOCOL_VERSION,- "capabilities": {"tools": {"listChanged": False}},- "serverInfo": SERVER_INFO,- })+ if "id" not in body:+ # A notification. Nothing to act on here — the legacy+ # `notifications/initialized` included — but it must be accepted+ # with 202 and no body, never answered.+ return Response(status_code=202)++ req_id = body["id"]+ if isinstance(req_id, bool) or not isinstance(req_id, (str, int)):+ return JSONResponse(status_code=400, content=_err(None, p.INVALID_REQUEST, "request id must be a string or integer"))++ params = body.get("params")+ if params is None:+ params = {}+ if not isinstance(params, dict):+ return JSONResponse(status_code=400, content=_err(req_id, p.INVALID_PARAMS, "params must be an object"))++ meta = params.get("_meta")+ header_version = request.headers.get("mcp-protocol-version")+ is_modern = (+ (isinstance(meta, dict) and p.META_PROTOCOL_VERSION in meta)+ or header_version in p.MODERN_VERSIONS+ or method == "server/discover"+ )++ try:+ if is_modern:+ status, payload = await _serve_modern(request, ctx, req_id, method, params, header_version)+ else:+ status, payload = await _serve_legacy(ctx, req_id, method, params, header_version)+ except p.ProtocolError as exc:+ return JSONResponse(status_code=exc.status, content=exc.body())+ return JSONResponse(status_code=status, content=payload)+++# --------------------------------------------------------------------- modern+++async def _serve_modern(+ request: Request,+ ctx: CallContext,+ req_id: Any,+ method: str,+ params: dict[str, Any],+ header_version: str | None,+) -> tuple[int, dict]:+ meta = params.get("_meta")+ if not isinstance(meta, dict):+ raise p.ProtocolError(400, p.INVALID_PARAMS, "missing params._meta", request_id=req_id)+ body_version = meta.get(p.META_PROTOCOL_VERSION)+ if not isinstance(body_version, str):+ raise p.ProtocolError(400, p.INVALID_PARAMS, f"missing _meta {p.META_PROTOCOL_VERSION}", request_id=req_id)+ if not isinstance(meta.get(p.META_CLIENT_CAPABILITIES), dict):+ raise p.ProtocolError(400, p.INVALID_PARAMS, f"missing _meta {p.META_CLIENT_CAPABILITIES}", request_id=req_id)++ if header_version is None:+ raise p.header_mismatch("MCP-Protocol-Version header is required", req_id)+ if header_version != body_version:+ raise p.header_mismatch(+ f"MCP-Protocol-Version header value '{header_version}' does not match body value '{body_version}'",+ req_id,)+ if body_version not in p.MODERN_VERSIONS:+ raise p.unsupported_version(body_version, req_id)++ header_method = request.headers.get("mcp-method")+ if header_method is None:+ raise p.header_mismatch("Mcp-Method header is required", req_id)+ if header_method != method:+ raise p.header_mismatch(f"Mcp-Method header value '{header_method}' does not match body value '{method}'", req_id)++ if method not in p.MODERN_METHODS:+ # The JSON-RPC body is what tells a client this 404 comes from a+ # modern MCP server rather than a legacy HTTP+SSE one.+ return 404, _err(req_id, p.METHOD_NOT_FOUND, f"Method not found: {method}")++ result_meta = {p.META_SERVER_INFO: SERVER_INFO}++ if method == "server/discover":+ return 200, _ok(req_id, {+ "resultType": "complete",+ "supportedVersions": list(p.SUPPORTED_VERSIONS),+ "capabilities": CAPABILITIES,+ "ttlMs": p.LIST_TTL_MS,+ "cacheScope": p.LIST_CACHE_SCOPE,+ "_meta": result_meta,+ })if method == "tools/list":- return JSONResponse(content=_ok(req_id, {"tools": list_tools()}))+ return 200, _ok(req_id, {+ "resultType": "complete",+ "tools": list_tools(legacy=False),+ "ttlMs": p.LIST_TTL_MS,+ "cacheScope": p.LIST_CACHE_SCOPE,+ "_meta": result_meta,+ })++ # tools/call+ name = params.get("name")+ raw_header_name = request.headers.get("mcp-name")+ if raw_header_name is None:+ raise p.header_mismatch("Mcp-Name header is required for tools/call", req_id)+ header_name = p.decode_header_value(raw_header_name)+ if header_name is None:+ raise p.header_mismatch("Mcp-Name header value contains invalid characters", req_id)+ if not isinstance(name, str) or header_name != name:+ raise p.header_mismatch(f"Mcp-Name header value '{header_name}' does not match body value '{name}'", req_id)++ return 200, await _call_tool(ctx, req_id, name, params.get("arguments"), result_meta=result_meta)+++# --------------------------------------------------------------------- legacy+++async def _serve_legacy(+ ctx: CallContext,+ req_id: Any,+ method: str,+ params: dict[str, Any],+ header_version: str | None,+) -> tuple[int, dict]:+ # A legacy client sends the version it negotiated on every request after+ # `initialize` (2025-06-18 and later). One this server never offered is+ # refused, and the modern error body lets a dual-era client re-select.+ if header_version is not None and header_version not in p.LEGACY_VERSIONS:+ raise p.unsupported_version(header_version, req_id)++ if method == "initialize":+ requested = params.get("protocolVersion")+ negotiated = requested if requested in p.LEGACY_VERSIONS else p.LATEST_LEGACY_VERSION+ return 200, _ok(req_id, {+ "protocolVersion": negotiated,+ "capabilities": CAPABILITIES,+ "serverInfo": SERVER_INFO,+ })++ if method == "ping":+ return 200, _ok(req_id, {})++ if method == "tools/list":+ return 200, _ok(req_id, {"tools": list_tools(legacy=True)})if method == "tools/call":name = params.get("name")- arguments = params.get("arguments") or {}if not isinstance(name, str):- return JSONResponse(content=_err(req_id, -32602, "tools/call requires 'name'"))- try:- async with async_session_maker() as session:- result = await call_tool(session, ctx, name, arguments)- # MCP wraps tool output in `content` blocks. Use the structured- # variant — many clients (and our own runtime) prefer JSON.- return JSONResponse(content=_ok(req_id, {- "content": [{"type": "text", "text": _safe_json(result)}],- "structuredContent": result,- "isError": False,- }))- except KeyError as exc:- return JSONResponse(content=_err(req_id, -32601, str(exc)))- except Exception as exc: # noqa: BLE001- logger.exception("MCP tool failure: %s", name)- return JSONResponse(content=_ok(req_id, {- "content": [{"type": "text", "text": f"Tool error: {exc}"}],- "isError": True,- }))-- return JSONResponse(content=_err(req_id, -32601, f"unknown method: {method}"))+ return 200, _err(req_id, p.INVALID_PARAMS, "tools/call requires 'name'")+ return 200, await _call_tool(ctx, req_id, name, params.get("arguments"), result_meta=None)++ return 200, _err(req_id, p.METHOD_NOT_FOUND, f"unknown method: {method}")+++# --------------------------------------------------------------------- shared+++async def _call_tool(+ ctx: CallContext,+ req_id: Any,+ name: str,+ arguments: Any,+ *,+ result_meta: dict | None,+) -> dict:+ """Run one tool. `result_meta` is set on the modern path only.++ An unknown tool is a protocol error (-32602), checked up front rather+ than inferred from a KeyError: a KeyError raised *inside* a tool is a+ bug in that tool, and reporting it as "unknown tool" would hide it. A+ tool that runs and fails is a tool execution error — a normal result+ with `isError: true` — so the model can read it and recover.+ """+ if name not in REGISTRY:+ return _err(req_id, p.INVALID_PARAMS, f"Unknown tool: {name}")+ if arguments is not None and not isinstance(arguments, dict):+ return _err(req_id, p.INVALID_PARAMS, "tools/call 'arguments' must be an object")++ try:+ async with async_session_maker() as session:+ result = await call_tool(session, ctx, name, arguments)+ # MCP wraps tool output in `content` blocks. Structured content is+ # returned too, with its JSON serialization as text for clients that+ # only read text, as the spec recommends.+ payload: dict[str, Any] = {+ "content": [{"type": "text", "text": _safe_json(result)}],+ "structuredContent": result,+ "isError": False,+ }+ except Exception as exc: # noqa: BLE001+ logger.exception("MCP tool failure: %s", name)+ payload = {+ "content": [{"type": "text", "text": f"Tool error: {exc}"}],+ "isError": True,+ }++ if result_meta is not None:+ payload = {"resultType": "complete", **payload, "_meta": result_meta}+ return _ok(req_id, payload)def _safe_json(obj: Any) -> str:- import jsontry:return json.dumps(obj, default=str)except Exception:diff --git a/backend/mcp_server/protocol.py b/backend/mcp_server/protocol.pynew file mode 100644index 00000000..4211932f--- /dev/null+++ b/backend/mcp_server/protocol.py@@ -0,0 +1,198 @@+"""Model Context Protocol wire rules for Securo's built-in server.++The server is dual-era, as the 2026-07-28 revision describes:++- **Modern** (`2026-07-28`): stateless. There is no `initialize` handshake;+ every request carries its protocol version and client capabilities in+ `params._meta`, mirrored into HTTP headers that the server must check+ against the body.+- **Legacy** (`2025-11-25`, `2025-06-18`, `2025-03-26`): the `initialize`+ handshake era. Kept because every MCP client that predates 2026-07-28+ speaks it, and because a dual-era client falls back to it when a modern+ request is refused.++How a request is classified is decided once, in `main.py`; this module holds+the constants and the checks both paths share.++Spec: https://modelcontextprotocol.io/specification/2026-07-28/+"""+from __future__ import annotations++import base64+import binascii+import re+from typing import Any, Optional++# Newest first. A modern client picks from `supportedVersions`; a legacy+# client negotiates within LEGACY_VERSIONS through `initialize`.+MODERN_VERSIONS: tuple[str, ...] = ("2026-07-28",)+LEGACY_VERSIONS: tuple[str, ...] = ("2025-11-25", "2025-06-18", "2025-03-26")+SUPPORTED_VERSIONS: tuple[str, ...] = MODERN_VERSIONS + LEGACY_VERSIONS++# Clients from before 2025-06-18 did not send `MCP-Protocol-Version`. The+# spec lets a server that supports them treat a header-less request as+# 2025-03-26, and Securo's own in-app agent sent no header until this+# change — so header-less requests stay on the legacy path.+HEADERLESS_LEGACY_VERSION = "2025-03-26"+LATEST_LEGACY_VERSION = LEGACY_VERSIONS[0]++MODERN_METHODS = frozenset({"server/discover", "tools/list", "tools/call"})+LEGACY_METHODS = frozenset({"initialize", "ping", "tools/list", "tools/call"})++# `_meta` keys reserved by the spec.+META_PROTOCOL_VERSION = "io.modelcontextprotocol/protocolVersion"+META_CLIENT_CAPABILITIES = "io.modelcontextprotocol/clientCapabilities"+META_SERVER_INFO = "io.modelcontextprotocol/serverInfo"++# Securo's own per-tool extras. `_meta` keys need a reverse-DNS prefix, and+# a prefix whose second label is `modelcontextprotocol`/`mcp` is reserved.+TOOL_META_KEY = "com.usesecuro/tool"++# JSON-RPC 2.0.+PARSE_ERROR = -32700+INVALID_REQUEST = -32600+METHOD_NOT_FOUND = -32601+INVALID_PARAMS = -32602+# Allocated by the MCP spec in its reserved -32020..-32099 sub-range.+HEADER_MISMATCH = -32020+UNSUPPORTED_PROTOCOL_VERSION = -32022++# Caching hints required on `server/discover` and `tools/list`. The tool set+# is fixed per deploy and identical for every caller, so it is `public`; five+# minutes keeps a client from re-listing on every turn without pinning a+# stale list across a release for long.+LIST_TTL_MS = 300_000+LIST_CACHE_SCOPE = "public"++_BASE64_SENTINEL = re.compile(r"^=\?base64\?(?P<body>.*)\?=$", re.DOTALL)+# RFC 9110 field-value characters: visible ASCII, space, horizontal tab.+_HEADER_SAFE = re.compile(r"^[\x20-\x7e\t]*$")+++class ProtocolError(Exception):+ """A request the transport must refuse with a specific status and code."""++ def __init__(+ self,+ status: int,+ code: int,+ message: str,+ *,+ data: Any = None,+ request_id: Any = None,+ ):+ super().__init__(message)+ self.status = status+ self.code = code+ self.message = message+ self.data = data+ self.request_id = request_id++ def body(self) -> dict[str, Any]:+ error: dict[str, Any] = {"code": self.code, "message": self.message}+ if self.data is not None:+ error["data"] = self.data+ out: dict[str, Any] = {"jsonrpc": "2.0", "error": error}+ # A JSON-RPC error with no id is allowed when the id could not be read.+ if self.request_id is not None:+ out["id"] = self.request_id+ return out+++def unsupported_version(requested: str, request_id: Any) -> ProtocolError:+ return ProtocolError(+ 400,+ UNSUPPORTED_PROTOCOL_VERSION,+ "Unsupported protocol version",+ data={"supported": list(SUPPORTED_VERSIONS), "requested": requested},+ request_id=request_id,+ )+++def header_mismatch(message: str, request_id: Any) -> ProtocolError:+ return ProtocolError(400, HEADER_MISMATCH, f"Header mismatch: {message}", request_id=request_id)+++def decode_header_value(value: str) -> Optional[str]:+ """Undo the spec's `=?base64?…?=` sentinel. None means undecodable.++ `Mcp-Name` is carried base64-encoded when the name cannot travel as a+ plain header value; the server must decode before comparing to the body.+ """+ match = _BASE64_SENTINEL.match(value)+ if match is None:+ return value if _HEADER_SAFE.match(value) else None+ try:+ return base64.b64decode(match.group("body"), validate=True).decode("utf-8")+ except (binascii.Error, UnicodeDecodeError):+ return None+++def encode_header_value(value: str) -> str:+ """The client side of `decode_header_value`."""+ needs_encoding = (+ not _HEADER_SAFE.match(value)+ or value != value.strip()+ or _BASE64_SENTINEL.match(value) is not None+ )+ if not needs_encoding:+ return value+ return "=?base64?" + base64.b64encode(value.encode("utf-8")).decode("ascii") + "?="+++def parse_allowed_origins(raw: str) -> frozenset[str]:+ return frozenset(o.strip().rstrip("/") for o in (raw or "").split(",") if o.strip())+++def origin_allowed(origin: Optional[str], allowed: frozenset[str]) -> bool:+ """The spec's DNS-rebinding guard.++ Servers MUST validate `Origin` and answer 403 when it is present and+ invalid. Every legitimate caller of this server is another process —+ the backend's agent runtime, or an MCP gateway in the cluster — and none+ of them send `Origin`. A browser always does. So an absent header passes+ and a present one must be explicitly allowed.+ """+ if origin is None:+ return True+ return origin.rstrip("/") in allowed+++# Proposals whose apply step only inserts a new row and touches nothing that+# already exists. Listed by name rather than matched by prefix:+# `propose_create_rule` can apply the new rule to existing transactions and+# overwrite their categories.+ADDITIVE_PROPOSALS = frozenset(+ {+ "propose_create_budget",+ "propose_create_category",+ "propose_create_goal",+ "propose_create_payee_rule",+ "propose_create_recurring_transaction",+ "propose_create_transaction",+ }+)+++def tool_annotations(name: str, *, is_proposal: bool) -> dict[str, Any]:+ """Behaviour hints for one tool, derived from what it can do.++ Clients treat these as untrusted hints, but a gateway uses them to decide+ what to put behind an approval prompt, so they err towards caution:++ - Every non-proposal tool only reads.+ - A proposal can write when an external caller applies it, so it is never+ read-only. The proposals in `ADDITIVE_PROPOSALS` only add rows, so they+ are marked non-destructive. Every other proposal omits+ `destructiveHint`, which the spec defaults to true —+ `propose_categorize` overwrites categories in bulk and+ `propose_cancel_recurring_transaction` can hard-delete, and a tool added+ later inherits the cautious default rather than a guess.+ - Nothing here reaches outside Securo's own ledger.+ """+ if not is_proposal:+ return {"readOnlyHint": True, "openWorldHint": False}+ hints: dict[str, Any] = {"readOnlyHint": False, "openWorldHint": False}+ if name in ADDITIVE_PROPOSALS:+ hints["destructiveHint"] = False+ return hintsdiff --git a/backend/mcp_server/registry.py b/backend/mcp_server/registry.pyindex 8918eb4e..26a97530 100644--- a/backend/mcp_server/registry.py+++ b/backend/mcp_server/registry.py@@ -57,17 +57,32 @@ def tool(return deco-def list_tools() -> list[dict[str, Any]]:- """MCP-compatible tool list payload."""- return [- {+def list_tools(*, legacy: bool = True) -> list[dict[str, Any]]:+ """MCP tool list payload, in registration order (the spec asks for a+ deterministic order so clients can cache the list).++ Securo's per-tool extras travel under a vendor-prefixed `_meta` key, the+ place the spec gives them. Legacy responses also keep the old top-level+ `_securo` object: during a rolling deploy the backend's agent runtime can+ briefly be one version behind the mcp-server, and it read that field.+ Modern responses leave it out, since `Tool` defines no such property.+ """+ from mcp_server.protocol import TOOL_META_KEY, tool_annotations++ out: list[dict[str, Any]] = []+ for s in REGISTRY.values():+ extras = {"is_proposal": s.is_proposal, "tags": s.tags}+ item: dict[str, Any] = {"name": s.name,"description": s.description,"inputSchema": s.parameters,- "_securo": {"is_proposal": s.is_proposal, "tags": s.tags},+ "annotations": tool_annotations(s.name, is_proposal=s.is_proposal),+ "_meta": {TOOL_META_KEY: extras},}- for s in REGISTRY.values()- ]+ if legacy:+ item["_securo"] = extras+ out.append(item)+ return outasync def call_tool(diff --git a/backend/tests/test_agents_mcp_client_dual_era.py b/backend/tests/test_agents_mcp_client_dual_era.pynew file mode 100644index 00000000..8367e562--- /dev/null+++ b/backend/tests/test_agents_mcp_client_dual_era.py@@ -0,0 +1,198 @@+"""The agent runtime's MCP client as a dual-era client (spec 2026-07-28).++It must speak the modern protocol to Securo's own server and to any modern+user-supplied server, and still fall back cleanly for a legacy one — which is+how every extra MCP server configured before this change was reached.+"""+from __future__ import annotations++import json+from typing import Any++import pytest++import app.agents.mcp.client as mcp_client_module+from app.agents.mcp.client import MCPClient, _encode_header_value, _is_modern_refusal, _parse_sse+++class _Resp:+ def __init__(self, status_code: int = 200, body: Any = None, *, content_type: str = "application/json", text: str | None = None):+ self.status_code = status_code+ self._body = body+ self.headers = {"content-type": content_type}+ self.text = text if text is not None else (json.dumps(body) if body is not None else "")++ def raise_for_status(self) -> None:+ if self.status_code >= 400:+ raise RuntimeError(f"HTTP {self.status_code}")++ def json(self) -> Any:+ if self._body is None:+ raise ValueError("no json")+ return self._body+++class _FakeHttp:+ queue: list[_Resp] = []+ calls: list[dict] = []++ def __init__(self, *_, **__):+ pass++ async def __aenter__(self):+ return self++ async def __aexit__(self, *exc):+ return False++ async def post(self, url, *, json=None, headers=None): # noqa: A002+ type(self).calls.append({"url": url, "json": json, "headers": headers or {}})+ return type(self).queue.pop(0)++[email protected](autouse=True)+def _fake(monkeypatch):+ _FakeHttp.queue = []+ _FakeHttp.calls = []+ monkeypatch.setattr(mcp_client_module.httpx, "AsyncClient", _FakeHttp)+ yield+++def _ok(result: dict, rid: int = 1) -> dict:+ return {"jsonrpc": "2.0", "id": rid, "result": result}+++async def test_first_request_is_modern_with_mirrored_headers_and_meta():+ _FakeHttp.queue = [_Resp(200, _ok({"resultType": "complete", "tools": []}))]+ client = MCPClient(name="securo", url="http://mcp/mcp")++ await client.list_tools(token="t")++ call = _FakeHttp.calls[0]+ meta = call["json"]["params"]["_meta"]+ assert meta["io.modelcontextprotocol/protocolVersion"] == "2026-07-28"+ assert meta["io.modelcontextprotocol/clientCapabilities"] == {}+ assert meta["io.modelcontextprotocol/clientInfo"]["name"] == "securo-agent-runtime"+ assert call["headers"]["MCP-Protocol-Version"] == "2026-07-28"+ assert call["headers"]["Mcp-Method"] == "tools/list"+ assert "Mcp-Name" not in call["headers"]+ assert "text/event-stream" in call["headers"]["Accept"]+ assert client._era == "modern"+++async def test_tools_call_sends_mcp_name():+ _FakeHttp.queue = [_Resp(200, _ok({"resultType": "complete", "content": [], "structuredContent": {"x": 1}, "isError": False}))]+ client = MCPClient(name="securo", url="http://mcp/mcp")++ out = await client.call_tool(name="list_accounts", arguments={}, token="t")++ assert _FakeHttp.calls[0]["headers"]["Mcp-Name"] == "list_accounts"+ assert _FakeHttp.calls[0]["json"]["params"]["name"] == "list_accounts"+ assert out["ok"] is True and out["data"] == {"x": 1}+++async def test_legacy_server_triggers_one_fallback_and_is_remembered():+ """A 4xx without a modern JSON-RPC error body means a legacy server: resend+ in the plain shape, and never probe that server again."""+ _FakeHttp.queue = [+ _Resp(400, {"detail": "bad request"}), # legacy server rejects _meta shape+ _Resp(200, _ok({"tools": [{"name": "a"}]})), # plain retry succeeds+ _Resp(200, _ok({"tools": [{"name": "a"}]})), # next call goes straight to legacy+ ]+ client = MCPClient(name="extra", url="http://legacy/mcp")++ first = await client.list_tools(token="t")+ second = await client.list_tools(token="t")++ assert [t.name for t in first] == ["a"] and [t.name for t in second] == ["a"]+ assert client._era == "legacy"+ assert len(_FakeHttp.calls) == 3+ assert "_meta" not in _FakeHttp.calls[1]["json"]["params"]+ assert "MCP-Protocol-Version" not in _FakeHttp.calls[1]["headers"]+ assert "_meta" not in _FakeHttp.calls[2]["json"]["params"], "the era is cached, no second probe"+++async def test_modern_refusal_raises_instead_of_falling_back():+ """A recognised modern error means the server is modern — correct the+ request, do not silently downgrade to a protocol it may not serve."""+ _FakeHttp.queue = [_Resp(400, {"jsonrpc": "2.0", "id": 1, "error": {"code": -32022, "message": "Unsupported", "data": {"supported": ["2027-01-01"], "requested": "2026-07-28"}}})]+ client = MCPClient(name="future", url="http://future/mcp")++ with pytest.raises(RuntimeError, match="-32022"):+ await client.list_tools(token="t")+ assert len(_FakeHttp.calls) == 1+ assert client._era == "modern"+++async def test_auth_failure_is_not_mistaken_for_a_legacy_server():+ _FakeHttp.queue = [_Resp(401, {"jsonrpc": "2.0", "error": {"code": -32001, "message": "invalid token"}})]+ client = MCPClient(name="securo", url="http://mcp/mcp")++ with pytest.raises(RuntimeError, match="401"):+ await client.list_tools(token="bad")+ assert client._era is None+ assert len(_FakeHttp.calls) == 1+++async def test_sse_response_is_parsed_for_the_matching_id():+ stream = (+ 'data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progress":1}}\n\n'+ 'data: {"jsonrpc":"2.0","id":1,"result":{"resultType":"complete","tools":[{"name":"s"}]}}\n\n'+ )+ _FakeHttp.queue = [_Resp(200, None, content_type="text/event-stream", text=stream)]+ client = MCPClient(name="streamy", url="http://s/mcp")++ tools = await client.list_tools(token="t")++ assert [t.name for t in tools] == ["s"]+++async def test_input_required_result_is_refused_clearly():+ _FakeHttp.queue = [_Resp(200, _ok({"resultType": "input_required", "inputRequests": {}}))]+ client = MCPClient(name="mrtr", url="http://m/mcp")++ with pytest.raises(RuntimeError, match="client input"):+ await client.call_tool(name="x", arguments={}, token="t")+++async def test_proposal_flag_is_read_from_vendor_meta():+ _FakeHttp.queue = [_Resp(200, _ok({"resultType": "complete", "tools": [+ {"name": "propose_x", "inputSchema": {"type": "object"}, "_meta": {"com.usesecuro/tool": {"is_proposal": True}}},+ {"name": "legacy_y", "_securo": {"is_proposal": True}},+ ]}))]+ client = MCPClient(name="securo", url="http://mcp/mcp")++ tools = await client.list_tools(token="t")++ assert [t.is_proposal for t in tools] == [True, True]+++def test_modern_refusal_detection_matches_the_spec():+ assert _is_modern_refusal(400, {"error": {"code": -32020}})+ assert _is_modern_refusal(400, {"error": {"code": -32022}})+ assert _is_modern_refusal(404, {"error": {"code": -32601}})+ assert _is_modern_refusal(400, {"error": {"code": -32602}})+ assert not _is_modern_refusal(404, {"detail": "Not Found"})+ assert not _is_modern_refusal(405, None)+ assert not _is_modern_refusal(400, {"error": {"code": -32600}})+++def test_header_value_encoding():+ assert _encode_header_value("list_accounts") == "list_accounts"+ encoded = _encode_header_value("Hello, 世界")+ assert encoded.startswith("=?base64?") and encoded.endswith("?=")+ assert _encode_header_value(" padded ").startswith("=?base64?")+ assert _encode_header_value("=?base64?literal?=").startswith("=?base64?") and _encode_header_value("=?base64?literal?=") != "=?base64?literal?="+++def test_sse_parser_ignores_unrelated_events():+ text = 'data: {"jsonrpc":"2.0","id":2,"result":{}}\n\ndata: not json\n\n'+ assert _parse_sse(text, 1) is Nonediff --git a/backend/tests/test_mcp_server_main.py b/backend/tests/test_mcp_server_main.pyindex 122f3dfd..50f53924 100644--- a/backend/tests/test_mcp_server_main.py+++ b/backend/tests/test_mcp_server_main.py@@ -125,6 +125,9 @@ async def test_mcp_rejects_non_string_method(test_user):@pytest.mark.asyncioasync def test_mcp_initialize_returns_protocol_handshake(test_user):+ """Legacy lifecycle. With no requested version the server offers its+ newest legacy one. It used to hardcode 2024-11-05, a version whose+ transport was the deprecated HTTP+SSE pair this server never served."""async with _client() as cli:r = await cli.post("/mcp",@@ -133,9 +136,10 @@ async def test_mcp_initialize_returns_protocol_handshake(test_user):)assert r.status_code == 200result = r.json()["result"]- assert result["protocolVersion"] == "2024-11-05"+ assert result["protocolVersion"] == "2025-11-25"assert result["serverInfo"]["name"] == "securo-builtin"assert "tools" in result["capabilities"]+ assert "mcp-session-id" not in r.headers@pytest.mark.asyncio@@ -199,7 +203,9 @@ async def test_mcp_tools_call_unknown_tool(test_user):headers=_auth_headers(test_user.id),)assert r.status_code == 200- assert r.json()["error"]["code"] == -32601+ # An unknown tool is Invalid params, not Method not found: the method+ # (tools/call) exists, its argument does not.+ assert r.json()["error"]["code"] == -32602@pytest.mark.asynciodiff --git a/backend/tests/test_mcp_server_protocol_2026.py b/backend/tests/test_mcp_server_protocol_2026.pynew file mode 100644index 00000000..e3d9c8bc--- /dev/null+++ b/backend/tests/test_mcp_server_protocol_2026.py@@ -0,0 +1,542 @@+"""The MCP server against the 2026-07-28 specification.++Every assertion here traces to a MUST/SHOULD in+https://modelcontextprotocol.io/specification/2026-07-28/ — transports+(Streamable HTTP), versioning, the base protocol, server/discover, tools and+caching. Legacy behaviour is kept and covered too, because the server is+dual-era: Securo's in-app agent and every pre-2026 client still speak it.+"""+from __future__ import annotations++import base64+import json++import httpx+import pytest++from app.agents.mcp.auth import mint_token++MODERN = "2026-07-28"+++def _client():+ from mcp_server.main import app++ return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://mcp.test")+++def _meta(version: str = MODERN, **extra) -> dict:+ meta = {+ "io.modelcontextprotocol/protocolVersion": version,+ "io.modelcontextprotocol/clientInfo": {"name": "spec-test", "version": "1"},+ "io.modelcontextprotocol/clientCapabilities": {},+ }+ meta.update(extra)+ return meta+++def _modern_headers(user_id, method: str, *, name: str | None = None, version: str = MODERN) -> dict:+ headers = {+ "Authorization": f"Bearer {mint_token(user_id=user_id)}",+ "Accept": "application/json, text/event-stream",+ "MCP-Protocol-Version": version,+ "Mcp-Method": method,+ }+ if name is not None:+ headers["Mcp-Name"] = name+ return headers+++def _auth(user_id) -> dict:+ return {"Authorization": f"Bearer {mint_token(user_id=user_id)}"}+++def fake_tool_run(monkeypatch):+ """tools/call without a database: record the call, return a canned dict."""+ import mcp_server.main as mcp_main++ calls: list[tuple[str, dict | None]] = []++ async def _call(session, ctx, name, arguments):+ calls.append((name, arguments))+ return {"items": [], "total": 0}++ class _Session:+ async def __aenter__(self):+ return object()++ async def __aexit__(self, *exc):+ return False++ monkeypatch.setattr(mcp_main, "call_tool", _call)+ monkeypatch.setattr(mcp_main, "async_session_maker", lambda: _Session())+ return calls+++# --------------------------------------------------------------- server/discover+++async def test_discover_is_implemented_and_advertises_versions_and_capabilities(test_user):+ """Servers MUST implement server/discover (server/discover.md)."""+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": "d1", "method": "server/discover", "params": {"_meta": _meta()}},+ headers=_modern_headers(test_user.id, "server/discover"),+ )+ assert r.status_code == 200+ body = r.json()+ assert body["id"] == "d1"+ result = body["result"]+ assert result["resultType"] == "complete"+ assert result["supportedVersions"][0] == MODERN+ assert "2025-11-25" in result["supportedVersions"], "dual-era: legacy versions are genuinely served"+ assert result["capabilities"]["tools"] == {"listChanged": False}+ assert result["_meta"]["io.modelcontextprotocol/serverInfo"]["name"] == "securo-builtin"+ # Caching hints are required on discover (utilities/caching.md).+ assert isinstance(result["ttlMs"], int) and result["ttlMs"] >= 0+ assert result["cacheScope"] in ("public", "private")+++# --------------------------------------------------------------- tools/list+++async def test_modern_tools_list_carries_result_type_caching_and_server_info(test_user):+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {"_meta": _meta()}},+ headers=_modern_headers(test_user.id, "tools/list"),+ )+ assert r.status_code == 200+ result = r.json()["result"]+ assert result["resultType"] == "complete"+ assert result["ttlMs"] >= 0+ assert result["cacheScope"] == "public", "the tool set is identical for every caller"+ assert result["_meta"]["io.modelcontextprotocol/serverInfo"]["name"] == "securo-builtin"+ assert len(result["tools"]) > 0+++async def test_every_tool_is_schema_valid_for_2026(test_user):+ """Tool.inputSchema MUST have type "object" at the root, and a modern+ Tool carries no non-standard top-level properties."""+ allowed_keys = {"name", "title", "description", "icons", "inputSchema", "outputSchema", "annotations", "_meta"}+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {"_meta": _meta()}},+ headers=_modern_headers(test_user.id, "tools/list"),+ )+ for tool in r.json()["result"]["tools"]:+ assert tool["inputSchema"].get("type") == "object", tool["name"]+ assert set(tool) <= allowed_keys, f"{tool['name']} has {set(tool) - allowed_keys}"+ assert "com.usesecuro/tool" in tool["_meta"], "Securo extras live under a vendor _meta key"+++async def test_tool_list_order_is_deterministic(test_user):+ """Servers SHOULD return tools in a deterministic order."""+ async with _client() as cli:+ names = []+ for i in range(2):+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": i, "method": "tools/list", "params": {"_meta": _meta()}},+ headers=_modern_headers(test_user.id, "tools/list"),+ )+ names.append([t["name"] for t in r.json()["result"]["tools"]])+ assert names[0] == names[1]+++async def test_annotations_tell_a_gateway_which_tools_write(test_user):+ """Reads are read-only; proposals are not. Only proposals that just add a+ row claim to be additive; everything else that writes keeps the spec's+ cautious default (destructiveHint absent = true)."""+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {"_meta": _meta()}},+ headers=_modern_headers(test_user.id, "tools/list"),+ )+ tools = {t["name"]: t for t in r.json()["result"]["tools"]}++ assert tools["list_transactions"]["annotations"]["readOnlyHint"] is True+ assert tools["propose_create_transaction"]["annotations"]["readOnlyHint"] is False+ assert tools["propose_create_transaction"]["annotations"]["destructiveHint"] is False+ # Bulk overwrite and hard delete must not be advertised as harmless.+ assert "destructiveHint" not in tools["propose_categorize"]["annotations"]+ assert "destructiveHint" not in tools["propose_cancel_recurring_transaction"]["annotations"]+ # A new rule can be applied to existing transactions and overwrite their+ # categories, so "create" in the name is not enough.+ assert "destructiveHint" not in tools["propose_create_rule"]["annotations"]+ for name, tool in tools.items():+ is_proposal = tool["_meta"]["com.usesecuro/tool"]["is_proposal"]+ assert tool["annotations"]["readOnlyHint"] is (not is_proposal), name+++# --------------------------------------------------------------- tools/call+++async def test_modern_tools_call_returns_result_type_and_structured_content(test_user, fake_tool_run):+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={+ "jsonrpc": "2.0", "id": 5, "method": "tools/call",+ "params": {"name": "list_categories", "arguments": {}, "_meta": _meta()},+ },+ headers=_modern_headers(test_user.id, "tools/call", name="list_categories"),+ )+ assert r.status_code == 200+ result = r.json()["result"]+ assert result["resultType"] == "complete"+ assert result["isError"] is False+ assert result["structuredContent"] == {"items": [], "total": 0}+ assert json.loads(result["content"][0]["text"]) == {"items": [], "total": 0}+ assert result["_meta"]["io.modelcontextprotocol/serverInfo"]["name"] == "securo-builtin"+ assert fake_tool_run == [("list_categories", {})]+++async def test_a_failing_tool_is_an_execution_error_not_a_protocol_error(test_user, monkeypatch):+ import mcp_server.main as mcp_main++ async def _boom(session, ctx, name, arguments):+ raise ValueError("date must be in the future")++ class _Session:+ async def __aenter__(self):+ return object()++ async def __aexit__(self, *exc):+ return False++ monkeypatch.setattr(mcp_main, "call_tool", _boom)+ monkeypatch.setattr(mcp_main, "async_session_maker", lambda: _Session())++ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={+ "jsonrpc": "2.0", "id": 6, "method": "tools/call",+ "params": {"name": "list_categories", "arguments": {}, "_meta": _meta()},+ },+ headers=_modern_headers(test_user.id, "tools/call", name="list_categories"),+ )+ result = r.json()["result"]+ assert result["isError"] is True+ assert result["resultType"] == "complete"+ assert "date must be in the future" in result["content"][0]["text"]+++async def test_a_key_error_inside_a_tool_is_not_reported_as_an_unknown_tool(test_user, monkeypatch):+ """The old server caught KeyError and called it "unknown tool", which hid+ real bugs in tools that raise KeyError internally."""+ import mcp_server.main as mcp_main++ async def _bug(session, ctx, name, arguments):+ raise KeyError("missing_dict_key")++ class _Session:+ async def __aenter__(self):+ return object()++ async def __aexit__(self, *exc):+ return False++ monkeypatch.setattr(mcp_main, "call_tool", _bug)+ monkeypatch.setattr(mcp_main, "async_session_maker", lambda: _Session())++ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 7, "method": "tools/call", "params": {"name": "list_categories"}},+ headers=_auth(test_user.id),+ )+ body = r.json()+ assert "error" not in body+ assert body["result"]["isError"] is True+++async def test_unknown_tool_is_invalid_params(test_user):+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 8, "method": "tools/call", "params": {"name": "nope", "_meta": _meta()}},+ headers=_modern_headers(test_user.id, "tools/call", name="nope"),+ )+ assert r.json()["error"]["code"] == -32602+++async def test_mcp_name_may_arrive_base64_encoded(test_user, fake_tool_run):+ """Servers MUST decode a `=?base64?…?=` Mcp-Name before comparing it."""+ encoded = "=?base64?" + base64.b64encode(b"list_categories").decode() + "?="+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 9, "method": "tools/call", "params": {"name": "list_categories", "_meta": _meta()}},+ headers=_modern_headers(test_user.id, "tools/call", name=encoded),+ )+ assert r.status_code == 200+ assert r.json()["result"]["isError"] is False+++# --------------------------------------------------------------- server validation+++async def _post_modern(user_id, *, headers_override=None, meta=None, method="tools/list", params_extra=None):+ params = {"_meta": meta if meta is not None else _meta(), **(params_extra or {})}+ headers = _modern_headers(user_id, method)+ if headers_override is not None:+ headers.update(headers_override)+ for k, v in list(headers.items()):+ if v is None:+ del headers[k]+ async with _client() as cli:+ return await cli.post("/mcp", json={"jsonrpc": "2.0", "id": 42, "method": method, "params": params}, headers=headers)+++async def test_missing_protocol_version_header_is_a_header_mismatch(test_user):+ r = await _post_modern(test_user.id, headers_override={"MCP-Protocol-Version": None})+ assert r.status_code == 400+ assert r.json()["error"]["code"] == -32020+++async def test_header_and_body_versions_must_match(test_user):+ r = await _post_modern(test_user.id, headers_override={"MCP-Protocol-Version": "2025-11-25"})+ assert r.status_code == 400+ assert r.json()["error"]["code"] == -32020+++async def test_unsupported_version_lists_what_is_supported(test_user):+ """UnsupportedProtocolVersionError: 400, -32022, data.supported + data.requested."""+ r = await _post_modern(+ test_user.id,+ headers_override={"MCP-Protocol-Version": "1900-01-01"},+ meta=_meta("1900-01-01"),+ )+ assert r.status_code == 400+ err = r.json()["error"]+ assert err["code"] == -32022+ assert err["data"]["requested"] == "1900-01-01"+ assert MODERN in err["data"]["supported"]+ assert r.json()["id"] == 42+++async def test_missing_mcp_method_header_is_a_header_mismatch(test_user):+ r = await _post_modern(test_user.id, headers_override={"Mcp-Method": None})+ assert r.status_code == 400+ assert r.json()["error"]["code"] == -32020+++async def test_mcp_method_header_must_match_the_body(test_user):+ r = await _post_modern(test_user.id, headers_override={"Mcp-Method": "server/discover"})+ assert r.status_code == 400+ assert r.json()["error"]["code"] == -32020+++async def test_tools_call_requires_a_matching_mcp_name(test_user):+ missing = await _post_modern(test_user.id, method="tools/call", params_extra={"name": "list_categories"})+ assert missing.status_code == 400 and missing.json()["error"]["code"] == -32020++ wrong = await _post_modern(+ test_user.id, method="tools/call", params_extra={"name": "list_categories"},+ headers_override={"Mcp-Name": "list_accounts"},+ )+ assert wrong.status_code == 400 and wrong.json()["error"]["code"] == -32020+++async def test_missing_client_capabilities_is_invalid_params_with_400(test_user):+ """A request missing a required `_meta` field is malformed: -32602, HTTP 400."""+ meta = _meta()+ del meta["io.modelcontextprotocol/clientCapabilities"]+ r = await _post_modern(test_user.id, meta=meta)+ assert r.status_code == 400+ assert r.json()["error"]["code"] == -32602+++async def test_modern_header_without_body_meta_is_malformed(test_user):+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}},+ headers=_modern_headers(test_user.id, "tools/list"),+ )+ assert r.status_code == 400+ assert r.json()["error"]["code"] == -32602+++async def test_unknown_modern_method_is_404_with_a_json_rpc_body(test_user):+ """404 + -32601, so a client can tell a modern server from a legacy 404."""+ r = await _post_modern(test_user.id, method="resources/list")+ assert r.status_code == 404+ assert r.json()["error"]["code"] == -32601+++async def test_initialize_is_not_a_modern_method(test_user):+ """2026-07-28 removed the handshake; a modern-shaped initialize is unknown."""+ r = await _post_modern(test_user.id, method="initialize")+ assert r.status_code == 404+++# --------------------------------------------------------------- transport+++async def test_notifications_get_202_and_no_body(test_user):+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "method": "notifications/initialized"},+ headers=_auth(test_user.id),+ )+ assert r.status_code == 202+ assert r.content == b""+++async def test_get_and_delete_are_405(test_user):+ """The GET stream and DELETE session termination were removed."""+ async with _client() as cli:+ get = await cli.get("/mcp", headers=_auth(test_user.id))+ delete = await cli.delete("/mcp", headers=_auth(test_user.id))+ assert get.status_code == 405+ assert delete.status_code == 405+++async def test_no_session_id_is_ever_minted_or_echoed(test_user):+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 1, "method": "server/discover", "params": {"_meta": _meta()}},+ headers={**_modern_headers(test_user.id, "server/discover"), "Mcp-Session-Id": "old-client-session"},+ )+ assert r.status_code == 200+ assert "mcp-session-id" not in r.headers+++async def test_a_foreign_origin_is_refused_with_403(test_user):+ """Servers MUST validate Origin (DNS rebinding) and 403 an invalid one —+ checked before auth, so a valid token from a hostile page still fails."""+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 1, "method": "server/discover", "params": {"_meta": _meta()}},+ headers={**_modern_headers(test_user.id, "server/discover"), "Origin": "https://evil.example"},+ )+ assert r.status_code == 403+++async def test_an_explicitly_allowed_origin_passes(test_user, monkeypatch):+ from app.agents.config import get_agent_settings++ get_agent_settings.cache_clear()+ monkeypatch.setenv("AGENTS_MCP_ALLOWED_ORIGINS", "https://app.example.com")+ try:+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 1, "method": "server/discover", "params": {"_meta": _meta()}},+ headers={**_modern_headers(test_user.id, "server/discover"), "Origin": "https://app.example.com"},+ )+ assert r.status_code == 200+ finally:+ get_agent_settings.cache_clear()+++async def test_request_id_must_not_be_null(test_user):+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": None, "method": "tools/list"},+ headers=_auth(test_user.id),+ )+ assert r.status_code == 400+ assert r.json()["error"]["code"] == -32600+++async def test_a_client_sent_response_is_refused(test_user):+ async with _client() as cli:+ r = await cli.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "result": {}}, headers=_auth(test_user.id))+ assert r.status_code == 400+++# --------------------------------------------------------------- legacy era+++async def test_headerless_request_still_works_for_old_clients(test_user):+ """The in-app agent sent bare requests before this change; during a+ rolling deploy an old backend can still be talking to a new server."""+ async with _client() as cli:+ r = await cli.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"}, headers=_auth(test_user.id))+ assert r.status_code == 200+ tool = r.json()["result"]["tools"][0]+ assert "_securo" in tool, "legacy responses keep the field old runtimes read"+ assert "resultType" not in r.json()["result"]+++async def test_legacy_initialize_echoes_a_supported_version(test_user):+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18"}},+ headers=_auth(test_user.id),+ )+ assert r.json()["result"]["protocolVersion"] == "2025-06-18"+++async def test_legacy_initialize_offers_latest_legacy_for_an_unknown_request(test_user):+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05"}},+ headers=_auth(test_user.id),+ )+ assert r.json()["result"]["protocolVersion"] == "2025-11-25"+++async def test_legacy_ping_is_answered(test_user):+ async with _client() as cli:+ r = await cli.post("/mcp", json={"jsonrpc": "2.0", "id": 3, "method": "ping"}, headers=_auth(test_user.id))+ assert r.status_code == 200+ assert r.json()["result"] == {}+++async def test_legacy_request_with_an_unsupported_version_header_is_refused(test_user):+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 4, "method": "ping"},+ headers={**_auth(test_user.id), "MCP-Protocol-Version": "1999-01-01"},+ )+ assert r.status_code == 400+ assert r.json()["error"]["code"] == -32022diff --git a/docker-compose.prod.yml b/docker-compose.prod.ymlindex dd760518..f21f4532 100644--- a/docker-compose.prod.yml+++ b/docker-compose.prod.yml@@ -59,6 +59,9 @@ x-backend-env: &backend-env# TTL for tokens minted from /agents/connections → "External MCP access".# Used by Claude Desktop, n8n, custom clients plugging into Securo.AGENTS_MCP_EXTERNAL_TTL_DAYS: ${AGENTS_MCP_EXTERNAL_TTL_DAYS:-90}+ # Browser origins the MCP server accepts, comma-separated. Blank admits+ # none; the agent runtime, gateways and desktop clients send no Origin.+ AGENTS_MCP_ALLOWED_ORIGINS: ${AGENTS_MCP_ALLOWED_ORIGINS:-}# LLM provider config: only the provider you actually use needs setting.AGENTS_DEFAULT_PROVIDER: ${AGENTS_DEFAULT_PROVIDER:-ollama}AGENTS_DEFAULT_MODEL: ${AGENTS_DEFAULT_MODEL:-}diff --git a/docker-compose.yml b/docker-compose.ymlindex bd787720..aaa64eec 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -65,6 +65,9 @@ x-backend-env: &backend-env# TTL for tokens minted from /agents/connections → "External MCP access".# Used by Claude Desktop, n8n, custom clients plugging into Securo.AGENTS_MCP_EXTERNAL_TTL_DAYS: ${AGENTS_MCP_EXTERNAL_TTL_DAYS:-90}+ # Browser origins the MCP server accepts, comma-separated. Blank admits+ # none; the agent runtime, gateways and desktop clients send no Origin.+ AGENTS_MCP_ALLOWED_ORIGINS: ${AGENTS_MCP_ALLOWED_ORIGINS:-}# LLM provider config: only the provider you actually use needs setting.AGENTS_DEFAULT_PROVIDER: ${AGENTS_DEFAULT_PROVIDER:-ollama}AGENTS_DEFAULT_MODEL: ${AGENTS_DEFAULT_MODEL:-}