diff --git a/README.md b/README.md index d02fe434..0a471192 100644 --- a/README.md +++ b/README.md @@ -122,3 +122,27 @@ and makes one tool request without retries, including questions and implementati starts. Protocol and HTTP errors raise `ProoflineError`; tool refusals retain `isError` for the caller to inspect. No browser configuration or cloud-trust API is added. Use the signed-in console for onboarding and connection changes. + +## Fix context and re-verification + +Sync and async clients expose `client.fixes.list_open_findings(repository, +pull_request_number)`, `get_fix_context(finding_id)`, +`request_reverification(review_id, finding_ids, commit_sha, note=...)` and +`get_reverification(request_id)` over the existing MCP endpoint. + +```python +result = client.fixes.request_reverification( + review_id, [finding_id], pushed_commit_sha, + note="Fixed the null case and added a regression test.", +) +if result.get("isError"): + raise RuntimeError("Re-verification was refused.") +``` + +Use `await` with `AsyncProoflineClient`. The commit must be the live pushed head; +the server confirms it. The request accepts 1–20 distinct findings of one review +and an optional 1–2,000-character note. Reads need `reviews:read`; requesting +verification also needs `reviews:request` and repository write access. +Calls never retry. Results retain untrusted-text wrappers, availability, +assessment gaps and `isError`. `PENDING` and `NOT_VERIFIED` do not establish a fix. +A tool request never records a human disposition. diff --git a/proofline/_mcp.py b/proofline/_mcp.py new file mode 100644 index 00000000..c85f781d --- /dev/null +++ b/proofline/_mcp.py @@ -0,0 +1,179 @@ +"""Typed knowledge calls over Proofline's stateless MCP endpoint. No tool-call retries.""" + +from __future__ import annotations + +import json +from typing import Any, NotRequired, TypedDict, cast + +import httpx + +from ._transport import ProoflineError + +PROTOCOL = "2025-11-25" + + +class TextContent(TypedDict): + type: str + text: str + + +class KnowledgeResult(TypedDict): + content: list[TextContent] + structuredContent: NotRequired[dict[str, Any]] + isError: NotRequired[bool] + + +def _refused() -> ProoflineError: + return ProoflineError(0, "urn:proofline:sdk:mcp", "Invalid or refused MCP response.") + + +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: + value["id"] = identity + if params is not None: + value["params"] = params + data = json.dumps(value).encode("utf-8") + if len(data) > 8192: + raise ValueError("MCP request exceeds 8192 bytes.") + return data + + +def _decode(response: httpx.Response, identity: int | None) -> dict[str, Any]: + if ( + response.status_code != (202 if identity is None else 200) + or "mcp-session-id" in response.headers + ): + raise _refused() + if identity is None: + if response.content: + raise _refused() + return {} + if response.headers.get("content-type", "").split(";")[0].strip() != "application/json": + raise _refused() + try: + value = response.json() + except ValueError: + raise _refused() from None + if ( + not isinstance(value, dict) + or value.get("jsonrpc") != "2.0" + or value.get("id") != identity + or "error" in value + or not isinstance(value.get("result"), dict) + ): + raise _refused() + return cast(dict[str, Any], value["result"]) + + +def _result(value: dict[str, Any]) -> KnowledgeResult: + content = value.get("content") + if not isinstance(content, list) or any( + not isinstance(item, dict) + or item.get("type") != "text" + or not isinstance(item.get("text"), str) + for item in content + ): + raise _refused() + if "isError" in value and not isinstance(value["isError"], bool): + raise _refused() + if "structuredContent" in value and not isinstance(value["structuredContent"], dict): + raise _refused() + return cast(KnowledgeResult, value) + + +def _repository(repository: str, commit: str | None) -> dict[str, Any]: + args = {"repository": repository} + if commit is not None: + args["commit"] = commit + return args + + +class McpTools: + """Knowledge operations preserve MCP result wrappers and isError refusals.""" + + def __init__(self, http: httpx.Client) -> None: + self._http = http + + def _call(self, name: str, args: dict[str, Any]) -> KnowledgeResult: + call = _body("tools/call", {"name": name, "arguments": args}, 2) + frames = [ + ( + _body( + "initialize", + { + "protocolVersion": PROTOCOL, + "capabilities": {}, + "clientInfo": {"name": "proofline-python", "version": "1"}, + }, + 1, + ), + 1, + ), + (_body("notifications/initialized", None, None), None), + (call, 2), + ] + result: dict[str, Any] = {} + for data, identity in frames: + headers = { + "Content-Type": "application/json", + "Accept": "application/json, text/event-stream", + "Origin": str(self._http.base_url).rstrip("/"), + } + if identity != 1: + headers["MCP-Protocol-Version"] = PROTOCOL + try: + response = self._http.post("/mcp", content=data, headers=headers) + except httpx.HTTPError: + raise ProoflineError( + 0, "urn:proofline:sdk:transport", "MCP transport failed." + ) from None + result = _decode(response, identity) + if identity == 1 and result.get("protocolVersion") != PROTOCOL: + raise _refused() + return _result(result) + + +class AsyncMcpTools: + """Knowledge operations preserve MCP result wrappers and isError refusals.""" + + def __init__(self, http: httpx.AsyncClient) -> None: + self._http = http + + async def _call(self, name: str, args: dict[str, Any]) -> KnowledgeResult: + call = _body("tools/call", {"name": name, "arguments": args}, 2) + frames = [ + ( + _body( + "initialize", + { + "protocolVersion": PROTOCOL, + "capabilities": {}, + "clientInfo": {"name": "proofline-python", "version": "1"}, + }, + 1, + ), + 1, + ), + (_body("notifications/initialized", None, None), None), + (call, 2), + ] + result: dict[str, Any] = {} + for data, identity in frames: + headers = { + "Content-Type": "application/json", + "Accept": "application/json, text/event-stream", + "Origin": str(self._http.base_url).rstrip("/"), + } + if identity != 1: + headers["MCP-Protocol-Version"] = PROTOCOL + try: + response = await self._http.post("/mcp", content=data, headers=headers) + except httpx.HTTPError: + raise ProoflineError( + 0, "urn:proofline:sdk:transport", "MCP transport failed." + ) from None + result = _decode(response, identity) + if identity == 1 and result.get("protocolVersion") != PROTOCOL: + raise _refused() + return _result(result) diff --git a/proofline/client.py b/proofline/client.py index 3994d845..de6b5251 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -70,6 +70,7 @@ from ._generated.types import UNSET, Response, Unset from ._transport import ProoflineError from .exports import ExportDataset, ExportFormat, ExportPage, decode_export +from .fixes import AsyncFixesClient, FixesClient from .knowledge import AsyncKnowledgeClient, KnowledgeClient from .outcomes import ReviewOutcome, outcome @@ -215,6 +216,7 @@ def __init__( ) self._api.set_httpx_client(self._http) self.knowledge = KnowledgeClient(self._http) + self.fixes = FixesClient(self._http) def close(self) -> None: self._http.close() @@ -548,6 +550,7 @@ def __init__( ) self._api.set_async_httpx_client(self._http) self.knowledge = AsyncKnowledgeClient(self._http) + self.fixes = AsyncFixesClient(self._http) async def aclose(self) -> None: await self._http.aclose() diff --git a/proofline/fixes.py b/proofline/fixes.py new file mode 100644 index 00000000..e9541041 --- /dev/null +++ b/proofline/fixes.py @@ -0,0 +1,61 @@ +"""Fix context and pushed-head verification. Tool refusals retain isError.""" + +from __future__ import annotations + +from typing import Any + +from ._mcp import AsyncMcpTools, KnowledgeResult, McpTools + + +class FixesClient(McpTools): + def list_open_findings(self, repository: str, pull_request_number: int) -> KnowledgeResult: + return self._call( + "list_open_findings", + {"repository": repository, "pull_request_number": pull_request_number}, + ) + + def get_fix_context(self, finding_id: str) -> KnowledgeResult: + return self._call("get_fix_context", {"finding_id": finding_id}) + + def request_reverification( + self, review_id: str, finding_ids: list[str], commit_sha: str, *, note: str | None = None + ) -> KnowledgeResult: + args: dict[str, Any] = { + "review_id": review_id, + "finding_ids": finding_ids, + "commit_sha": commit_sha, + } + if note is not None: + args["note"] = note + return self._call("request_reverification", args) + + def get_reverification(self, request_id: str) -> KnowledgeResult: + return self._call("get_reverification", {"request_id": request_id}) + + +class AsyncFixesClient(AsyncMcpTools): + async def list_open_findings( + self, repository: str, pull_request_number: int + ) -> KnowledgeResult: + return await self._call( + "list_open_findings", + {"repository": repository, "pull_request_number": pull_request_number}, + ) + + async def get_fix_context(self, finding_id: str) -> KnowledgeResult: + return await self._call("get_fix_context", {"finding_id": finding_id}) + + async def request_reverification( + self, review_id: str, finding_ids: list[str], commit_sha: str, *, note: str | None = None + ) -> KnowledgeResult: + args: dict[str, Any] = { + "review_id": review_id, + "finding_ids": finding_ids, + "commit_sha": commit_sha, + } + if note is not None: + args["note"] = note + return await self._call("request_reverification", args) + + async def get_reverification(self, request_id: str) -> KnowledgeResult: + return await self._call("get_reverification", {"request_id": request_id}) diff --git a/proofline/knowledge.py b/proofline/knowledge.py index 8290289d..efa7a15d 100644 --- a/proofline/knowledge.py +++ b/proofline/knowledge.py @@ -1,138 +1,9 @@ -"""Typed knowledge calls over Proofline's stateless MCP endpoint. No tool-call retries.""" - -from __future__ import annotations - -import json -from typing import Any, NotRequired, TypedDict, cast - -import httpx - -from ._transport import ProoflineError - -PROTOCOL = "2025-11-25" - - -class TextContent(TypedDict): - type: str - text: str - - -class KnowledgeResult(TypedDict): - content: list[TextContent] - structuredContent: NotRequired[dict[str, Any]] - isError: NotRequired[bool] - - -def _refused() -> ProoflineError: - return ProoflineError(0, "urn:proofline:sdk:mcp", "Invalid or refused MCP response.") - - -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: - value["id"] = identity - if params is not None: - value["params"] = params - data = json.dumps(value).encode("utf-8") - if len(data) > 8192: - raise ValueError("MCP request exceeds 8192 bytes.") - return data - - -def _decode(response: httpx.Response, identity: int | None) -> dict[str, Any]: - if ( - response.status_code != (202 if identity is None else 200) - or "mcp-session-id" in response.headers - ): - raise _refused() - if identity is None: - if response.content: - raise _refused() - return {} - if response.headers.get("content-type", "").split(";")[0].strip() != "application/json": - raise _refused() - try: - value = response.json() - except ValueError: - raise _refused() from None - if ( - not isinstance(value, dict) - or value.get("jsonrpc") != "2.0" - or value.get("id") != identity - or "error" in value - or not isinstance(value.get("result"), dict) - ): - raise _refused() - return cast(dict[str, Any], value["result"]) - - -def _result(value: dict[str, Any]) -> KnowledgeResult: - content = value.get("content") - if not isinstance(content, list) or any( - not isinstance(item, dict) - or item.get("type") != "text" - or not isinstance(item.get("text"), str) - for item in content - ): - raise _refused() - if "isError" in value and not isinstance(value["isError"], bool): - raise _refused() - if "structuredContent" in value and not isinstance(value["structuredContent"], dict): - raise _refused() - return cast(KnowledgeResult, value) - - -def _repository(repository: str, commit: str | None) -> dict[str, Any]: - args = {"repository": repository} - if commit is not None: - args["commit"] = commit - return args - - -class KnowledgeClient: - """Knowledge operations preserve MCP result wrappers and isError refusals.""" - - def __init__(self, http: httpx.Client) -> None: - self._http = http - - def _call(self, name: str, args: dict[str, Any]) -> KnowledgeResult: - call = _body("tools/call", {"name": name, "arguments": args}, 2) - frames = [ - ( - _body( - "initialize", - { - "protocolVersion": PROTOCOL, - "capabilities": {}, - "clientInfo": {"name": "proofline-python", "version": "1"}, - }, - 1, - ), - 1, - ), - (_body("notifications/initialized", None, None), None), - (call, 2), - ] - result: dict[str, Any] = {} - for data, identity in frames: - headers = { - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "Origin": str(self._http.base_url).rstrip("/"), - } - if identity != 1: - headers["MCP-Protocol-Version"] = PROTOCOL - try: - response = self._http.post("/mcp", content=data, headers=headers) - except httpx.HTTPError: - raise ProoflineError( - 0, "urn:proofline:sdk:transport", "MCP transport failed." - ) from None - result = _decode(response, identity) - if identity == 1 and result.get("protocolVersion") != PROTOCOL: - raise _refused() - return _result(result) +"""Published knowledge operations through the scoped MCP server.""" +from ._mcp import AsyncMcpTools, KnowledgeResult, McpTools, _repository + + +class KnowledgeClient(McpTools): def list_wiki_pages(self, repository: str, *, commit: str | None = None) -> KnowledgeResult: return self._call("list_wiki_pages", _repository(repository, commit)) @@ -161,50 +32,7 @@ def get_plan_implementation(self, implementation_id: str) -> KnowledgeResult: return self._call("get_plan_implementation", {"implementation_id": implementation_id}) -class AsyncKnowledgeClient: - """Knowledge operations preserve MCP result wrappers and isError refusals.""" - - def __init__(self, http: httpx.AsyncClient) -> None: - self._http = http - - async def _call(self, name: str, args: dict[str, Any]) -> KnowledgeResult: - call = _body("tools/call", {"name": name, "arguments": args}, 2) - frames = [ - ( - _body( - "initialize", - { - "protocolVersion": PROTOCOL, - "capabilities": {}, - "clientInfo": {"name": "proofline-python", "version": "1"}, - }, - 1, - ), - 1, - ), - (_body("notifications/initialized", None, None), None), - (call, 2), - ] - result: dict[str, Any] = {} - for data, identity in frames: - headers = { - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "Origin": str(self._http.base_url).rstrip("/"), - } - if identity != 1: - headers["MCP-Protocol-Version"] = PROTOCOL - try: - response = await self._http.post("/mcp", content=data, headers=headers) - except httpx.HTTPError: - raise ProoflineError( - 0, "urn:proofline:sdk:transport", "MCP transport failed." - ) from None - result = _decode(response, identity) - if identity == 1 and result.get("protocolVersion") != PROTOCOL: - raise _refused() - return _result(result) - +class AsyncKnowledgeClient(AsyncMcpTools): async def list_wiki_pages( self, repository: str, *, commit: str | None = None ) -> KnowledgeResult: diff --git a/tests/test_http.py b/tests/test_http.py index 79bd0ec7..519ba8dc 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1421,3 +1421,69 @@ async def invoke() -> Any: with pytest.raises(ProoflineError): await invoke() assert len(server.requests) == 9 + + +@MODES +async def test_fixes_preserve_unavailable_context_and_never_retry(mode: str) -> None: + observed: list[dict[str, Any]] = [] + refuse = False + result = { + "content": [{"type": "text", "text": "untrusted source"}], + "structuredContent": {"status": "UNAVAILABLE", "items": None}, + } + + def respond(request: Request, index: int) -> Reply: + body = json.loads(request.body) + assert request.headers["Authorization"] == f"Bearer {TOKEN}" + 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"") + observed.append(body["params"]) + if refuse: + return Reply(status=503, body={"detail": "unavailable"}, headers={"Retry-After": "0"}) + return Reply(body={"jsonrpc": "2.0", "id": 2, "result": result}) + + with Server(respond) as server: + async with session(mode, server.url) as client: + + async def invoke(name: str, *args: Any, **kwargs: Any) -> Any: + answer = getattr(client.fixes, name)(*args, **kwargs) + return await answer if inspect.isawaitable(answer) else answer + + assert await invoke("list_open_findings", "owner/name", 7) == result + assert await invoke("get_fix_context", str(REVIEW)) == result + assert ( + await invoke( + "request_reverification", + str(REVIEW), + [str(REVIEW)], + "a" * 40, + note="fixed code", + ) + == result + ) + assert await invoke("get_reverification", str(REVIEW)) == result + assert observed == [ + { + "name": "list_open_findings", + "arguments": {"repository": "owner/name", "pull_request_number": 7}, + }, + {"name": "get_fix_context", "arguments": {"finding_id": str(REVIEW)}}, + { + "name": "request_reverification", + "arguments": { + "review_id": str(REVIEW), + "finding_ids": [str(REVIEW)], + "commit_sha": "a" * 40, + "note": "fixed code", + }, + }, + {"name": "get_reverification", "arguments": {"request_id": str(REVIEW)}}, + ] + refuse = True + with pytest.raises(ProoflineError): + await invoke("request_reverification", str(REVIEW), [str(REVIEW)], "a" * 40) + assert len(observed) == 5