polyctl 0.7.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- polyctl/__init__.py +7 -0
- polyctl/__main__.py +5 -0
- polyctl/a2a.py +226 -0
- polyctl/a2a_mcp.py +546 -0
- polyctl/acp.py +417 -0
- polyctl/adapters/README.md +101 -0
- polyctl/adapters/aider.json +32 -0
- polyctl/adapters/amazon-q.json +15 -0
- polyctl/adapters/amp.json +16 -0
- polyctl/adapters/antigravity.json +120 -0
- polyctl/adapters/claude-code.json +229 -0
- polyctl/adapters/cloud-generic.json +57 -0
- polyctl/adapters/codex.json +47 -0
- polyctl/adapters/command-code.json +45 -0
- polyctl/adapters/copilot.json +17 -0
- polyctl/adapters/cursor-agent.json +29 -0
- polyctl/adapters/deepseek.json +13 -0
- polyctl/adapters/droid.json +34 -0
- polyctl/adapters/gemini.json +30 -0
- polyctl/adapters/grok.json +22 -0
- polyctl/adapters/hermes.json +34 -0
- polyctl/adapters/kilocode.json +30 -0
- polyctl/adapters/kimi.json +23 -0
- polyctl/adapters/kiro.json +332 -0
- polyctl/adapters/ollama.json +29 -0
- polyctl/adapters/omp.json +34 -0
- polyctl/adapters/openai-api.json +68 -0
- polyctl/adapters/opencode.json +162 -0
- polyctl/adapters/pi.json +24 -0
- polyctl/adapters/pr-agent.json +54 -0
- polyctl/adapters/profiles.json +9 -0
- polyctl/adapters/qoder.json +163 -0
- polyctl/adapters/qwen.json +27 -0
- polyctl/adapters/reasonix.json +25 -0
- polyctl/adapters/rewriters/rtk.json +24 -0
- polyctl/adapters/trae.json +31 -0
- polyctl/adapters/vendors.json +42 -0
- polyctl/adapters/warp.json +88 -0
- polyctl/allowlist.py +1756 -0
- polyctl/api_review.py +920 -0
- polyctl/cli.py +835 -0
- polyctl/conformance_harness.py +9 -0
- polyctl/demo.py +503 -0
- polyctl/drivers.py +146 -0
- polyctl/email.py +160 -0
- polyctl/features.py +98 -0
- polyctl/journal.py +144 -0
- polyctl/language.py +945 -0
- polyctl/lib.py +1296 -0
- polyctl/matrix.py +660 -0
- polyctl/mcp.py +1362 -0
- polyctl/ntfy.py +169 -0
- polyctl/outbound.py +39 -0
- polyctl/parts/__init__.py +5 -0
- polyctl/parts/cli_authority.py +2615 -0
- polyctl/parts/cli_channels.py +1325 -0
- polyctl/parts/cli_checks.py +2293 -0
- polyctl/parts/cli_completion.py +686 -0
- polyctl/parts/cli_evidence.py +141 -0
- polyctl/parts/cli_gain.py +375 -0
- polyctl/parts/cli_harness.py +392 -0
- polyctl/parts/cli_hooks.py +1816 -0
- polyctl/parts/cli_install.py +638 -0
- polyctl/parts/cli_lanes.py +106 -0
- polyctl/parts/cli_maintenance.py +2536 -0
- polyctl/parts/cli_next.py +248 -0
- polyctl/parts/cli_pr.py +53 -0
- polyctl/parts/cli_project.py +2857 -0
- polyctl/parts/cli_review.py +5158 -0
- polyctl/parts/cli_status.py +898 -0
- polyctl/parts/lib_adapters.py +2933 -0
- polyctl/parts/lib_alarms.py +2106 -0
- polyctl/parts/lib_events.py +224 -0
- polyctl/parts/lib_evidence.py +412 -0
- polyctl/parts/lib_gates.py +2099 -0
- polyctl/parts/lib_lanes.py +829 -0
- polyctl/parts/lib_mail.py +1541 -0
- polyctl/parts/lib_next.py +652 -0
- polyctl/parts/lib_pr.py +331 -0
- polyctl/parts/lib_slices.py +3337 -0
- polyctl/parts/lib_state.py +2415 -0
- polyctl/parts/lib_transcript.py +4118 -0
- polyctl/pressure.py +325 -0
- polyctl/prices.json +47 -0
- polyctl/procs.py +1194 -0
- polyctl/settings.py +505 -0
- polyctl/skill/SKILL.md +365 -0
- polyctl/skillkit.py +503 -0
- polyctl/storage.py +2055 -0
- polyctl/telegram.py +327 -0
- polyctl/tiers.py +123 -0
- polyctl/verdicts.py +41 -0
- polyctl/watchdog.py +3887 -0
- polyctl/web.py +337 -0
- polyctl-0.7.0.dist-info/METADATA +235 -0
- polyctl-0.7.0.dist-info/RECORD +99 -0
- polyctl-0.7.0.dist-info/WHEEL +4 -0
- polyctl-0.7.0.dist-info/entry_points.txt +5 -0
- polyctl-0.7.0.dist-info/licenses/LICENSE +21 -0
polyctl/mcp.py
ADDED
|
@@ -0,0 +1,1362 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""polyctl-mcp — expose this project's orchestration state over MCP, read-mostly.
|
|
3
|
+
|
|
4
|
+
Any MCP-capable client (Claude Code, Cursor, Zed, an IDE extension) can then ask
|
|
5
|
+
what the implementer is doing and what has been measured, without shelling out
|
|
6
|
+
and without learning this tool's output format.
|
|
7
|
+
|
|
8
|
+
One rule shapes the surface: **authority never goes on it.** `commit-ok` decides
|
|
9
|
+
whether work may land, and exposing it here would let the implementer grant
|
|
10
|
+
itself the authority the separation exists to withhold. Reading is free; the one
|
|
11
|
+
expensive action, `verify`, is opt-in because it runs the project's real gates.
|
|
12
|
+
No resource, prompt or tool records an approval, a `commit-ok`, a waiver, an
|
|
13
|
+
answer or a `harness-seen`; a step that is a person's comes back as the CLI
|
|
14
|
+
command text only (MCP-RES).
|
|
15
|
+
|
|
16
|
+
A second rule narrows it per session (MCP-ROLES): a server started for a role,
|
|
17
|
+
`--role architect|implementer|reviewer`, lists and runs that role's tools alone. A
|
|
18
|
+
reviewer reads and sends nothing; an implementer works its mailbox; the architect
|
|
19
|
+
keeps every tool. `polyctl init` writes the role into a registration only one role reads. A
|
|
20
|
+
role it does not know stops the server, naming the roles: served every tool, a mistyped
|
|
21
|
+
reviewer could act as the architect (HUNT-LEADS-SEC).
|
|
22
|
+
|
|
23
|
+
A third rule scopes which projects the server speaks for (MCP-RES): started for one
|
|
24
|
+
project, it serves that project's tools, read-only resources (`polyctl://<project>/board`,
|
|
25
|
+
`roles`, `ledger`, `decisions`) and prompts (`status`, `land-slice`, `stuck`); started
|
|
26
|
+
with `--project all`, one server serves every project in polyctl's project registry
|
|
27
|
+
(`project_registry_path`), each tool, resource and prompt naming its project, and
|
|
28
|
+
refuses any project outside the registry.
|
|
29
|
+
|
|
30
|
+
JSON-RPC 2.0 over stdio, standard library only.
|
|
31
|
+
"""
|
|
32
|
+
import json
|
|
33
|
+
import math
|
|
34
|
+
import os
|
|
35
|
+
import re
|
|
36
|
+
import shlex
|
|
37
|
+
import sys
|
|
38
|
+
import time
|
|
39
|
+
import urllib.parse
|
|
40
|
+
|
|
41
|
+
from . import __version__, language, lib as A, settings as S
|
|
42
|
+
UTF8 = "utf-8" # every text file polyctl writes or reads; Windows would otherwise use cp1252
|
|
43
|
+
|
|
44
|
+
PROTOCOL = "2025-06-18"
|
|
45
|
+
PROTOCOL_2026 = "2026-07-28"
|
|
46
|
+
PROTOCOLS = (PROTOCOL_2026, PROTOCOL)
|
|
47
|
+
LEGACY_PROTOCOLS = (PROTOCOL,)
|
|
48
|
+
INVALID_PARAMS = -32602
|
|
49
|
+
RESOURCE_NOT_FOUND = -32002
|
|
50
|
+
UNSUPPORTED_PROTOCOL_VERSION = -32022
|
|
51
|
+
RESOURCE_SCHEME = "polyctl"
|
|
52
|
+
RESOURCE_MIME_TYPE = "application/json"
|
|
53
|
+
PROJECT_SCOPES = ("all",)
|
|
54
|
+
CAPABILITIES = {"tools": {}, "resources": {}, "prompts": {}}
|
|
55
|
+
SLICE_ID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*(?:/[A-Za-z0-9][A-Za-z0-9._-]*)?\Z")
|
|
56
|
+
QUESTION_ID_RE = re.compile(r"D-\d+\Z")
|
|
57
|
+
ID_PATTERNS = {
|
|
58
|
+
"slice": SLICE_ID_RE,
|
|
59
|
+
"question": QUESTION_ID_RE,
|
|
60
|
+
}
|
|
61
|
+
SUGGESTED_COMMAND_TEMPLATES = (
|
|
62
|
+
"answer",
|
|
63
|
+
"harness-seen",
|
|
64
|
+
"person-review",
|
|
65
|
+
"commit-ok",
|
|
66
|
+
"review",
|
|
67
|
+
"collect-review",
|
|
68
|
+
"commit",
|
|
69
|
+
"waive-review",
|
|
70
|
+
"waive-gate",
|
|
71
|
+
"mail-ack",
|
|
72
|
+
"init",
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def valid_caller_id(kind, value):
|
|
77
|
+
"""True when caller-supplied `value` matches the pattern polyctl's own `kind` ids follow (MCP-2026-2)."""
|
|
78
|
+
pattern = ID_PATTERNS.get(kind)
|
|
79
|
+
return pattern is not None and isinstance(value, str) and 0 < len(value) <= 200 and bool(pattern.match(value))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _require_caller_id(kind, value):
|
|
83
|
+
if not valid_caller_id(kind, value):
|
|
84
|
+
raise ValueError(f"invalid {kind} id {value!r}")
|
|
85
|
+
return value
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _require_project_key(value):
|
|
89
|
+
if not A._usable_key(value):
|
|
90
|
+
raise ValueError(f"invalid project key {value!r}")
|
|
91
|
+
return value
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def suggested_command(*words):
|
|
95
|
+
"""Build a suggested CLI command from `words`, passing every word through `shlex.quote` (MCP-2026-2)."""
|
|
96
|
+
if not words:
|
|
97
|
+
raise ValueError("suggested_command requires at least one word")
|
|
98
|
+
quoted = []
|
|
99
|
+
for word in words:
|
|
100
|
+
text = str(word)
|
|
101
|
+
if "\0" in text:
|
|
102
|
+
raise ValueError("command word cannot contain NUL")
|
|
103
|
+
quoted.append(shlex.quote(text))
|
|
104
|
+
return " ".join(quoted)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def suggested_command_words(template, root=None, *, slice_id=None, question_id=None, project=None):
|
|
108
|
+
"""The unquoted word tuple for one suggested CLI command template, validating caller ids first (MCP-2026-2)."""
|
|
109
|
+
if project is not None:
|
|
110
|
+
_require_project_key(project)
|
|
111
|
+
if slice_id is not None:
|
|
112
|
+
_require_caller_id("slice", slice_id)
|
|
113
|
+
if question_id is not None:
|
|
114
|
+
_require_caller_id("question", question_id)
|
|
115
|
+
if template == "mail-ack":
|
|
116
|
+
return ("polyctl", "mail", "ack")
|
|
117
|
+
if template == "init":
|
|
118
|
+
return ("polyctl", "init")
|
|
119
|
+
if not isinstance(root, str) or not root or "\0" in root:
|
|
120
|
+
raise ValueError(f"invalid project root {root!r}")
|
|
121
|
+
prefix = ("polyctl", "-C", root)
|
|
122
|
+
if template == "answer":
|
|
123
|
+
return prefix + ("answer", question_id or "ID", "KEY")
|
|
124
|
+
if template == "harness-seen":
|
|
125
|
+
return prefix + ("harness", "seen", "--by", "NAME")
|
|
126
|
+
if template == "person-review":
|
|
127
|
+
return prefix + ("person-review", "--by", "NAME", "--verdict", "APPROVED", "--digest", "DIGEST")
|
|
128
|
+
if template == "commit-ok":
|
|
129
|
+
return prefix + ("commit-ok", "--verify")
|
|
130
|
+
if template == "review":
|
|
131
|
+
return prefix + ("review",)
|
|
132
|
+
if template == "collect-review":
|
|
133
|
+
return prefix + ("collect-review", "NONCE", "--response", "FILE", "--model", "MODEL", "--by", "NAME")
|
|
134
|
+
if template == "commit":
|
|
135
|
+
target = _require_caller_id("slice", slice_id)
|
|
136
|
+
return prefix + ("commit", "-m", f"{target}: SUMMARY")
|
|
137
|
+
if template == "waive-review":
|
|
138
|
+
target = _require_caller_id("slice", slice_id)
|
|
139
|
+
return prefix + ("waive", "review", "--slice", target, "--by", "NAME", "--why", "REASON")
|
|
140
|
+
if template == "waive-gate":
|
|
141
|
+
return prefix + ("waive", "GATE", "--slice", slice_id or "SLICE", "--by", "NAME", "--why", "REASON")
|
|
142
|
+
raise ValueError(f"unknown suggested command template {template!r}")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def render_suggested_command(template, root=None, *, slice_id=None, question_id=None, project=None):
|
|
146
|
+
"""Render one suggested CLI command template with every word passed through `shlex.quote` (MCP-2026-2)."""
|
|
147
|
+
return suggested_command(
|
|
148
|
+
*suggested_command_words(template, root, slice_id=slice_id, question_id=question_id, project=project)
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
TOOLS = [
|
|
153
|
+
{"name": "polyctl_status",
|
|
154
|
+
"description": "Implementer state, context/cost telemetry, git state and open reviews.",
|
|
155
|
+
"inputSchema": {"type": "object", "properties": {}}},
|
|
156
|
+
{"name": "polyctl_board",
|
|
157
|
+
"description": "Where each pre-authorised work item is: running, blocked (with what it "
|
|
158
|
+
"waits on), queued, inbox, verified, done. Blocked items are the ones a "
|
|
159
|
+
"human must act on.",
|
|
160
|
+
"inputSchema": {"type": "object", "properties": {}}},
|
|
161
|
+
{"name": "polyctl_next",
|
|
162
|
+
"description": "What stands in this project right now and whose hand closes it: a person's "
|
|
163
|
+
"items first (a harness change no person has read, a stand-in review request "
|
|
164
|
+
"awaiting the answer a person carries back, urgent mail, an open rule "
|
|
165
|
+
"proposal), then the staged candidate's landing chain at the first stage that "
|
|
166
|
+
"does not hold. Each item carries the command that closes it. Read-only: it "
|
|
167
|
+
"starts and records nothing, and a person's command is named, never typed.",
|
|
168
|
+
"inputSchema": {"type": "object",
|
|
169
|
+
"properties": {"who": {"type": "string", "enum": ["person", "implementer"],
|
|
170
|
+
"description": "only this actor's items"}}}},
|
|
171
|
+
{"name": "polyctl_candidate",
|
|
172
|
+
"description": "The candidate staged now and what a review judges it against: the running "
|
|
173
|
+
"slice and its boundary, the candidate's digest and paths, and the committed "
|
|
174
|
+
"source a test-only candidate exercises. Not the diff. Read-only.",
|
|
175
|
+
"inputSchema": {"type": "object", "properties": {}}},
|
|
176
|
+
{"name": "polyctl_notices",
|
|
177
|
+
"description": "Alerts this project raised, including ones the rate limit suppressed.",
|
|
178
|
+
"inputSchema": {"type": "object",
|
|
179
|
+
"properties": {"limit": {"type": "integer", "default": 10},
|
|
180
|
+
"include_suppressed": {"type": "boolean", "default": False}}}},
|
|
181
|
+
{"name": "polyctl_fleet",
|
|
182
|
+
"description": "One row per project with a local agent session, ordered by what needs a "
|
|
183
|
+
"human first.",
|
|
184
|
+
"inputSchema": {"type": "object", "properties": {}}},
|
|
185
|
+
{"name": "polyctl_inbox",
|
|
186
|
+
"description": "Coordination messages addressed to you that you have not yet "
|
|
187
|
+
"acknowledged. Check this at the start of every turn. Each message "
|
|
188
|
+
"carries an id; acknowledge it with polyctl_ack once you have applied or "
|
|
189
|
+
"explicitly rejected it.",
|
|
190
|
+
"inputSchema": {"type": "object", "properties": {}}},
|
|
191
|
+
{"name": "polyctl_ack",
|
|
192
|
+
"description": "Acknowledge one coordination message: it is removed, which is how "
|
|
193
|
+
"delivery is confirmed. Acknowledge only after applying or explicitly "
|
|
194
|
+
"rejecting the message — never on a partial read.",
|
|
195
|
+
"inputSchema": {"type": "object", "required": ["id"],
|
|
196
|
+
"properties": {"id": {"type": "string"},
|
|
197
|
+
"outcome": {"type": "string",
|
|
198
|
+
"description": "applied | rejected: why"}}}},
|
|
199
|
+
{"name": "polyctl_report",
|
|
200
|
+
"description": "Tell the architect something, at any point in a turn. Use kind "
|
|
201
|
+
"'blocked' when you cannot proceed without a decision — that escalates "
|
|
202
|
+
"immediately rather than waiting for a detector to infer it. Use "
|
|
203
|
+
"'status' or 'done' for everything else.",
|
|
204
|
+
"inputSchema": {"type": "object", "required": ["kind", "summary"],
|
|
205
|
+
"properties": {
|
|
206
|
+
"kind": {"type": "string", "enum": ["blocked", "status", "done"]},
|
|
207
|
+
"summary": {"type": "string"},
|
|
208
|
+
"detail": {"type": "string"},
|
|
209
|
+
"needs": {"type": "string",
|
|
210
|
+
"description": "for kind=blocked: what input would unblock it"}}}},
|
|
211
|
+
{"name": "polyctl_ask",
|
|
212
|
+
"description": "Ask the architect or the human a question you cannot answer "
|
|
213
|
+
"yourself, with options. Prefer this over parking on a prose "
|
|
214
|
+
"blocker: an options question is answerable from a phone in one "
|
|
215
|
+
"tap, a paragraph is not. Free text is always available as a last "
|
|
216
|
+
"option, so list what you think is likely, not everything.",
|
|
217
|
+
"inputSchema": {"type": "object", "required": ["question", "options"],
|
|
218
|
+
"properties": {
|
|
219
|
+
"question": {"type": "string"},
|
|
220
|
+
"options": {"type": "array", "items": {"type": "string"},
|
|
221
|
+
"description": "2-8 concrete choices"},
|
|
222
|
+
"context": {"type": "string",
|
|
223
|
+
"description": "what makes this a real question"},
|
|
224
|
+
"slice": {"type": "string"}}}},
|
|
225
|
+
{"name": "polyctl_decisions",
|
|
226
|
+
"description": "Questions you asked and whether they have been answered. Check "
|
|
227
|
+
"this at the start of a turn: an answered question is the thing "
|
|
228
|
+
"that unparks a slice. A rule proposal's question is 'proposed' "
|
|
229
|
+
"until a person answers it.",
|
|
230
|
+
"inputSchema": {"type": "object",
|
|
231
|
+
"properties": {"state": {"type": "string",
|
|
232
|
+
"enum": ["open", "proposed", "answered"]}}}},
|
|
233
|
+
{"name": "polyctl_propose",
|
|
234
|
+
"description": "Propose a change to a rule you work under - a step of the playbook, a "
|
|
235
|
+
"steering or rule file, .polyctl/authority.md, a gate - instead of editing it. "
|
|
236
|
+
"It is recorded in the decision ledger with the outcomes of the project's "
|
|
237
|
+
"recent slices, and a person accepts or rejects it; until one does, keep "
|
|
238
|
+
"working under the rule as it stands. polyctl_decisions shows the answer. The "
|
|
239
|
+
"same change proposed again is not recorded twice.",
|
|
240
|
+
"inputSchema": {"type": "object", "required": ["text", "why"],
|
|
241
|
+
"properties": {
|
|
242
|
+
"text": {"type": "string",
|
|
243
|
+
"description": "the change: what the rule would say, or what would change"},
|
|
244
|
+
"why": {"type": "string",
|
|
245
|
+
"description": "what went wrong under the rule as it stands"},
|
|
246
|
+
"rule_file": {"type": "string",
|
|
247
|
+
"description": "the file that holds the rule, as a path in the project"}}}},
|
|
248
|
+
{"name": "polyctl_fanout",
|
|
249
|
+
"description": "Before fanning out to sub-agents: may a fan-out of this size "
|
|
250
|
+
"start now (hard cap, recent limit hit, provider window)? "
|
|
251
|
+
"After: record what it cost so the next estimate is real. "
|
|
252
|
+
"47 agents once died at 36 with a session limit; this is the "
|
|
253
|
+
"gate that would have refused it.",
|
|
254
|
+
"inputSchema": {"type": "object", "required": ["agents"],
|
|
255
|
+
"properties": {
|
|
256
|
+
"action": {"type": "string", "enum": ["ok", "record"]},
|
|
257
|
+
"agents": {"type": "integer"},
|
|
258
|
+
"per_agent_tokens": {"type": "integer"},
|
|
259
|
+
"done": {"type": "integer"}, "errors": {"type": "integer"},
|
|
260
|
+
"tokens": {"type": "integer"}, "note": {"type": "string"}}}},
|
|
261
|
+
{"name": "polyctl_watchdog",
|
|
262
|
+
"description": "Why the watchdog did or did not act. explain runs one dry cycle "
|
|
263
|
+
"and returns its measurements and verdicts; trace returns the recorded "
|
|
264
|
+
"cycles. Read-only.",
|
|
265
|
+
"inputSchema": {"type": "object",
|
|
266
|
+
"properties": {"action": {"type": "string", "enum": ["explain", "trace"]},
|
|
267
|
+
"last": {"type": "integer"}}}},
|
|
268
|
+
{"name": "polyctl_verify",
|
|
269
|
+
"description": "Run the project's declared gates and record the measured result. "
|
|
270
|
+
"Expensive; disabled unless the server was started with --allow-verify.",
|
|
271
|
+
"inputSchema": {"type": "object",
|
|
272
|
+
"properties": {"profile": {"type": "string"}}}},
|
|
273
|
+
]
|
|
274
|
+
|
|
275
|
+
EVERY_TOOL = tuple(tool["name"] for tool in TOOLS)
|
|
276
|
+
|
|
277
|
+
# The tools each role's playbook uses, and the only ones a server started for that role lists or
|
|
278
|
+
# runs (MCP-ROLES). The implementer's are the tools the playbook's "Talking" section names, and
|
|
279
|
+
# polyctl_verify, the gate step of its loop, still behind --allow-verify. A reviewer judges a candidate:
|
|
280
|
+
# it reads the project's state, the board and the candidate, and sends no mail and no report. The
|
|
281
|
+
# architect keeps every tool it had before roles existed.
|
|
282
|
+
ROLE_TOOLS = {
|
|
283
|
+
"architect": EVERY_TOOL,
|
|
284
|
+
"implementer": ("polyctl_status", "polyctl_board", "polyctl_next", "polyctl_notices", "polyctl_inbox", "polyctl_ack", "polyctl_report", "polyctl_ask",
|
|
285
|
+
"polyctl_decisions", "polyctl_propose", "polyctl_fanout", "polyctl_watchdog", "polyctl_verify"),
|
|
286
|
+
"reviewer": ("polyctl_status", "polyctl_board", "polyctl_candidate"),
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def role_tools(role):
|
|
291
|
+
"""The names of the tools a server started for `role` lists and runs.
|
|
292
|
+
|
|
293
|
+
Every tool when `role` is None: a registration written before roles existed, or one several
|
|
294
|
+
roles read, keeps what it served then, and `role_notice` says so. No tool for a role this
|
|
295
|
+
server does not know. It was served every tool, so a mistyped `--role reviwer` was a reviewer
|
|
296
|
+
that could report and acknowledge mail as the architect does (HUNT-LEADS-SEC); `served_role`
|
|
297
|
+
refuses such a role before the server starts, and this holds to it should one reach a call.
|
|
298
|
+
"""
|
|
299
|
+
if role is None:
|
|
300
|
+
return EVERY_TOOL
|
|
301
|
+
return ROLE_TOOLS.get(role, ())
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def served_role(argv):
|
|
305
|
+
"""The role the server's arguments name, read as POLYCTL_ROLE is - without case or surrounding space - or None.
|
|
306
|
+
|
|
307
|
+
ValueError, naming the roles, for a `--role` that names none of them, or nothing at all: both were
|
|
308
|
+
served every tool (HUNT-LEADS-SEC). `--role=<role>` is read too, which was taken for no role.
|
|
309
|
+
"""
|
|
310
|
+
named = [index for index, word in enumerate(argv) if word == "--role" or word.startswith("--role=")]
|
|
311
|
+
if not named:
|
|
312
|
+
return None
|
|
313
|
+
index = named[-1]
|
|
314
|
+
given = argv[index].partition("=")[2] if argv[index] != "--role" else \
|
|
315
|
+
(argv[index + 1] if index + 1 < len(argv) else "")
|
|
316
|
+
role = given.strip().lower()
|
|
317
|
+
if role not in ROLE_TOOLS:
|
|
318
|
+
known = ", ".join(sorted(ROLE_TOOLS))
|
|
319
|
+
init_cmd = render_suggested_command("init")
|
|
320
|
+
raise ValueError(f"polyctl mcp: --role {given!r} is none of {known}, so the server does not start; name one of "
|
|
321
|
+
f"them in the registration - `{init_cmd}` writes it - or leave --role out for every tool")
|
|
322
|
+
return role
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def served_project(argv):
|
|
326
|
+
"""The project scope the server's arguments name (`all`), or None for one project (MCP-RES).
|
|
327
|
+
|
|
328
|
+
ValueError when `--project` is given anything other than `all`: one project is chosen with `-C <dir>`,
|
|
329
|
+
and `--project all` serves every project in polyctl's project registry (`project_registry_path`).
|
|
330
|
+
"""
|
|
331
|
+
named = [index for index, word in enumerate(argv) if word == "--project" or word.startswith("--project=")]
|
|
332
|
+
if not named:
|
|
333
|
+
return None
|
|
334
|
+
index = named[-1]
|
|
335
|
+
given = argv[index].partition("=")[2] if argv[index] != "--project" else \
|
|
336
|
+
(argv[index + 1] if index + 1 < len(argv) else "")
|
|
337
|
+
scope = given.strip().lower()
|
|
338
|
+
if scope not in PROJECT_SCOPES:
|
|
339
|
+
raise ValueError(f"polyctl mcp: --project {given!r} is not 'all', so the server does not start; use --project all "
|
|
340
|
+
"for every registered project, or -C <dir> without --project for one project")
|
|
341
|
+
return scope
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def role_notice(role):
|
|
345
|
+
"""The line a server started with no role prints on stderr, or None.
|
|
346
|
+
|
|
347
|
+
stderr, because stdout is the protocol: an MCP client keeps what its server writes there in
|
|
348
|
+
its own log, where the person who wrote the registration finds it.
|
|
349
|
+
"""
|
|
350
|
+
if role is not None:
|
|
351
|
+
return None
|
|
352
|
+
known = ", ".join(sorted(ROLE_TOOLS))
|
|
353
|
+
init_cmd = render_suggested_command("init")
|
|
354
|
+
return (f"polyctl mcp: started with no --role, so every tool is served; the roles are {known}, "
|
|
355
|
+
f"and `{init_cmd}` writes one into each registration a single role reads")
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _project_name(cfg):
|
|
359
|
+
"""The served project's stable name, read without writing `.polyctl/project-key` or the registry."""
|
|
360
|
+
root = (cfg or {}).get("root") or ""
|
|
361
|
+
abs_root = os.path.abspath(root) if root else ""
|
|
362
|
+
reg_key = (A.registered_key(root)
|
|
363
|
+
or next((name for name, path in registered_projects().items() if path == abs_root), None)) if root else None
|
|
364
|
+
for candidate in (
|
|
365
|
+
reg_key,
|
|
366
|
+
str((cfg or {}).get("project") or "").strip(),
|
|
367
|
+
os.path.basename(abs_root.rstrip("/\\")) if abs_root else "",
|
|
368
|
+
):
|
|
369
|
+
if A._usable_key(candidate):
|
|
370
|
+
return candidate
|
|
371
|
+
return "project"
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def registered_projects():
|
|
375
|
+
"""{project: root} for every existing project in polyctl's project registry (`A.project_registry_path()`)."""
|
|
376
|
+
found = {}
|
|
377
|
+
for name, row in sorted(A.project_registry().items()):
|
|
378
|
+
path = row.get("root")
|
|
379
|
+
if A._usable_key(name) and isinstance(path, str) and os.path.isdir(path):
|
|
380
|
+
found[name] = os.path.abspath(path)
|
|
381
|
+
return found
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _served_projects(cfg, project_scope=None):
|
|
385
|
+
"""[(project, root, project_cfg)] for the projects this server serves, in stable order."""
|
|
386
|
+
if project_scope == "all":
|
|
387
|
+
return [(name, root, dict(A.load_config(root), root=root))
|
|
388
|
+
for name, root in sorted(registered_projects().items())]
|
|
389
|
+
root = os.path.abspath(cfg["root"])
|
|
390
|
+
return [(_project_name(cfg), root, dict(cfg, root=root))]
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _resolve_project(cfg, project_scope, requested):
|
|
394
|
+
"""((project, root, project_cfg), None) for `requested`, or (None, error_message)."""
|
|
395
|
+
if project_scope == "all":
|
|
396
|
+
projects = registered_projects()
|
|
397
|
+
if not isinstance(requested, str) or not requested.strip():
|
|
398
|
+
known = ", ".join(sorted(projects)) or "none registered"
|
|
399
|
+
return None, f"project is required with --project all (registered: {known})"
|
|
400
|
+
if requested not in projects:
|
|
401
|
+
known = ", ".join(sorted(projects)) or "none registered"
|
|
402
|
+
return None, (f"project {requested!r} is not in polyctl's project registry "
|
|
403
|
+
f"({A.project_registry_path()}; registered: {known})")
|
|
404
|
+
root = projects[requested]
|
|
405
|
+
return (requested, root, dict(A.load_config(root), root=root)), None
|
|
406
|
+
current = _project_name(cfg)
|
|
407
|
+
root = os.path.abspath(cfg["root"])
|
|
408
|
+
if requested is not None:
|
|
409
|
+
if not isinstance(requested, str) or requested != current:
|
|
410
|
+
return None, (f"project {requested!r} is not served by this server "
|
|
411
|
+
f"(serving {current!r}); start with --project all for every registered project")
|
|
412
|
+
return (current, root, dict(cfg, root=root)), None
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def tools_for_role(role, project_scope=None):
|
|
416
|
+
"""The tool definitions a server started for `role` and `project_scope` lists (MCP-ROLES, MCP-RES).
|
|
417
|
+
|
|
418
|
+
With `--project all`, every tool's inputSchema names `project` as a required string so each call
|
|
419
|
+
identifies the registered project it acts on.
|
|
420
|
+
"""
|
|
421
|
+
served = role_tools(role)
|
|
422
|
+
listed = []
|
|
423
|
+
for tool in TOOLS:
|
|
424
|
+
if tool["name"] not in served:
|
|
425
|
+
continue
|
|
426
|
+
if project_scope != "all":
|
|
427
|
+
listed.append(tool)
|
|
428
|
+
continue
|
|
429
|
+
schema = dict(tool["inputSchema"])
|
|
430
|
+
props = dict({"project": {"type": "string",
|
|
431
|
+
"description": "project name in polyctl's project registry"}},
|
|
432
|
+
**dict(schema.get("properties") or {}))
|
|
433
|
+
required = list(schema.get("required") or [])
|
|
434
|
+
if "project" not in required:
|
|
435
|
+
required = ["project"] + required
|
|
436
|
+
schema["properties"] = props
|
|
437
|
+
schema["required"] = required
|
|
438
|
+
listed.append(dict(tool, inputSchema=schema))
|
|
439
|
+
return listed
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def status_payload(cfg):
|
|
443
|
+
from . import cli, watchdog as W
|
|
444
|
+
root = cfg["root"]
|
|
445
|
+
# The server loads the config once, and an agent starts it before its own session has written a
|
|
446
|
+
# transcript: a session `auto` found no session for is looked for again (SESSION-IDENTITY).
|
|
447
|
+
if not (A.session_state(cfg, "implementer") or {}).get("session"):
|
|
448
|
+
cfg = dict(A.load_config(root), root=root)
|
|
449
|
+
mode = cli.project_mode(cfg)
|
|
450
|
+
enforcement = cli.ENFORCEMENT_OFF_LITE_LINE if mode == "lite" else "on"
|
|
451
|
+
impl = cfg.get("implementer") or {}
|
|
452
|
+
adapter = A.load_adapter(impl.get("adapter", "")) if impl else {}
|
|
453
|
+
state, age, desc = A.busy(cfg, adapter) if impl else ("unknown", None, "")
|
|
454
|
+
msgs, _ = A.session_paths(cfg)
|
|
455
|
+
recs = A.read_tail(msgs, 4_000_000) if msgs else []
|
|
456
|
+
tel = A.telemetry(recs, adapter, msgs) if recs else {}
|
|
457
|
+
g = A.git_state(root)
|
|
458
|
+
revs = A.reviews(root, cfg["reviews"], limit=3)
|
|
459
|
+
# Processes that could not be counted are null, and the reason says why: none were seen is not none run
|
|
460
|
+
# (WINDOWS-TABLE-CLOSED).
|
|
461
|
+
from .procs import TableUnreadable
|
|
462
|
+
unread = None
|
|
463
|
+
try:
|
|
464
|
+
processes = len(A.agent_pids(root, adapter)) if impl else 0
|
|
465
|
+
except TableUnreadable as exc:
|
|
466
|
+
processes, unread = None, str(exc)
|
|
467
|
+
return dict(
|
|
468
|
+
{"project": cfg.get("project") or os.path.basename(root), "root": root,
|
|
469
|
+
"mode": mode, "enforcement": enforcement,
|
|
470
|
+
"adapter": impl.get("adapter"), "state": state, "seconds_since_write": age,
|
|
471
|
+
"doing": desc, "spinning_minutes": A.spinning(root),
|
|
472
|
+
"nothing_to_do_since": (W.load_state(root).get("idle_answer") or {}).get("since"),
|
|
473
|
+
"context_percent": tel.get("ctx"), "turns": tel.get("turns"),
|
|
474
|
+
"cost_total": tel.get("total"), "cost_delegated": tel.get("delegated"), "cost_unit": tel.get("unit"),
|
|
475
|
+
"head": g["log"][0] if g["log"] else None,
|
|
476
|
+
"dirty_files": len(g["dirty"]), "unpushed": g["ahead"],
|
|
477
|
+
"behind": g.get("behind"), "base": g.get("base"), "merged": g.get("merged"),
|
|
478
|
+
"mailbox": A.mailbox(root, cfg["mailbox"]),
|
|
479
|
+
"reviews": [{"file": f, "verdict": v} for f, v in revs],
|
|
480
|
+
"throughput": A.throughput(root, cfg),
|
|
481
|
+
"held": A.hold_state(root),
|
|
482
|
+
"agent_processes": processes, "agent_processes_unread": unread},
|
|
483
|
+
**({"push_guard": push_guard}
|
|
484
|
+
if mode != "lite" and (push_guard := cli._push_guard_status_line(cli._polyctl_hook_inventory(root))) is not None
|
|
485
|
+
else {}),
|
|
486
|
+
)
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def board_payload(root):
|
|
490
|
+
b = A.board(root)
|
|
491
|
+
graph = A.board_graph(root)
|
|
492
|
+
return {"states": {k: v for k, v in b.items() if v},
|
|
493
|
+
"ready": [item["id"] for item in graph["ready"]], "problems": graph["problems"],
|
|
494
|
+
"a2a": {k: A.A2A_STATE.get(k) for k in b if b[k]},
|
|
495
|
+
"counts": {k: len(v) for k, v in b.items()}}
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def next_payload(cfg, who=None):
|
|
499
|
+
"""What stands in this project, as the items `polyctl next` shows (NEXT).
|
|
500
|
+
|
|
501
|
+
One reading for every surface, so an agent and a person cannot be told different things: this calls
|
|
502
|
+
the same `A.next_items` the terminal calls. `who` narrows it to one actor's items, which is what a
|
|
503
|
+
playbook asks for at the end of a turn. Counts are the items that name a command - a superseded
|
|
504
|
+
review request is listed and asks nothing of anyone.
|
|
505
|
+
"""
|
|
506
|
+
items = A.next_items(cfg)
|
|
507
|
+
counts = {name: sum(1 for item in items if item["who"] == name and item.get("command"))
|
|
508
|
+
for name in (A.PERSON, "implementer")}
|
|
509
|
+
mine = [item for item in items if item["who"] == who] if who is not None else items
|
|
510
|
+
return {"project": cfg.get("project") or A.next_project_key(cfg["root"]), "counts": counts, "items": mine}
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def candidate_payload(cfg):
|
|
514
|
+
"""The candidate staged now, and what a review judges it against (MCP-ROLES).
|
|
515
|
+
|
|
516
|
+
What `polyctl review` builds its request from, read the same way: the running slice, its boundary
|
|
517
|
+
(the file its row points at, or its sentence), the candidate's identity and paths, and the
|
|
518
|
+
committed source a test-only candidate exercises (#97), within review.context_bytes. The diff
|
|
519
|
+
is left out: a reviewer is handed the one it judges, and a submitted review judges the tree it
|
|
520
|
+
pinned, which the index may have moved on from - the digest tells the two apart.
|
|
521
|
+
"""
|
|
522
|
+
root = cfg["root"]
|
|
523
|
+
running = A.running_slice(root)
|
|
524
|
+
source = A.read_boundary(root, running)
|
|
525
|
+
out = {"slice": (running or {}).get("id"), "title": (running or {}).get("title"),
|
|
526
|
+
"boundary": (source or {}).get("text") or A.slice_boundary(running) or None}
|
|
527
|
+
try:
|
|
528
|
+
candidate = A.index_candidate(root)
|
|
529
|
+
except (RuntimeError, ValueError) as exc:
|
|
530
|
+
return dict(out, candidate=None, context=None, problem=f"the staged candidate cannot be measured: {exc}")
|
|
531
|
+
out["candidate"] = {key: candidate[key] for key in ("digest", "head", "index_tree", "changed_paths")}
|
|
532
|
+
context = A.review_context(root, candidate["changed_paths"], candidate["index_tree"], candidate["head"],
|
|
533
|
+
S.get(cfg, "review.context_bytes"))
|
|
534
|
+
out["context"] = None if context is None else \
|
|
535
|
+
{key: context[key] for key in ("rev", "paths", "names", "omitted", "text")}
|
|
536
|
+
return out
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def roles_payload(cfg):
|
|
540
|
+
"""The project's actors, held roles and any pending role assignment, read-only (MCP-RES)."""
|
|
541
|
+
root = cfg["root"]
|
|
542
|
+
try:
|
|
543
|
+
with open(os.path.join(root, ".polyctl", "config.json"), encoding=UTF8) as fh:
|
|
544
|
+
stored = json.load(fh)
|
|
545
|
+
except (OSError, ValueError):
|
|
546
|
+
stored = {}
|
|
547
|
+
source = stored if isinstance(stored, dict) and stored else cfg
|
|
548
|
+
actors, roles, _ = A.role_table(source)
|
|
549
|
+
held = A.effective_roles(root, dict(source, roles=roles))
|
|
550
|
+
waiting, after = A.pending_roles(root, source)
|
|
551
|
+
return {
|
|
552
|
+
"roles": {role: held.get(role) for role in A.ROLE_BLOCKS},
|
|
553
|
+
"actors": {
|
|
554
|
+
name: {key: block[key] for key in ("adapter", "model", "effort", "family") if block.get(key)}
|
|
555
|
+
for name, block in sorted(actors.items())
|
|
556
|
+
},
|
|
557
|
+
"pending": {"roles": waiting, "after": after} if waiting else None,
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def ledger_payload(root):
|
|
562
|
+
"""Read-only summary of the project's ledgers, carrying no authority token (MCP-RES)."""
|
|
563
|
+
from .storage import read_chained_history
|
|
564
|
+
slice_rows = [row for row in A.slice_moves(root) if isinstance(row, dict)]
|
|
565
|
+
verifications = [row for row in A.verification_history(root) if isinstance(row, dict)]
|
|
566
|
+
reviews = [row for row in read_chained_history(A.review_ledger_path(root), A.REVIEW_CHAIN) if isinstance(row, dict)]
|
|
567
|
+
decisions = [row for row in A.decision_rows(root) if isinstance(row, dict)]
|
|
568
|
+
waivers = [row for row in A.waiver_rows(root) if isinstance(row, dict)]
|
|
569
|
+
latest_v = A.latest_verification(root)
|
|
570
|
+
return {
|
|
571
|
+
"counts": {
|
|
572
|
+
"slices": len(slice_rows),
|
|
573
|
+
"verifications": len(verifications),
|
|
574
|
+
"reviews": len(reviews),
|
|
575
|
+
"decisions": len(decisions),
|
|
576
|
+
"waivers": len(waivers),
|
|
577
|
+
},
|
|
578
|
+
"latest_slice": (
|
|
579
|
+
{key: slice_rows[-1].get(key) for key in ("slice", "from", "to", "at", "by", "why")
|
|
580
|
+
if key in slice_rows[-1]}
|
|
581
|
+
if slice_rows else None
|
|
582
|
+
),
|
|
583
|
+
"latest_verification": (
|
|
584
|
+
{key: latest_v.get(key) for key in ("id", "passed", "ok", "profile", "at")
|
|
585
|
+
if key in latest_v}
|
|
586
|
+
if isinstance(latest_v, dict) else None
|
|
587
|
+
),
|
|
588
|
+
"latest_review": (
|
|
589
|
+
{"id": reviews[-1].get("artefact") or reviews[-1].get("id"),
|
|
590
|
+
"slice": reviews[-1].get("slice"),
|
|
591
|
+
"verdict": reviews[-1].get("verdict"),
|
|
592
|
+
"at": reviews[-1].get("at")}
|
|
593
|
+
if reviews else None
|
|
594
|
+
),
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def decisions_payload(root, limit=10):
|
|
599
|
+
"""The project's latest architect decisions and asked questions, read-only (MCP-RES)."""
|
|
600
|
+
recorded = [row for row in A.decision_rows(root)
|
|
601
|
+
if isinstance(row, dict) and row.get("kind") != "proposal"][-limit:]
|
|
602
|
+
asked = A.decisions(root)
|
|
603
|
+
return {
|
|
604
|
+
"decisions": recorded,
|
|
605
|
+
"questions": asked[:limit],
|
|
606
|
+
"open_count": sum(1 for item in asked if item.get("state") in ("open", "proposed")),
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
RESOURCE_SPECS = (
|
|
611
|
+
{"kind": "board",
|
|
612
|
+
"title": "Board",
|
|
613
|
+
"description": "Where each pre-authorised work item stands on the project's board, read-only and carrying no authority."},
|
|
614
|
+
{"kind": "roles",
|
|
615
|
+
"title": "Role table",
|
|
616
|
+
"description": "The project's actors, role assignments and any pending reassignment, read-only and carrying no authority."},
|
|
617
|
+
{"kind": "ledger",
|
|
618
|
+
"title": "Ledger summary",
|
|
619
|
+
"description": "Summary of the project's slice, verification, review, decision and waiver ledgers, read-only and carrying no authority."},
|
|
620
|
+
{"kind": "decisions",
|
|
621
|
+
"title": "Latest decisions",
|
|
622
|
+
"description": "The project's latest architect decisions and asked questions, read-only and carrying no authority."},
|
|
623
|
+
)
|
|
624
|
+
RESOURCE_SPEC_BY_KIND = {spec["kind"]: spec for spec in RESOURCE_SPECS}
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
def resource_uri(project, kind):
|
|
628
|
+
"""The stable `polyctl://<project>/<kind>` URI of one read-only resource, with `<project>` percent-encoded (MCP-RES, MCP-2026-2)."""
|
|
629
|
+
return f"{RESOURCE_SCHEME}://{urllib.parse.quote(str(project), safe='')}/{kind}"
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
def _parse_resource_uri(uri):
|
|
633
|
+
"""(project, kind) for a valid `polyctl://<project>/<kind>` URI, or (None, None)."""
|
|
634
|
+
prefix = f"{RESOURCE_SCHEME}://"
|
|
635
|
+
if not isinstance(uri, str) or not uri.startswith(prefix) or any(ch.isspace() for ch in uri):
|
|
636
|
+
return None, None
|
|
637
|
+
rest = uri[len(prefix):]
|
|
638
|
+
raw_project, sep, kind = rest.partition("/")
|
|
639
|
+
if not sep or not raw_project or not kind or "/" in kind or any(ch in raw_project for ch in "#?\\"):
|
|
640
|
+
return None, None
|
|
641
|
+
project = urllib.parse.unquote(raw_project)
|
|
642
|
+
if not A._usable_key(project):
|
|
643
|
+
return None, None
|
|
644
|
+
if kind not in RESOURCE_SPEC_BY_KIND:
|
|
645
|
+
return None, None
|
|
646
|
+
return project, kind
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def _cursor_error(params):
|
|
650
|
+
if params is None:
|
|
651
|
+
return None
|
|
652
|
+
if not isinstance(params, dict):
|
|
653
|
+
return {"code": INVALID_PARAMS, "message": "Invalid params"}
|
|
654
|
+
if params.get("cursor") is not None:
|
|
655
|
+
return {"code": INVALID_PARAMS, "message": "Invalid params: unknown cursor"}
|
|
656
|
+
return None
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def resources_list(cfg, project_scope=None, params=None):
|
|
660
|
+
"""Answer `resources/list`: (result, error) for the served project or every registered project (MCP-RES)."""
|
|
661
|
+
err = _cursor_error(params)
|
|
662
|
+
if err is not None:
|
|
663
|
+
return None, err
|
|
664
|
+
resources = []
|
|
665
|
+
for project, _, _ in _served_projects(cfg, project_scope):
|
|
666
|
+
for spec in RESOURCE_SPECS:
|
|
667
|
+
kind = spec["kind"]
|
|
668
|
+
resources.append({
|
|
669
|
+
"uri": resource_uri(project, kind),
|
|
670
|
+
"name": f"{project}/{kind}",
|
|
671
|
+
"title": f"{project} {spec['title'].lower()}",
|
|
672
|
+
"description": spec["description"],
|
|
673
|
+
"mimeType": RESOURCE_MIME_TYPE,
|
|
674
|
+
})
|
|
675
|
+
return {"resources": resources}, None
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
def resource_templates_list(params=None):
|
|
679
|
+
"""Answer `resources/templates/list`: (result, error) for per-project `polyctl://{project}/<kind>` URIs (MCP-RES)."""
|
|
680
|
+
err = _cursor_error(params)
|
|
681
|
+
if err is not None:
|
|
682
|
+
return None, err
|
|
683
|
+
templates = [{
|
|
684
|
+
"uriTemplate": f"{RESOURCE_SCHEME}://{{project}}/{spec['kind']}",
|
|
685
|
+
"name": spec["kind"],
|
|
686
|
+
"title": spec["title"],
|
|
687
|
+
"description": spec["description"],
|
|
688
|
+
"mimeType": RESOURCE_MIME_TYPE,
|
|
689
|
+
} for spec in RESOURCE_SPECS]
|
|
690
|
+
return {"resourceTemplates": templates}, None
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
def resource_read(cfg, project_scope=None, params=None, negotiated=None):
|
|
694
|
+
"""Answer `resources/read`: (result, error), read-only and refusing any project outside the registry (MCP-RES).
|
|
695
|
+
|
|
696
|
+
In MCP `2025-06-18` an unknown or unserved resource URI answers with `-32002` (`Resource not found`);
|
|
697
|
+
in `2026-07-28` (SEP-2164) it answers with `-32602` (`Invalid params`).
|
|
698
|
+
"""
|
|
699
|
+
if not isinstance(params, dict) or not isinstance(params.get("uri"), str) or not params.get("uri"):
|
|
700
|
+
return None, {"code": INVALID_PARAMS, "message": "Invalid params: uri is required"}
|
|
701
|
+
uri = params["uri"]
|
|
702
|
+
not_found_code = INVALID_PARAMS if negotiated == PROTOCOL_2026 else RESOURCE_NOT_FOUND
|
|
703
|
+
project, kind = _parse_resource_uri(uri)
|
|
704
|
+
if project is None:
|
|
705
|
+
return None, {"code": not_found_code, "message": f"Resource not found: {uri}", "data": {"uri": uri}}
|
|
706
|
+
resolved, problem = _resolve_project(cfg, project_scope, project)
|
|
707
|
+
if problem is not None:
|
|
708
|
+
return None, {"code": not_found_code, "message": problem, "data": {"uri": uri}}
|
|
709
|
+
project_name, root, project_cfg = resolved
|
|
710
|
+
canonical_uri = resource_uri(project_name, kind)
|
|
711
|
+
if kind == "board":
|
|
712
|
+
body = board_payload(root)
|
|
713
|
+
elif kind == "roles":
|
|
714
|
+
body = roles_payload(project_cfg)
|
|
715
|
+
elif kind == "ledger":
|
|
716
|
+
body = ledger_payload(root)
|
|
717
|
+
else:
|
|
718
|
+
body = decisions_payload(root)
|
|
719
|
+
payload = dict({"project": project_name, "uri": canonical_uri, "authority": "none"}, **body)
|
|
720
|
+
return {
|
|
721
|
+
"contents": [{
|
|
722
|
+
"uri": canonical_uri,
|
|
723
|
+
"mimeType": RESOURCE_MIME_TYPE,
|
|
724
|
+
"text": json.dumps(payload, ensure_ascii=False, indent=2, default=str),
|
|
725
|
+
}]
|
|
726
|
+
}, None
|
|
727
|
+
|
|
728
|
+
|
|
729
|
+
PROMPT_SPECS = (
|
|
730
|
+
{"name": "status",
|
|
731
|
+
"title": "Day's status",
|
|
732
|
+
"description": "Summarise the day's status for the project by calling its read-only polyctl tools in order.",
|
|
733
|
+
"tools": ("polyctl_status", "polyctl_board", "polyctl_decisions", "polyctl_notices"),
|
|
734
|
+
"arguments": ()},
|
|
735
|
+
{"name": "land-slice",
|
|
736
|
+
"title": "Land a named slice",
|
|
737
|
+
"description": "Prepare a named slice to land by calling polyctl's inspection and gate tools in order; "
|
|
738
|
+
"every authority step stays a CLI command for a person.",
|
|
739
|
+
"tools": ("polyctl_board", "polyctl_status", "polyctl_inbox", "polyctl_decisions", "polyctl_verify", "polyctl_candidate"),
|
|
740
|
+
"arguments": ({"name": "slice",
|
|
741
|
+
"description": "Slice id on the project's board to land",
|
|
742
|
+
"required": True},)},
|
|
743
|
+
{"name": "stuck",
|
|
744
|
+
"title": "Explain what is stuck",
|
|
745
|
+
"description": "Explain what is stuck in the project by calling polyctl's inspection tools in order; "
|
|
746
|
+
"any authority step comes back as a CLI command for a person.",
|
|
747
|
+
"tools": ("polyctl_status", "polyctl_board", "polyctl_decisions", "polyctl_notices", "polyctl_watchdog", "polyctl_inbox"),
|
|
748
|
+
"arguments": ()},
|
|
749
|
+
)
|
|
750
|
+
PROMPT_SPEC_BY_NAME = {spec["name"]: spec for spec in PROMPT_SPECS}
|
|
751
|
+
|
|
752
|
+
|
|
753
|
+
def prompts_for_role(role):
|
|
754
|
+
"""The prompt specs whose ordered tools are all served for `role` (MCP-2026-2)."""
|
|
755
|
+
served = set(role_tools(role))
|
|
756
|
+
return tuple(spec for spec in PROMPT_SPECS if set(spec["tools"]).issubset(served))
|
|
757
|
+
|
|
758
|
+
|
|
759
|
+
def _prompt_arguments(spec, project_scope=None):
|
|
760
|
+
project_arg = {
|
|
761
|
+
"name": "project",
|
|
762
|
+
"description": "Project name in polyctl's project registry",
|
|
763
|
+
"required": project_scope == "all",
|
|
764
|
+
}
|
|
765
|
+
return [project_arg] + [dict(arg) for arg in spec["arguments"]]
|
|
766
|
+
|
|
767
|
+
|
|
768
|
+
def prompts_list(project_scope=None, params=None, role=None):
|
|
769
|
+
"""Answer `prompts/list`: (result, error) for the menu prompts a person picks from (MCP-RES, MCP-2026-2)."""
|
|
770
|
+
err = _cursor_error(params)
|
|
771
|
+
if err is not None:
|
|
772
|
+
return None, err
|
|
773
|
+
prompts = [{
|
|
774
|
+
"name": spec["name"],
|
|
775
|
+
"title": spec["title"],
|
|
776
|
+
"description": spec["description"],
|
|
777
|
+
"arguments": _prompt_arguments(spec, project_scope),
|
|
778
|
+
} for spec in prompts_for_role(role)]
|
|
779
|
+
return {"prompts": prompts}, None
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
def _prompt_text(name, project_name, root, slice_id=None, question_id=None):
|
|
783
|
+
_require_project_key(project_name)
|
|
784
|
+
if slice_id is not None:
|
|
785
|
+
_require_caller_id("slice", slice_id)
|
|
786
|
+
if question_id is not None:
|
|
787
|
+
_require_caller_id("question", question_id)
|
|
788
|
+
call_arg = json.dumps({"project": project_name}, ensure_ascii=False)
|
|
789
|
+
answer_cmd = render_suggested_command("answer", root, question_id=question_id, project=project_name)
|
|
790
|
+
seen_cmd = render_suggested_command("harness-seen", root, project=project_name)
|
|
791
|
+
person_review_cmd = render_suggested_command("person-review", root, project=project_name)
|
|
792
|
+
commit_ok_cmd = render_suggested_command("commit-ok", root, project=project_name)
|
|
793
|
+
if name == "status":
|
|
794
|
+
return (
|
|
795
|
+
f"Project: {project_name}\n"
|
|
796
|
+
f"Inspect the day's status for project `{project_name}` by calling these polyctl MCP tools in order:\n"
|
|
797
|
+
f"1. `polyctl_status` with arguments `{call_arg}` — read implementer state, telemetry, git state and open reviews.\n"
|
|
798
|
+
f"2. `polyctl_board` with arguments `{call_arg}` — read running, blocked, ready, verified and done slices.\n"
|
|
799
|
+
f"3. `polyctl_decisions` with arguments `{call_arg}` — read open, proposed and answered questions.\n"
|
|
800
|
+
f"4. `polyctl_notices` with arguments `{call_arg}` — read recent alerts and notices.\n\n"
|
|
801
|
+
"Authority stays in the CLI — no MCP resource, prompt or tool records an approval, a commit-ok, "
|
|
802
|
+
"a waiver, an answer or a harness-seen. If a person must act, return the exact CLI command text "
|
|
803
|
+
"for them to run in their terminal:\n"
|
|
804
|
+
f"- Answer an open question: `{answer_cmd}`\n"
|
|
805
|
+
f"- Record harness configuration changes as seen: `{seen_cmd}`\n"
|
|
806
|
+
f"- Record a person review verdict: `{person_review_cmd}`\n"
|
|
807
|
+
f"- Grant commit authority: `{commit_ok_cmd}`"
|
|
808
|
+
)
|
|
809
|
+
if name == "land-slice":
|
|
810
|
+
_require_caller_id("slice", slice_id)
|
|
811
|
+
verify_arg = json.dumps({"project": project_name, "profile": "quick"}, ensure_ascii=False)
|
|
812
|
+
review_cmd = render_suggested_command("review", root, project=project_name)
|
|
813
|
+
collect_cmd = render_suggested_command("collect-review", root, project=project_name)
|
|
814
|
+
commit_cmd = render_suggested_command("commit", root, slice_id=slice_id, project=project_name)
|
|
815
|
+
waive_review_cmd = render_suggested_command("waive-review", root, slice_id=slice_id, project=project_name)
|
|
816
|
+
return (
|
|
817
|
+
f"Project: {project_name}\n"
|
|
818
|
+
f"Slice: {slice_id}\n"
|
|
819
|
+
f"Prepare slice `{slice_id}` in project `{project_name}` to land by calling these polyctl MCP tools in order:\n"
|
|
820
|
+
f"1. `polyctl_board` with arguments `{call_arg}` — confirm `{slice_id}` is on the board and check its state.\n"
|
|
821
|
+
f"2. `polyctl_status` with arguments `{call_arg}` — check dirty files, head, open reviews and unacknowledged mail.\n"
|
|
822
|
+
f"3. `polyctl_inbox` with arguments `{call_arg}` — read any unacknowledged coordination messages (and acknowledge handled ones with `polyctl_ack`).\n"
|
|
823
|
+
f"4. `polyctl_decisions` with arguments `{call_arg}` — confirm no open question blocks `{slice_id}`.\n"
|
|
824
|
+
f"5. `polyctl_verify` with arguments `{verify_arg}` — run the declared gates when the server was started with `--allow-verify`.\n"
|
|
825
|
+
f"6. `polyctl_candidate` with arguments `{call_arg}` — read the staged candidate's digest, paths and boundary for `{slice_id}`.\n\n"
|
|
826
|
+
"Authority stays in the CLI — no MCP resource, prompt or tool records an approval, a commit-ok, "
|
|
827
|
+
"a waiver, an answer or a harness-seen. Return any person step as CLI command text only:\n"
|
|
828
|
+
f"- Independent or person review: `{review_cmd}` or `{person_review_cmd}` "
|
|
829
|
+
f"(or `{collect_cmd}`)\n"
|
|
830
|
+
f"- Grant commit authority for the staged candidate: `{commit_ok_cmd}`\n"
|
|
831
|
+
f"- Commit the granted candidate: `{commit_cmd}`\n"
|
|
832
|
+
f"- Waive a gate on the record (person only): `{waive_review_cmd}`\n"
|
|
833
|
+
f"- Answer an open question (person only): `{answer_cmd}`\n"
|
|
834
|
+
f"- Record harness configuration changes as seen (person only): `{seen_cmd}`"
|
|
835
|
+
)
|
|
836
|
+
waive_gate_cmd = render_suggested_command("waive-gate", root, slice_id=slice_id, project=project_name)
|
|
837
|
+
return (
|
|
838
|
+
f"Project: {project_name}\n"
|
|
839
|
+
f"Explain what is stuck in project `{project_name}` by calling these polyctl MCP tools in order:\n"
|
|
840
|
+
f"1. `polyctl_status` with arguments `{call_arg}` — check implementer state, spinning minutes, held state and unread processes.\n"
|
|
841
|
+
f"2. `polyctl_board` with arguments `{call_arg}` — find blocked slices, what each waits on, and any board graph problems.\n"
|
|
842
|
+
f"3. `polyctl_decisions` with arguments `{call_arg}` — list open questions and rule proposals waiting on a person.\n"
|
|
843
|
+
f"4. `polyctl_notices` with arguments `{call_arg}` — inspect recent anomaly notices.\n"
|
|
844
|
+
f"5. `polyctl_watchdog` with arguments `{call_arg}` — run one dry explain cycle to see why the watchdog did or did not act.\n"
|
|
845
|
+
f"6. `polyctl_inbox` with arguments `{call_arg}` — check unacknowledged coordination messages.\n\n"
|
|
846
|
+
"Authority stays in the CLI — no MCP resource, prompt or tool records an approval, a commit-ok, "
|
|
847
|
+
"a waiver, an answer or a harness-seen. When a person's action is needed to unblock the project, "
|
|
848
|
+
"return the command text only:\n"
|
|
849
|
+
f"- Answer an open decision or proposal: `{answer_cmd}`\n"
|
|
850
|
+
f"- Mark harness changes seen: `{seen_cmd}`\n"
|
|
851
|
+
f"- Record a person review: `{person_review_cmd}`\n"
|
|
852
|
+
f"- Waive a gate on the record: `{waive_gate_cmd}`\n"
|
|
853
|
+
f"- Grant commit authority: `{commit_ok_cmd}`"
|
|
854
|
+
)
|
|
855
|
+
|
|
856
|
+
|
|
857
|
+
def prompt_get(cfg, project_scope=None, params=None, role=None):
|
|
858
|
+
"""Answer `prompts/get`: (result, error) naming the project and ordered polyctl tools to call (MCP-RES, MCP-2026-2)."""
|
|
859
|
+
if not isinstance(params, dict) or not isinstance(params.get("name"), str):
|
|
860
|
+
return None, {"code": INVALID_PARAMS, "message": "Invalid params: prompt name is required"}
|
|
861
|
+
name = params["name"]
|
|
862
|
+
spec = PROMPT_SPEC_BY_NAME.get(name)
|
|
863
|
+
if spec is None:
|
|
864
|
+
return None, {"code": INVALID_PARAMS, "message": f"Invalid params: unknown prompt {name!r}"}
|
|
865
|
+
served = set(role_tools(role))
|
|
866
|
+
unserved = [tool for tool in spec["tools"] if tool not in served]
|
|
867
|
+
if unserved:
|
|
868
|
+
return None, {
|
|
869
|
+
"code": INVALID_PARAMS,
|
|
870
|
+
"message": (f"Invalid params: prompt {name!r} calls {', '.join(unserved)}, which is not served "
|
|
871
|
+
f"with --role {role}"),
|
|
872
|
+
}
|
|
873
|
+
raw_args = params.get("arguments")
|
|
874
|
+
if raw_args is None:
|
|
875
|
+
raw_args = {}
|
|
876
|
+
if not isinstance(raw_args, dict) or any(not isinstance(k, str) or not isinstance(v, str)
|
|
877
|
+
for k, v in raw_args.items()):
|
|
878
|
+
return None, {"code": INVALID_PARAMS, "message": "Invalid params: arguments must be a map of strings"}
|
|
879
|
+
resolved, problem = _resolve_project(cfg, project_scope, raw_args.get("project"))
|
|
880
|
+
if problem is not None:
|
|
881
|
+
return None, {"code": INVALID_PARAMS, "message": f"Invalid params: {problem}"}
|
|
882
|
+
project_name, root, _ = resolved
|
|
883
|
+
slice_id = None
|
|
884
|
+
if name == "land-slice" or "slice" in raw_args:
|
|
885
|
+
raw_slice = raw_args.get("slice", "")
|
|
886
|
+
slice_id = raw_slice.strip() if isinstance(raw_slice, str) else ""
|
|
887
|
+
if not slice_id:
|
|
888
|
+
return None, {"code": INVALID_PARAMS, "message": "Invalid params: argument 'slice' is required"}
|
|
889
|
+
if not valid_caller_id("slice", slice_id):
|
|
890
|
+
return None, {"code": INVALID_PARAMS, "message": f"Invalid params: invalid slice id {raw_slice!r}"}
|
|
891
|
+
question_id = None
|
|
892
|
+
if "question" in raw_args:
|
|
893
|
+
raw_question = raw_args.get("question", "")
|
|
894
|
+
question_id = raw_question.strip() if isinstance(raw_question, str) else ""
|
|
895
|
+
if not valid_caller_id("question", question_id):
|
|
896
|
+
return None, {"code": INVALID_PARAMS, "message": f"Invalid params: invalid question id {raw_question!r}"}
|
|
897
|
+
text = _prompt_text(name, project_name, root, slice_id=slice_id, question_id=question_id)
|
|
898
|
+
return {
|
|
899
|
+
"description": f"{spec['description']} (project: {project_name})",
|
|
900
|
+
"messages": [{
|
|
901
|
+
"role": "user",
|
|
902
|
+
"content": {"type": "text", "text": text},
|
|
903
|
+
}],
|
|
904
|
+
}, None
|
|
905
|
+
|
|
906
|
+
|
|
907
|
+
def _attach_project(payload, project_name, project_scope):
|
|
908
|
+
if project_scope == "all" and isinstance(payload, dict) and "error" not in payload:
|
|
909
|
+
return dict({"project": project_name}, **payload)
|
|
910
|
+
return payload
|
|
911
|
+
|
|
912
|
+
|
|
913
|
+
def call(name, args, cfg, allow_verify, role=None, project_scope=None):
|
|
914
|
+
"""Run one tool for a server started for `role` and `project_scope`, and return what it answers.
|
|
915
|
+
|
|
916
|
+
A tool outside the role's set is refused here, not only left off the listing: a client can
|
|
917
|
+
call a name it was never shown, and the refusal is the same whichever way the call arrives.
|
|
918
|
+
With `--project all`, every call must name a project in polyctl's project registry (`project_registry_path`),
|
|
919
|
+
and any project outside the registry is refused before the tool runs (MCP-RES).
|
|
920
|
+
"""
|
|
921
|
+
args = args if isinstance(args, dict) else {}
|
|
922
|
+
if name not in EVERY_TOOL:
|
|
923
|
+
return {"error": f"unknown tool {name}"}
|
|
924
|
+
if name not in role_tools(role):
|
|
925
|
+
return {"error": f"{name} is not one of the {role}'s tools; this server was started with --role {role}"}
|
|
926
|
+
resolved, problem = _resolve_project(cfg, project_scope, args.get("project"))
|
|
927
|
+
if problem is not None:
|
|
928
|
+
return {"error": problem}
|
|
929
|
+
project_name, root, cfg = resolved
|
|
930
|
+
if name == "polyctl_status":
|
|
931
|
+
out = status_payload(cfg)
|
|
932
|
+
if project_scope == "all":
|
|
933
|
+
out = dict(out, project=project_name)
|
|
934
|
+
return out
|
|
935
|
+
if name == "polyctl_board":
|
|
936
|
+
return _attach_project(board_payload(root), project_name, project_scope)
|
|
937
|
+
if name == "polyctl_next":
|
|
938
|
+
out = next_payload(cfg, args.get("who"))
|
|
939
|
+
if project_scope == "all":
|
|
940
|
+
out = dict(out, project=project_name)
|
|
941
|
+
return out
|
|
942
|
+
if name == "polyctl_candidate":
|
|
943
|
+
return _attach_project(candidate_payload(cfg), project_name, project_scope)
|
|
944
|
+
if name == "polyctl_notices":
|
|
945
|
+
return _attach_project({"notices": A.notices(root, args.get("limit", 10),
|
|
946
|
+
args.get("include_suppressed", False))},
|
|
947
|
+
project_name, project_scope)
|
|
948
|
+
if name == "polyctl_fleet":
|
|
949
|
+
if project_scope == "all":
|
|
950
|
+
projects = [{"name": proj, "root": path} for proj, path in sorted(registered_projects().items())]
|
|
951
|
+
return {"project": project_name, "projects": projects}
|
|
952
|
+
return {"projects": [{"name": os.path.basename(w["path"]), "root": w["path"]}
|
|
953
|
+
for w in A.all_workspaces()]}
|
|
954
|
+
if name == "polyctl_inbox":
|
|
955
|
+
# The same files the file-based protocol uses. One source of truth: an MCP
|
|
956
|
+
# store beside the mailbox would be a second place for the same fact, and
|
|
957
|
+
# every failure in this project's history has come from two records of one
|
|
958
|
+
# thing drifting apart.
|
|
959
|
+
box = cfg.get("mailbox", "agent-mail")
|
|
960
|
+
out = []
|
|
961
|
+
for m in A.mailbox(root, box):
|
|
962
|
+
if not A.addressed_to(m, cfg, "implementer"):
|
|
963
|
+
continue # our own outbound, or the watchdog's; not addressed to us
|
|
964
|
+
try:
|
|
965
|
+
body = open(os.path.join(root, box, m), errors="replace", encoding=UTF8).read(20000)
|
|
966
|
+
except OSError:
|
|
967
|
+
continue
|
|
968
|
+
out.append({"id": m, "body": body})
|
|
969
|
+
A.mail_seen(root, [message["id"] for message in out], "implementer") # shown, not handled (#30)
|
|
970
|
+
return _attach_project({"messages": out, "count": len(out),
|
|
971
|
+
"note": "acknowledge each with polyctl_ack after applying or rejecting it"},
|
|
972
|
+
project_name, project_scope)
|
|
973
|
+
|
|
974
|
+
if name == "polyctl_ack":
|
|
975
|
+
box = cfg.get("mailbox", "agent-mail")
|
|
976
|
+
mid = os.path.basename(args.get("id", ""))
|
|
977
|
+
path = os.path.join(root, box, mid)
|
|
978
|
+
if not mid or mid == "README.md" or not os.path.exists(path):
|
|
979
|
+
return {"error": f"no such message: {args.get('id')}"}
|
|
980
|
+
# Only what polyctl_inbox lists: mail addressed to the implementer. Any name in the mailbox was taken, so an
|
|
981
|
+
# implementer consumed the architect's reports, the hunter's leads and the watchdog's anomalies - deleted,
|
|
982
|
+
# or with mail.store append-only recorded handled, which the store keeps from the actor deciding what was
|
|
983
|
+
# handled precisely so that it cannot erase the question (LEADS-MCP).
|
|
984
|
+
if not A.addressed_to(mid, cfg, "implementer"):
|
|
985
|
+
mail_ack_cmd = render_suggested_command("mail-ack")
|
|
986
|
+
return {"error": f"{mid} is not addressed to the implementer, so polyctl_ack does not take it: it acknowledges "
|
|
987
|
+
"only what polyctl_inbox lists. Mail to the architect, and the watchdog's, is acknowledged by "
|
|
988
|
+
f"the one it is for, with `{mail_ack_cmd}`; leave it where it is."}
|
|
989
|
+
if A.mail_store_mode(root) == "append-only":
|
|
990
|
+
A.ingest_mail(root, cfg)
|
|
991
|
+
A.handle_message(root, cfg, mid, "implementer", args.get("outcome", "applied")) # a record (#80)
|
|
992
|
+
else:
|
|
993
|
+
os.remove(path)
|
|
994
|
+
A.record_notice(root, "ack", f"{mid}: {args.get('outcome', 'applied')}",
|
|
995
|
+
sent=False, key="ack")
|
|
996
|
+
A.mail_ledger_append(root, {"event": "consumed", "id": mid,
|
|
997
|
+
"outcome": args.get("outcome", "applied")})
|
|
998
|
+
return _attach_project({"acknowledged": mid, "outcome": args.get("outcome", "applied")},
|
|
999
|
+
project_name, project_scope)
|
|
1000
|
+
|
|
1001
|
+
if name == "polyctl_report":
|
|
1002
|
+
if args.get("slice") is not None and not valid_caller_id("slice", args.get("slice")):
|
|
1003
|
+
return {"error": f"invalid slice id {args.get('slice')!r}"}
|
|
1004
|
+
box = cfg.get("mailbox", "agent-mail")
|
|
1005
|
+
os.makedirs(os.path.join(root, box), exist_ok=True)
|
|
1006
|
+
kind = args.get("kind", "status")
|
|
1007
|
+
# `blocked` writes the marker the watchdog escalates on within one cycle.
|
|
1008
|
+
# The agent saying so directly beats a detector inferring it twenty
|
|
1009
|
+
# minutes later, which is what used to happen. It is the project's
|
|
1010
|
+
# language's marker; the watchdog reads every language's (LANGUAGE-FILES).
|
|
1011
|
+
header = language.marker(cfg, "decision") if kind == "blocked" else f"## {kind.upper()}"
|
|
1012
|
+
slug = A.safe_slug(args["summary"].lower(), "report")
|
|
1013
|
+
# The same request twice is one request. An implementer nudged into a
|
|
1014
|
+
# turn with nothing to do reports the same blocker again; eighty copies
|
|
1015
|
+
# of "queue empty" stood in one mailbox after eleven hours, each a fresh
|
|
1016
|
+
# anomaly and a fresh wake. Fold a repeat into the standing report and
|
|
1017
|
+
# keep that file's age — the age is the fact the architect needs.
|
|
1018
|
+
impl, arch = A.mail_names(cfg)
|
|
1019
|
+
# the standing report may be addressed by a name the architect's mail had before (#72)
|
|
1020
|
+
markers = [f"-{impl}-to-{name}-{kind.upper()}-" for name in A.architect_mail_names(cfg)]
|
|
1021
|
+
dup = None
|
|
1022
|
+
for m in A.mailbox(root, box):
|
|
1023
|
+
if any(marker in m for marker in markers) and \
|
|
1024
|
+
A._report_summary(os.path.join(root, box, m)) == args["summary"].strip():
|
|
1025
|
+
dup = m
|
|
1026
|
+
if dup:
|
|
1027
|
+
n = A.bump_repeat(os.path.join(root, box, dup), cfg)
|
|
1028
|
+
return _attach_project(
|
|
1029
|
+
{"written": dup, "repeated": n, "escalates": kind == "blocked",
|
|
1030
|
+
"delivered_to_phone": 0,
|
|
1031
|
+
"note": (f"the same {kind} report is already standing ({n}× now); the architect "
|
|
1032
|
+
f"sees one file with its original time. Do not report it again; end the turn.")},
|
|
1033
|
+
project_name, project_scope)
|
|
1034
|
+
name_ = f"{time.strftime('%Y%m%d-%H%M')}-{impl}-to-{arch}-{kind.upper()}-{slug}.md"
|
|
1035
|
+
text = f"# {args['summary']}\n\n{header}\n\n"
|
|
1036
|
+
# Counts are quoted from the ledger, not typed; a green claim over a red
|
|
1037
|
+
# verification is said to be what it is (#6).
|
|
1038
|
+
inconsistent = A.report_inconsistency(
|
|
1039
|
+
root, " ".join(str(args.get(field) or "") for field in ("summary", "detail", "needs")))
|
|
1040
|
+
if inconsistent:
|
|
1041
|
+
text += f"## INCONSISTENT\n\n{inconsistent}\n\n"
|
|
1042
|
+
if args.get("detail"):
|
|
1043
|
+
text += args["detail"] + "\n\n"
|
|
1044
|
+
if args.get("needs"):
|
|
1045
|
+
text += f"**Needs:** {args['needs']}\n"
|
|
1046
|
+
evidence = A.verification_evidence(root)
|
|
1047
|
+
if evidence:
|
|
1048
|
+
text += f"**Verification:** {evidence}\n"
|
|
1049
|
+
name_ = A.write_mail(root, cfg, name_, text, {"kind": kind, "from": impl, "to": arch,
|
|
1050
|
+
"slice": args.get("slice")})
|
|
1051
|
+
delivered = 0
|
|
1052
|
+
if kind == "blocked":
|
|
1053
|
+
try:
|
|
1054
|
+
from . import telegram
|
|
1055
|
+
delivered = telegram.send(
|
|
1056
|
+
language.text(cfg, "report.blocked-phone", summary=args["summary"],
|
|
1057
|
+
needs=args.get("needs") or args.get("detail") or ""),
|
|
1058
|
+
root)
|
|
1059
|
+
except Exception:
|
|
1060
|
+
pass
|
|
1061
|
+
return _attach_project(
|
|
1062
|
+
{"written": name_, "escalates": kind == "blocked",
|
|
1063
|
+
"delivered_to_phone": delivered, "inconsistent": inconsistent,
|
|
1064
|
+
"note": ("the architect is woken on the next watchdog cycle"
|
|
1065
|
+
if kind == "blocked" else "queued for the architect")},
|
|
1066
|
+
project_name, project_scope)
|
|
1067
|
+
|
|
1068
|
+
if name == "polyctl_watchdog":
|
|
1069
|
+
from types import SimpleNamespace
|
|
1070
|
+
from . import watchdog as W
|
|
1071
|
+
if args.get("action", "explain") == "trace":
|
|
1072
|
+
return _attach_project({"cycles": W.cycles(root, int(args.get("last") or 20))},
|
|
1073
|
+
project_name, project_scope)
|
|
1074
|
+
W.run(SimpleNamespace(root=root, idle_minutes=None, dry_run=True))
|
|
1075
|
+
return _attach_project({"facts": dict(W._FACTS), "trace": list(W._TRACE),
|
|
1076
|
+
"verdict": W._TRACE[-1] if W._TRACE else ""},
|
|
1077
|
+
project_name, project_scope)
|
|
1078
|
+
if name == "polyctl_fanout":
|
|
1079
|
+
if args.get("action") == "record":
|
|
1080
|
+
return _attach_project(
|
|
1081
|
+
A.record_fanout(root, args["agents"], args.get("done"), args.get("errors"),
|
|
1082
|
+
args.get("tokens"), args.get("note")),
|
|
1083
|
+
project_name, project_scope)
|
|
1084
|
+
return _attach_project(
|
|
1085
|
+
A.fanout_verdict(root, cfg, int(args["agents"]), args.get("per_agent_tokens")),
|
|
1086
|
+
project_name, project_scope)
|
|
1087
|
+
if name == "polyctl_ask":
|
|
1088
|
+
if args.get("slice") is not None and not valid_caller_id("slice", args.get("slice")):
|
|
1089
|
+
return {"error": f"invalid slice id {args.get('slice')!r}"}
|
|
1090
|
+
rec = A.ask(root, args["question"], args.get("options") or [],
|
|
1091
|
+
context=args.get("context"), slice_id=args.get("slice"), cfg=cfg)
|
|
1092
|
+
# Delivery is decided here, not by the caller. An implementer with its own
|
|
1093
|
+
# channel to a phone is a spam surface; an implementer that reports and
|
|
1094
|
+
# lets the centre route is not.
|
|
1095
|
+
delivered = 0
|
|
1096
|
+
try:
|
|
1097
|
+
from .cli import _phone_decision
|
|
1098
|
+
delivered = _phone_decision(rec, cfg)
|
|
1099
|
+
except Exception:
|
|
1100
|
+
pass
|
|
1101
|
+
return _attach_project({"id": rec["id"], "options": rec["options"],
|
|
1102
|
+
"delivered_to_phone": delivered,
|
|
1103
|
+
"note": "park the slice and take the next queued item; check "
|
|
1104
|
+
"polyctl_decisions next turn"},
|
|
1105
|
+
project_name, project_scope)
|
|
1106
|
+
|
|
1107
|
+
if name == "polyctl_decisions":
|
|
1108
|
+
return _attach_project({"decisions": A.decisions(root, args.get("state"))},
|
|
1109
|
+
project_name, project_scope)
|
|
1110
|
+
|
|
1111
|
+
if name == "polyctl_propose":
|
|
1112
|
+
# A proposal, never an edit: it records the change and asks a person, and writes no rule file. It is
|
|
1113
|
+
# the agent's to make, as a question is; the answer is a person's, and no tool here gives one.
|
|
1114
|
+
try:
|
|
1115
|
+
proposal, question, created = A.propose(root, cfg, args.get("text"), args.get("why"),
|
|
1116
|
+
rule_file=args.get("rule_file"), via="mcp")
|
|
1117
|
+
except A.ProposalRefused as exc:
|
|
1118
|
+
return {"error": str(exc)}
|
|
1119
|
+
if not created:
|
|
1120
|
+
return _attach_project(
|
|
1121
|
+
{"id": proposal["id"], "question": proposal["question"], "standing": True,
|
|
1122
|
+
"note": "this change is proposed already and waits for a person; do not propose it again"},
|
|
1123
|
+
project_name, project_scope)
|
|
1124
|
+
delivered = 0
|
|
1125
|
+
try:
|
|
1126
|
+
from .cli import _phone_decision
|
|
1127
|
+
delivered = _phone_decision(question, cfg)
|
|
1128
|
+
except Exception:
|
|
1129
|
+
pass
|
|
1130
|
+
return _attach_project(
|
|
1131
|
+
{"id": proposal["id"], "question": proposal["question"], "delivered_to_phone": delivered,
|
|
1132
|
+
"note": "a person accepts or rejects it; keep working under the rule as it stands, and read "
|
|
1133
|
+
"the answer with polyctl_decisions"},
|
|
1134
|
+
project_name, project_scope)
|
|
1135
|
+
|
|
1136
|
+
if name == "polyctl_verify":
|
|
1137
|
+
if not allow_verify:
|
|
1138
|
+
return {"error": "verify is disabled; start the server with --allow-verify"}
|
|
1139
|
+
import subprocess
|
|
1140
|
+
r = subprocess.run([sys.executable, "-m", "polyctl", "-C", root, "verify"]
|
|
1141
|
+
+ (["-p", args["profile"]] if args.get("profile") else []),
|
|
1142
|
+
capture_output=True, text=True, encoding=UTF8, errors="replace", timeout=3600,
|
|
1143
|
+
cwd=A.self_child_cwd(), env=A.self_child_env())
|
|
1144
|
+
return _attach_project({"exit": r.returncode, "output": (r.stdout or r.stderr)[-4000:],
|
|
1145
|
+
"record": A.latest_verification(root)},
|
|
1146
|
+
project_name, project_scope)
|
|
1147
|
+
return {"error": f"unknown tool {name}"}
|
|
1148
|
+
|
|
1149
|
+
|
|
1150
|
+
def _server_info():
|
|
1151
|
+
return {"name": "polyctl", "version": __version__}
|
|
1152
|
+
|
|
1153
|
+
|
|
1154
|
+
def _capabilities():
|
|
1155
|
+
return {key: dict(value) for key, value in CAPABILITIES.items()}
|
|
1156
|
+
|
|
1157
|
+
|
|
1158
|
+
def _discover_result():
|
|
1159
|
+
return {"resultType": "complete",
|
|
1160
|
+
"supportedVersions": list(PROTOCOLS),
|
|
1161
|
+
"capabilities": _capabilities(),
|
|
1162
|
+
"_meta": {"io.modelcontextprotocol/serverInfo": _server_info()}}
|
|
1163
|
+
|
|
1164
|
+
|
|
1165
|
+
def _negotiate_initialize(params):
|
|
1166
|
+
"""Answer `initialize` (2025-06-18 lifecycle): (result, error).
|
|
1167
|
+
|
|
1168
|
+
MCP `2026-07-28` is stateless and removed the `initialize` handshake in favour of
|
|
1169
|
+
`server/discover` and per-request `params._meta` (`basic/versioning`, `basic/index`
|
|
1170
|
+
#Statelessness). Naming `2026-07-28` on `initialize` previously answered with a
|
|
1171
|
+
`2026-07-28` handshake result while subsequent no-`_meta` calls were served as
|
|
1172
|
+
`2025-06-18`; refuse `2026-07-28` on `initialize` and point at `server/discover`,
|
|
1173
|
+
while legacy clients keep working on `2025-06-18` (MCP-2026-2).
|
|
1174
|
+
"""
|
|
1175
|
+
if params is None:
|
|
1176
|
+
params = {}
|
|
1177
|
+
if not isinstance(params, dict):
|
|
1178
|
+
return None, {"code": INVALID_PARAMS, "message": "Invalid params"}
|
|
1179
|
+
requested = params.get("protocolVersion")
|
|
1180
|
+
if requested is not None and (not isinstance(requested, str) or not requested):
|
|
1181
|
+
return None, {"code": INVALID_PARAMS, "message": "Invalid params"}
|
|
1182
|
+
meta = params.get("_meta")
|
|
1183
|
+
meta_version = meta.get("io.modelcontextprotocol/protocolVersion") if isinstance(meta, dict) else None
|
|
1184
|
+
if requested == PROTOCOL_2026 or meta_version == PROTOCOL_2026:
|
|
1185
|
+
return None, {
|
|
1186
|
+
"code": INVALID_PARAMS,
|
|
1187
|
+
"message": (f"Invalid params: protocolVersion {PROTOCOL_2026!r} is stateless and does not use "
|
|
1188
|
+
"initialize; probe with server/discover and send "
|
|
1189
|
+
"io.modelcontextprotocol/protocolVersion in params._meta on each request, "
|
|
1190
|
+
f"or initialize with {PROTOCOL!r}"),
|
|
1191
|
+
"data": {"supported": list(PROTOCOLS), "requested": PROTOCOL_2026},
|
|
1192
|
+
}
|
|
1193
|
+
version = requested if requested in LEGACY_PROTOCOLS else PROTOCOL
|
|
1194
|
+
return {"protocolVersion": version,
|
|
1195
|
+
"capabilities": _capabilities(),
|
|
1196
|
+
"serverInfo": _server_info()}, None
|
|
1197
|
+
|
|
1198
|
+
|
|
1199
|
+
def _negotiate_meta(params, require_meta=False):
|
|
1200
|
+
"""Validate 2026-07-28 `params._meta` when present or required (MCP-2026): (version, error)."""
|
|
1201
|
+
if params is None:
|
|
1202
|
+
if require_meta:
|
|
1203
|
+
return None, {"code": INVALID_PARAMS, "message": "Invalid params"}
|
|
1204
|
+
return None, None
|
|
1205
|
+
if not isinstance(params, dict):
|
|
1206
|
+
return None, {"code": INVALID_PARAMS, "message": "Invalid params"}
|
|
1207
|
+
if "_meta" not in params:
|
|
1208
|
+
if require_meta:
|
|
1209
|
+
return None, {"code": INVALID_PARAMS, "message": "Invalid params"}
|
|
1210
|
+
return None, None
|
|
1211
|
+
meta = params.get("_meta")
|
|
1212
|
+
if not isinstance(meta, dict):
|
|
1213
|
+
return None, {"code": INVALID_PARAMS, "message": "Invalid params"}
|
|
1214
|
+
if not require_meta and set(meta) == {"progressToken"} and type(meta.get("progressToken")) in (str, int):
|
|
1215
|
+
return None, None
|
|
1216
|
+
requested = meta.get("io.modelcontextprotocol/protocolVersion")
|
|
1217
|
+
if not isinstance(requested, str) or not requested:
|
|
1218
|
+
return None, {"code": INVALID_PARAMS, "message": "Invalid params"}
|
|
1219
|
+
if requested not in PROTOCOLS:
|
|
1220
|
+
return None, {"code": UNSUPPORTED_PROTOCOL_VERSION,
|
|
1221
|
+
"message": "Unsupported protocol version",
|
|
1222
|
+
"data": {"supported": list(PROTOCOLS), "requested": requested}}
|
|
1223
|
+
capabilities = meta.get("io.modelcontextprotocol/clientCapabilities", {})
|
|
1224
|
+
if not isinstance(capabilities, dict):
|
|
1225
|
+
return None, {"code": INVALID_PARAMS, "message": "Invalid params"}
|
|
1226
|
+
client_info = meta.get("io.modelcontextprotocol/clientInfo")
|
|
1227
|
+
if client_info is not None and (
|
|
1228
|
+
not isinstance(client_info, dict)
|
|
1229
|
+
or not isinstance(client_info.get("name"), str)
|
|
1230
|
+
or not isinstance(client_info.get("version"), str)):
|
|
1231
|
+
return None, {"code": INVALID_PARAMS, "message": "Invalid params"}
|
|
1232
|
+
log_level = meta.get("io.modelcontextprotocol/logLevel")
|
|
1233
|
+
if log_level is not None and not isinstance(log_level, str):
|
|
1234
|
+
return None, {"code": INVALID_PARAMS, "message": "Invalid params"}
|
|
1235
|
+
return requested, None
|
|
1236
|
+
|
|
1237
|
+
|
|
1238
|
+
def main():
|
|
1239
|
+
# MCP's stdio transport is UTF-8. A client writes a request in it whatever the platform's code
|
|
1240
|
+
# page, and each reply below is seven-bit JSON, which reads the same in any (#71).
|
|
1241
|
+
A.utf8_streams()
|
|
1242
|
+
root = None
|
|
1243
|
+
allow_verify = "--allow-verify" in sys.argv
|
|
1244
|
+
if "-C" in sys.argv:
|
|
1245
|
+
root = sys.argv[sys.argv.index("-C") + 1]
|
|
1246
|
+
# The role and project scope the registration names (MCP-ROLES, MCP-RES): fixed for the session,
|
|
1247
|
+
# since a harness starts its servers once, when its session starts. Read without case or
|
|
1248
|
+
# surrounding space, so a hand-written `Reviewer` is the reviewer; a role or `--project` value
|
|
1249
|
+
# the server does not know stops the server before it answers anything (HUNT-LEADS-SEC).
|
|
1250
|
+
try:
|
|
1251
|
+
role = served_role(sys.argv[1:])
|
|
1252
|
+
project_scope = served_project(sys.argv[1:])
|
|
1253
|
+
except ValueError as refused:
|
|
1254
|
+
print(refused, file=sys.stderr, flush=True)
|
|
1255
|
+
return 2
|
|
1256
|
+
served = role_tools(role)
|
|
1257
|
+
notice = role_notice(role)
|
|
1258
|
+
if notice:
|
|
1259
|
+
print(notice, file=sys.stderr, flush=True)
|
|
1260
|
+
cfg = {"root": A.find_root(root)} if project_scope == "all" else A.load_config(A.find_root(root))
|
|
1261
|
+
|
|
1262
|
+
for line in sys.stdin:
|
|
1263
|
+
line = line.strip()
|
|
1264
|
+
if not line:
|
|
1265
|
+
continue
|
|
1266
|
+
try:
|
|
1267
|
+
req = json.loads(line)
|
|
1268
|
+
except (ValueError, RecursionError):
|
|
1269
|
+
# Not JSON - or JSON this parser will not hold, a number of more than 4300 digits or nesting deeper than
|
|
1270
|
+
# it recurses, which raised no JSONDecodeError and ended the server (LEADS-MCP).
|
|
1271
|
+
continue
|
|
1272
|
+
if not isinstance(req, dict):
|
|
1273
|
+
# A JSON array or a scalar is no request, and reading it as one ended the server, as it ended the A2A
|
|
1274
|
+
# bridge (A2A-HARDEN): answered as invalid, and the next line is read (LEADS-MCP).
|
|
1275
|
+
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": None, "error": {
|
|
1276
|
+
"code": -32600, "message": "a request is a JSON object"}}) + "\n")
|
|
1277
|
+
sys.stdout.flush()
|
|
1278
|
+
continue
|
|
1279
|
+
rid, method = req.get("id"), req.get("method")
|
|
1280
|
+
# Never dispatch or echo a container id: encoding a deeply nested one ended the server (LEADS-OPEN).
|
|
1281
|
+
if (rid is not None and type(rid) not in (str, int, float)) or (
|
|
1282
|
+
isinstance(rid, float) and not math.isfinite(rid)):
|
|
1283
|
+
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": None, "error": {
|
|
1284
|
+
"code": -32600, "message": "a request id must be a string, finite number or null"}}) + "\n")
|
|
1285
|
+
sys.stdout.flush()
|
|
1286
|
+
continue
|
|
1287
|
+
try:
|
|
1288
|
+
error = None
|
|
1289
|
+
negotiated = None
|
|
1290
|
+
if method in ("notifications/initialized", "initialized"):
|
|
1291
|
+
continue # notification: no reply
|
|
1292
|
+
elif method == "initialize":
|
|
1293
|
+
result, error = _negotiate_initialize(req.get("params"))
|
|
1294
|
+
else:
|
|
1295
|
+
params = req.get("params")
|
|
1296
|
+
negotiated, error = _negotiate_meta(params, require_meta=(method == "server/discover"))
|
|
1297
|
+
if error is None:
|
|
1298
|
+
if method == "server/discover":
|
|
1299
|
+
result = _discover_result()
|
|
1300
|
+
elif method == "tools/list":
|
|
1301
|
+
result = {"tools": tools_for_role(role, project_scope)}
|
|
1302
|
+
elif method == "tools/call":
|
|
1303
|
+
p = params if isinstance(params, dict) else {}
|
|
1304
|
+
args = p.get("arguments") if isinstance(p.get("arguments"), dict) else {}
|
|
1305
|
+
payload = call(p.get("name"), args, cfg, allow_verify, role, project_scope)
|
|
1306
|
+
# Ride along on whatever the agent called. MCP has no way to push,
|
|
1307
|
+
# so the next best thing is to attach the message to the next
|
|
1308
|
+
# response it asks for — which costs nothing and arrives sooner
|
|
1309
|
+
# than the agent's own next inbox check. Only where polyctl_inbox is served:
|
|
1310
|
+
# the note sends the agent there, and a role without it - a reviewer -
|
|
1311
|
+
# can neither read the message nor acknowledge it.
|
|
1312
|
+
if (isinstance(payload, dict) and "error" not in payload
|
|
1313
|
+
and p.get("name") != "polyctl_inbox" and "polyctl_inbox" in served):
|
|
1314
|
+
resolved, problem = _resolve_project(cfg, project_scope, args.get("project"))
|
|
1315
|
+
if problem is None:
|
|
1316
|
+
_, target_root, target_cfg = resolved
|
|
1317
|
+
urgent = A.urgent_messages(target_root, target_cfg)
|
|
1318
|
+
if urgent:
|
|
1319
|
+
payload["URGENT_UNACKNOWLEDGED"] = [
|
|
1320
|
+
{"id": u["id"], "title": u["title"]} for u in urgent]
|
|
1321
|
+
payload["URGENT_NOTE"] = (
|
|
1322
|
+
"Read these with polyctl_inbox and acknowledge them before "
|
|
1323
|
+
"continuing. polyctl commit-ok will refuse while any remain.")
|
|
1324
|
+
result = {"content": [{"type": "text",
|
|
1325
|
+
"text": json.dumps(payload, ensure_ascii=False,
|
|
1326
|
+
indent=2, default=str)}]}
|
|
1327
|
+
elif method == "resources/list":
|
|
1328
|
+
result, error = resources_list(cfg, project_scope, params)
|
|
1329
|
+
elif method == "resources/templates/list":
|
|
1330
|
+
result, error = resource_templates_list(params)
|
|
1331
|
+
elif method == "resources/read":
|
|
1332
|
+
result, error = resource_read(cfg, project_scope, params, negotiated=negotiated)
|
|
1333
|
+
elif method == "prompts/list":
|
|
1334
|
+
result, error = prompts_list(project_scope, params, role=role)
|
|
1335
|
+
elif method == "prompts/get":
|
|
1336
|
+
result, error = prompt_get(cfg, project_scope, params, role=role)
|
|
1337
|
+
elif method == "ping":
|
|
1338
|
+
result = {}
|
|
1339
|
+
else:
|
|
1340
|
+
raise ValueError(f"method not found: {method}")
|
|
1341
|
+
if error is None and method != "server/discover" and negotiated == PROTOCOL_2026:
|
|
1342
|
+
result = dict({"resultType": "complete"}, **result,
|
|
1343
|
+
_meta={"io.modelcontextprotocol/serverInfo": _server_info()})
|
|
1344
|
+
except Exception as e: # never take the transport down
|
|
1345
|
+
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": rid,
|
|
1346
|
+
"error": {"code": -32603, "message": str(e)}}) + "\n")
|
|
1347
|
+
sys.stdout.flush()
|
|
1348
|
+
continue
|
|
1349
|
+
if error is not None:
|
|
1350
|
+
if rid is not None:
|
|
1351
|
+
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": rid, "error": error}, default=str) + "\n")
|
|
1352
|
+
sys.stdout.flush()
|
|
1353
|
+
continue
|
|
1354
|
+
if rid is not None:
|
|
1355
|
+
# Escaped to ASCII, as the error reply above always was: this write is outside the handler, and
|
|
1356
|
+
# a character the stream cannot carry, or a lone surrogate a request held, took the server down.
|
|
1357
|
+
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": rid, "result": result}, default=str) + "\n")
|
|
1358
|
+
sys.stdout.flush()
|
|
1359
|
+
|
|
1360
|
+
|
|
1361
|
+
if __name__ == "__main__":
|
|
1362
|
+
sys.exit(main())
|