Coverage for src/governed_harness/embedded/mcp_server.py: 84%

142 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-12 16:06 +0000

1"""``harness mcp serve``: the harness as a Model Context Protocol server over stdio (#56). 

2 

3Embedded mode: an agent drives the governed flow from its own session (Claude Code, Codex or 

4any MCP client) while the harness keeps enforcing the gates, the digests and the decisions. 

5The server speaks JSON-RPC 2.0, one message per line on standard input and output 

6(``initialize``, ``ping``, ``tools/list``, ``tools/call``) and exposes read and governed 

7actions only: 

8 

9============================= ======================================================= 

10Tool What it does 

11============================= ======================================================= 

12``harness_project`` What the harness detects (new or existing, packs, ...) 

13``harness_status`` The status projection of a run 

14``harness_inbox`` Runs that wait for a person 

15``harness_task_create`` Create a task from a task document 

16``harness_task_questions`` The open clarification questions of a task 

17``harness_task_clarify`` Record the person's answers, relayed by the session 

18``harness_run_start`` Start a run (default provider ``session``) 

19``harness_run_continue`` Continue a run (after the session's edits, for example) 

20``harness_check`` The gate's validators and checks, nothing recorded 

21``harness_review`` The decision brief of a run 

22``harness_standards`` The standards cards for some files 

23============================= ======================================================= 

24 

25Human decisions are **not** exposed: no tool decides a gate, acceptance tests, a plan, the 

26architecture, a budget raise, an exception or a memory record. A tool result says what a person 

27must run (``next``), and the person runs it in a terminal. A clarification answer is recorded 

28with the person's identity and marked as relayed by an agent session.""" 

29 

30from __future__ import annotations 

31 

32import json 

33import sys 

34import tempfile 

35from collections.abc import Callable 

36from pathlib import Path 

37from typing import IO, Any 

38 

39import yaml 

40 

41from governed_harness import __version__ 

42from governed_harness.application import HarnessApplication 

43from governed_harness.domain.errors import HarnessError, NotFoundError 

44 

45PROTOCOL_VERSIONS = ("2025-06-18", "2025-03-26", "2024-11-05") 

46SERVER_NAME = "governed-harness" 

47HUMAN_ONLY = ( 

48 "harness gate decide", 

49 "harness acceptance decide", 

50 "harness acceptance dispute", 

51 "harness plan decide", 

52 "harness architecture decide", 

53 "harness budget raise", 

54 "harness memory approve", 

55) 

56 

57INSTRUCTIONS = ( 

58 "Governed Agent Harness. Drive a governed change: harness_task_create, harness_run_start " 

59 "(provider session: you implement in this session), then edit the workspace and call " 

60 "harness_run_continue; use harness_check before you continue and harness_status to read " 

61 "findings. Clarification questions are answered by the person: ask them and relay their " 

62 "exact words with harness_task_clarify. Never decide for a person: gate, acceptance, plan " 

63 "and architecture decisions are made by a person in a terminal." 

64) 

65 

66 

67def _schema(properties: dict[str, Any], required: tuple[str, ...] = ()) -> dict[str, Any]: 

68 return { 

69 "type": "object", 

70 "properties": properties, 

71 "required": list(required), 

72 "additionalProperties": False, 

73 } 

74 

75 

76_RUN = {"type": "string", "description": "Run id, a unique prefix or latest"} 

77TOOLS: tuple[dict[str, Any], ...] = ( 

78 { 

79 "name": "harness_project", 

80 "description": "What the harness detects about the project: new or existing, standards " 

81 "packs, testing strategy, architecture and forge. Reads only.", 

82 "inputSchema": _schema({}), 

83 }, 

84 { 

85 "name": "harness_status", 

86 "description": "The status of a run: phases, validations, findings, gate, decision.", 

87 "inputSchema": _schema({"run": _RUN}), 

88 }, 

89 { 

90 "name": "harness_inbox", 

91 "description": "Runs that wait for a person (a decision or clarification answers).", 

92 "inputSchema": _schema({}), 

93 }, 

94 { 

95 "name": "harness_task_create", 

96 "description": "Create (or replace) a task from a task document: title, intent, " 

97 "requirements, acceptanceCriteria, constraints. Use implementation mode none: you " 

98 "implement in this session.", 

99 "inputSchema": _schema( 

100 {"task": {"type": "object", "description": "The task document (task.yaml fields)"}}, 

101 ("task",), 

102 ), 

103 }, 

104 { 

105 "name": "harness_task_questions", 

106 "description": "The open clarification questions of a task, for the person to answer.", 

107 "inputSchema": _schema({"taskId": {"type": "string"}}, ("taskId",)), 

108 }, 

109 { 

110 "name": "harness_task_clarify", 

111 "description": "Record the person's answers to the clarification questions (question id " 

112 "to the person's exact words). Recorded with the person's identity, marked as relayed " 

113 "by an agent session. Do not answer for the person.", 

114 "inputSchema": _schema( 

115 { 

116 "taskId": {"type": "string"}, 

117 "answers": {"type": "object", "additionalProperties": {"type": "string"}}, 

118 }, 

119 ("taskId", "answers"), 

120 ), 

121 }, 

122 { 

123 "name": "harness_run_start", 

124 "description": "Start a governed run of a task. The default provider session waits in " 

125 "IMPLEMENTATION for your edits; harness_run_continue then verifies them.", 

126 "inputSchema": _schema( 

127 {"taskId": {"type": "string"}, "provider": {"type": "string", "default": "session"}}, 

128 ("taskId",), 

129 ), 

130 }, 

131 { 

132 "name": "harness_run_continue", 

133 "description": "Continue a run: after your edits, after a person's decision or answers.", 

134 "inputSchema": _schema({"run": _RUN}, ("run",)), 

135 }, 

136 { 

137 "name": "harness_check", 

138 "description": "Run the gate's validators and diff checks on the workspace without " 

139 "recording anything.", 

140 "inputSchema": _schema({"run": _RUN}), 

141 }, 

142 { 

143 "name": "harness_review", 

144 "description": "The decision brief of a run: what was asked and changed, the gate, the " 

145 "risks and what a person must decide.", 

146 "inputSchema": _schema({"run": _RUN}), 

147 }, 

148 { 

149 "name": "harness_standards", 

150 "description": "The standards cards that apply to some files (follow them).", 

151 "inputSchema": _schema( 

152 {"files": {"type": "array", "items": {"type": "string"}}}, ("files",) 

153 ), 

154 }, 

155) 

156"""The tools of the server; a tool that decides for a person does not exist here.""" 

157 

158 

159def exit_code(execution: dict[str, Any]) -> int: 

160 """The exit code ``harness run start`` would give for this execution.""" 

161 status, phase = execution.get("status"), execution.get("currentPhase") 

162 if status == "PASSED": 162 ↛ 163line 162 didn't jump to line 163 because the condition on line 162 was never true

163 return 0 

164 if status == "CANCELLED": 164 ↛ 165line 164 didn't jump to line 165 because the condition on line 164 was never true

165 return 130 

166 if status == "BLOCKED" and phase == "DECISION": 

167 return 4 

168 if status == "ERROR": 168 ↛ 169line 168 didn't jump to line 169 because the condition on line 168 was never true

169 return 1 

170 return 6 

171 

172 

173class McpServer: 

174 def __init__(self, workspace: Path, application: HarnessApplication | None = None) -> None: 

175 self.workspace = workspace 

176 self.application = application or HarnessApplication() 

177 self._handlers: dict[str, Callable[[dict[str, Any]], Any]] = { 

178 "harness_project": lambda args: self.application.project(self.workspace), 

179 "harness_status": lambda args: self.application.status( 

180 self.workspace, args.get("run") or "latest" 

181 ), 

182 "harness_inbox": lambda args: self.application.inbox(self.workspace), 

183 "harness_task_create": self._task_create, 

184 "harness_task_questions": lambda args: self.application.list_clarifications( 

185 self.workspace, str(args["taskId"]) 

186 ), 

187 "harness_task_clarify": self._task_clarify, 

188 "harness_run_start": self._run_start, 

189 "harness_run_continue": self._run_continue, 

190 "harness_check": self._check, 

191 "harness_review": lambda args: self.application.review( 

192 self.workspace, args.get("run") or "latest" 

193 ), 

194 "harness_standards": lambda args: self.application.standards( 

195 self.workspace, files=tuple(str(item) for item in args.get("files") or []) 

196 ), 

197 } 

198 

199 # ----- tools ------------------------------------------------------------------------------- 

200 def _task_create(self, args: dict[str, Any]) -> Any: 

201 task = args.get("task") 

202 if not isinstance(task, dict): 202 ↛ 203line 202 didn't jump to line 203 because the condition on line 202 was never true

203 raise ValueError("task must be an object") 

204 with tempfile.TemporaryDirectory(prefix="harness-mcp-") as scratch: 

205 source = Path(scratch) / "task.yaml" 

206 source.write_text(yaml.safe_dump(task, sort_keys=False), encoding="utf-8") 

207 created = self.application.create_task(self.workspace, source) 

208 return created.model_dump(mode="json", by_alias=True) 

209 

210 def _task_clarify(self, args: dict[str, Any]) -> Any: 

211 answers = args.get("answers") 

212 if not isinstance(answers, dict) or not answers: 212 ↛ 213line 212 didn't jump to line 213 because the condition on line 212 was never true

213 raise ValueError("answers must map question ids to the person's answers") 

214 with tempfile.TemporaryDirectory(prefix="harness-mcp-") as scratch: 

215 source = Path(scratch) / "answers.yaml" 

216 source.write_text( 

217 yaml.safe_dump({"answers": {str(k): str(v) for k, v in answers.items()}}), 

218 encoding="utf-8", 

219 ) 

220 return self.application.clarify_task( 

221 self.workspace, task_id=str(args["taskId"]), answers_file=source, relayed=True 

222 ) 

223 

224 def _check(self, args: dict[str, Any]) -> Any: 

225 """The run's check state when the gate contract wrote one, else the validators only.""" 

226 run = args.get("run") 

227 try: 

228 return self.application.check(self.workspace, run) 

229 except NotFoundError: 

230 return self.application.check(self.workspace, None) 

231 

232 def _execution(self, execution: Any) -> dict[str, Any]: 

233 value: dict[str, Any] = execution.model_dump(mode="json", by_alias=True) 

234 value["exitCode"] = exit_code(value) 

235 if value.get("currentPhase") == "DECISION" and value["exitCode"] == 4: 

236 value["next"] = ( 

237 f"A person decides in a terminal: harness review --run {value['executionId']} " 

238 f"then harness gate decide --run {value['executionId']}" 

239 ) 

240 return value 

241 

242 def _run_start(self, args: dict[str, Any]) -> Any: 

243 provider = str(args.get("provider") or "session") 

244 return self._execution( 

245 self.application.start_run(self.workspace, str(args["taskId"]), provider) 

246 ) 

247 

248 def _run_continue(self, args: dict[str, Any]) -> Any: 

249 return self._execution(self.application.continue_run(self.workspace, str(args["run"]))) 

250 

251 def call_tool(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]: 

252 handler = self._handlers.get(name) 

253 if handler is None: 253 ↛ 254line 253 didn't jump to line 254 because the condition on line 253 was never true

254 return { 

255 "content": [{"type": "text", "text": f"unknown tool {name}"}], 

256 "isError": True, 

257 } 

258 try: 

259 value = handler(arguments) 

260 except HarnessError as error: 

261 payload = {"status": "ERROR", "error": str(error), "exitCode": error.exit_code} 

262 return { 

263 "content": [{"type": "text", "text": json.dumps(payload)}], 

264 "structuredContent": payload, 

265 "isError": True, 

266 } 

267 except (ValueError, KeyError, TypeError, OSError) as error: 

268 payload = {"status": "ERROR", "error": str(error)} 

269 return { 

270 "content": [{"type": "text", "text": json.dumps(payload)}], 

271 "structuredContent": payload, 

272 "isError": True, 

273 } 

274 plain = json.loads(json.dumps(_plain(value), default=str)) 

275 result: dict[str, Any] = { 

276 "content": [{"type": "text", "text": json.dumps(plain, ensure_ascii=False)}], 

277 "isError": False, 

278 } 

279 if isinstance(plain, dict): 279 ↛ 281line 279 didn't jump to line 281 because the condition on line 279 was always true

280 result["structuredContent"] = plain 

281 return result 

282 

283 # ----- JSON-RPC ------------------------------------------------------------------------------ 

284 def handle(self, message: dict[str, Any]) -> dict[str, Any] | None: 

285 method = message.get("method") 

286 identifier = message.get("id") 

287 params = message.get("params") or {} 

288 if identifier is None: 

289 return None # a notification (initialized, cancelled): nothing to answer 

290 if method == "initialize": 

291 requested = str(params.get("protocolVersion") or PROTOCOL_VERSIONS[0]) 

292 version = requested if requested in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0] 

293 result: Any = { 

294 "protocolVersion": version, 

295 "capabilities": {"tools": {"listChanged": False}}, 

296 "serverInfo": {"name": SERVER_NAME, "version": __version__}, 

297 "instructions": INSTRUCTIONS, 

298 } 

299 elif method == "ping": 

300 result = {} 

301 elif method == "tools/list": 

302 result = {"tools": list(TOOLS)} 

303 elif method == "tools/call": 

304 name = str(params.get("name") or "") 

305 arguments = params.get("arguments") or {} 

306 if not isinstance(arguments, dict): 306 ↛ 307line 306 didn't jump to line 307 because the condition on line 306 was never true

307 return _error(identifier, -32602, "arguments must be an object") 

308 result = self.call_tool(name, arguments) 

309 else: 

310 return _error(identifier, -32601, f"method not found: {method}") 

311 return {"jsonrpc": "2.0", "id": identifier, "result": result} 

312 

313 def serve(self, reader: IO[str], writer: IO[str]) -> int: 

314 for line in reader: 

315 text = line.strip() 

316 if not text: 316 ↛ 317line 316 didn't jump to line 317 because the condition on line 316 was never true

317 continue 

318 reply = self._reply(text) 

319 # Nothing is written for a notification or a batch of notifications. 

320 if reply is not None and reply != []: 

321 writer.write(json.dumps(reply) + "\n") 

322 writer.flush() 

323 return 0 

324 

325 def _reply(self, text: str) -> dict[str, Any] | list[dict[str, Any]] | None: 

326 """The reply to one line: a response, a batch of responses, or ``None``.""" 

327 try: 

328 message = json.loads(text) 

329 except ValueError: 

330 return _error(None, -32700, "parse error") 

331 if isinstance(message, list): 331 ↛ 332line 331 didn't jump to line 332 because the condition on line 331 was never true

332 return [ 

333 reply 

334 for item in message 

335 if isinstance(item, dict) and (reply := self.handle(item)) is not None 

336 ] 

337 if isinstance(message, dict): 337 ↛ 339line 337 didn't jump to line 339 because the condition on line 337 was always true

338 return self.handle(message) 

339 return _error(None, -32600, "invalid request") 

340 

341 

342def _error(identifier: Any, code: int, message: str) -> dict[str, Any]: 

343 return {"jsonrpc": "2.0", "id": identifier, "error": {"code": code, "message": message}} 

344 

345 

346def _plain(value: Any) -> Any: 

347 if hasattr(value, "model_dump"): 347 ↛ 348line 347 didn't jump to line 348 because the condition on line 347 was never true

348 return value.model_dump(mode="json", by_alias=True) 

349 if isinstance(value, list): 349 ↛ 350line 349 didn't jump to line 350 because the condition on line 349 was never true

350 return [_plain(item) for item in value] 

351 if isinstance(value, tuple): 351 ↛ 352line 351 didn't jump to line 352 because the condition on line 351 was never true

352 return [_plain(item) for item in value] 

353 return value 

354 

355 

356def serve_stdio(workspace: Path) -> int: 

357 return McpServer(workspace).serve(sys.stdin, sys.stdout) 

358 

359 

360__all__ = ["HUMAN_ONLY", "INSTRUCTIONS", "TOOLS", "McpServer", "exit_code", "serve_stdio"]