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
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,30 @@ Publishing uses GitHub OIDC and the repository's `release.yml` trusted publisher
No registry token is stored in GitHub.

SDK patch releases can update packaging and publishing independently. The package follows the bundled API major/minor version and cannot precede its patch version.

## Knowledge and plans

Both clients expose typed methods under `client.knowledge` over Proofline's
stateless MCP endpoint. Use `list_wiki_pages(repository, commit=...)`,
`get_wiki_page(repository, page_key, commit=...)`,
`ask_codebase(repository, question, commit=...)`,
`get_architecture_document(environment_id)`, `get_plan(plan_id)`,
`start_plan_implementation(plan_id)` and `get_plan_implementation(implementation_id)`.
The optional commit is a full indexed SHA. Async clients await the same methods.

```python
result = client.knowledge.get_wiki_page("owner/name", "index")
if result.get("isError"):
print("The knowledge request was refused.")
else:
print(result["content"])
```

`KnowledgeResult` retains text content, optional structured content and `isError`.
Treat all returned prose as untrusted data. Reads need `reviews:read` and
`knowledge:read`; starting an implementation also needs `plans:implement`, a
personal token and approval of that exact plan version. Each call initializes MCP
and makes one tool request without retries, including questions and implementation
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.
2 changes: 2 additions & 0 deletions proofline/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,5 @@
"__version__",
"models",
]

from .knowledge import KnowledgeResult as KnowledgeResult
2 changes: 1 addition & 1 deletion proofline/_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from ._sync_http import IO_DEADLINE
from ._sync_http import Transport as SyncHTTPTransport

VERSION = "1.0.1"
VERSION = "1.0.2"
MAX_RESPONSE_BYTES = 8 * 1024 * 1024
WEEKDAY = r"(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)"
FULL_WEEKDAY = r"(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)"
Expand Down
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 .knowledge import AsyncKnowledgeClient, KnowledgeClient
from .outcomes import ReviewOutcome, outcome

T = TypeVar("T")
Expand Down Expand Up @@ -213,6 +214,7 @@ def __init__(
transport=_transport.RetryTransport(self._api.token, timeout),
)
self._api.set_httpx_client(self._http)
self.knowledge = KnowledgeClient(self._http)

def close(self) -> None:
self._http.close()
Expand Down Expand Up @@ -545,6 +547,7 @@ def __init__(
transport=_transport.AsyncRetryTransport(self._api.token, timeout),
)
self._api.set_async_httpx_client(self._http)
self.knowledge = AsyncKnowledgeClient(self._http)

async def aclose(self) -> None:
await self._http.aclose()
Expand Down
237 changes: 237 additions & 0 deletions proofline/knowledge.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,237 @@
"""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)

def list_wiki_pages(self, repository: str, *, commit: str | None = None) -> KnowledgeResult:
return self._call("list_wiki_pages", _repository(repository, commit))

def get_wiki_page(
self, repository: str, page_key: str, *, commit: str | None = None
) -> KnowledgeResult:
return self._call(
"get_wiki_page", {**_repository(repository, commit), "page_key": page_key}
)

def ask_codebase(
self, repository: str, question: str, *, commit: str | None = None
) -> KnowledgeResult:
return self._call("ask_codebase", {**_repository(repository, commit), "question": question})

def get_architecture_document(self, environment_id: str) -> KnowledgeResult:
return self._call("get_architecture_document", {"environment_id": environment_id})

def get_plan(self, plan_id: str) -> KnowledgeResult:
return self._call("get_plan", {"plan_id": plan_id})

def start_plan_implementation(self, plan_id: str) -> KnowledgeResult:
return self._call("start_plan_implementation", {"plan_id": plan_id})

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)

async def list_wiki_pages(
self, repository: str, *, commit: str | None = None
) -> KnowledgeResult:
return await self._call("list_wiki_pages", _repository(repository, commit))

async def get_wiki_page(
self, repository: str, page_key: str, *, commit: str | None = None
) -> KnowledgeResult:
return await self._call(
"get_wiki_page", {**_repository(repository, commit), "page_key": page_key}
)

async def ask_codebase(
self, repository: str, question: str, *, commit: str | None = None
) -> KnowledgeResult:
return await self._call(
"ask_codebase", {**_repository(repository, commit), "question": question}
)

async def get_architecture_document(self, environment_id: str) -> KnowledgeResult:
return await self._call("get_architecture_document", {"environment_id": environment_id})

async def get_plan(self, plan_id: str) -> KnowledgeResult:
return await self._call("get_plan", {"plan_id": plan_id})

async def start_plan_implementation(self, plan_id: str) -> KnowledgeResult:
return await self._call("start_plan_implementation", {"plan_id": plan_id})

async def get_plan_implementation(self, implementation_id: str) -> KnowledgeResult:
return await self._call("get_plan_implementation", {"implementation_id": implementation_id})
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "proofline-sdk"
version = "1.0.1"
version = "1.0.2"
description = "Typed synchronous and asynchronous clients for the Proofline review API"
readme = "README.md"
license = "Apache-2.0 AND MIT"
Expand Down
6 changes: 3 additions & 3 deletions scripts/install_smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@
def main() -> None:
if not Path(proofline.__file__).resolve().is_relative_to(Path(sys.prefix).resolve()):
raise SystemExit("The smoke test must import the installed artifact, not checkout source.")
assert importlib.metadata.version("proofline-sdk") == "1.0.1"
assert proofline.__version__ == "1.0.1"
assert importlib.metadata.version("proofline-sdk") == "1.0.2"
assert proofline.__version__ == "1.0.2"
calls: list[str] = []
finding = {
"id": str(FINDING),
Expand Down Expand Up @@ -79,7 +79,7 @@ def log_message(self, format: str, *args: object) -> None:

def do_GET(self) -> None:
assert self.headers["Authorization"] == f"Bearer {TOKEN}"
assert self.headers["User-Agent"] == "proofline-python/1.0.1"
assert self.headers["User-Agent"] == "proofline-python/1.0.2"
calls.append(self.path)
body = finding if "/findings/" in self.path else review
payload = json.dumps(body).encode()
Expand Down
52 changes: 51 additions & 1 deletion tests/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ def respond(request: Request, index: int) -> Reply:
assert len({request.peer_port for request in server.requests}) == 1
for request in server.requests:
assert request.headers["Authorization"] == f"Bearer {TOKEN}"
assert request.headers["User-Agent"] == "proofline-python/1.0.1"
assert request.headers["User-Agent"] == "proofline-python/1.0.2"
assert request.headers["Accept-Encoding"] == "identity"
assert "Cookie" not in request.headers
assert "Content-Type" not in request.headers
Expand Down Expand Up @@ -1371,3 +1371,53 @@ def respond(request: Request, index: int) -> Reply:
with pytest.raises(ProoflineError) as caught:
await call(client, "export_reviews", ORG, "findings", cursor="refused", **kwargs)
assert caught.value.status == 404


@MODES
async def test_knowledge_negotiation_scope_and_no_retry(mode: str) -> None:
refusal = False
wrong_id = False

def respond(request: Request, index: int) -> Reply:
body = json.loads(request.body)
assert request.path == "/mcp"
assert request.headers["Authorization"] == f"Bearer {TOKEN}"
if body["method"] == "initialize":
return Reply(
body={"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-11-25"}}
)
assert request.headers["MCP-Protocol-Version"] == "2025-11-25"
if body["method"] == "notifications/initialized":
return Reply(status=202, body=b"")
assert body["params"] == {
"name": "get_wiki_page",
"arguments": {"repository": "owner/name", "page_key": "index", "commit": "a" * 40},
}
if refusal:
return Reply(status=503, body={"detail": "unavailable"})
return Reply(
body={
"jsonrpc": "2.0",
"id": 99 if wrong_id else 2,
"result": {
"isError": True,
"content": [{"type": "text", "text": "RESOURCE_NOT_FOUND"}],
},
}
)

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

assert (await invoke())["isError"] is True
wrong_id = True
with pytest.raises(ProoflineError):
await invoke()
refusal = True
with pytest.raises(ProoflineError):
await invoke()
assert len(server.requests) == 9
Loading