Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. On an HTTP 200 reply, a well-formed JSON-RPC error raises `ProoflineError` with type `urn:proofline:sdk:mcp`, a `title` of `JSON-RPC error <code>`, and the server message as `detail` with the credential redacted; any other status or a malformed error raises the fixed `Invalid or refused MCP response.` refusal instead. 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

Expand Down
76 changes: 69 additions & 7 deletions proofline/_mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
from typing import Any, NotRequired, TypedDict, cast

import httpx2
from pydantic import SecretStr

from ._transport import ProoflineError
from ._transport import BearerAuth, ProoflineError, redacted

PROTOCOL = "2025-11-25"

Expand All @@ -27,6 +28,60 @@ def _refused() -> ProoflineError:
return ProoflineError(0, "urn:proofline:sdk:mcp", "Invalid or refused MCP response.")


def _jsonrpc_error(value: dict[str, Any], token: SecretStr | None) -> ProoflineError:
"""Keep a well-formed JSON-RPC error's code and redacted message.

Anything malformed stays the fixed refusal: the error must be an object
with an integer code (a bool is not one) and a string message, and the
response cannot carry both an error and a result.
"""
error = value.get("error")
if (
"result" in value
or not isinstance(error, dict)
or not isinstance(error.get("code"), int)
or isinstance(error.get("code"), bool)
or not isinstance(error.get("message"), str)
):
return _refused()
message: str = error["message"]
if token is not None:
message = cast(str, redacted(message, token.get_secret_value()))
return ProoflineError(
0,
"urn:proofline:sdk:mcp",
message,
title=f"JSON-RPC error {error['code']}",
)


def _bearer(header: str) -> SecretStr | None:
scheme, _, value = header.partition(" ")
if scheme.lower() == "bearer" and value.strip():
return SecretStr(value.strip())
return None


def _token(
http: httpx2.Client | httpx2.AsyncClient,
response: httpx2.Response | None = None,
) -> SecretStr | None:
# The credential that can echo back is the one on the actual request, so
# it wins over client settings: custom auth can add it per request.
if response is not None:
try:
header = response.request.headers.get("authorization", "")
except RuntimeError:
header = ""
token = _bearer(header)
if token is not None:
return token
auth = http.auth
if isinstance(auth, BearerAuth):
return auth.token
return _bearer(http.headers.get("authorization", ""))


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:
Expand All @@ -39,7 +94,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, token: SecretStr | None = None
) -> dict[str, Any]:
if (
response.status_code != (202 if identity is None else 200)
or "mcp-session-id" in response.headers
Expand All @@ -49,7 +106,8 @@ def _decode(response: httpx2.Response, identity: int | None) -> dict[str, Any]:
if response.content:
raise _refused()
return {}
if response.headers.get("content-type", "").split(";")[0].strip() != "application/json":
content_type = response.headers.get("content-type", "").split(";")[0].strip().lower()
if content_type != "application/json":
raise _refused()
try:
value = response.json()
Expand All @@ -58,11 +116,15 @@ def _decode(response: httpx2.Response, identity: int | None) -> dict[str, Any]:
if (
not isinstance(value, dict)
or value.get("jsonrpc") != "2.0"
or not isinstance(value.get("id"), int)
or isinstance(value.get("id"), bool)
or value.get("id") != identity
or "error" in value
or not isinstance(value.get("result"), dict)
):
raise _refused()
if "error" in value:
raise _jsonrpc_error(value, token)
if not isinstance(value.get("result"), dict):
raise _refused()
return cast(dict[str, Any], value["result"])


Expand Down Expand Up @@ -132,7 +194,7 @@ def _call(
raise ProoflineError(
0, "urn:proofline:sdk:transport", "MCP transport failed."
) from None
result = _decode(response, identity)
result = _decode(response, identity, _token(self._http, response))
if identity == 1 and result.get("protocolVersion") != PROTOCOL:
raise _refused()
return _result(result)
Expand Down Expand Up @@ -181,7 +243,7 @@ async def _call(
raise ProoflineError(
0, "urn:proofline:sdk:transport", "MCP transport failed."
) from None
result = _decode(response, identity)
result = _decode(response, identity, _token(self._http, response))
if identity == 1 and result.get("protocolVersion") != PROTOCOL:
raise _refused()
return _result(result)
Expand Down
5 changes: 5 additions & 0 deletions proofline/_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ class BearerAuth(httpx2.Auth):
def __init__(self, token: SecretStr) -> None:
self._token = token

@property
def token(self) -> SecretStr:
"""Read-only token access so error paths can redact it."""
return self._token

def auth_flow(
self, request: httpx2.Request
) -> Generator[httpx2.Request, httpx2.Response, None]:
Expand Down
241 changes: 241 additions & 0 deletions tests/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -2693,6 +2693,247 @@ def test_mcp_public_types_accept_legacy_and_targeted_calls(tmp_path: Path) -> No
subprocess.run([sys.executable, "-m", "mypy", str(fixture)], check=True)


@MODES
async def test_mcp_jsonrpc_error_keeps_code_and_redacted_message(mode: str) -> None:
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,
"error": {
"code": -32602,
"message": f"Invalid arguments: credential {TOKEN} was refused",
},
}
)

with Server(respond) as server:
async with session(mode, server.url) as client:
with pytest.raises(ProoflineError) as caught:
outcome = client.mcp.list_organizations()
if inspect.isawaitable(outcome):
await outcome
error = caught.value
assert error.type == "urn:proofline:sdk:mcp"
assert error.title == "JSON-RPC error -32602"
assert error.detail == "Invalid arguments: credential [redacted] was refused"
assert TOKEN not in error.detail
calls = [
request
for request in server.requests
if json.loads(request.body)["method"] == "tools/call"
]
assert len(calls) == 1


@MODES
async def test_mcp_jsonrpc_error_malformed_still_refused(mode: str) -> None:
payloads = [
# The response id must be the request's integer id; a bool is not one.
{"jsonrpc": "2.0", "id": True, "error": {"code": -32602, "message": "refused"}},
# A float aliases the request's integer id (2.0 == 2) without the guard.
{"jsonrpc": "2.0", "id": 2.0, "error": {"code": -32602, "message": "refused"}},
# The error must be an object.
{"jsonrpc": "2.0", "id": 2, "error": "refused"},
# The code must be an integer; a bool is not one.
{"jsonrpc": "2.0", "id": 2, "error": {"code": True, "message": "refused"}},
{"jsonrpc": "2.0", "id": 2, "error": {"code": "-32602", "message": "refused"}},
# The message must be a string.
{"jsonrpc": "2.0", "id": 2, "error": {"code": -32602, "message": 5}},
# A response cannot carry both an error and a result.
{
"jsonrpc": "2.0",
"id": 2,
"error": {"code": -32602, "message": "refused"},
"result": {},
},
]
seen = 0

def respond(request: Request, index: int) -> Reply:
nonlocal seen
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"")
payload = payloads[seen]
seen += 1
return Reply(body=payload)

with Server(respond) as server:
async with session(mode, server.url) as client:
for _ in payloads:
with pytest.raises(ProoflineError) as caught:
outcome = client.mcp.list_organizations()
if inspect.isawaitable(outcome):
await outcome
error = caught.value
assert error.type == "urn:proofline:sdk:mcp"
assert error.detail == "Invalid or refused MCP response."
assert error.title is None
assert seen == len(payloads)
calls = [
request
for request in server.requests
if json.loads(request.body)["method"] == "tools/call"
]
assert len(calls) == len(payloads)


@MODES
async def test_mcp_jsonrpc_non_integer_id_rejected_before_tool_call(mode: str) -> None:
# True aliases init id 1 (True == 1) and 1.0 equals it (1.0 == 1) without
# the integer guard, so either response would be accepted and a tool call
# would follow. The guard must refuse both before any tool call happens.
for bad_id in (True, 1.0):

def respond(request: Request, index: int) -> Reply:
body = json.loads(request.body)
if body["method"] == "initialize":
return Reply(
body={
"jsonrpc": "2.0",
"id": bad_id,
"result": {"protocolVersion": "2025-11-25"},
}
)
if body["method"] == "notifications/initialized":
return Reply(status=202, body=b"")
return Reply(
body={"jsonrpc": "2.0", "id": 2, "result": {"organizations": []}}
)

with Server(respond) as server:
async with session(mode, server.url) as client:
with pytest.raises(ProoflineError) as caught:
outcome = client.mcp.list_organizations()
if inspect.isawaitable(outcome):
await outcome
error = caught.value
assert error.type == "urn:proofline:sdk:mcp"
assert error.detail == "Invalid or refused MCP response."
calls = [
request
for request in server.requests
if json.loads(request.body)["method"] == "tools/call"
]
assert calls == []


class _InjectBearerAuth(httpx2.Auth):
# Adds the credential per request, as custom auth flows do; neither the
# client's auth attribute nor its default headers carry it.
def auth_flow(self, request: httpx2.Request) -> Any:
request.headers["Authorization"] = f"Bearer {TOKEN}"
yield request


@MODES
async def test_mcp_jsonrpc_error_redacts_custom_auth_header(mode: str) -> None:
# A bearer token injected by a custom auth flow must be redacted from a
# well-formed JSON-RPC error message too: it is on the outgoing request.
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,
"error": {
"code": -32602,
"message": f"Invalid arguments: credential {TOKEN} was refused",
},
}
)

with Server(respond) as server:
if mode == "sync":
http: Any = httpx2.Client(base_url=server.url, auth=_InjectBearerAuth())
mcp: Any = client_module.McpClient(http)
else:
http = httpx2.AsyncClient(base_url=server.url, auth=_InjectBearerAuth())
mcp = client_module.AsyncMcpClient(http)
try:
with pytest.raises(ProoflineError) as caught:
outcome = mcp.list_organizations()
if inspect.isawaitable(outcome):
await outcome
error = caught.value
assert error.type == "urn:proofline:sdk:mcp"
assert error.title == "JSON-RPC error -32602"
assert TOKEN not in (error.detail or "")
finally:
if mode == "sync":
http.close()
else:
await http.aclose()


@MODES
async def test_mcp_jsonrpc_error_redacts_raw_authorization_header(mode: str) -> None:
# A token carried in a raw Authorization header (no BearerAuth) must be
# redacted from a well-formed JSON-RPC error message too.
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,
"error": {
"code": -32602,
"message": f"Invalid arguments: credential {TOKEN} was refused",
},
}
)

with Server(respond) as server:
if mode == "sync":
http: Any = httpx2.Client(
base_url=server.url, headers={"Authorization": f"Bearer {TOKEN}"}
)
mcp: Any = client_module.McpClient(http)
else:
http = httpx2.AsyncClient(
base_url=server.url, headers={"Authorization": f"Bearer {TOKEN}"}
)
mcp = client_module.AsyncMcpClient(http)
try:
with pytest.raises(ProoflineError) as caught:
outcome = mcp.list_organizations()
if inspect.isawaitable(outcome):
await outcome
error = caught.value
assert error.type == "urn:proofline:sdk:mcp"
assert error.title == "JSON-RPC error -32602"
assert TOKEN not in (error.detail or "")
finally:
if mode == "sync":
http.close()
else:
await http.aclose()


@MODES
async def test_export_ndjson_preserves_unicode_line_separators(mode: str) -> None:
kwargs = {
Expand Down