Skip to content
Merged
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
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
179 changes: 179 additions & 0 deletions proofline/_mcp.py
Original file line number Diff line number Diff line change
@@ -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)
3 changes: 3 additions & 0 deletions proofline/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand Down
61 changes: 61 additions & 0 deletions proofline/fixes.py
Original file line number Diff line number Diff line change
@@ -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})
Loading
Loading