diff --git a/README.md b/README.md index 721949da..517773fd 100644 --- a/README.md +++ b/README.md @@ -145,7 +145,7 @@ The response names the recorded report and its covered and instrumented line cou 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`. -Pass the chosen UUID string as the optional keyword `organization_id` on any `knowledge` or `fixes` method: +Pass the chosen UUID string as the optional keyword `organization_id` on any `knowledge`, `fixes`, `config` or `setup` method: ```python organizations = client.mcp.list_organizations() @@ -211,6 +211,43 @@ if result.get("isError"): Calls under `client.fixes` never retry. Results retain untrusted-text wrappers, availability, assessment gaps, and `isError`. `PENDING` and `NOT_VERIFIED` do not establish a fix, and a tool request never records a human disposition. +## Setup and configuration + +Both clients expose the hosted setup reads under `client.setup` and configuration changes under `client.config`, over the same stateless MCP endpoint as `proofline setup` and `proofline config`. Every method accepts the optional `organization_id` keyword described above: + +- `setup.get_setup_status()` +- `setup.list_setup_candidates(query=...)` +- `config.get_configuration(environment_id=..., repository=...)` +- `config.list_operations(area=..., subject=...)` +- `config.describe_operation(operation, parameters)` +- `config.propose_change(operation, parameters=..., input=..., expected_revision=..., cited_files=..., request_id=...)` +- `config.apply_change(change_id)` + +The setup reads and `get_configuration` require `setup:write`. `describe_operation` and `apply_change` require `org:configure`; `list_operations` and `propose_change` accept either scope, although an ordinary proposal needs `org:configure`. The MCP endpoint also requires `reviews:read`. + +```python +described = client.config.describe_operation( + "repository.wiki_settings.update", {"repo_id": repository_id} +) +data = described["structuredContent"]["data"] +proposal = client.config.propose_change( + "repository.wiki_settings.update", + parameters={"repo_id": repository_id}, + input={"enabled": True}, + expected_revision=data["revision"], +) +if proposal.get("isError"): + raise RuntimeError("The proposal was refused.") +change = proposal["structuredContent"]["data"] +if "approval_url" in change: + print("An administrator must approve the change at", change["approval_url"]) +else: + print(change["diff"]) + applied = client.config.apply_change(change["change_id"]) +``` + +A proposal applies nothing. `propose_change` sends a new UUID version 7 as `request_id` on each call; to retry the identical call after an uncertain result, pass the same value, for example one from `new_request_id()`. Each entry of `cited_files` names the `repository_id`, the full `commit_sha` and the repository-relative `path` of a file read at that commit. An ordinary change applies through `apply_change`. A sensitive change returns an `approval_url` from either call, and applies only when an organization administrator approves it in a browser. Like the other MCP helpers, these methods never retry, raise `ProoflineError` for protocol and HTTP errors, and return tool refusals and held changes with `isError` and the server's reason for the caller to inspect. Treat returned prose as untrusted data. + ## Development The repository bundles its public API contract in `openapi.public.json`. New public operations generate typed methods on both `ProoflineClient` and `AsyncProoflineClient` along with the code in `proofline/_generated/`. diff --git a/proofline/__init__.py b/proofline/__init__.py index 689b454d..7d6bd1e5 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -34,6 +34,7 @@ from ._transport import VERSION as __version__ from ._transport import ProoflineError, RunNowRefusal from .client import AsyncProoflineClient, ProoflineClient, ReviewFilters +from .configuration import CitedFile, new_request_id from .exports import ExportDataset, ExportFormat, ExportPage from .knowledge import KnowledgeResult from .outcomes import AssessmentGap, CheckGap, ReviewOutcome @@ -44,6 +45,7 @@ "AssessmentGap", "AsyncProoflineClient", "CheckGap", + "CitedFile", "CommitReviewRequest", "CommitReviewResponse", "CoverageUploadRequest", @@ -80,4 +82,5 @@ "UploadedReport", "__version__", "models", + "new_request_id", ] diff --git a/proofline/client.py b/proofline/client.py index 1d8c1519..d93941a8 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -72,6 +72,12 @@ from ._generated.types import UNSET, Response, Unset from ._mcp import AsyncMcpClient, McpClient from ._transport import ProoflineError +from .configuration import ( + AsyncConfigurationClient, + AsyncSetupClient, + ConfigurationClient, + SetupClient, +) from .exports import ExportDataset, ExportFormat, ExportPage, decode_export from .fixes import AsyncFixesClient, FixesClient from .knowledge import AsyncKnowledgeClient, KnowledgeClient @@ -240,6 +246,8 @@ def __init__( self.mcp = McpClient(self._http) self.knowledge = KnowledgeClient(self._http) self.fixes = FixesClient(self._http) + self.config = ConfigurationClient(self._http) + self.setup = SetupClient(self._http) def close(self) -> None: self._http.close() @@ -610,6 +618,8 @@ def __init__( self.mcp = AsyncMcpClient(self._http) self.knowledge = AsyncKnowledgeClient(self._http) self.fixes = AsyncFixesClient(self._http) + self.config = AsyncConfigurationClient(self._http) + self.setup = AsyncSetupClient(self._http) async def aclose(self) -> None: await self._http.aclose() diff --git a/proofline/configuration.py b/proofline/configuration.py new file mode 100644 index 00000000..f2e1467c --- /dev/null +++ b/proofline/configuration.py @@ -0,0 +1,211 @@ +"""Setup reads and configuration changes through the scoped MCP server. + +A proposal applies nothing; an ordinary change applies only through apply_change, +and a sensitive one only through browser approval. Tool refusals retain isError. +""" + +from __future__ import annotations + +import os +import time +from collections.abc import Mapping, Sequence +from typing import Any, TypedDict +from uuid import UUID + +from ._mcp import AsyncMcpTools, KnowledgeResult, McpTools + + +class CitedFile(TypedDict): + """A repository file, read at a full commit SHA, behind an inferred value.""" + + repository_id: str + commit_sha: str + path: str + + +def new_request_id() -> str: + """Return a fresh time-ordered UUID (version 7) for one propose_change call.""" + value = (time.time_ns() // 1_000_000 & (1 << 48) - 1) << 80 + value |= int.from_bytes(os.urandom(10), "big") + value = value & ~(0xF << 76) | 0x7 << 76 + value = value & ~(0x3 << 62) | 0x2 << 62 + return str(UUID(int=value)) + + +def _optional(**values: Any) -> dict[str, Any]: + return {name: value for name, value in values.items() if value is not None} + + +def _describe(operation: str, parameters: Mapping[str, str] | None) -> dict[str, Any]: + return {"operation": operation, "parameters": dict(parameters or {})} + + +def _proposal( + operation: str, + parameters: Mapping[str, str] | None, + input: Any, + expected_revision: str | None, + cited_files: Sequence[CitedFile] | None, + request_id: str | None, +) -> dict[str, Any]: + args: dict[str, Any] = {"operation": operation, "parameters": dict(parameters or {})} + if input is not None: + args["input"] = input + if expected_revision is not None: + args["expected_revision"] = expected_revision + if cited_files is not None: + args["cited_files"] = [dict(cited) for cited in cited_files] + args["request_id"] = new_request_id() if request_id is None else request_id + return args + + +class ConfigurationClient(McpTools): + def get_configuration( + self, + *, + environment_id: str | None = None, + repository: str | None = None, + organization_id: str | None = None, + ) -> KnowledgeResult: + return self._call( + "get_configuration", + _optional(environment_id=environment_id, repository=repository), + organization_id=organization_id, + ) + + def list_operations( + self, + *, + area: str | None = None, + subject: str | None = None, + organization_id: str | None = None, + ) -> KnowledgeResult: + return self._call( + "list_operations", + _optional(area=area, subject=subject), + organization_id=organization_id, + ) + + def describe_operation( + self, + operation: str, + parameters: Mapping[str, str] | None = None, + *, + organization_id: str | None = None, + ) -> KnowledgeResult: + return self._call( + "describe_operation", + _describe(operation, parameters), + organization_id=organization_id, + ) + + def propose_change( + self, + operation: str, + *, + parameters: Mapping[str, str] | None = None, + input: Any = None, + expected_revision: str | None = None, + cited_files: Sequence[CitedFile] | None = None, + request_id: str | None = None, + organization_id: str | None = None, + ) -> KnowledgeResult: + return self._call( + "propose_change", + _proposal(operation, parameters, input, expected_revision, cited_files, request_id), + organization_id=organization_id, + ) + + def apply_change( + self, change_id: str, *, organization_id: str | None = None + ) -> KnowledgeResult: + return self._call("apply_change", {"change_id": change_id}, organization_id=organization_id) + + +class AsyncConfigurationClient(AsyncMcpTools): + async def get_configuration( + self, + *, + environment_id: str | None = None, + repository: str | None = None, + organization_id: str | None = None, + ) -> KnowledgeResult: + return await self._call( + "get_configuration", + _optional(environment_id=environment_id, repository=repository), + organization_id=organization_id, + ) + + async def list_operations( + self, + *, + area: str | None = None, + subject: str | None = None, + organization_id: str | None = None, + ) -> KnowledgeResult: + return await self._call( + "list_operations", + _optional(area=area, subject=subject), + organization_id=organization_id, + ) + + async def describe_operation( + self, + operation: str, + parameters: Mapping[str, str] | None = None, + *, + organization_id: str | None = None, + ) -> KnowledgeResult: + return await self._call( + "describe_operation", + _describe(operation, parameters), + organization_id=organization_id, + ) + + async def propose_change( + self, + operation: str, + *, + parameters: Mapping[str, str] | None = None, + input: Any = None, + expected_revision: str | None = None, + cited_files: Sequence[CitedFile] | None = None, + request_id: str | None = None, + organization_id: str | None = None, + ) -> KnowledgeResult: + return await self._call( + "propose_change", + _proposal(operation, parameters, input, expected_revision, cited_files, request_id), + organization_id=organization_id, + ) + + async def apply_change( + self, change_id: str, *, organization_id: str | None = None + ) -> KnowledgeResult: + return await self._call( + "apply_change", {"change_id": change_id}, organization_id=organization_id + ) + + +class SetupClient(McpTools): + def get_setup_status(self, *, organization_id: str | None = None) -> KnowledgeResult: + return self._call("get_setup_status", {}, organization_id=organization_id) + + def list_setup_candidates( + self, *, query: str | None = None, organization_id: str | None = None + ) -> KnowledgeResult: + return self._call( + "list_setup_candidates", _optional(query=query), organization_id=organization_id + ) + + +class AsyncSetupClient(AsyncMcpTools): + async def get_setup_status(self, *, organization_id: str | None = None) -> KnowledgeResult: + return await self._call("get_setup_status", {}, organization_id=organization_id) + + async def list_setup_candidates( + self, *, query: str | None = None, organization_id: str | None = None + ) -> KnowledgeResult: + return await self._call( + "list_setup_candidates", _optional(query=query), organization_id=organization_id + ) diff --git a/tests/test_configuration.py b/tests/test_configuration.py new file mode 100644 index 00000000..1b588a61 --- /dev/null +++ b/tests/test_configuration.py @@ -0,0 +1,241 @@ +from __future__ import annotations + +import inspect +import json +import time +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from typing import Any +from uuid import UUID + +import pytest +from pydantic import SecretStr + +from proofline import ( + AsyncProoflineClient, + CitedFile, + ProoflineClient, + ProoflineError, + new_request_id, +) + +from .fixtures import ORG, REPOSITORY, REVIEW, TOKEN +from .http_server import Reply, Request, Server + +MODES = pytest.mark.parametrize("mode", ["sync", "async"]) +CHANGE = "00000000-0000-7000-8000-000000000009" + + +@asynccontextmanager +async def session(mode: str, url: str) -> AsyncIterator[Any]: + if mode == "sync": + with ProoflineClient(SecretStr(TOKEN), base_url=url) as client: + yield client + else: + async with AsyncProoflineClient(SecretStr(TOKEN), base_url=url) as async_client: + yield async_client + + +def tool_server(results: list[dict[str, Any]], observed: list[dict[str, Any]]) -> Server: + """Answer the MCP handshake, then each tool call with the next result.""" + + def respond(request: Request, index: int) -> Reply: + assert request.path == "/mcp" + assert request.headers["Authorization"] == f"Bearer {TOKEN}" + body = json.loads(request.body) + 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"") + observed.append(body["params"]) + result = results.pop(0) + if "status" in result: + return Reply(status=result["status"], body={"detail": "unavailable"}) + return Reply(body={"jsonrpc": "2.0", "id": 2, "result": result}) + + return Server(respond) + + +def answer(data: dict[str, Any], *, refused: bool = False) -> dict[str, Any]: + body = {"ok": not refused, ("error" if refused else "data"): data} + return { + "isError": refused, + "structuredContent": body, + "content": [{"type": "text", "text": json.dumps(body)}], + } + + +async def invoke(client: Any, group: str, name: str, *args: Any, **kwargs: Any) -> Any: + result = getattr(getattr(client, group), name)(*args, **kwargs) + return await result if inspect.isawaitable(result) else result + + +@MODES +async def test_reads_forward_only_the_given_selectors(mode: str) -> None: + cases: list[tuple[str, str, tuple[Any, ...], dict[str, Any], dict[str, Any]]] = [ + ("config", "get_configuration", (), {}, {}), + ( + "config", + "get_configuration", + (), + {"environment_id": str(REVIEW)}, + {"environment_id": str(REVIEW)}, + ), + ( + "config", + "get_configuration", + (), + {"repository": "owner/name"}, + {"repository": "owner/name"}, + ), + ("config", "list_operations", (), {}, {}), + ( + "config", + "list_operations", + (), + {"area": "REPOSITORY_REVIEW_SETTINGS", "subject": "repository"}, + {"area": "REPOSITORY_REVIEW_SETTINGS", "subject": "repository"}, + ), + ( + "config", + "describe_operation", + ("organization.settings.update",), + {}, + {"operation": "organization.settings.update", "parameters": {}}, + ), + ( + "config", + "describe_operation", + ("repository.wiki_settings.update", {"repo_id": "slug", "label": "a=b"}), + {}, + { + "operation": "repository.wiki_settings.update", + "parameters": {"repo_id": "slug", "label": "a=b"}, + }, + ), + ("config", "apply_change", (CHANGE,), {}, {"change_id": CHANGE}), + ("setup", "get_setup_status", (), {}, {}), + ("setup", "list_setup_candidates", (), {}, {}), + ("setup", "list_setup_candidates", (), {"query": "api"}, {"query": "api"}), + ] + results = [answer({"case": index}) for index in range(len(cases) * 2)] + observed: list[dict[str, Any]] = [] + with tool_server(results, observed) as server: + async with session(mode, server.url) as client: + index = 0 + for group, name, args, kwargs, expected in cases: + for target in (None, str(ORG)): + targeted = {} if target is None else {"organization_id": target} + result = await invoke(client, group, name, *args, **kwargs, **targeted) + assert result["structuredContent"]["data"] == {"case": index} + assert observed[-1] == { + "name": name, + "arguments": {**expected, **targeted}, + } + index += 1 + # Each call is one handshake and one tool request, never a retry. + assert len(server.requests) == len(observed) * 3 + + +@MODES +async def test_propose_sends_the_change_with_a_fresh_request_id(mode: str) -> None: + cited: CitedFile = { + "repository_id": str(REPOSITORY), + "commit_sha": "b" * 40, + "path": "infra/main.tf", + } + held = answer( + { + "applied": False, + "change_id": CHANGE, + "diff": {"current": {"enabled": False}, "proposed": {"enabled": True}}, + } + ) + observed: list[dict[str, Any]] = [] + with tool_server([held, held, held, held], observed) as server: + async with session(mode, server.url) as client: + for _ in range(2): + result = await invoke( + client, + "config", + "propose_change", + "environment.review_focus.update", + parameters={"env_id": str(REPOSITORY)}, + input={"focus": "production"}, + expected_revision="a" * 64, + cited_files=[cited], + ) + assert result == held + # A retry of the identical call keeps the caller's request ID. + await invoke( + client, "config", "propose_change", "organization.settings.update", + request_id=CHANGE, organization_id=str(ORG), + ) # fmt: skip + # An operation without a body sends no input. + await invoke(client, "config", "propose_change", "repository.wiki_settings.reset") + + generated = [UUID(params["arguments"].pop("request_id")) for params in observed[:2]] + assert [identity.version for identity in generated] == [7, 7] + assert generated[0] != generated[1] + for params in observed[:2]: + assert params == { + "name": "propose_change", + "arguments": { + "operation": "environment.review_focus.update", + "parameters": {"env_id": str(REPOSITORY)}, + "input": {"focus": "production"}, + "expected_revision": "a" * 64, + "cited_files": [cited], + }, + } + assert observed[2]["arguments"] == { + "operation": "organization.settings.update", + "parameters": {}, + "request_id": CHANGE, + "organization_id": str(ORG), + } + assert set(observed[3]["arguments"]) == {"operation", "parameters", "request_id"} + + +@MODES +async def test_refusals_and_held_changes_are_returned_and_never_retried(mode: str) -> None: + refusal = answer( + {"code": "NOT_AUTHORIZED", "message": "Missing org:configure", "retryable": False}, + refused=True, + ) + sensitive = answer( + { + "applied": False, + "reason": "An administrator must approve this change in the browser.", + "approval_url": f"https://proofline.sh/orgs/by-id/{ORG}/configuration-changes/{CHANGE}", + } + ) + observed: list[dict[str, Any]] = [] + with tool_server([refusal, sensitive, {"status": 503}], observed) as server: + async with session(mode, server.url) as client: + result = await invoke(client, "config", "propose_change", "org.settings.update") + assert result["isError"] is True + assert result["structuredContent"]["error"]["code"] == "NOT_AUTHORIZED" + held = await invoke(client, "config", "apply_change", CHANGE) + assert held["structuredContent"]["data"]["applied"] is False + with pytest.raises(ProoflineError): + await invoke(client, "config", "apply_change", CHANGE) + assert [params["name"] for params in observed] == [ + "propose_change", + "apply_change", + "apply_change", + ] + + +def test_new_request_id_is_a_time_ordered_rfc_9562_uuid() -> None: + before = time.time_ns() // 1_000_000 + identities = [UUID(new_request_id()) for _ in range(200)] + after = time.time_ns() // 1_000_000 + assert len(set(identities)) == 200 + for identity in identities: + assert identity.version == 7 + assert identity.variant == "specified in RFC 4122" + assert before <= identity.int >> 80 <= after diff --git a/tests/test_http.py b/tests/test_http.py index 0af9d60f..cb640d06 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2530,6 +2530,14 @@ def test_mcp_public_types_accept_legacy_and_targeted_calls(tmp_path: Path) -> No 'fixes.get_fix_context("finding-id")', 'fixes.request_reverification("review-id", ["finding-id"], "a" * 40, note="fixed")', 'fixes.get_reverification("request-id")', + 'config.get_configuration(repository="owner/name")', + 'config.list_operations(area="REPOSITORY_REVIEW_SETTINGS", subject="repository")', + 'config.describe_operation("repository.wiki_settings.update", {"repo_id": "id"})', + 'config.propose_change("op", input={"enabled": True}, expected_revision="a" * 64, ' + 'cited_files=[{"repository_id": "id", "commit_sha": "a" * 40, "path": "main.tf"}])', + 'config.apply_change("change-id")', + "setup.get_setup_status()", + 'setup.list_setup_candidates(query="api")', ] for prefix, kind, wait in [ ("", "ProoflineClient", ""), @@ -2539,7 +2547,9 @@ def test_mcp_public_types_accept_legacy_and_targeted_calls(tmp_path: Path) -> No lines.append(f" result: KnowledgeResult = {wait}client.mcp.list_organizations()") for expression in calls: lines.append(f" result = {wait}client.{expression}") - targeted = expression[:-1] + ', organization_id="00000000-0000-7000-8000-000000000001")' + separator = "" if expression.endswith("()") else ", " + target = 'organization_id="00000000-0000-7000-8000-000000000001")' + targeted = expression[:-1] + separator + target lines.append(f" result = {wait}client.{targeted}") fixture = tmp_path / "mcp_types.py" fixture.write_text("\n".join(lines))