diff --git a/pkgguard/__init__.py b/pkgguard/__init__.py index 6c1b89e..b2cc541 100644 --- a/pkgguard/__init__.py +++ b/pkgguard/__init__.py @@ -8,7 +8,7 @@ Licensed under the Apache License 2.0. See LICENSE. """ -__version__ = "0.1.3" +__version__ = "0.1.4" __author__ = "Blvkware" __license__ = "Apache-2.0" __url__ = "https://blvkware.dev" diff --git a/pkgguard/mcp_server.py b/pkgguard/mcp_server.py index a0e220b..3e97139 100644 --- a/pkgguard/mcp_server.py +++ b/pkgguard/mcp_server.py @@ -8,7 +8,7 @@ import json import sys -from typing import Any, Dict, List +from typing import Any, Dict, Optional from . import __version__ from .agent import authorize_command, decision_to_dict @@ -24,11 +24,18 @@ def _rpc_response(request_id: Any, result: Any = None, error: Any = None) -> Dic def _authorize_tool(args: Dict[str, Any]) -> Dict[str, Any]: - command = str(args.get("command", "")).strip() - if not command: - raise ValueError("command is required") - allow_review = bool(args.get("allow_review", False)) - new_package_policy = str(args.get("new_package_policy", "block")) + if not isinstance(args, dict): + raise ValueError("arguments must be an object") + command = args.get("command") + if not isinstance(command, str) or not command.strip(): + raise ValueError("command must be a non-empty string") + command = command.strip() + allow_review = args.get("allow_review", False) + if not isinstance(allow_review, bool): + raise ValueError("allow_review must be a boolean") + new_package_policy = args.get("new_package_policy", "block") + if new_package_policy not in ("block", "review"): + raise ValueError("new_package_policy must be block or review") decision = authorize_command(command, new_package_policy) payload = decision_to_dict(decision, allow_review=allow_review) return { @@ -41,15 +48,45 @@ def _authorize_tool(args: Dict[str, Any]) -> Dict[str, Any]: } -def _handle_request(request: Dict[str, Any]) -> Dict[str, Any]: +#: MCP revisions this server speaks over stdio. initialize answers with the client's +#: version when it is one of these, otherwise with the newest, per the lifecycle spec. +SUPPORTED_PROTOCOL_VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05") + +_OUTPUT_SCHEMA = { + "type": "object", + "properties": { + "decision": {"type": "string", "enum": ["ALLOW", "REVIEW", "BLOCK"]}, + "safe_to_execute": {"type": "boolean"}, + "ecosystem": {"type": ["string", "null"]}, + "packages": {"type": "array", "items": {"type": "string"}}, + "reason": {"type": "string"}, + "assessments": {"type": "array", "items": {"type": "object"}}, + }, + "required": ["decision", "safe_to_execute", "packages", "reason", "assessments"], +} + + +def _handle_request(request: Any) -> Optional[Dict[str, Any]]: + if not isinstance(request, dict) or request.get("jsonrpc") != "2.0" or not isinstance(request.get("method"), str): + return _rpc_response(None, error={"code": -32600, "message": "Invalid Request"}) method = request.get("method") request_id = request.get("id") + if "id" not in request: + return None + if isinstance(request_id, bool) or not isinstance(request_id, (str, int)): + return _rpc_response(None, error={"code": -32600, "message": "Invalid Request ID"}) + if "params" in request and not isinstance(request["params"], dict): + return _rpc_response(request_id, error={"code": -32602, "message": "params must be an object"}) + + if method == "ping": + return _rpc_response(request_id, {}) if method == "initialize": + requested = request.get("params", {}).get("protocolVersion") return _rpc_response( request_id, { - "protocolVersion": "2024-11-05", + "protocolVersion": requested if requested in SUPPORTED_PROTOCOL_VERSIONS else SUPPORTED_PROTOCOL_VERSIONS[0], "capabilities": {"tools": {}}, "serverInfo": {"name": "pkgguard", "version": __version__}, }, @@ -62,7 +99,10 @@ def _handle_request(request: Dict[str, Any]) -> Dict[str, Any]: "tools": [ { "name": "authorize_install_command", + "title": "Authorize an install command", "description": "Authorize an agent-generated install command before it reaches a package manager.", + "annotations": {"readOnlyHint": True, "destructiveHint": False, "idempotentHint": True, "openWorldHint": True}, + "outputSchema": _OUTPUT_SCHEMA, "inputSchema": { "type": "object", "properties": { @@ -87,7 +127,7 @@ def _handle_request(request: Dict[str, Any]) -> Dict[str, Any]: if tool_name != "authorize_install_command": return _rpc_response( request_id, - error={"code": -32601, "message": f"Unknown tool: {tool_name}"}, + error={"code": -32602, "message": f"Unknown tool: {tool_name}"}, ) try: result = _authorize_tool(params.get("arguments", {})) diff --git a/tests/test_mcp_validation.py b/tests/test_mcp_validation.py new file mode 100644 index 0000000..39c96b9 --- /dev/null +++ b/tests/test_mcp_validation.py @@ -0,0 +1,84 @@ +import io +import json + +import pytest + +from pkgguard import mcp_server + + +def call(arguments): + return mcp_server._handle_request({ + "jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": {"name": "authorize_install_command", "arguments": arguments}, + }) + + +@pytest.mark.parametrize("value", ["false", "true", 0, 1, [], {}, None]) +def test_approval_requires_a_real_boolean(value, monkeypatch): + def unexpected(*args): + pytest.fail("invalid approval must be rejected before checking a command") + monkeypatch.setattr(mcp_server, "authorize_command", unexpected) + assert call({"command": "pip install requests", "allow_review": value})["error"]["code"] == -32602 + + +@pytest.mark.parametrize("arguments", [None, [], "bad", 42, {"command": 42}, {"command": " "}, + {"command": "pip install requests", "new_package_policy": "allow"}]) +def test_invalid_arguments_are_parameter_errors(arguments): + assert call(arguments)["error"]["code"] == -32602 + + +def test_stdio_survives_invalid_envelopes(monkeypatch): + requests = [None, [], 42, "bad", {"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": None}, + {"jsonrpc": "2.0", "id": 3, "method": "ping"}] + output = io.StringIO() + monkeypatch.setattr(mcp_server.sys, "stdin", io.StringIO("\n".join(json.dumps(r) for r in requests))) + monkeypatch.setattr(mcp_server.sys, "stdout", output) + assert mcp_server.main() == 0 + responses = [json.loads(line) for line in output.getvalue().splitlines()] + assert len(responses) == len(requests) + assert [r["error"]["code"] for r in responses[:4]] == [-32600] * 4 + assert responses[4]["error"]["code"] == -32602 + assert responses[-1] == {"jsonrpc": "2.0", "id": 3, "result": {}} + + +def test_notifications_never_execute_tool_calls(monkeypatch): + def unexpected(*args): + pytest.fail("a notification must not authorize an install") + monkeypatch.setattr(mcp_server, "authorize_command", unexpected) + assert mcp_server._handle_request({"jsonrpc": "2.0", "method": "tools/call", "params": { + "name": "authorize_install_command", "arguments": {"command": "pip install requests"}}}) is None + + +@pytest.mark.parametrize("approved", [False, True]) +def test_explicit_boolean_preserves_review_policy(approved, monkeypatch): + from pkgguard.agent import CommandDecision + monkeypatch.setattr(mcp_server, "authorize_command", lambda *args: CommandDecision( + command="pip install new-package", decision="REVIEW", ecosystem="pypi", packages=["new-package"])) + result = call({"command": "pip install new-package", "allow_review": approved}) + assert result["result"]["structuredContent"]["safe_to_execute"] is approved + + +def test_initialize_negotiates_protocol_version(): + from pkgguard.mcp_server import SUPPORTED_PROTOCOL_VERSIONS, _handle_request + + for version in ("2025-11-25", "2025-06-18", "2024-11-05"): + reply = _handle_request({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": version}}) + assert reply["result"]["protocolVersion"] == version + reply = _handle_request({"jsonrpc": "2.0", "id": 2, "method": "initialize", "params": {"protocolVersion": "1900-01-01"}}) + assert reply["result"]["protocolVersion"] == SUPPORTED_PROTOCOL_VERSIONS[0] + + +def test_tool_declares_read_only_and_output_schema(): + from pkgguard.mcp_server import _handle_request + + tool = _handle_request({"jsonrpc": "2.0", "id": 1, "method": "tools/list"})["result"]["tools"][0] + assert tool["annotations"]["readOnlyHint"] is True + assert tool["outputSchema"]["type"] == "object" + assert set(tool["outputSchema"]["required"]) <= {"decision", "safe_to_execute", "packages", "reason", "assessments"} + + +def test_unknown_tool_is_invalid_params(): + from pkgguard.mcp_server import _handle_request + + reply = _handle_request({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "nope", "arguments": {}}}) + assert reply["error"]["code"] == -32602