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
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,23 @@ with ProoflineClient() as client:

The response names the recorded report and its covered and instrumented line counts. An identical upload returns that report with `created=False`. Refused reports raise `ProoflineError`. Uploading a report does not establish a check verdict.

## MCP tool discovery

Use `client.mcp.list_tools()` to read one page of the server's advertised tool definitions. Each page is an `McpToolPage` with a `tools` list of `McpToolDefinition` values and an optional `nextCursor`. Additional server metadata is preserved.

```python
from proofline import McpToolPage, ProoflineClient

with ProoflineClient() as client:
page: McpToolPage = client.mcp.list_tools()
for tool in page["tools"]:
print(tool["name"], tool["inputSchema"])
if (cursor := page.get("nextCursor")) is not None:
next_page = client.mcp.list_tools(cursor=cursor)
```

With `AsyncProoflineClient`, use `await client.mcp.list_tools()` and await any subsequent page. Pass the cursor back unchanged. The catalog describes the server's tools. It does not invoke them or establish that the credential can call them. HTTP and protocol failures raise `ProoflineError`.

## MCP organization selection

With an MCP OAuth credential approved for several organizations, discover its currently authorized targets with `client.mcp.list_organizations()`. It returns a `KnowledgeResult`; inspect `isError` before reading `structuredContent["data"]["organizations"]`. Each entry contains `organization_id`, `github_login`, and `scopes`.
Expand Down
3 changes: 3 additions & 0 deletions proofline/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
StopResponse,
UploadedReport,
)
from ._mcp import McpToolDefinition, McpToolPage
from ._transport import VERSION as __version__
from ._transport import ProoflineError, RunNowRefusal
from .client import AsyncProoflineClient, ProoflineClient, ReviewFilters
Expand All @@ -57,6 +58,8 @@
"FileReviewRequest",
"FileReviewResponse",
"KnowledgeResult",
"McpToolDefinition",
"McpToolPage",
"PatchReviewRequest",
"PatchReviewResponse",
"PatchTriggerSource",
Expand Down
230 changes: 158 additions & 72 deletions proofline/_mcp.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"""Typed knowledge calls over Proofline's stateless MCP endpoint. No tool-call retries."""
"""Typed calls and discovery over Proofline's stateless MCP endpoint. No tool-call retries."""

from __future__ import annotations

import json
from typing import Any, NotRequired, TypedDict, cast
from typing import Any, NoReturn, NotRequired, TypedDict, cast

import httpx2

Expand All @@ -23,6 +23,22 @@ class KnowledgeResult(TypedDict):
isError: NotRequired[bool]


class McpToolDefinition(TypedDict):
name: str
inputSchema: dict[str, Any]
title: NotRequired[str]
description: NotRequired[str]
outputSchema: NotRequired[dict[str, Any]]
annotations: NotRequired[dict[str, Any]]
_meta: NotRequired[dict[str, Any]]


class McpToolPage(TypedDict):
tools: list[McpToolDefinition]
nextCursor: NotRequired[str]
_meta: NotRequired[dict[str, Any]]


def _refused() -> ProoflineError:
return ProoflineError(0, "urn:proofline:sdk:mcp", "Invalid or refused MCP response.")

Expand All @@ -39,6 +55,10 @@ def _body(method: str, params: dict[str, Any] | None, identity: int | None) -> b
return data


def _invalid_json_constant(_: str) -> NoReturn:
raise ValueError("Invalid JSON constant.")


def _decode(response: httpx2.Response, identity: int | None) -> dict[str, Any]:
if (
response.status_code != (202 if identity is None else 200)
Expand All @@ -49,15 +69,16 @@ 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":
if response.headers.get("content-type", "").split(";")[0].strip().lower() != "application/json":
raise _refused()
try:
value = response.json()
except ValueError:
raise _refused() from None
value = response.json(parse_constant=_invalid_json_constant)
except (ValueError, RecursionError):
value = None
if (
not isinstance(value, dict)
or value.get("jsonrpc") != "2.0"
or type(value.get("id")) is not int
or value.get("id") != identity
or "error" in value
or not isinstance(value.get("result"), dict)
Expand All @@ -82,6 +103,79 @@ def _result(value: dict[str, Any]) -> KnowledgeResult:
return cast(KnowledgeResult, value)


def _tool_page(value: dict[str, Any]) -> McpToolPage:
tools = value.get("tools")
if not isinstance(tools, list):
raise _refused()
if "nextCursor" in value and not isinstance(value["nextCursor"], str):
raise _refused()
if "_meta" in value and not isinstance(value["_meta"], dict):
raise _refused()
for tool in tools:
if not isinstance(tool, dict) or not isinstance(tool.get("name"), str):
raise _refused()
for key in ("title", "description"):
if key in tool and not isinstance(tool[key], str):
raise _refused()
for key in ("annotations", "_meta"):
if key in tool and not isinstance(tool[key], dict):
raise _refused()
for key in ("inputSchema", "outputSchema"):
if key == "outputSchema" and key not in tool:
continue
schema = tool.get(key)
if not isinstance(schema, dict) or schema.get("type") != "object":
raise _refused()
return cast(McpToolPage, value)


def _frames(method: str, params: dict[str, Any] | None) -> list[tuple[bytes, int | None]]:
return [
(
_body(
"initialize",
{
"protocolVersion": PROTOCOL,
"capabilities": {},
"clientInfo": {"name": "proofline-python", "version": "1"},
},
1,
),
1,
),
(_body("notifications/initialized", None, None), None),
(_body(method, params, 2), 2),
]


def _headers(origin: str, identity: int | None) -> dict[str, str]:
headers = {
"Content-Type": "application/json",
"Accept": "application/json, text/event-stream",
"Origin": origin.rstrip("/"),
}
if identity != 1:
headers["MCP-Protocol-Version"] = PROTOCOL
return headers


def _check_initialize(result: dict[str, Any], method: str) -> None:
if result.get("protocolVersion") != PROTOCOL:
raise _refused()
if method == "tools/list":
capabilities = result.get("capabilities")
if not isinstance(capabilities, dict) or not isinstance(capabilities.get("tools"), dict):
raise _refused()


def _list_params(cursor: str | None) -> dict[str, Any] | None:
if cursor is None:
return None
if not isinstance(cursor, str):
raise ValueError("MCP tools/list cursor must be a string.")
return {"cursor": cursor}


def _repository(repository: str, commit: str | None) -> dict[str, Any]:
args = {"repository": repository}
if commit is not None:
Expand All @@ -100,42 +194,34 @@ def _call(
) -> KnowledgeResult:
if organization_id is not None:
args = {**args, "organization_id": organization_id}
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),
]
return _result(self._exchange("tools/call", {"name": name, "arguments": args}))

def _exchange(self, method: str, params: dict[str, Any] | None) -> dict[str, Any]:
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
for data, identity in _frames(method, params):
headers = _headers(str(self._http.base_url), identity)
try:
response = self._http.post("/mcp", content=data, headers=headers)
except ProoflineError as error:
if method != "tools/list" or not error.status:
raise
failure = ProoflineError(
error.status, "urn:proofline:sdk:mcp", "MCP HTTP request failed."
)
except httpx2.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)
failure = ProoflineError(0, "urn:proofline:sdk:transport", "MCP transport failed.")
except RecursionError:
if method != "tools/list":
raise
failure = _refused()
else:
result = _decode(response, identity)
if identity == 1:
_check_initialize(result, method)
continue
# The original exception can retain response text or request headers.
raise failure
return result


class AsyncMcpTools:
Expand All @@ -149,53 +235,53 @@ async def _call(
) -> KnowledgeResult:
if organization_id is not None:
args = {**args, "organization_id": organization_id}
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),
]
return _result(await self._exchange("tools/call", {"name": name, "arguments": args}))

async def _exchange(self, method: str, params: dict[str, Any] | None) -> dict[str, Any]:
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
for data, identity in _frames(method, params):
headers = _headers(str(self._http.base_url), identity)
try:
response = await self._http.post("/mcp", content=data, headers=headers)
except ProoflineError as error:
if method != "tools/list" or not error.status:
raise
failure = ProoflineError(
error.status, "urn:proofline:sdk:mcp", "MCP HTTP request failed."
)
except httpx2.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)
failure = ProoflineError(0, "urn:proofline:sdk:transport", "MCP transport failed.")
except RecursionError:
if method != "tools/list":
raise
failure = _refused()
else:
result = _decode(response, identity)
if identity == 1:
_check_initialize(result, method)
continue
# The original exception can retain response text or request headers.
raise failure
return result


class McpClient(McpTools):
"""Discover the organizations currently authorized for this MCP credential."""
"""Discover the server's tools and the credential's authorized organizations."""

def list_tools(self, *, cursor: str | None = None) -> McpToolPage:
"""Read one page of tool definitions from the server."""
return _tool_page(self._exchange("tools/list", _list_params(cursor)))

def list_organizations(self) -> KnowledgeResult:
return self._call("list_organizations", {})


class AsyncMcpClient(AsyncMcpTools):
"""Discover the organizations currently authorized for this MCP credential."""
"""Discover the server's tools and the credential's authorized organizations."""

async def list_tools(self, *, cursor: str | None = None) -> McpToolPage:
"""Read one page of tool definitions from the server."""
return _tool_page(await self._exchange("tools/list", _list_params(cursor)))

async def list_organizations(self) -> KnowledgeResult:
return await self._call("list_organizations", {})
Loading