diff --git a/README.md b/README.md index 250fb32e..ca5ba4ce 100644 --- a/README.md +++ b/README.md @@ -211,7 +211,7 @@ else: print(result["content"]) ``` -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. +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. A JSON-RPC error response raises `ProoflineError` with type `urn:proofline:sdk:mcp`, the error code in `title` (for example `JSON-RPC error -32602`) and the server's message in `detail`, with the token redacted. A malformed error keeps the fixed detail `Invalid or refused MCP response.` and no title. 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. ## Fix context and re-verification diff --git a/proofline/_mcp.py b/proofline/_mcp.py index f80c5e00..1e4032d7 100644 --- a/proofline/_mcp.py +++ b/proofline/_mcp.py @@ -7,7 +7,7 @@ import httpx2 -from ._transport import ProoflineError +from ._transport import BearerAuth, ProoflineError, redacted PROTOCOL = "2025-11-25" @@ -27,6 +27,23 @@ def _refused() -> ProoflineError: return ProoflineError(0, "urn:proofline:sdk:mcp", "Invalid or refused MCP response.") +def _rpc_error(error: object, secret: str | None) -> ProoflineError: + """Keep a well-formed JSON-RPC error's code and message, with the token redacted.""" + if not isinstance(error, dict): + return _refused() + code, message = error.get("code"), error.get("message") + if not isinstance(code, int) or isinstance(code, bool) or not isinstance(message, str): + return _refused() + if secret: + message = cast(str, redacted(message, secret)) + return ProoflineError(0, "urn:proofline:sdk:mcp", message, title=f"JSON-RPC error {code}") + + +def _secret(http: httpx2.Client | httpx2.AsyncClient) -> str | None: + auth = http.auth + return auth.token.get_secret_value() if isinstance(auth, BearerAuth) else None + + def _body(method: str, params: dict[str, Any] | None, identity: int | None) -> bytes: value: dict[str, Any] = {"jsonrpc": "2.0", "method": method} if identity is not None: @@ -39,7 +56,9 @@ def _body(method: str, params: dict[str, Any] | None, identity: int | None) -> b return data -def _decode(response: httpx2.Response, identity: int | None) -> dict[str, Any]: +def _decode( + response: httpx2.Response, identity: int | None, secret: str | None = None +) -> dict[str, Any]: if ( response.status_code != (202 if identity is None else 200) or "mcp-session-id" in response.headers @@ -55,6 +74,14 @@ def _decode(response: httpx2.Response, identity: int | None) -> dict[str, Any]: value = response.json() except ValueError: raise _refused() from None + if ( + isinstance(value, dict) + and value.get("jsonrpc") == "2.0" + and value.get("id") == identity + and "error" in value + and "result" not in value + ): + raise _rpc_error(value["error"], secret) if ( not isinstance(value, dict) or value.get("jsonrpc") != "2.0" @@ -132,7 +159,7 @@ def _call( raise ProoflineError( 0, "urn:proofline:sdk:transport", "MCP transport failed." ) from None - result = _decode(response, identity) + result = _decode(response, identity, _secret(self._http)) if identity == 1 and result.get("protocolVersion") != PROTOCOL: raise _refused() return _result(result) @@ -181,7 +208,7 @@ async def _call( raise ProoflineError( 0, "urn:proofline:sdk:transport", "MCP transport failed." ) from None - result = _decode(response, identity) + result = _decode(response, identity, _secret(self._http)) if identity == 1 and result.get("protocolVersion") != PROTOCOL: raise _refused() return _result(result) diff --git a/proofline/_transport.py b/proofline/_transport.py index d3e99302..77513f0f 100644 --- a/proofline/_transport.py +++ b/proofline/_transport.py @@ -72,6 +72,10 @@ class BearerAuth(httpx2.Auth): def __init__(self, token: SecretStr) -> None: self._token = token + @property + def token(self) -> SecretStr: + return self._token + def auth_flow( self, request: httpx2.Request ) -> Generator[httpx2.Request, httpx2.Response, None]: diff --git a/tests/test_http.py b/tests/test_http.py index 68c6228e..4b9052f6 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2732,3 +2732,59 @@ def respond(request: Request, index: int) -> Reply: assert len(exported.rows) == 1 assert exported.rows[0]["claim"] == row["claim"] assert exported.next_cursor == "next-page" + + +@MODES +async def test_mcp_jsonrpc_error_keeps_code_and_redacted_message(mode: str) -> None: + errors: list[Any] = [ + {"code": -32602, "message": f"Invalid params: commit must be a full SHA ({TOKEN})"}, + {"code": "-32602", "message": "code is not an integer"}, + {"code": True, "message": "code is a boolean"}, + {"code": -32602}, + "not an object", + ] + current: dict[str, Any] = {} + + def respond(request: Request, index: int) -> Reply: + body = json.loads(request.body) + if body["method"] == "initialize": + return Reply( + body={"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-11-25"}} + ) + if body["method"] == "notifications/initialized": + return Reply(status=202, body=b"") + return Reply(body={"jsonrpc": "2.0", "id": 2, **current}) + + with Server(respond) as server: + async with session(mode, server.url) as client: + + async def invoke() -> Any: + result = client.knowledge.get_wiki_page("owner/name", "index", commit="a" * 40) + return await result if inspect.isawaitable(result) else result + + current.clear() + current["error"] = errors[0] + with pytest.raises(ProoflineError) as caught: + await invoke() + assert caught.value.type == "urn:proofline:sdk:mcp" + assert caught.value.title == "JSON-RPC error -32602" + assert caught.value.detail == ("Invalid params: commit must be a full SHA ([redacted])") + assert TOKEN not in repr(caught.value) + str(caught.value) + + for error in errors[1:]: + current.clear() + current["error"] = error + with pytest.raises(ProoflineError) as caught: + await invoke() + assert caught.value.title is None + assert caught.value.detail == "Invalid or refused MCP response." + + # A response carrying both members is not a valid JSON-RPC error. + current.clear() + current.update(error=errors[0], result={"content": []}) + with pytest.raises(ProoflineError) as caught: + await invoke() + assert caught.value.title is None + assert TOKEN not in caught.value.detail + # Each call initializes and makes one tool request, never retrying an error. + assert len(server.requests) == 6 * 3