From ca4cc51ab27e61dbc20019fcc33e1a3b74971f04 Mon Sep 17 00:00:00 2001 From: jobsrip <131525874+jobsrip@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:24:19 +0000 Subject: [PATCH] Add typed MCP tool discovery to the Python SDK MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AI assistance: implemented and reviewed with Codex under the author’s direction. --- README.md | 17 ++++ proofline/__init__.py | 3 + proofline/_mcp.py | 230 +++++++++++++++++++++++++++++------------- tests/test_http.py | 185 ++++++++++++++++++++++++++++++++- 4 files changed, 361 insertions(+), 74 deletions(-) diff --git a/README.md b/README.md index 250fb32e..bcb65515 100644 --- a/README.md +++ b/README.md @@ -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`. diff --git a/proofline/__init__.py b/proofline/__init__.py index 689b454d..409674d0 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -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 @@ -57,6 +58,8 @@ "FileReviewRequest", "FileReviewResponse", "KnowledgeResult", + "McpToolDefinition", + "McpToolPage", "PatchReviewRequest", "PatchReviewResponse", "PatchTriggerSource", diff --git a/proofline/_mcp.py b/proofline/_mcp.py index f80c5e00..34680552 100644 --- a/proofline/_mcp.py +++ b/proofline/_mcp.py @@ -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 @@ -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.") @@ -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) @@ -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) @@ -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: @@ -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: @@ -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", {}) diff --git a/tests/test_http.py b/tests/test_http.py index 68c6228e..8e3830ee 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -62,6 +62,7 @@ from proofline._generated.models.finding_fix_prompt_type_1 import FindingFixPromptType1 from proofline._generated.models.reviews_export_row import ReviewsExportRow from proofline._generated.types import UNSET +from proofline._mcp import AsyncMcpClient, McpClient from proofline._transport import REFUSAL_SHAPES from .fixtures import ( @@ -96,7 +97,9 @@ async def session(mode: str, url: str, **kwargs: Any) -> AsyncIterator[Client]: yield async_client -async def call(client: Client, name: str, *args: Any, **kwargs: Any) -> Any: +async def call( + client: Client | McpClient | AsyncMcpClient, name: str, *args: Any, **kwargs: Any +) -> Any: result = getattr(client, name)(*args, **kwargs) return await result if inspect.isawaitable(result) else result @@ -2309,6 +2312,178 @@ def respond(request: Request, index: int) -> Reply: assert page.next_cursor is None +def catalog_initialize(version: str = "2025-11-25", identity: int = 1) -> Reply: + return Reply( + body={ + "jsonrpc": "2.0", + "id": identity, + "result": { + "protocolVersion": version, + "capabilities": {"tools": {}}, + "serverInfo": {"name": "test", "version": "1"}, + }, + } + ) + + +@MODES +async def test_mcp_lists_tools_with_cursor_and_server_metadata(mode: str) -> None: + cursor = "opaque + / тест" + first = { + "tools": [ + { + "name": "get_review_status", + "title": "Review status", + "description": "Untrusted tool description", + "inputSchema": {"type": "object", "required": ["review_id"]}, + "outputSchema": {"type": "object"}, + "annotations": {"readOnlyHint": True}, + "_meta": {"example.org/scopes": ["reviews:read"]}, + "execution": {"taskSupport": "optional"}, + } + ], + "nextCursor": cursor, + "_meta": {"example.org/catalog": 1}, + "serverExtension": {"revision": 2}, + } + second: dict[str, Any] = {"tools": []} + + def respond(request: Request, index: int) -> Reply: + frame = json.loads(request.body) + if frame["method"] == "initialize": + return catalog_initialize() + if frame["method"] == "notifications/initialized": + return Reply(status=202, body=b"") + return Reply( + body={"jsonrpc": "2.0", "id": 2, "result": first if index == 2 else second}, + headers={"Content-Type": "Application/JSON; charset=utf-8"}, + ) + + with Server(respond) as server: + async with session(mode, server.url) as client: + assert await call(client.mcp, "list_tools") == first + assert await call(client.mcp, "list_tools", cursor=cursor) == second + frames = [json.loads(request.body) for request in server.requests] + assert [frame["method"] for frame in frames] == [ + "initialize", + "notifications/initialized", + "tools/list", + ] * 2 + assert frames[2] == {"jsonrpc": "2.0", "method": "tools/list", "id": 2} + assert frames[5] == {**frames[2], "params": {"cursor": cursor}} + assert all(request.path == "/mcp" for request in server.requests) + assert all( + request.headers["Authorization"] == f"Bearer {TOKEN}" for request in server.requests + ) + assert [request.headers.get("MCP-Protocol-Version") for request in server.requests] == [ + None, + "2025-11-25", + "2025-11-25", + ] * 2 + + +@MODES +@pytest.mark.parametrize( + "result", + [ + {"nextCursor": "opaque"}, + {"tools": {}}, + {"tools": [None]}, + {"tools": [{"inputSchema": {"type": "object"}}]}, + {"tools": [{"name": "review", "inputSchema": {"type": "array"}}]}, + {"tools": [{"name": "review", "inputSchema": {"type": "object"}, "annotations": []}]}, + {"tools": [], "nextCursor": None}, + {"tools": [], "_meta": []}, + ], +) +async def test_mcp_list_tools_rejects_malformed_pages(mode: str, result: dict[str, Any]) -> None: + def respond(request: Request, index: int) -> Reply: + if index == 0: + return catalog_initialize() + if index == 1: + return Reply(status=202, body=b"") + return Reply(body={"jsonrpc": "2.0", "id": 2, "result": result}) + + with Server(respond) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as error: + await call(client.mcp, "list_tools") + assert error.value.detail == "Invalid or refused MCP response." + assert len(server.requests) == 3 + + +@MODES +@pytest.mark.parametrize( + ("frame_index", "reply"), + [ + (0, Reply(body={"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-11-25"}})), + (0, catalog_initialize(version="2025-06-18")), + (0, catalog_initialize(identity=True)), + (1, Reply(status=202, body=TOKEN.encode())), + (2, Reply(status=302, headers={"Location": "http://127.0.0.1:1/mcp"})), + (2, Reply(status=403, body={"detail": f"{TOKEN} private diagnostic"})), + (2, Reply(status=503, body={"detail": TOKEN}, headers={"Retry-After": "0"})), + (2, Reply(body={"jsonrpc": "2.0", "id": 99, "result": {"tools": []}})), + (2, Reply(body={"jsonrpc": "2.0", "id": 2.0, "result": {"tools": []}})), + (2, Reply(body={"jsonrpc": "2.0", "id": 2, "error": {"code": -32601, "message": TOKEN}})), + (2, Reply(body=TOKEN.encode())), + (2, Reply(body=b'{"jsonrpc":"2.0","id":2,"result":{"tools":[],"_meta":{"bad":NaN}}}')), + ], +) +async def test_mcp_list_tools_protocol_failures_are_safe( + mode: str, frame_index: int, reply: Reply +) -> None: + def respond(request: Request, index: int) -> Reply: + if index == frame_index: + return reply + return catalog_initialize() if index == 0 else Reply(status=202, body=b"") + + with Server(respond) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as error: + await call(client.mcp, "list_tools") + assert error.value.type == "urn:proofline:sdk:mcp" + if reply.status >= 300: + assert error.value.status == reply.status + assert error.value.detail == "MCP HTTP request failed." + else: + assert error.value.detail == "Invalid or refused MCP response." + assert TOKEN not in str(error.value) + assert TOKEN not in repr(error.value) + assert error.value.__context__ is None + assert error.value.__cause__ is None + assert len(server.requests) == frame_index + 1 + + +@MODES +async def test_mcp_list_tools_refuses_deeply_nested_http_error(mode: str) -> None: + def respond(request: Request, index: int) -> Reply: + if index == 0: + return catalog_initialize() + if index == 1: + return Reply(status=202, body=b"") + return Reply(status=403, body=b'{"nested":' + b"[" * 2000 + b"0" + b"]" * 2000 + b"}") + + with Server(respond) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as error: + await call(client.mcp, "list_tools") + assert error.value.detail == "Invalid or refused MCP response." + assert error.value.__context__ is None + assert len(server.requests) == 3 + + +@MODES +async def test_mcp_list_tools_checks_cursor_before_network_access(mode: str) -> None: + with Server(lambda request, index: Reply(status=500)) as server: + async with session(mode, server.url) as client: + with pytest.raises(ValueError, match="cursor must be a string"): + await call(client.mcp, "list_tools", cursor=123) + with pytest.raises(ValueError, match="MCP request exceeds 8192 bytes"): + await call(client.mcp, "list_tools", cursor="λ" * 4096) + assert server.requests == [] + + @MODES async def test_knowledge_negotiation_scope_and_no_retry(mode: str) -> None: refusal = False @@ -2663,7 +2838,10 @@ async def refused(target: str | None, code: str) -> None: def test_mcp_public_types_accept_legacy_and_targeted_calls(tmp_path: Path) -> None: # Compile consumer code through the public entry point; dynamic HTTP tests # cannot catch a missing keyword in just one sync/async method signature. - lines = ["from proofline import ProoflineClient, AsyncProoflineClient, KnowledgeResult"] + lines = [ + "from proofline import (ProoflineClient, AsyncProoflineClient, KnowledgeResult, " + "McpToolPage, McpToolDefinition)" + ] calls = [ 'knowledge.list_wiki_pages("owner/name", commit="a" * 40)', 'knowledge.get_wiki_page("owner/name", "index")', @@ -2683,6 +2861,9 @@ def test_mcp_public_types_accept_legacy_and_targeted_calls(tmp_path: Path) -> No ]: lines.append(f"{prefix}def use_{kind}(client: {kind}) -> None:") lines.append(f" result: KnowledgeResult = {wait}client.mcp.list_organizations()") + lines.append(f" page: McpToolPage = {wait}client.mcp.list_tools()") + lines.append(f' page = {wait}client.mcp.list_tools(cursor=page.get("nextCursor"))') + lines.append(' tool: McpToolDefinition = page["tools"][0]') for expression in calls: lines.append(f" result = {wait}client.{expression}") targeted = expression[:-1] + ', organization_id="00000000-0000-7000-8000-000000000001")'