@rvdbreemen/adr-kit-opencode 0.52.0
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.
- package/.claude-plugin/plugin.json +29 -0
- package/LICENSE +21 -0
- package/README.md +850 -0
- package/bin/adr +1552 -0
- package/bin/adr-audit +454 -0
- package/bin/adr-context +584 -0
- package/bin/adr-discover +546 -0
- package/bin/adr-doctor +166 -0
- package/bin/adr-generate-scripts +421 -0
- package/bin/adr-grill-signal +131 -0
- package/bin/adr-guardian +1263 -0
- package/bin/adr-index +199 -0
- package/bin/adr-judge +2832 -0
- package/bin/adr-judge-precommit +87 -0
- package/bin/adr-lint +2087 -0
- package/bin/adr-mcp +1093 -0
- package/bin/adr-migrate +644 -0
- package/bin/adr-quality +275 -0
- package/bin/adr-readiness +211 -0
- package/bin/adr-readiness-ci +111 -0
- package/bin/adr-related +401 -0
- package/bin/adr-renumber +254 -0
- package/bin/adr-retire +467 -0
- package/bin/adr-settings +399 -0
- package/bin/adr-status +797 -0
- package/bin/adr-suggest +803 -0
- package/bin/adr-watch +674 -0
- package/bin/adr_catalog.py +536 -0
- package/bin/adr_config.py +280 -0
- package/bin/adr_doctor_checks.py +407 -0
- package/bin/adr_doctor_core.py +342 -0
- package/bin/adr_doctor_models.py +186 -0
- package/bin/adr_doctor_probes.py +216 -0
- package/bin/adr_format.py +786 -0
- package/bin/adr_grill_signal.py +123 -0
- package/bin/adr_guardian_queue.py +218 -0
- package/bin/adr_history_scan.py +278 -0
- package/bin/adr_index_core.py +443 -0
- package/bin/adr_llm.py +333 -0
- package/bin/adr_llm_judge_migration.py +314 -0
- package/bin/adr_quality_core.py +674 -0
- package/bin/adr_query.py +678 -0
- package/bin/adr_readiness.py +442 -0
- package/bin/adr_readiness_ci.py +123 -0
- package/bin/adr_regex.py +165 -0
- package/bin/adr_regex_worker.py +30 -0
- package/bin/adr_retrieval_health.py +385 -0
- package/bin/adr_schema.py +448 -0
- package/bin/adr_state.py +172 -0
- package/bin/bump-version +71 -0
- package/clients/workflows.json +229 -0
- package/hooks/__init__.py +1 -0
- package/hooks/adapters/__init__.py +13 -0
- package/hooks/adapters/claude.py +27 -0
- package/hooks/adapters/codex.py +26 -0
- package/hooks/adapters/copilot.py +11 -0
- package/hooks/adr-hook.py +128 -0
- package/hooks/adr_hook_core.py +843 -0
- package/hooks/adr_pr_guard.py +367 -0
- package/instructions/ADR-guide.md +48 -0
- package/instructions/adr.coding.md +82 -0
- package/instructions/adr.review.md +182 -0
- package/opencode/plugin.ts +451 -0
- package/package.json +41 -0
- package/schemas/adr-context-probes.schema.json +56 -0
- package/schemas/adr-enforcement.schema.json +57 -0
- package/schemas/adr-frontmatter.schema.json +144 -0
- package/schemas/adr-index.schema.json +276 -0
- package/schemas/adr-kit-config.schema.json +371 -0
- package/schemas/adr-readiness.schema.json +41 -0
- package/schemas/client-capabilities.schema.json +503 -0
- package/schemas/client-certification.schema.json +101 -0
- package/schemas/doctor-output.schema.json +92 -0
- package/schemas/marketplace.json.schema.json +70 -0
- package/schemas/plugin.json.schema.json +67 -0
- package/scripts/adr_settings.py +239 -0
- package/scripts/benchmark-adr-grilling.py +323 -0
- package/scripts/benchmark-client-generation.py +178 -0
- package/scripts/build-client-adapters.py +139 -0
- package/scripts/bump-version.py +304 -0
- package/scripts/check-branch-sync.py +243 -0
- package/scripts/check-release-version.py +81 -0
- package/scripts/client_certification.py +153 -0
- package/scripts/client_evidence.py +280 -0
- package/scripts/client_generation.py +288 -0
- package/scripts/client_generation_artifacts.py +351 -0
- package/scripts/client_generation_model.py +173 -0
- package/scripts/client_generation_state.py +260 -0
- package/scripts/client_support_matrix.py +360 -0
- package/scripts/install-agent-envs.py +300 -0
- package/scripts/probe-client-events.py +183 -0
- package/scripts/project_setup.py +379 -0
- package/scripts/refresh-otgw-corpus.py +219 -0
- package/scripts/settings.py +81 -0
- package/scripts/setup-project.py +205 -0
- package/scripts/sync-agent-plugins.py +17 -0
- package/scripts/version_sites.py +377 -0
- package/skills/adr/SKILL.md +780 -0
- package/skills/audit/SKILL.md +103 -0
- package/skills/context/SKILL.md +77 -0
- package/skills/grill/SKILL.md +84 -0
- package/skills/grill/agents/openai.yaml +4 -0
- package/skills/guardian/SKILL.md +316 -0
- package/skills/init/SKILL.md +499 -0
- package/skills/install-hooks/SKILL.md +154 -0
- package/skills/judge/SKILL.md +168 -0
- package/skills/lint/SKILL.md +321 -0
- package/skills/migrate/SKILL.md +313 -0
- package/skills/related/SKILL.md +62 -0
- package/skills/retire/SKILL.md +41 -0
- package/skills/review/SKILL.md +167 -0
- package/skills/settings/SKILL.md +73 -0
- package/skills/setup/SKILL.md +128 -0
- package/skills/supersede/SKILL.md +136 -0
- package/skills/upgrade/SKILL.md +273 -0
- package/templates/adr-kit-guide.md +354 -0
- package/templates/adr-template.canonical.md +115 -0
- package/templates/adr-template.madr.md +131 -0
- package/templates/adr-template.md +131 -0
- package/templates/adr-template.nygard.md +111 -0
- package/templates/cc-settings/guardian-hook-entry.json +9 -0
- package/templates/githooks/pre-commit +337 -0
- package/templates/github-workflows/adr-audit.yml +58 -0
- package/templates/github-workflows/adr-guardian-audit.yml +133 -0
- package/templates/github-workflows/adr-index-check.yml +30 -0
- package/templates/github-workflows/adr-judge.yml +31 -0
- package/templates/github-workflows/adr-readiness.yml +18 -0
- package/templates/validate_adr_template.py +38 -0
- package/templates/validate_adr_template.sh +74 -0
package/bin/adr-mcp
ADDED
|
@@ -0,0 +1,1093 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""adr-mcp: thin Model Context Protocol server wrapping the adr-kit CLIs.
|
|
3
|
+
|
|
4
|
+
Speaks MCP over stdio: newline-delimited JSON-RPC 2.0 messages on
|
|
5
|
+
stdin/stdout (MCP stdio transport does NOT use Content-Length framing).
|
|
6
|
+
Hand-rolled on the Python stdlib only, so no `mcp` package is required.
|
|
7
|
+
|
|
8
|
+
The protocol surface is deliberately tiny (server/discover, initialize,
|
|
9
|
+
initialized, tools/list, tools/call, ping); the dispatch table in serve() is
|
|
10
|
+
shaped so swapping in the official `mcp` SDK later is a local change.
|
|
11
|
+
|
|
12
|
+
Protocol era: this server is dual-era (ADR-016). MCP revision 2026-07-28
|
|
13
|
+
removed the initialize handshake in favour of stateless per-request
|
|
14
|
+
envelopes, so both surfaces are served from one process:
|
|
15
|
+
|
|
16
|
+
* handshake era (2024-11-05 .. 2025-11-25) - reached through `initialize`,
|
|
17
|
+
which confirms a declared version or counter-offers the newest one.
|
|
18
|
+
* modern era (2026-07-28) - reached through `server/discover` or through
|
|
19
|
+
the reserved `io.modelcontextprotocol/protocolVersion` key in
|
|
20
|
+
`params._meta`. Modern results carry `resultType`, `_meta.serverInfo`
|
|
21
|
+
and, on `server/discover` and `tools/list`, `ttlMs` / `cacheScope`.
|
|
22
|
+
|
|
23
|
+
The era is a PURE FUNCTION of the single frame being answered: no
|
|
24
|
+
per-process and no per-connection era state, so the same bytes always get
|
|
25
|
+
the same answer. That is deliberate - the spec forbids relying on prior
|
|
26
|
+
requests over the same connection to establish context. See ADR-016 and
|
|
27
|
+
docs/research/2026-07-29-mcp-2026-07-28-revision.md.
|
|
28
|
+
|
|
29
|
+
Exposes exactly 5 tools, each a subprocess call into a sibling bin/ script:
|
|
30
|
+
|
|
31
|
+
adr_context {query, limit?, paths?, components?, symbols?, topics?,
|
|
32
|
+
statuses?, authorities?, include_history?, strict_index?}
|
|
33
|
+
-> bin/adr-context --format json
|
|
34
|
+
adr_judge {diff} -> bin/adr-judge --json (declarative pass
|
|
35
|
+
only, never --llm: key-free by design)
|
|
36
|
+
adr_status {} -> bin/adr-status --format json
|
|
37
|
+
adr_quality {adr_id?} -> bin/adr-quality --format json per ADR
|
|
38
|
+
adr_readiness {adr_id?, all_proposed?, base?, head?, today?}
|
|
39
|
+
-> bin/adr-readiness --format json
|
|
40
|
+
|
|
41
|
+
adr-suggest is intentionally NOT exposed: it is an LLM-only advisory (its
|
|
42
|
+
deterministic part is just a docs-only skip filter), and this server stays
|
|
43
|
+
key-free. Thin beats feature count; see docs/research/2026-06-12-adr-landscape.md.
|
|
44
|
+
|
|
45
|
+
Usage:
|
|
46
|
+
adr-mcp [--root DIR] [--adr-dir DIR]
|
|
47
|
+
|
|
48
|
+
Project root resolution: --root flag > PROJECT_ROOT env > current directory.
|
|
49
|
+
ADR directory defaults to <root>/docs/adr.
|
|
50
|
+
|
|
51
|
+
Every tool also accepts optional ``project_root`` and ``adr_dir`` arguments.
|
|
52
|
+
They let plugin clients select the active workspace per call even when the
|
|
53
|
+
MCP process itself starts inside an installed plugin cache.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
from __future__ import annotations
|
|
57
|
+
|
|
58
|
+
import argparse
|
|
59
|
+
import json
|
|
60
|
+
import os
|
|
61
|
+
import re
|
|
62
|
+
import subprocess
|
|
63
|
+
import sys
|
|
64
|
+
from pathlib import Path
|
|
65
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
66
|
+
|
|
67
|
+
BIN_DIR = Path(__file__).resolve().parent
|
|
68
|
+
REPO_ROOT = BIN_DIR.parent
|
|
69
|
+
|
|
70
|
+
# ---------------------------------------------------------------------------
|
|
71
|
+
# Protocol version registry (ADR-016)
|
|
72
|
+
# ---------------------------------------------------------------------------
|
|
73
|
+
#
|
|
74
|
+
# Versions are an ENUMERATED SET, never a sortable scalar. Membership is a
|
|
75
|
+
# tuple lookup; an unrecognised peer string is never ordered against a known
|
|
76
|
+
# one, because date-shaped strings only happen to sort lexicographically
|
|
77
|
+
# ("zzz" > "2025-11-25" is True) and future identifiers may not be dates.
|
|
78
|
+
|
|
79
|
+
# Reachable through the `initialize` handshake. One stateless code path
|
|
80
|
+
# serves all four: the tools-only subset (initialize / tools/list /
|
|
81
|
+
# tools/call / ping) is identical across them, so nothing has to remember
|
|
82
|
+
# which revision was negotiated.
|
|
83
|
+
HANDSHAKE_PROTOCOL_VERSIONS = ("2024-11-05", "2025-03-26", "2025-06-18", "2025-11-25")
|
|
84
|
+
|
|
85
|
+
# The stateless per-request envelope era.
|
|
86
|
+
MODERN_PROTOCOL_VERSIONS = ("2026-07-28",)
|
|
87
|
+
|
|
88
|
+
# Every version this server implements, oldest first.
|
|
89
|
+
KNOWN_PROTOCOL_VERSIONS = HANDSHAKE_PROTOCOL_VERSIONS + MODERN_PROTOCOL_VERSIONS
|
|
90
|
+
|
|
91
|
+
# Counter-offered when an `initialize` names a version outside the handshake
|
|
92
|
+
# set, or names none. The handshake revisions mandate a counter-offer, never
|
|
93
|
+
# an error, so -32022 must never reach an `initialize` response.
|
|
94
|
+
HANDSHAKE_COUNTER_OFFER = HANDSHAKE_PROTOCOL_VERSIONS[-1]
|
|
95
|
+
|
|
96
|
+
# Reserved `_meta` keys, spelled exactly as the specification does. The
|
|
97
|
+
# `io.modelcontextprotocol/` prefix is spec-reserved, so legacy traffic
|
|
98
|
+
# cannot mint these.
|
|
99
|
+
PROTOCOL_VERSION_META_KEY = "io.modelcontextprotocol/protocolVersion"
|
|
100
|
+
CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities"
|
|
101
|
+
CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo"
|
|
102
|
+
SERVER_INFO_META_KEY = "io.modelcontextprotocol/serverInfo"
|
|
103
|
+
LOG_LEVEL_META_KEY = "io.modelcontextprotocol/logLevel"
|
|
104
|
+
|
|
105
|
+
# Cache hints for modern `server/discover` and `tools/list` results only.
|
|
106
|
+
# `tools/call` is not a cacheable operation. "public" because the tool list
|
|
107
|
+
# is identical for every caller and carries no user-specific data. An int is
|
|
108
|
+
# emitted deliberately: schema.ts says `ttlMs: number` (@minimum 0) while the
|
|
109
|
+
# generated schema.json says "type": "integer"; an int satisfies both.
|
|
110
|
+
MODERN_CACHE_TTL_MS = 300000
|
|
111
|
+
MODERN_CACHE_SCOPE = "public"
|
|
112
|
+
|
|
113
|
+
MODERN_INSTRUCTIONS = (
|
|
114
|
+
"adr-kit: read-only Architecture Decision Record tooling. Call tools/list "
|
|
115
|
+
"for the five deterministic, key-free tools (adr_context, adr_judge, "
|
|
116
|
+
"adr_status, adr_quality, adr_readiness). Every tool accepts optional "
|
|
117
|
+
"project_root and adr_dir arguments to select the active workspace."
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
# Per-tool subprocess timeout. The wrapped CLIs are regex-only and fast;
|
|
121
|
+
# this only guards against pathological inputs.
|
|
122
|
+
CLI_TIMEOUT_S = 60
|
|
123
|
+
|
|
124
|
+
_ADR_ID_RE = re.compile(r"ADR-0*(\d{1,4})", re.IGNORECASE)
|
|
125
|
+
|
|
126
|
+
WORKSPACE_PROPERTIES: Dict[str, Dict[str, Any]] = {
|
|
127
|
+
"project_root": {
|
|
128
|
+
"type": "string",
|
|
129
|
+
"description": (
|
|
130
|
+
"Absolute path to the active project. Use this for plugin-provided "
|
|
131
|
+
"servers whose process starts in a plugin cache."
|
|
132
|
+
),
|
|
133
|
+
},
|
|
134
|
+
"adr_dir": {
|
|
135
|
+
"type": "string",
|
|
136
|
+
"description": (
|
|
137
|
+
"Optional ADR directory. Relative paths are resolved from project_root."
|
|
138
|
+
),
|
|
139
|
+
},
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# ---------------------------------------------------------------------------
|
|
144
|
+
# Server metadata
|
|
145
|
+
# ---------------------------------------------------------------------------
|
|
146
|
+
|
|
147
|
+
def server_version() -> str:
|
|
148
|
+
"""Read the version from the native manifest in any client distribution."""
|
|
149
|
+
manifests = (
|
|
150
|
+
REPO_ROOT / ".claude-plugin" / "plugin.json",
|
|
151
|
+
REPO_ROOT / ".codex-plugin" / "plugin.json",
|
|
152
|
+
REPO_ROOT / "plugin.json",
|
|
153
|
+
)
|
|
154
|
+
for manifest in manifests:
|
|
155
|
+
try:
|
|
156
|
+
data = json.loads(manifest.read_text(encoding="utf-8"))
|
|
157
|
+
version = data.get("version")
|
|
158
|
+
if isinstance(version, str) and version:
|
|
159
|
+
return version
|
|
160
|
+
except (OSError, ValueError):
|
|
161
|
+
continue
|
|
162
|
+
return "0.0.0"
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
# ---------------------------------------------------------------------------
|
|
166
|
+
# Tool definitions (MCP tools/list shape)
|
|
167
|
+
# ---------------------------------------------------------------------------
|
|
168
|
+
|
|
169
|
+
TOOL_DEFINITIONS: List[Dict[str, Any]] = [
|
|
170
|
+
{
|
|
171
|
+
"name": "adr_context",
|
|
172
|
+
"description": (
|
|
173
|
+
"Find the Architecture Decision Records most relevant to a task "
|
|
174
|
+
"through the local generated index. Deterministic, key-free, and "
|
|
175
|
+
"read-only; returns authority-labelled explained matches as JSON. "
|
|
176
|
+
f"The bounded subprocess timeout is {CLI_TIMEOUT_S} seconds."
|
|
177
|
+
),
|
|
178
|
+
"inputSchema": {
|
|
179
|
+
"type": "object",
|
|
180
|
+
"properties": {
|
|
181
|
+
"query": {
|
|
182
|
+
"type": "string",
|
|
183
|
+
"description": "Task description or question to rank ADRs against.",
|
|
184
|
+
},
|
|
185
|
+
"limit": {
|
|
186
|
+
"type": "integer",
|
|
187
|
+
"description": "Maximum number of ADRs to return.",
|
|
188
|
+
"minimum": 1,
|
|
189
|
+
"maximum": 100,
|
|
190
|
+
},
|
|
191
|
+
"paths": {
|
|
192
|
+
"type": "array",
|
|
193
|
+
"items": {"type": "string", "minLength": 1, "maxLength": 240},
|
|
194
|
+
"maxItems": 32,
|
|
195
|
+
"description": "Target or changed paths used for Enforcement scope matching.",
|
|
196
|
+
},
|
|
197
|
+
"components": {
|
|
198
|
+
"type": "array",
|
|
199
|
+
"items": {"type": "string", "minLength": 1, "maxLength": 240},
|
|
200
|
+
"maxItems": 32,
|
|
201
|
+
},
|
|
202
|
+
"symbols": {
|
|
203
|
+
"type": "array",
|
|
204
|
+
"items": {"type": "string", "minLength": 1, "maxLength": 240},
|
|
205
|
+
"maxItems": 32,
|
|
206
|
+
},
|
|
207
|
+
"topics": {
|
|
208
|
+
"type": "array",
|
|
209
|
+
"items": {"type": "string", "minLength": 1, "maxLength": 240},
|
|
210
|
+
"maxItems": 32,
|
|
211
|
+
},
|
|
212
|
+
"statuses": {
|
|
213
|
+
"type": "array",
|
|
214
|
+
"items": {
|
|
215
|
+
"type": "string",
|
|
216
|
+
"enum": [
|
|
217
|
+
"Accepted", "Proposed", "Superseded", "Rejected",
|
|
218
|
+
"Deprecated", "Amended", "Unknown"
|
|
219
|
+
],
|
|
220
|
+
},
|
|
221
|
+
"uniqueItems": True,
|
|
222
|
+
"maxItems": 7,
|
|
223
|
+
"description": "Optional lifecycle-status filter.",
|
|
224
|
+
},
|
|
225
|
+
"authorities": {
|
|
226
|
+
"type": "array",
|
|
227
|
+
"items": {
|
|
228
|
+
"type": "string",
|
|
229
|
+
"enum": ["governing", "advisory", "historical"],
|
|
230
|
+
},
|
|
231
|
+
"uniqueItems": True,
|
|
232
|
+
"maxItems": 3,
|
|
233
|
+
"description": "Optional authority filter.",
|
|
234
|
+
},
|
|
235
|
+
"include_history": {
|
|
236
|
+
"type": "boolean",
|
|
237
|
+
"description": "Permit historical ADRs; false by default.",
|
|
238
|
+
},
|
|
239
|
+
"strict_index": {
|
|
240
|
+
"type": "boolean",
|
|
241
|
+
"description": "Fail instead of using Markdown fallback.",
|
|
242
|
+
},
|
|
243
|
+
"min_score": {
|
|
244
|
+
"type": "number",
|
|
245
|
+
"minimum": 0,
|
|
246
|
+
"maximum": 1,
|
|
247
|
+
},
|
|
248
|
+
**WORKSPACE_PROPERTIES,
|
|
249
|
+
},
|
|
250
|
+
"required": ["query"],
|
|
251
|
+
},
|
|
252
|
+
},
|
|
253
|
+
{
|
|
254
|
+
"name": "adr_judge",
|
|
255
|
+
"description": (
|
|
256
|
+
"Judge a unified diff against the Enforcement blocks of Accepted "
|
|
257
|
+
"ADRs (declarative pass only, no LLM, key-free). Returns findings "
|
|
258
|
+
"and the adr-judge exit status (0 = clean, 1 = violations)."
|
|
259
|
+
),
|
|
260
|
+
"inputSchema": {
|
|
261
|
+
"type": "object",
|
|
262
|
+
"properties": {
|
|
263
|
+
"diff": {
|
|
264
|
+
"type": "string",
|
|
265
|
+
"description": "Unified diff text (e.g. output of git diff --cached).",
|
|
266
|
+
},
|
|
267
|
+
**WORKSPACE_PROPERTIES,
|
|
268
|
+
},
|
|
269
|
+
"required": ["diff"],
|
|
270
|
+
},
|
|
271
|
+
},
|
|
272
|
+
{
|
|
273
|
+
"name": "adr_status",
|
|
274
|
+
"description": (
|
|
275
|
+
"ADR repository health dashboard: totals, status breakdown, "
|
|
276
|
+
"enforcement health, retirement candidates. Returns JSON."
|
|
277
|
+
),
|
|
278
|
+
"inputSchema": {
|
|
279
|
+
"type": "object",
|
|
280
|
+
"properties": {**WORKSPACE_PROPERTIES},
|
|
281
|
+
},
|
|
282
|
+
},
|
|
283
|
+
{
|
|
284
|
+
"name": "adr_quality",
|
|
285
|
+
"description": (
|
|
286
|
+
"Score ADRs on quality via 4 gates (0.0-1.0 each, grade A-D). "
|
|
287
|
+
"Pass adr_id (e.g. 'ADR-001' or '1') for one ADR; omit it to "
|
|
288
|
+
"score every ADR in the repository. Returns JSON."
|
|
289
|
+
),
|
|
290
|
+
"inputSchema": {
|
|
291
|
+
"type": "object",
|
|
292
|
+
"properties": {
|
|
293
|
+
"adr_id": {
|
|
294
|
+
"type": "string",
|
|
295
|
+
"description": "ADR identifier such as 'ADR-001', '001' or '1'. Omit to score all ADRs.",
|
|
296
|
+
},
|
|
297
|
+
**WORKSPACE_PROPERTIES,
|
|
298
|
+
},
|
|
299
|
+
},
|
|
300
|
+
},
|
|
301
|
+
{
|
|
302
|
+
"name": "adr_readiness",
|
|
303
|
+
"description": (
|
|
304
|
+
"Inspect ADR lifecycle readiness and explicit implementation links. "
|
|
305
|
+
"Read-only, deterministic, key-free, and incapable of accepting ADRs."
|
|
306
|
+
),
|
|
307
|
+
"inputSchema": {
|
|
308
|
+
"type": "object",
|
|
309
|
+
"properties": {
|
|
310
|
+
"adr_id": {
|
|
311
|
+
"type": "string",
|
|
312
|
+
"description": "Optional ADR identifier such as ADR-011.",
|
|
313
|
+
},
|
|
314
|
+
"all_proposed": {
|
|
315
|
+
"type": "boolean",
|
|
316
|
+
"description": "Return every Proposed ADR.",
|
|
317
|
+
},
|
|
318
|
+
"base": {
|
|
319
|
+
"type": "string",
|
|
320
|
+
"description": "Optional git base ref; requires head.",
|
|
321
|
+
},
|
|
322
|
+
"head": {
|
|
323
|
+
"type": "string",
|
|
324
|
+
"description": "Optional git head ref; requires base.",
|
|
325
|
+
},
|
|
326
|
+
"today": {
|
|
327
|
+
"type": "string",
|
|
328
|
+
"description": "Optional deterministic YYYY-MM-DD evaluation date.",
|
|
329
|
+
},
|
|
330
|
+
**WORKSPACE_PROPERTIES,
|
|
331
|
+
},
|
|
332
|
+
},
|
|
333
|
+
},
|
|
334
|
+
]
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
# ---------------------------------------------------------------------------
|
|
338
|
+
# CLI subprocess plumbing
|
|
339
|
+
# ---------------------------------------------------------------------------
|
|
340
|
+
|
|
341
|
+
def run_cli(
|
|
342
|
+
script: str,
|
|
343
|
+
args: List[str],
|
|
344
|
+
root: Path,
|
|
345
|
+
stdin_text: Optional[str] = None,
|
|
346
|
+
env_extra: Optional[Dict[str, str]] = None,
|
|
347
|
+
) -> Tuple[int, str, str]:
|
|
348
|
+
"""Run a sibling bin/ script via the current interpreter.
|
|
349
|
+
|
|
350
|
+
Returns (exit_code, stdout, stderr). Raises subprocess.TimeoutExpired
|
|
351
|
+
on timeout; callers convert that into a tool error.
|
|
352
|
+
"""
|
|
353
|
+
cmd = [sys.executable, str(BIN_DIR / script)] + args
|
|
354
|
+
env = dict(os.environ)
|
|
355
|
+
if env_extra:
|
|
356
|
+
env.update(env_extra)
|
|
357
|
+
# Make the child WRITE utf-8, since we decode it as utf-8 just below.
|
|
358
|
+
#
|
|
359
|
+
# Honest scope (measured, TASK-69): every CLI wrapped here emits JSON with
|
|
360
|
+
# ensure_ascii=True, so their *stdout* is pure ASCII today and this line
|
|
361
|
+
# changes nothing on that path -- an A/B with it disabled produced
|
|
362
|
+
# byte-identical output. It is kept for the two places that are not
|
|
363
|
+
# ASCII-safe by construction: the child's *stderr*, which carries free-form
|
|
364
|
+
# warning text that can quote a non-ASCII path, and any future CLI that
|
|
365
|
+
# dumps with ensure_ascii=False. Without it those decode through
|
|
366
|
+
# errors="replace" and become U+FFFD.
|
|
367
|
+
#
|
|
368
|
+
# It is NOT what fixed the corruption this task was filed for; that was
|
|
369
|
+
# _pin_stdio_to_utf8 on our own stdout. Set after env_extra so a caller
|
|
370
|
+
# cannot unset it by accident.
|
|
371
|
+
env["PYTHONIOENCODING"] = "utf-8"
|
|
372
|
+
proc = subprocess.run(
|
|
373
|
+
cmd,
|
|
374
|
+
input=stdin_text,
|
|
375
|
+
capture_output=True,
|
|
376
|
+
text=True,
|
|
377
|
+
encoding="utf-8",
|
|
378
|
+
errors="replace",
|
|
379
|
+
cwd=str(root),
|
|
380
|
+
env=env,
|
|
381
|
+
timeout=CLI_TIMEOUT_S,
|
|
382
|
+
)
|
|
383
|
+
return proc.returncode, proc.stdout, proc.stderr
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _parse_json_or_raw(text: str) -> Any:
|
|
387
|
+
try:
|
|
388
|
+
return json.loads(text)
|
|
389
|
+
except ValueError:
|
|
390
|
+
return text
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _text_result(payload: Any, is_error: bool = False) -> Dict[str, Any]:
|
|
394
|
+
"""Wrap a payload as an MCP tools/call result: one text content item."""
|
|
395
|
+
if isinstance(payload, str):
|
|
396
|
+
text = payload
|
|
397
|
+
else:
|
|
398
|
+
text = json.dumps(payload, indent=2, ensure_ascii=False)
|
|
399
|
+
result: Dict[str, Any] = {"content": [{"type": "text", "text": text}]}
|
|
400
|
+
if is_error:
|
|
401
|
+
result["isError"] = True
|
|
402
|
+
return result
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _call_paths(
|
|
406
|
+
arguments: Dict[str, Any],
|
|
407
|
+
default_root: Path,
|
|
408
|
+
default_adr_dir: Path,
|
|
409
|
+
) -> Tuple[Path, Path]:
|
|
410
|
+
"""Resolve optional per-call workspace paths without changing server state."""
|
|
411
|
+
raw_root = arguments.get("project_root")
|
|
412
|
+
if raw_root is not None and (not isinstance(raw_root, str) or not raw_root.strip()):
|
|
413
|
+
raise ValueError("'project_root' must be a non-empty string")
|
|
414
|
+
if raw_root and not Path(raw_root).expanduser().is_absolute():
|
|
415
|
+
raise ValueError("'project_root' must be an absolute path")
|
|
416
|
+
root = Path(raw_root).expanduser().resolve() if raw_root else default_root
|
|
417
|
+
if not root.is_dir():
|
|
418
|
+
raise ValueError(f"project root not found: {root}")
|
|
419
|
+
|
|
420
|
+
raw_adr_dir = arguments.get("adr_dir")
|
|
421
|
+
if raw_adr_dir is not None and (
|
|
422
|
+
not isinstance(raw_adr_dir, str) or not raw_adr_dir.strip()
|
|
423
|
+
):
|
|
424
|
+
raise ValueError("'adr_dir' must be a non-empty string")
|
|
425
|
+
if raw_adr_dir:
|
|
426
|
+
candidate = Path(raw_adr_dir).expanduser()
|
|
427
|
+
adr_dir = (candidate if candidate.is_absolute() else root / candidate).resolve()
|
|
428
|
+
elif raw_root:
|
|
429
|
+
adr_dir = root / "docs" / "adr"
|
|
430
|
+
else:
|
|
431
|
+
adr_dir = default_adr_dir
|
|
432
|
+
try:
|
|
433
|
+
adr_dir.relative_to(root)
|
|
434
|
+
except ValueError as exc:
|
|
435
|
+
raise ValueError(f"ADR directory must stay within project root: {adr_dir}") from exc
|
|
436
|
+
return root, adr_dir
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
# ---------------------------------------------------------------------------
|
|
440
|
+
# Tool handlers
|
|
441
|
+
# ---------------------------------------------------------------------------
|
|
442
|
+
|
|
443
|
+
def tool_adr_context(arguments: Dict[str, Any], root: Path, adr_dir: Path) -> Dict[str, Any]:
|
|
444
|
+
try:
|
|
445
|
+
root, adr_dir = _call_paths(arguments, root, adr_dir)
|
|
446
|
+
except ValueError as exc:
|
|
447
|
+
return _text_result(f"adr_context: {exc}", is_error=True)
|
|
448
|
+
query = arguments.get("query")
|
|
449
|
+
if not isinstance(query, str) or not query.strip():
|
|
450
|
+
return _text_result("adr_context: 'query' must be a non-empty string", is_error=True)
|
|
451
|
+
args = ["--format", "json", "--adr-dir", str(adr_dir)]
|
|
452
|
+
limit = arguments.get("limit")
|
|
453
|
+
if limit is not None:
|
|
454
|
+
if (
|
|
455
|
+
not isinstance(limit, int)
|
|
456
|
+
or isinstance(limit, bool)
|
|
457
|
+
or not 1 <= limit <= 100
|
|
458
|
+
):
|
|
459
|
+
return _text_result(
|
|
460
|
+
"adr_context: 'limit' must be an integer between 1 and 100",
|
|
461
|
+
is_error=True,
|
|
462
|
+
)
|
|
463
|
+
args += ["--limit", str(limit)]
|
|
464
|
+
list_options = {
|
|
465
|
+
"paths": "--path",
|
|
466
|
+
"components": "--component",
|
|
467
|
+
"symbols": "--symbol",
|
|
468
|
+
"topics": "--topic",
|
|
469
|
+
"statuses": "--status",
|
|
470
|
+
"authorities": "--authority",
|
|
471
|
+
}
|
|
472
|
+
allowed_values = {
|
|
473
|
+
"statuses": {
|
|
474
|
+
"Accepted", "Proposed", "Superseded", "Rejected",
|
|
475
|
+
"Deprecated", "Amended", "Unknown",
|
|
476
|
+
},
|
|
477
|
+
"authorities": {"governing", "advisory", "historical"},
|
|
478
|
+
}
|
|
479
|
+
for field, option in list_options.items():
|
|
480
|
+
values = arguments.get(field, [])
|
|
481
|
+
if (
|
|
482
|
+
not isinstance(values, list)
|
|
483
|
+
or len(values) > 32
|
|
484
|
+
or any(
|
|
485
|
+
not isinstance(value, str)
|
|
486
|
+
or not value.strip()
|
|
487
|
+
or len(value) > 240
|
|
488
|
+
for value in values
|
|
489
|
+
)
|
|
490
|
+
):
|
|
491
|
+
return _text_result(
|
|
492
|
+
f"adr_context: '{field}' must be an array of at most 32 "
|
|
493
|
+
"non-empty strings",
|
|
494
|
+
is_error=True,
|
|
495
|
+
)
|
|
496
|
+
if field in allowed_values and any(
|
|
497
|
+
value not in allowed_values[field] for value in values
|
|
498
|
+
):
|
|
499
|
+
return _text_result(
|
|
500
|
+
f"adr_context: '{field}' contains an unsupported value",
|
|
501
|
+
is_error=True,
|
|
502
|
+
)
|
|
503
|
+
for value in values:
|
|
504
|
+
args += [option, value]
|
|
505
|
+
for field, option in (
|
|
506
|
+
("include_history", "--include-history"),
|
|
507
|
+
("strict_index", "--strict-index"),
|
|
508
|
+
):
|
|
509
|
+
value = arguments.get(field, False)
|
|
510
|
+
if not isinstance(value, bool):
|
|
511
|
+
return _text_result(
|
|
512
|
+
f"adr_context: '{field}' must be a boolean",
|
|
513
|
+
is_error=True,
|
|
514
|
+
)
|
|
515
|
+
if value:
|
|
516
|
+
args.append(option)
|
|
517
|
+
min_score = arguments.get("min_score")
|
|
518
|
+
if min_score is not None:
|
|
519
|
+
if (
|
|
520
|
+
not isinstance(min_score, (int, float))
|
|
521
|
+
or isinstance(min_score, bool)
|
|
522
|
+
or not 0 <= float(min_score) <= 1
|
|
523
|
+
):
|
|
524
|
+
return _text_result(
|
|
525
|
+
"adr_context: 'min_score' must be a number between 0 and 1",
|
|
526
|
+
is_error=True,
|
|
527
|
+
)
|
|
528
|
+
args += ["--min-score", str(min_score)]
|
|
529
|
+
args.append(query)
|
|
530
|
+
rc, out, err = run_cli("adr-context", args, root)
|
|
531
|
+
if rc != 0:
|
|
532
|
+
return _text_result(f"adr-context exited {rc}: {err.strip() or out.strip()}", is_error=True)
|
|
533
|
+
return _text_result(_parse_json_or_raw(out))
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def tool_adr_judge(arguments: Dict[str, Any], root: Path, adr_dir: Path) -> Dict[str, Any]:
|
|
537
|
+
try:
|
|
538
|
+
root, adr_dir = _call_paths(arguments, root, adr_dir)
|
|
539
|
+
except ValueError as exc:
|
|
540
|
+
return _text_result(f"adr_judge: {exc}", is_error=True)
|
|
541
|
+
diff = arguments.get("diff")
|
|
542
|
+
if not isinstance(diff, str) or not diff.strip():
|
|
543
|
+
return _text_result("adr_judge: 'diff' must be a non-empty string", is_error=True)
|
|
544
|
+
args = [
|
|
545
|
+
"--diff", "-",
|
|
546
|
+
"--adr-dir", str(adr_dir),
|
|
547
|
+
"--repo-root", str(root),
|
|
548
|
+
"--snapshot", "worktree", # TASK-65: the caller has a worktree; "diff" cannot see a modified file's post-image.
|
|
549
|
+
"--json",
|
|
550
|
+
]
|
|
551
|
+
# Never run the LLM pass from the MCP server: key-free by design.
|
|
552
|
+
# --llm is simply not passed; ADR_KIT_NO_LLM=1 is belt and braces.
|
|
553
|
+
rc, out, err = run_cli(
|
|
554
|
+
"adr-judge", args, root, stdin_text=diff, env_extra={"ADR_KIT_NO_LLM": "1"},
|
|
555
|
+
)
|
|
556
|
+
if rc == 2:
|
|
557
|
+
return _text_result(f"adr-judge exited 2 (config/input error): {err.strip()}", is_error=True)
|
|
558
|
+
# rc 0 (clean) and rc 1 (violations) are both valid judge outcomes.
|
|
559
|
+
payload = {"exit_code": rc, "verdict": "violation" if rc == 1 else "ok",
|
|
560
|
+
"result": _parse_json_or_raw(out)}
|
|
561
|
+
return _text_result(payload)
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def tool_adr_status(arguments: Dict[str, Any], root: Path, adr_dir: Path) -> Dict[str, Any]:
|
|
565
|
+
try:
|
|
566
|
+
root, adr_dir = _call_paths(arguments, root, adr_dir)
|
|
567
|
+
except ValueError as exc:
|
|
568
|
+
return _text_result(f"adr_status: {exc}", is_error=True)
|
|
569
|
+
rc, out, err = run_cli("adr-status", ["--format", "json", "--adr-dir", str(adr_dir)], root)
|
|
570
|
+
if rc != 0:
|
|
571
|
+
return _text_result(f"adr-status exited {rc}: {err.strip() or out.strip()}", is_error=True)
|
|
572
|
+
return _text_result(_parse_json_or_raw(out))
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def _resolve_adr_files(adr_dir: Path, adr_id: Optional[str]) -> List[Path]:
|
|
576
|
+
"""List ADR markdown files, optionally filtered to one numeric id."""
|
|
577
|
+
files = sorted(p for p in adr_dir.glob("ADR-*.md") if p.is_file())
|
|
578
|
+
if adr_id is None:
|
|
579
|
+
return files
|
|
580
|
+
match = _ADR_ID_RE.search(adr_id) or re.fullmatch(r"0*(\d{1,4})", adr_id.strip())
|
|
581
|
+
if not match:
|
|
582
|
+
return []
|
|
583
|
+
wanted = int(match.group(1))
|
|
584
|
+
selected = []
|
|
585
|
+
for path in files:
|
|
586
|
+
m = _ADR_ID_RE.search(path.name)
|
|
587
|
+
if m and int(m.group(1)) == wanted:
|
|
588
|
+
selected.append(path)
|
|
589
|
+
return selected
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def tool_adr_quality(arguments: Dict[str, Any], root: Path, adr_dir: Path) -> Dict[str, Any]:
|
|
593
|
+
try:
|
|
594
|
+
root, adr_dir = _call_paths(arguments, root, adr_dir)
|
|
595
|
+
except ValueError as exc:
|
|
596
|
+
return _text_result(f"adr_quality: {exc}", is_error=True)
|
|
597
|
+
adr_id = arguments.get("adr_id")
|
|
598
|
+
if adr_id is not None and not isinstance(adr_id, str):
|
|
599
|
+
return _text_result("adr_quality: 'adr_id' must be a string", is_error=True)
|
|
600
|
+
if not adr_dir.is_dir():
|
|
601
|
+
return _text_result(f"adr_quality: ADR directory not found: {adr_dir}", is_error=True)
|
|
602
|
+
files = _resolve_adr_files(adr_dir, adr_id)
|
|
603
|
+
if not files:
|
|
604
|
+
what = f"no ADR matching '{adr_id}'" if adr_id else "no ADR files"
|
|
605
|
+
return _text_result(f"adr_quality: {what} in {adr_dir}", is_error=True)
|
|
606
|
+
reports = []
|
|
607
|
+
for path in files:
|
|
608
|
+
rc, out, err = run_cli("adr-quality", ["--format", "json", str(path)], root)
|
|
609
|
+
if rc == 2:
|
|
610
|
+
reports.append({"file": path.name, "error": err.strip() or f"exit {rc}"})
|
|
611
|
+
else:
|
|
612
|
+
entry = _parse_json_or_raw(out)
|
|
613
|
+
if isinstance(entry, dict):
|
|
614
|
+
entry.setdefault("file", path.name)
|
|
615
|
+
reports.append(entry)
|
|
616
|
+
payload: Any = reports[0] if adr_id else {"adrs": reports}
|
|
617
|
+
return _text_result(payload)
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def tool_adr_readiness(
|
|
621
|
+
arguments: Dict[str, Any], root: Path, adr_dir: Path
|
|
622
|
+
) -> Dict[str, Any]:
|
|
623
|
+
try:
|
|
624
|
+
root, adr_dir = _call_paths(arguments, root, adr_dir)
|
|
625
|
+
except ValueError as exc:
|
|
626
|
+
return _text_result(f"adr_readiness: {exc}", is_error=True)
|
|
627
|
+
cli_args = [
|
|
628
|
+
"--format",
|
|
629
|
+
"json",
|
|
630
|
+
"--repo-root",
|
|
631
|
+
str(root),
|
|
632
|
+
"--adr-dir",
|
|
633
|
+
str(adr_dir),
|
|
634
|
+
]
|
|
635
|
+
adr_id = arguments.get("adr_id")
|
|
636
|
+
if adr_id is not None:
|
|
637
|
+
if not isinstance(adr_id, str) or not adr_id.strip():
|
|
638
|
+
return _text_result(
|
|
639
|
+
"adr_readiness: 'adr_id' must be a non-empty string",
|
|
640
|
+
is_error=True,
|
|
641
|
+
)
|
|
642
|
+
cli_args.append(adr_id)
|
|
643
|
+
if arguments.get("all_proposed") is True:
|
|
644
|
+
cli_args.append("--all-proposed")
|
|
645
|
+
elif arguments.get("all_proposed") not in {None, False}:
|
|
646
|
+
return _text_result(
|
|
647
|
+
"adr_readiness: 'all_proposed' must be a boolean",
|
|
648
|
+
is_error=True,
|
|
649
|
+
)
|
|
650
|
+
base = arguments.get("base")
|
|
651
|
+
head = arguments.get("head")
|
|
652
|
+
if (base is None) != (head is None):
|
|
653
|
+
return _text_result(
|
|
654
|
+
"adr_readiness: 'base' and 'head' must be supplied together",
|
|
655
|
+
is_error=True,
|
|
656
|
+
)
|
|
657
|
+
if base is not None:
|
|
658
|
+
if not all(isinstance(value, str) and value.strip() for value in (base, head)):
|
|
659
|
+
return _text_result(
|
|
660
|
+
"adr_readiness: 'base' and 'head' must be non-empty strings",
|
|
661
|
+
is_error=True,
|
|
662
|
+
)
|
|
663
|
+
cli_args.extend(["--base", base, "--head", head])
|
|
664
|
+
today = arguments.get("today")
|
|
665
|
+
if today is not None:
|
|
666
|
+
if not isinstance(today, str) or not today.strip():
|
|
667
|
+
return _text_result(
|
|
668
|
+
"adr_readiness: 'today' must be a non-empty string",
|
|
669
|
+
is_error=True,
|
|
670
|
+
)
|
|
671
|
+
cli_args.extend(["--today", today])
|
|
672
|
+
rc, out, err = run_cli("adr-readiness", cli_args, root)
|
|
673
|
+
if rc != 0:
|
|
674
|
+
return _text_result(
|
|
675
|
+
f"adr-readiness exited {rc}: {err.strip() or out.strip()}",
|
|
676
|
+
is_error=True,
|
|
677
|
+
)
|
|
678
|
+
return _text_result(_parse_json_or_raw(out))
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
TOOL_HANDLERS = {
|
|
682
|
+
"adr_context": tool_adr_context,
|
|
683
|
+
"adr_judge": tool_adr_judge,
|
|
684
|
+
"adr_status": tool_adr_status,
|
|
685
|
+
"adr_quality": tool_adr_quality,
|
|
686
|
+
"adr_readiness": tool_adr_readiness,
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
|
|
690
|
+
# ---------------------------------------------------------------------------
|
|
691
|
+
# JSON-RPC 2.0 plumbing (newline-delimited over stdio)
|
|
692
|
+
# ---------------------------------------------------------------------------
|
|
693
|
+
|
|
694
|
+
PARSE_ERROR = -32700
|
|
695
|
+
INVALID_REQUEST = -32600
|
|
696
|
+
METHOD_NOT_FOUND = -32601
|
|
697
|
+
INVALID_PARAMS = -32602
|
|
698
|
+
INTERNAL_ERROR = -32603
|
|
699
|
+
|
|
700
|
+
# Specification-reserved range (-32020..-32099). Only the one code this
|
|
701
|
+
# server can legitimately reach is defined here: -32020 (HeaderMismatch) is
|
|
702
|
+
# HTTP-only and unreachable on stdio, and -32021 (MissingRequiredClient-
|
|
703
|
+
# Capability) has no code path because the server never samples, elicits or
|
|
704
|
+
# asks for roots. Neither may be emitted (ADR-016).
|
|
705
|
+
UNSUPPORTED_PROTOCOL_VERSION = -32022
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
def _pin_stdio_to_utf8() -> None:
|
|
709
|
+
"""Force UTF-8, LF-terminated stdio regardless of the host's locale.
|
|
710
|
+
|
|
711
|
+
The MCP stdio transport mandates UTF-8 and newline-delimited framing. Python
|
|
712
|
+
opens std streams in text mode using the platform default, which on a cp1252
|
|
713
|
+
Windows host breaks both (TASK-69):
|
|
714
|
+
|
|
715
|
+
* ``bin/adr-status`` emits U+2014 in "Superseded - consider archiving"; it
|
|
716
|
+
left as the cp1252 byte 0x97, so the frame was not valid UTF-8. Strict
|
|
717
|
+
readers abort the session; lenient ones silently accept mojibake.
|
|
718
|
+
* U+2192 from ``adr-context`` has no cp1252 mapping at all, so
|
|
719
|
+
``_write_message`` raised ``UnicodeEncodeError``, which ``dispatch``'s
|
|
720
|
+
broad handler turned into JSON-RPC -32603. The tool result was lost.
|
|
721
|
+
* Text-mode writes translated the trailing "\\n" to "\\r\\n".
|
|
722
|
+
|
|
723
|
+
``newline=""`` disables that translation, so the "\\n" appended in
|
|
724
|
+
``_write_message`` reaches the wire as one byte. Reconfiguration happens
|
|
725
|
+
once in ``main`` before ``serve``; the ``hasattr`` guard covers a caller
|
|
726
|
+
that replaced a std stream with an object lacking ``reconfigure``.
|
|
727
|
+
"""
|
|
728
|
+
for stream, kwargs in (
|
|
729
|
+
(sys.stdin, {"encoding": "utf-8"}),
|
|
730
|
+
(sys.stdout, {"encoding": "utf-8", "newline": ""}),
|
|
731
|
+
# stderr carries diagnostics, not protocol. errors="replace" keeps an
|
|
732
|
+
# unmappable character in a log line from raising inside the server.
|
|
733
|
+
(sys.stderr, {"encoding": "utf-8", "errors": "replace"}),
|
|
734
|
+
):
|
|
735
|
+
if hasattr(stream, "reconfigure"):
|
|
736
|
+
try:
|
|
737
|
+
stream.reconfigure(**kwargs)
|
|
738
|
+
except (ValueError, OSError):
|
|
739
|
+
# A detached or non-seekable stream; the default encoding stays.
|
|
740
|
+
pass
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
def _write_message(payload: Dict[str, Any]) -> None:
|
|
744
|
+
sys.stdout.write(json.dumps(payload, ensure_ascii=False) + "\n")
|
|
745
|
+
sys.stdout.flush()
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
def _reply_result(req_id: Any, result: Dict[str, Any]) -> None:
|
|
749
|
+
_write_message({"jsonrpc": "2.0", "id": req_id, "result": result})
|
|
750
|
+
|
|
751
|
+
|
|
752
|
+
def _reply_error(
|
|
753
|
+
req_id: Any, code: int, message: str, data: Optional[Dict[str, Any]] = None
|
|
754
|
+
) -> None:
|
|
755
|
+
error: Dict[str, Any] = {"code": code, "message": message}
|
|
756
|
+
if data is not None:
|
|
757
|
+
error["data"] = data
|
|
758
|
+
_write_message({"jsonrpc": "2.0", "id": req_id, "error": error})
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
# ---------------------------------------------------------------------------
|
|
762
|
+
# Method handlers
|
|
763
|
+
# ---------------------------------------------------------------------------
|
|
764
|
+
|
|
765
|
+
def frame_is_modern(method: str, params: Dict[str, Any]) -> bool:
|
|
766
|
+
"""Classify one frame's protocol era. A PURE FUNCTION of that frame.
|
|
767
|
+
|
|
768
|
+
No per-process and no per-connection state is consulted or kept, so the
|
|
769
|
+
same bytes always get the same answer. Exactly two rules (ADR-016):
|
|
770
|
+
|
|
771
|
+
1. `server/discover`, or a `params._meta` carrying the reserved
|
|
772
|
+
`io.modelcontextprotocol/protocolVersion` key -> modern. The sentinel
|
|
773
|
+
is that one key, not the required pair: its prefix is spec-reserved so
|
|
774
|
+
a legacy client cannot mint it, while a bare `_meta` is no evidence at
|
|
775
|
+
all (legacy requests already put `progressToken` there). Checking only
|
|
776
|
+
the version key means a half-built envelope still routes modern and
|
|
777
|
+
gets a -32602 naming what is missing, instead of being misrouted to
|
|
778
|
+
legacy and failing confusingly.
|
|
779
|
+
2. Anything else -> legacy.
|
|
780
|
+
|
|
781
|
+
`initialize` is the one explicit exception to rule 1: it routes legacy
|
|
782
|
+
even when the modern envelope is stamped on it, because `initialize`
|
|
783
|
+
does not exist at 2026-07-28 at all, so an envelope on it is a client
|
|
784
|
+
defect rather than an era signal (TASK-58.1 AC #6).
|
|
785
|
+
|
|
786
|
+
There is deliberately NO era lock: locking would make a byte-identical
|
|
787
|
+
frame get two different answers depending on what arrived earlier on the
|
|
788
|
+
same stdin, which is what "Servers MUST NOT rely on prior requests over
|
|
789
|
+
the same connection to establish context" forbids.
|
|
790
|
+
"""
|
|
791
|
+
if method == "initialize":
|
|
792
|
+
return False
|
|
793
|
+
if method == "server/discover":
|
|
794
|
+
return True
|
|
795
|
+
meta = params.get("_meta")
|
|
796
|
+
return isinstance(meta, dict) and PROTOCOL_VERSION_META_KEY in meta
|
|
797
|
+
|
|
798
|
+
|
|
799
|
+
def modern_envelope_error(
|
|
800
|
+
params: Dict[str, Any]
|
|
801
|
+
) -> Optional[Tuple[int, str, Optional[Dict[str, Any]]]]:
|
|
802
|
+
"""Validate a modern-routed frame's envelope and negotiate its version.
|
|
803
|
+
|
|
804
|
+
Returns (code, message, data) for the first failure, or None when the
|
|
805
|
+
frame may be served. Routing signal and validation stay separate: a
|
|
806
|
+
frame routed modern on the sentinel alone is still rejected here when
|
|
807
|
+
the rest of the envelope is absent.
|
|
808
|
+
"""
|
|
809
|
+
meta = params.get("_meta")
|
|
810
|
+
if not isinstance(meta, dict):
|
|
811
|
+
meta = {}
|
|
812
|
+
missing = [
|
|
813
|
+
key
|
|
814
|
+
for key in (PROTOCOL_VERSION_META_KEY, CLIENT_CAPABILITIES_META_KEY)
|
|
815
|
+
if key not in meta
|
|
816
|
+
]
|
|
817
|
+
if missing:
|
|
818
|
+
return (
|
|
819
|
+
INVALID_PARAMS,
|
|
820
|
+
"Invalid params: modern request is missing required _meta key(s): "
|
|
821
|
+
+ ", ".join(missing),
|
|
822
|
+
None,
|
|
823
|
+
)
|
|
824
|
+
requested = meta[PROTOCOL_VERSION_META_KEY]
|
|
825
|
+
if not isinstance(requested, str):
|
|
826
|
+
# A shape defect, not a negotiation failure: -32022 is the one code
|
|
827
|
+
# auto-negotiating clients do not fall back from.
|
|
828
|
+
return (
|
|
829
|
+
INVALID_PARAMS,
|
|
830
|
+
f"Invalid params: '{PROTOCOL_VERSION_META_KEY}' must be a string",
|
|
831
|
+
None,
|
|
832
|
+
)
|
|
833
|
+
if requested not in MODERN_PROTOCOL_VERSIONS:
|
|
834
|
+
# Era-scoped: a modern answer lists modern versions only, because a
|
|
835
|
+
# handshake revision cannot be reached through a modern envelope.
|
|
836
|
+
return (
|
|
837
|
+
UNSUPPORTED_PROTOCOL_VERSION,
|
|
838
|
+
f"Unsupported protocol version: {requested!r}",
|
|
839
|
+
{"supported": list(MODERN_PROTOCOL_VERSIONS), "requested": requested},
|
|
840
|
+
)
|
|
841
|
+
return None
|
|
842
|
+
|
|
843
|
+
|
|
844
|
+
def _modern_result(
|
|
845
|
+
payload: Dict[str, Any], cacheable: bool = False
|
|
846
|
+
) -> Dict[str, Any]:
|
|
847
|
+
"""Stamp a modern-era result: resultType, cache hints, _meta.serverInfo.
|
|
848
|
+
|
|
849
|
+
`resultType` is always "complete": the five tools are fully parameterised
|
|
850
|
+
by their arguments, so the server never emits "input_required" and never
|
|
851
|
+
invents a value of its own. Cache hints are stamped on `server/discover`
|
|
852
|
+
and `tools/list` only - `CallToolResult` extends `Result`, not
|
|
853
|
+
`CacheableResult`.
|
|
854
|
+
"""
|
|
855
|
+
result: Dict[str, Any] = {"resultType": "complete"}
|
|
856
|
+
result.update(payload)
|
|
857
|
+
if cacheable:
|
|
858
|
+
result["ttlMs"] = MODERN_CACHE_TTL_MS
|
|
859
|
+
result["cacheScope"] = MODERN_CACHE_SCOPE
|
|
860
|
+
meta = dict(result.get("_meta") or {})
|
|
861
|
+
meta[SERVER_INFO_META_KEY] = {"name": "adr-kit", "version": server_version()}
|
|
862
|
+
result["_meta"] = meta
|
|
863
|
+
return result
|
|
864
|
+
|
|
865
|
+
|
|
866
|
+
def negotiate_handshake_version(requested: Any) -> str:
|
|
867
|
+
"""Confirm a declared handshake version, or counter-offer the newest.
|
|
868
|
+
|
|
869
|
+
Absent, unknown, or a modern-era value such as "2026-07-28" all get the
|
|
870
|
+
counter-offer. The handshake revisions mandate exactly this ("Otherwise,
|
|
871
|
+
the server MUST respond with another protocol version it supports"), so
|
|
872
|
+
-32022 is never emitted on the legacy surface. Nothing is ever reflected
|
|
873
|
+
back unvalidated.
|
|
874
|
+
"""
|
|
875
|
+
if isinstance(requested, str) and requested in HANDSHAKE_PROTOCOL_VERSIONS:
|
|
876
|
+
return requested
|
|
877
|
+
return HANDSHAKE_COUNTER_OFFER
|
|
878
|
+
|
|
879
|
+
|
|
880
|
+
def handle_initialize(params: Dict[str, Any]) -> Dict[str, Any]:
|
|
881
|
+
return {
|
|
882
|
+
"protocolVersion": negotiate_handshake_version(params.get("protocolVersion")),
|
|
883
|
+
"capabilities": {"tools": {}},
|
|
884
|
+
"serverInfo": {"name": "adr-kit", "version": server_version()},
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
|
|
888
|
+
def handle_server_discover(params: Dict[str, Any]) -> Dict[str, Any]:
|
|
889
|
+
"""The modern-era replacement for the handshake.
|
|
890
|
+
|
|
891
|
+
Returns the five required DiscoverResult fields plus the two optional
|
|
892
|
+
ones this server has something to say with. There is deliberately no
|
|
893
|
+
top-level `serverInfo` and no top-level `protocolVersion`: neither field
|
|
894
|
+
exists in DiscoverResult this revision, and identity travels in `_meta`.
|
|
895
|
+
`supportedVersions` lists the MODERN versions only - legacy reachability
|
|
896
|
+
is settled by the handshake, and advertising a handshake revision here
|
|
897
|
+
would invite a client to send it inside an envelope that does not exist.
|
|
898
|
+
"""
|
|
899
|
+
return _modern_result(
|
|
900
|
+
{
|
|
901
|
+
"supportedVersions": list(MODERN_PROTOCOL_VERSIONS),
|
|
902
|
+
"capabilities": {"tools": {}},
|
|
903
|
+
"instructions": MODERN_INSTRUCTIONS,
|
|
904
|
+
},
|
|
905
|
+
cacheable=True,
|
|
906
|
+
)
|
|
907
|
+
|
|
908
|
+
|
|
909
|
+
def handle_tools_list(params: Dict[str, Any]) -> Dict[str, Any]:
|
|
910
|
+
return {"tools": TOOL_DEFINITIONS}
|
|
911
|
+
|
|
912
|
+
|
|
913
|
+
def handle_tools_call(params: Dict[str, Any], root: Path, adr_dir: Path) -> Dict[str, Any]:
|
|
914
|
+
name = params.get("name")
|
|
915
|
+
handler = TOOL_HANDLERS.get(name)
|
|
916
|
+
if handler is None:
|
|
917
|
+
raise KeyError(name)
|
|
918
|
+
arguments = params.get("arguments") or {}
|
|
919
|
+
if not isinstance(arguments, dict):
|
|
920
|
+
return _text_result(f"{name}: 'arguments' must be an object", is_error=True)
|
|
921
|
+
try:
|
|
922
|
+
return handler(arguments, root, adr_dir)
|
|
923
|
+
except subprocess.TimeoutExpired:
|
|
924
|
+
return _text_result(f"{name}: underlying CLI timed out after {CLI_TIMEOUT_S}s", is_error=True)
|
|
925
|
+
except Exception as exc: # noqa: BLE001 - tool failure must not kill the loop
|
|
926
|
+
return _text_result(f"{name}: internal error: {exc}", is_error=True)
|
|
927
|
+
|
|
928
|
+
|
|
929
|
+
def dispatch(message: Dict[str, Any], root: Path, adr_dir: Path) -> None:
|
|
930
|
+
"""Handle one JSON-RPC message. Notifications get no reply."""
|
|
931
|
+
req_id = message.get("id")
|
|
932
|
+
is_notification = "id" not in message
|
|
933
|
+
method = message.get("method")
|
|
934
|
+
params = message.get("params") or {}
|
|
935
|
+
if not isinstance(params, dict):
|
|
936
|
+
params = {}
|
|
937
|
+
|
|
938
|
+
if not isinstance(method, str):
|
|
939
|
+
if not is_notification:
|
|
940
|
+
_reply_error(req_id, INVALID_REQUEST, "Invalid request: missing method")
|
|
941
|
+
return
|
|
942
|
+
|
|
943
|
+
if method.startswith("notifications/"):
|
|
944
|
+
# notifications/initialized, notifications/cancelled,
|
|
945
|
+
# notifications/progress, ...: accepted and ignored in both eras.
|
|
946
|
+
# The notification rules forbid a response, and the five tool
|
|
947
|
+
# handlers are synchronous subprocess calls that cannot be
|
|
948
|
+
# interrupted mid-flight, so nothing further is emitted either.
|
|
949
|
+
return
|
|
950
|
+
|
|
951
|
+
try:
|
|
952
|
+
if frame_is_modern(method, params):
|
|
953
|
+
_dispatch_modern(req_id, is_notification, method, params, root, adr_dir)
|
|
954
|
+
else:
|
|
955
|
+
_dispatch_legacy(req_id, is_notification, method, params, root, adr_dir)
|
|
956
|
+
except Exception as exc: # noqa: BLE001 - the loop must survive anything
|
|
957
|
+
if not is_notification:
|
|
958
|
+
_reply_error(req_id, INTERNAL_ERROR, f"Internal error: {exc}")
|
|
959
|
+
|
|
960
|
+
|
|
961
|
+
def _dispatch_legacy(
|
|
962
|
+
req_id: Any,
|
|
963
|
+
is_notification: bool,
|
|
964
|
+
method: str,
|
|
965
|
+
params: Dict[str, Any],
|
|
966
|
+
root: Path,
|
|
967
|
+
adr_dir: Path,
|
|
968
|
+
) -> None:
|
|
969
|
+
"""Handshake-era dispatch. Results keep exactly their historical shape.
|
|
970
|
+
|
|
971
|
+
No resultType, no _meta.serverInfo, no ttlMs and no cacheScope:
|
|
972
|
+
CacheableResult does not exist in the handshake revisions, so stamping
|
|
973
|
+
those fields here would invent wire fields the client's schema does not
|
|
974
|
+
define.
|
|
975
|
+
"""
|
|
976
|
+
if method == "initialize":
|
|
977
|
+
_reply_result(req_id, handle_initialize(params))
|
|
978
|
+
elif method == "ping":
|
|
979
|
+
_reply_result(req_id, {})
|
|
980
|
+
elif method == "tools/list":
|
|
981
|
+
_reply_result(req_id, handle_tools_list(params))
|
|
982
|
+
elif method == "tools/call":
|
|
983
|
+
try:
|
|
984
|
+
_reply_result(req_id, handle_tools_call(params, root, adr_dir))
|
|
985
|
+
except KeyError:
|
|
986
|
+
_reply_error(req_id, INVALID_PARAMS,
|
|
987
|
+
f"Unknown tool: {params.get('name')!r}")
|
|
988
|
+
else:
|
|
989
|
+
if not is_notification:
|
|
990
|
+
_reply_error(req_id, METHOD_NOT_FOUND, f"Method not found: {method}")
|
|
991
|
+
|
|
992
|
+
|
|
993
|
+
def _dispatch_modern(
|
|
994
|
+
req_id: Any,
|
|
995
|
+
is_notification: bool,
|
|
996
|
+
method: str,
|
|
997
|
+
params: Dict[str, Any],
|
|
998
|
+
root: Path,
|
|
999
|
+
adr_dir: Path,
|
|
1000
|
+
) -> None:
|
|
1001
|
+
"""Modern-era (2026-07-28) dispatch.
|
|
1002
|
+
|
|
1003
|
+
Envelope validation and version negotiation run first and take
|
|
1004
|
+
precedence over any result, including on `server/discover`: a probe
|
|
1005
|
+
without the required keys is malformed, and a probe naming an
|
|
1006
|
+
unsupported version gets -32022 whose `data.supported` carries exactly
|
|
1007
|
+
the list `supportedVersions` would have carried.
|
|
1008
|
+
"""
|
|
1009
|
+
failure = modern_envelope_error(params)
|
|
1010
|
+
if failure is not None:
|
|
1011
|
+
code, message, data = failure
|
|
1012
|
+
if not is_notification:
|
|
1013
|
+
_reply_error(req_id, code, message, data)
|
|
1014
|
+
return
|
|
1015
|
+
|
|
1016
|
+
if method == "server/discover":
|
|
1017
|
+
_reply_result(req_id, handle_server_discover(params))
|
|
1018
|
+
elif method == "tools/list":
|
|
1019
|
+
_reply_result(req_id, _modern_result(handle_tools_list(params), cacheable=True))
|
|
1020
|
+
elif method == "tools/call":
|
|
1021
|
+
try:
|
|
1022
|
+
_reply_result(
|
|
1023
|
+
req_id, _modern_result(handle_tools_call(params, root, adr_dir))
|
|
1024
|
+
)
|
|
1025
|
+
except KeyError:
|
|
1026
|
+
_reply_error(req_id, INVALID_PARAMS,
|
|
1027
|
+
f"Unknown tool: {params.get('name')!r}")
|
|
1028
|
+
else:
|
|
1029
|
+
# `ping` lands here: revision 2026-07-28 removed it, so it is not
|
|
1030
|
+
# advertised or served in this era. There is no result to stamp.
|
|
1031
|
+
if not is_notification:
|
|
1032
|
+
_reply_error(req_id, METHOD_NOT_FOUND, f"Method not found: {method}")
|
|
1033
|
+
|
|
1034
|
+
|
|
1035
|
+
def serve(root: Path, adr_dir: Path) -> int:
|
|
1036
|
+
"""Main loop: one JSON-RPC message per line on stdin until EOF."""
|
|
1037
|
+
for line in sys.stdin:
|
|
1038
|
+
line = line.strip()
|
|
1039
|
+
if not line:
|
|
1040
|
+
continue
|
|
1041
|
+
try:
|
|
1042
|
+
message = json.loads(line)
|
|
1043
|
+
except ValueError:
|
|
1044
|
+
_reply_error(None, PARSE_ERROR, "Parse error")
|
|
1045
|
+
continue
|
|
1046
|
+
if not isinstance(message, dict):
|
|
1047
|
+
_reply_error(None, INVALID_REQUEST, "Invalid request: expected object")
|
|
1048
|
+
continue
|
|
1049
|
+
dispatch(message, root, adr_dir)
|
|
1050
|
+
return 0
|
|
1051
|
+
|
|
1052
|
+
|
|
1053
|
+
# ---------------------------------------------------------------------------
|
|
1054
|
+
# Entry point
|
|
1055
|
+
# ---------------------------------------------------------------------------
|
|
1056
|
+
|
|
1057
|
+
def main() -> int:
|
|
1058
|
+
parser = argparse.ArgumentParser(
|
|
1059
|
+
prog="adr-mcp",
|
|
1060
|
+
description="Thin MCP stdio server wrapping the adr-kit CLIs.",
|
|
1061
|
+
)
|
|
1062
|
+
parser.add_argument(
|
|
1063
|
+
"--root",
|
|
1064
|
+
default=None,
|
|
1065
|
+
help="Project root the tools operate on. Default: PROJECT_ROOT env, "
|
|
1066
|
+
"then the current working directory.",
|
|
1067
|
+
)
|
|
1068
|
+
parser.add_argument(
|
|
1069
|
+
"--adr-dir",
|
|
1070
|
+
default=None,
|
|
1071
|
+
help="Directory containing ADR-*.md files. Default: <root>/docs/adr.",
|
|
1072
|
+
)
|
|
1073
|
+
args = parser.parse_args()
|
|
1074
|
+
|
|
1075
|
+
# Before anything writes a byte: the transport contract is UTF-8 + LF.
|
|
1076
|
+
_pin_stdio_to_utf8()
|
|
1077
|
+
|
|
1078
|
+
root = Path(args.root or os.environ.get("PROJECT_ROOT") or os.getcwd()).resolve()
|
|
1079
|
+
if not root.is_dir():
|
|
1080
|
+
print(f"adr-mcp: project root not found: {root}", file=sys.stderr)
|
|
1081
|
+
return 2
|
|
1082
|
+
adr_dir = Path(args.adr_dir).resolve() if args.adr_dir else root / "docs" / "adr"
|
|
1083
|
+
|
|
1084
|
+
print(f"adr-mcp {server_version()} serving root={root} adr_dir={adr_dir}",
|
|
1085
|
+
file=sys.stderr)
|
|
1086
|
+
try:
|
|
1087
|
+
return serve(root, adr_dir)
|
|
1088
|
+
except KeyboardInterrupt:
|
|
1089
|
+
return 0
|
|
1090
|
+
|
|
1091
|
+
|
|
1092
|
+
if __name__ == "__main__":
|
|
1093
|
+
sys.exit(main())
|