From edc564d244f72b8e2bf307cc10c7c959f412d2c8 Mon Sep 17 00:00:00 2001 From: 50022005 Date: Wed, 2 Dec 2026 19:11:28 +0500 Subject: [PATCH] Reject ambiguous and malformed MCP JSON responses --- README.md | 2 + proofline/_mcp.py | 19 ++++++++- tests/test_mcp_json.py | 87 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 106 insertions(+), 2 deletions(-) create mode 100644 tests/test_mcp_json.py diff --git a/README.md b/README.md index 250fb32e..5e0e9a3b 100644 --- a/README.md +++ b/README.md @@ -213,6 +213,8 @@ else: Each call initializes MCP and makes one tool request without retries, including questions and implementation starts. `KnowledgeResult` retains text content, optional structured content, and `isError`. Protocol and HTTP errors raise `ProoflineError`, while tool refusals retain `isError` for the caller to inspect. Treat all returned prose as untrusted data. The SDK does not include a browser configuration or cloud-trust API; use the signed-in console for onboarding and connection changes. +MCP responses with duplicate JSON members, non-standard `NaN`/infinity constants, or nesting beyond the JSON decoder's limit raise `ProoflineError`. A duplicate refusal flag is never silently replaced by a success flag. + ## Fix context and re-verification Both clients expose finding and re-verification methods under `client.fixes` over the stateless MCP endpoint. Every method accepts the optional `organization_id` keyword described above: diff --git a/proofline/_mcp.py b/proofline/_mcp.py index f80c5e00..4c9be1e2 100644 --- a/proofline/_mcp.py +++ b/proofline/_mcp.py @@ -39,6 +39,21 @@ def _body(method: str, params: dict[str, Any] | None, identity: int | None) -> b return data +def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + # Never choose between conflicting protocol IDs, results or refusal flags. + value: dict[str, Any] = {} + for key, item in pairs: + if key in value: + raise ValueError("Duplicate JSON member.") + value[key] = item + return value + + +def _invalid_constant(value: str) -> Any: + # Python's decoder otherwise accepts NaN and infinities, which are not JSON. + raise ValueError("Invalid JSON constant.") + + def _decode(response: httpx2.Response, identity: int | None) -> dict[str, Any]: if ( response.status_code != (202 if identity is None else 200) @@ -52,8 +67,8 @@ def _decode(response: httpx2.Response, identity: int | None) -> dict[str, Any]: if response.headers.get("content-type", "").split(";")[0].strip() != "application/json": raise _refused() try: - value = response.json() - except ValueError: + value = response.json(object_pairs_hook=_unique_object, parse_constant=_invalid_constant) + except (ValueError, RecursionError): raise _refused() from None if ( not isinstance(value, dict) diff --git a/tests/test_mcp_json.py b/tests/test_mcp_json.py new file mode 100644 index 00000000..804e4ed4 --- /dev/null +++ b/tests/test_mcp_json.py @@ -0,0 +1,87 @@ +from __future__ import annotations + +import json + +import pytest + +from proofline import ProoflineError + +from .http_server import Reply, Request, Server +from .test_http import MODES, call, session + + +@MODES +@pytest.mark.parametrize("stage", ["initialize", "tools/call"]) +@pytest.mark.parametrize( + "payload", + [ + '"jsonrpc":"2.0","id":99,"id":ID,"result":RESULT', + '"jsonrpc":"1.0","jsonrpc":"2.0","id":ID,"result":RESULT', + '"jsonrpc":"2.0","id":ID,"result":{},"result":RESULT', + '"jsonrpc":"2.0","id":ID,"result":RESULT,"extra":{"x":1,"x":2}', + '"jsonrpc":"2.0","id":ID,"result":RESULT,"extra":NaN', + '"jsonrpc":"2.0","id":ID,"result":RESULT,"extra":Infinity', + '"jsonrpc":"2.0","id":ID,"result":RESULT,"extra":-Infinity', + ], +) +async def test_ambiguous_mcp_json_is_refused(mode: str, stage: str, payload: str) -> None: + def respond(request: Request, index: int) -> Reply: + body = json.loads(request.body) + method = body["method"] + if method == "notifications/initialized": + return Reply(status=202, body=b"") + result = ( + {"protocolVersion": "2025-11-25"} + if method == "initialize" + else {"content": [], "isError": False} + ) + if method == stage: + raw = payload.replace("ID", str(body["id"])).replace("RESULT", json.dumps(result)) + return Reply(body=("{" + raw + "}").encode()) + return Reply(body={"jsonrpc": "2.0", "id": body["id"], "result": result}) + + with Server(respond) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as caught: + await call(client.knowledge, "get_wiki_page", "owner/name", "index") + assert caught.value.type == "urn:proofline:sdk:mcp" + assert caught.value.detail == "Invalid or refused MCP response." + assert len(server.requests) == (1 if stage == "initialize" else 3) + + +@MODES +async def test_duplicate_tool_refusal_flag_is_not_overwritten(mode: str) -> None: + def respond(request: Request, index: int) -> Reply: + if index == 0: + return Reply( + body={ + "jsonrpc": "2.0", + "id": 1, + "result": { + "protocolVersion": "2025-11-25", + }, + } + ) + if index == 1: + return Reply(status=202, body=b"") + return Reply( + body=b'{"jsonrpc":"2.0","id":2,"result":{"content":[],"isError":true,"isError":false}}' + ) + + with Server(respond) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError): + await call(client.knowledge, "get_wiki_page", "owner/name", "index") + assert len(server.requests) == 3 + + +@MODES +async def test_deeply_nested_mcp_json_retains_typed_error(mode: str) -> None: + raw = b'{"jsonrpc":"2.0","id":1,"result":{"extra":' + b"[" * 2000 + raw += b"0" + b"]" * 2000 + b"}}" + with Server(lambda request, index: Reply(body=raw)) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as caught: + await call(client.knowledge, "get_wiki_page", "owner/name", "index") + assert caught.value.type == "urn:proofline:sdk:mcp" + assert len(server.requests) == 1