errors.py file-level

at sha256:c · View file ↗ · Intel ↗

History
1 files
1 commits
0 hotspots
0 🧊 dead
0 💥 blast risk
sha256:c docs(KD-STAGING): sync governance after KD-6b DONE Mirror workspace go… · aaronrene · Jul 10, 2026
1 """JSON-RPC error envelope helpers for the Muse MCP server (§KD-5a.0)."""
2
3 from __future__ import annotations
4
5 from typing import Any
6
7 from muse.core.validation import sanitize_display
8
9 # JSON-RPC 2.0 standard codes
10 PARSE_ERROR = -32700
11 INVALID_REQUEST = -32600
12 METHOD_NOT_FOUND = -32601
13 INVALID_PARAMS = -32602
14 INTERNAL_ERROR = -32603
15
16 # Application-level tool error (result carries reason in data)
17 TOOL_ERROR = -32001
18
19
20 class MCPApplicationError(Exception):
21 """Structured tool/resource error with a stable ``reason`` token."""
22
23 def __init__(
24 self,
25 reason: str,
26 message: str,
27 *,
28 detail: str | None = None,
29 ) -> None:
30 self.reason = reason
31 self.message = sanitize_display(message)
32 self.detail = sanitize_display(detail) if detail else None
33 super().__init__(message)
34
35 def to_data(self) -> dict[str, str]:
36 data: dict[str, str] = {"reason": self.reason}
37 if self.detail:
38 data["detail"] = self.detail
39 return data
40
41
42 def error_response(
43 req_id: str | int | None,
44 code: int,
45 message: str,
46 *,
47 data: dict[str, Any] | None = None,
48 ) -> dict[str, Any]:
49 """Build a JSON-RPC 2.0 error object."""
50 payload: dict[str, Any] = {
51 "jsonrpc": "2.0",
52 "id": req_id,
53 "error": {
54 "code": code,
55 "message": sanitize_display(message),
56 },
57 }
58 if data:
59 payload["error"]["data"] = data
60 return payload
61
62
63 def success_response(req_id: str | int | None, result: Any) -> dict[str, Any]:
64 """Build a JSON-RPC 2.0 success object."""
65 return {"jsonrpc": "2.0", "id": req_id, "result": result}