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.
Files changed (99) hide show
  1. polyctl/__init__.py +7 -0
  2. polyctl/__main__.py +5 -0
  3. polyctl/a2a.py +226 -0
  4. polyctl/a2a_mcp.py +546 -0
  5. polyctl/acp.py +417 -0
  6. polyctl/adapters/README.md +101 -0
  7. polyctl/adapters/aider.json +32 -0
  8. polyctl/adapters/amazon-q.json +15 -0
  9. polyctl/adapters/amp.json +16 -0
  10. polyctl/adapters/antigravity.json +120 -0
  11. polyctl/adapters/claude-code.json +229 -0
  12. polyctl/adapters/cloud-generic.json +57 -0
  13. polyctl/adapters/codex.json +47 -0
  14. polyctl/adapters/command-code.json +45 -0
  15. polyctl/adapters/copilot.json +17 -0
  16. polyctl/adapters/cursor-agent.json +29 -0
  17. polyctl/adapters/deepseek.json +13 -0
  18. polyctl/adapters/droid.json +34 -0
  19. polyctl/adapters/gemini.json +30 -0
  20. polyctl/adapters/grok.json +22 -0
  21. polyctl/adapters/hermes.json +34 -0
  22. polyctl/adapters/kilocode.json +30 -0
  23. polyctl/adapters/kimi.json +23 -0
  24. polyctl/adapters/kiro.json +332 -0
  25. polyctl/adapters/ollama.json +29 -0
  26. polyctl/adapters/omp.json +34 -0
  27. polyctl/adapters/openai-api.json +68 -0
  28. polyctl/adapters/opencode.json +162 -0
  29. polyctl/adapters/pi.json +24 -0
  30. polyctl/adapters/pr-agent.json +54 -0
  31. polyctl/adapters/profiles.json +9 -0
  32. polyctl/adapters/qoder.json +163 -0
  33. polyctl/adapters/qwen.json +27 -0
  34. polyctl/adapters/reasonix.json +25 -0
  35. polyctl/adapters/rewriters/rtk.json +24 -0
  36. polyctl/adapters/trae.json +31 -0
  37. polyctl/adapters/vendors.json +42 -0
  38. polyctl/adapters/warp.json +88 -0
  39. polyctl/allowlist.py +1756 -0
  40. polyctl/api_review.py +920 -0
  41. polyctl/cli.py +835 -0
  42. polyctl/conformance_harness.py +9 -0
  43. polyctl/demo.py +503 -0
  44. polyctl/drivers.py +146 -0
  45. polyctl/email.py +160 -0
  46. polyctl/features.py +98 -0
  47. polyctl/journal.py +144 -0
  48. polyctl/language.py +945 -0
  49. polyctl/lib.py +1296 -0
  50. polyctl/matrix.py +660 -0
  51. polyctl/mcp.py +1362 -0
  52. polyctl/ntfy.py +169 -0
  53. polyctl/outbound.py +39 -0
  54. polyctl/parts/__init__.py +5 -0
  55. polyctl/parts/cli_authority.py +2615 -0
  56. polyctl/parts/cli_channels.py +1325 -0
  57. polyctl/parts/cli_checks.py +2293 -0
  58. polyctl/parts/cli_completion.py +686 -0
  59. polyctl/parts/cli_evidence.py +141 -0
  60. polyctl/parts/cli_gain.py +375 -0
  61. polyctl/parts/cli_harness.py +392 -0
  62. polyctl/parts/cli_hooks.py +1816 -0
  63. polyctl/parts/cli_install.py +638 -0
  64. polyctl/parts/cli_lanes.py +106 -0
  65. polyctl/parts/cli_maintenance.py +2536 -0
  66. polyctl/parts/cli_next.py +248 -0
  67. polyctl/parts/cli_pr.py +53 -0
  68. polyctl/parts/cli_project.py +2857 -0
  69. polyctl/parts/cli_review.py +5158 -0
  70. polyctl/parts/cli_status.py +898 -0
  71. polyctl/parts/lib_adapters.py +2933 -0
  72. polyctl/parts/lib_alarms.py +2106 -0
  73. polyctl/parts/lib_events.py +224 -0
  74. polyctl/parts/lib_evidence.py +412 -0
  75. polyctl/parts/lib_gates.py +2099 -0
  76. polyctl/parts/lib_lanes.py +829 -0
  77. polyctl/parts/lib_mail.py +1541 -0
  78. polyctl/parts/lib_next.py +652 -0
  79. polyctl/parts/lib_pr.py +331 -0
  80. polyctl/parts/lib_slices.py +3337 -0
  81. polyctl/parts/lib_state.py +2415 -0
  82. polyctl/parts/lib_transcript.py +4118 -0
  83. polyctl/pressure.py +325 -0
  84. polyctl/prices.json +47 -0
  85. polyctl/procs.py +1194 -0
  86. polyctl/settings.py +505 -0
  87. polyctl/skill/SKILL.md +365 -0
  88. polyctl/skillkit.py +503 -0
  89. polyctl/storage.py +2055 -0
  90. polyctl/telegram.py +327 -0
  91. polyctl/tiers.py +123 -0
  92. polyctl/verdicts.py +41 -0
  93. polyctl/watchdog.py +3887 -0
  94. polyctl/web.py +337 -0
  95. polyctl-0.7.0.dist-info/METADATA +235 -0
  96. polyctl-0.7.0.dist-info/RECORD +99 -0
  97. polyctl-0.7.0.dist-info/WHEEL +4 -0
  98. polyctl-0.7.0.dist-info/entry_points.txt +5 -0
  99. polyctl-0.7.0.dist-info/licenses/LICENSE +21 -0
polyctl/a2a_mcp.py ADDED
@@ -0,0 +1,546 @@
1
+ #!/usr/bin/env python3
2
+ """polyctl-a2a-mcp — reach A2A agents from an MCP-only client.
3
+
4
+ Kiro speaks MCP and does not speak A2A: no agent card, no task lifecycle, no
5
+ `.well-known/agent-card.json` anywhere in its CLI or IDE. This bridges that gap in
6
+ the one direction that helps — remote A2A agents appear as MCP tools, so an
7
+ MCP-only implementer can discover them, send them work and follow the result.
8
+
9
+ It cannot make MCP interruptible. Nothing can; see docs/mcp.md.
10
+
11
+ ## Why not just use the existing bridge
12
+
13
+ `a2anet/a2a-mcp` does the same job and predates this. It speaks A2A 0.3, and 0.3
14
+ is not what the specification says any more: 1.0 renamed every JSON-RPC method
15
+ (`message/send` → `SendMessage`), re-cased the roles (`user` → `ROLE_USER`),
16
+ prefixed every task state (`input-required` → `TASK_STATE_INPUT_REQUIRED`) and
17
+ changed the content type. An 0.3-only client silently fails against a 1.0 agent,
18
+ and a 1.0-only client fails against everything deployed today.
19
+
20
+ So this negotiates. It reads the agent card, takes the version the agent declares,
21
+ and speaks that dialect — falling back to trying both when a card says nothing,
22
+ because a card that omits its version is more common than one that lies about it.
23
+
24
+ Standard library only.
25
+ """
26
+ import json
27
+ import math
28
+ import os
29
+ import re
30
+ import sys
31
+ import urllib.error
32
+ import urllib.request
33
+
34
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
35
+ from polyctl import __version__, lib as A, outbound # noqa: E402
36
+ UTF8 = "utf-8" # every text file polyctl writes or reads; Windows would otherwise use cp1252
37
+
38
+ PROTOCOL = "2025-06-18"
39
+ CARD_PATHS = ("/.well-known/agent-card.json", "/.well-known/agent.json")
40
+
41
+ # The two dialects, side by side, because the wire format is the whole problem.
42
+ DIALECTS = {
43
+ "1.0": {"send": "SendMessage", "get": "GetTask", "list": "ListTasks",
44
+ "cancel": "CancelTask", "role_user": "ROLE_USER",
45
+ "content_type": "application/a2a+json",
46
+ "state_prefix": "TASK_STATE_", "part_kind": False},
47
+ "0.3": {"send": "message/send", "get": "tasks/get", "list": "tasks/list",
48
+ "cancel": "tasks/cancel", "role_user": "user",
49
+ "content_type": "application/json",
50
+ "state_prefix": "", "part_kind": True},
51
+ }
52
+
53
+
54
+ def normalise_state(state):
55
+ """One vocabulary for the caller, whichever dialect produced it."""
56
+ if not state:
57
+ return "unknown"
58
+ s = str(state)
59
+ if s.startswith("TASK_STATE_"):
60
+ s = s[len("TASK_STATE_"):]
61
+ return s.lower().replace("_", "-")
62
+
63
+
64
+ ROOT = None
65
+
66
+ # A header's value names a variable that holds it as `${NAME}`, read where the bridge runs (LEADS-SECRETS).
67
+ VARIABLE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
68
+ # A header whose name says it carries a credential: in the project's file its value must name a variable. Read by the
69
+ # words of the name, so `X-Api-Key` and `Proxy-Authorization` are and `X-Monkey` is not (LEADS-SECRETS).
70
+ CREDENTIAL_WORDS = frozenset({"auth", "authorization", "authentication", "key", "apikey", "token", "secret",
71
+ "password", "passwd", "cookie", "session", "credential", "credentials", "bearer"})
72
+ # The fewest characters a credential is sent with: one shorter is guessed sooner than hidden, and an answer that
73
+ # echoes it could not be told from ordinary text to be redacted (LEADS-SECRETS).
74
+ CREDENTIAL_MIN = 8
75
+
76
+
77
+ def secret_parts(value):
78
+ """The parts of a credential header's value that are secret: of each `;` or `,` item, a `name=value` pair's value,
79
+ and of an item with no name, its last word - the token after `Bearer`, a cookie's value, never its name."""
80
+ parts = []
81
+ for item in re.split(r"[;,]", str(value)):
82
+ item = item.strip()
83
+ pair = re.match(r"^[A-Za-z0-9_.!#$%&'*+^`|~-]+=(.*)$", item)
84
+ if item:
85
+ parts.append(pair.group(1).strip() if pair else (item.split() or [""])[-1])
86
+ return parts
87
+
88
+
89
+ def credential_header(name):
90
+ """Whether a header's name says it carries a credential, read by its words."""
91
+ return any(word in CREDENTIAL_WORDS for word in re.split(r"[^a-z0-9]+", str(name).lower()) if word)
92
+
93
+
94
+ def registries():
95
+ """The files agents are registered in, in the order `agents` reads them: the project's, then the machine's."""
96
+ return (os.path.join(ROOT or os.getcwd(), ".polyctl", "a2a-agents.json"),
97
+ os.path.join(A.HOME, ".polyctl", "a2a-agents.json"))
98
+
99
+
100
+ def _origin(url):
101
+ """`scheme://host:port` of an http or https URL, its host lower-cased and its default port written; else None."""
102
+ from urllib.parse import urlsplit
103
+ try:
104
+ parts = urlsplit(str(url or ""))
105
+ port = parts.port
106
+ except ValueError:
107
+ return None
108
+ if parts.scheme not in ("http", "https") or not parts.hostname:
109
+ return None
110
+ return f"{parts.scheme}://{parts.hostname.lower()}:{port or (443 if parts.scheme == 'https' else 80)}"
111
+
112
+
113
+ def bound_variables():
114
+ """{variable: {origin}}: where the machine's file sends each variable one of its headers names (LEADS-SECRETS).
115
+
116
+ `.polyctl/a2a-agents.json` is a file the implementer writes: one that kept `Bearer ${WEATHER_A2A_TOKEN}` and named
117
+ another URL had the bridge send the token to that host. A variable the project's file names is sent only to an
118
+ origin the machine's `~/.polyctl/a2a-agents.json`, outside every tree, sends it to.
119
+ """
120
+ try:
121
+ with open(registries()[1], encoding=UTF8) as fh:
122
+ machine = json.load(fh)
123
+ except (OSError, ValueError):
124
+ return {}
125
+ bound = {}
126
+ for agent in machine.values() if isinstance(machine, dict) else []:
127
+ headers = agent.get("headers") if isinstance(agent, dict) else None
128
+ origin = _origin(agent.get("url")) if isinstance(headers, dict) else None
129
+ for value in (headers or {}).values() if origin else []:
130
+ for variable in VARIABLE.findall(str(value)):
131
+ bound.setdefault(variable, set()).add(origin)
132
+ return bound
133
+
134
+
135
+ def resolved(aid, agent, in_project, bound=None):
136
+ """(the agent with each `${NAME}` in its headers replaced by that variable's value, None), or (None, why not).
137
+
138
+ `.polyctl/a2a-agents.json` is a file of the project, which a commit takes with the rest of `.polyctl/`, and an
139
+ Authorization header written into it went into the repository's history with it. In the project's file a
140
+ credential header names the variable that holds it, which is set where the bridge runs, and one written out
141
+ there is refused rather than sent; `~/.polyctl/a2a-agents.json`, outside every repository, may hold one. A variable
142
+ the project's file names is sent only to an origin the machine's file sends it to (`bound`, bound_variables). A value
143
+ that holds a line break is refused here too: http.client refuses it with the value in its error, which the
144
+ bridge answered with (LEADS-SECRETS).
145
+ """
146
+ headers = agent.get("headers") or {}
147
+ if not isinstance(headers, dict):
148
+ return None, f"agent {aid}: its headers are no JSON object"
149
+ out = {}
150
+ for name, value in headers.items():
151
+ text = str(value)
152
+ named = VARIABLE.findall(text)
153
+ unset = [variable for variable in named if not os.environ.get(variable)]
154
+ if unset:
155
+ return None, (f"agent {aid}: its {name} header names ${{{unset[0]}}}, which is not set where the bridge "
156
+ "runs: set it in the environment the MCP client starts the bridge with")
157
+ origin = _origin(agent.get("url"))
158
+ loose = [variable for variable in named if in_project and origin not in (bound or {}).get(variable, ())]
159
+ if loose:
160
+ return None, (f"agent {aid}: its {name} header names ${{{loose[0]}}}, which the machine's "
161
+ f"~/.polyctl/a2a-agents.json sends to no agent at {origin or 'its URL'}: .polyctl/a2a-agents.json is "
162
+ "a file an agent can write, and a URL changed there carried the credential to another host; "
163
+ "register the agent with its URL and that header in ~/.polyctl/a2a-agents.json")
164
+ if in_project and not named and credential_header(name):
165
+ return None, (f"agent {aid}: its {name} header is written into .polyctl/a2a-agents.json, which a commit "
166
+ "takes with the project; name the variable that holds it instead, as \"Bearer ${NAME}\", "
167
+ "and set NAME where the bridge runs")
168
+ out[name] = VARIABLE.sub(lambda found: os.environ[found.group(1)].strip(), text)
169
+ if "\n" in out[name] or "\r" in out[name]:
170
+ return None, f"agent {aid}: its {name} header holds a line break, which no header may"
171
+ # A value a variable holds is a credential whatever the header's name, since that is what a variable is for
172
+ # here: each is hidden in what the bridge answers, so none shorter than can be told apart is sent.
173
+ short = [variable for variable in named if len(os.environ[variable].strip()) < CREDENTIAL_MIN]
174
+ if short or credential_header(name) and any(len(part) < CREDENTIAL_MIN for part in secret_parts(out[name])):
175
+ return None, (f"agent {aid}: its {name} header carries a credential of fewer than {CREDENTIAL_MIN} "
176
+ "characters, which polyctl sends nowhere: one that short is guessed, and an answer that echoes "
177
+ "it cannot be told apart to be hidden")
178
+ return dict(agent, headers=out), None
179
+
180
+
181
+ def registry():
182
+ """(configured agents, whether they are the project's): {id: {url, headers?, version?}} and where they came from,
183
+ read in one opening of one file - the project's `.polyctl/a2a-agents.json` when it has one, else the machine's.
184
+
185
+ A file, not an environment variable. The rest of this tool keeps its state in
186
+ files that a human can read during an incident, and a registry that only
187
+ exists inside a process's environment is the one thing you cannot inspect when
188
+ something is wrong. A credential is the exception: a header names the variable
189
+ that holds it (`resolved`). Whose file it was is taken from the same opening: told apart by a second look, a
190
+ project file renamed away between the reading and the look was taken for the machine's, and its URLs were sent
191
+ the person's variables with no origin bound to them (LEADS-SECRETS).
192
+ """
193
+ for at, path in enumerate(registries()):
194
+ try:
195
+ with open(path, encoding=UTF8) as fh:
196
+ data = json.load(fh)
197
+ except FileNotFoundError:
198
+ continue
199
+ except (OSError, ValueError):
200
+ return {}, at == 0
201
+ return (data if isinstance(data, dict) else {}), at == 0
202
+ return {}, False
203
+
204
+
205
+ def agents():
206
+ """The configured agents, as `registry` reads them."""
207
+ return registry()[0]
208
+
209
+
210
+ def _shown_url(url):
211
+ """An agent's URL as an answer shows it: its origin - scheme, host and port - alone. A credential can stand in
212
+ every other part of it, its user, its path (`/a2a/<token>`), its query (`?access_token=...`), and the model the
213
+ bridge answers needs none of them (LEADS-SECRETS)."""
214
+ from urllib.parse import urlsplit
215
+ try:
216
+ parts = urlsplit(str(url or ""))
217
+ netloc = (parts.hostname or "") + (f":{parts.port}" if parts.port else "")
218
+ except ValueError:
219
+ return "…"
220
+ return f"{parts.scheme}://{netloc}" if parts.scheme and netloc else "…"
221
+
222
+
223
+ # Follow no redirect: urllib carried every header of a request - an agent's Authorization among them - to wherever a
224
+ # redirect pointed, another host included (A2A-HARDEN). An agent that moved is written anew in .polyctl/a2a-agents.json.
225
+ # The opener is the one every request of polyctl's that carries a credential leaves by (HUNT-LEADS-SEC).
226
+ _OPENER = outbound.OPENER
227
+
228
+
229
+ def _post(url, headers, payload, timeout=60):
230
+ body = json.dumps(payload).encode()
231
+ req = urllib.request.Request(url, data=body, headers=headers)
232
+ with _OPENER.open(req, timeout=timeout) as r:
233
+ return json.loads(r.read().decode() or "{}")
234
+
235
+
236
+ def fetch_card(url, headers=None, timeout=20):
237
+ """The agent card, and the dialect it implies."""
238
+ base = url.rstrip("/")
239
+ for path in CARD_PATHS:
240
+ for candidate in (base + path, base.rsplit("/", 1)[0] + path):
241
+ try:
242
+ req = urllib.request.Request(candidate, headers=headers or {})
243
+ with _OPENER.open(req, timeout=timeout) as r:
244
+ card = json.loads(r.read().decode())
245
+ declared = str(card.get("protocolVersion", "")).strip()
246
+ # Interfaces can declare per-binding versions; prefer the JSON-RPC one.
247
+ for iface in card.get("interfaces") or card.get("additionalInterfaces") or []:
248
+ if str(iface.get("protocolBinding", "")).upper() == "JSONRPC":
249
+ declared = str(iface.get("protocolVersion", declared))
250
+ break
251
+ return card, ("1.0" if declared.startswith("1") else
252
+ "0.3" if declared else None), candidate
253
+ except Exception:
254
+ continue
255
+ return None, None, None
256
+
257
+
258
+ def rpc(agent, method_key, params, version=None, timeout=90):
259
+ """One JSON-RPC call in whichever dialect the agent speaks.
260
+
261
+ When the card declares nothing, try 1.0 and fall back to 0.3 on a
262
+ method-not-found. Guessing once and caching beats failing on a card that
263
+ simply omitted a field.
264
+
265
+ A message is sent in the other dialect only when the first said it does not
266
+ take the method or the request: after a timeout, a dropped connection or any
267
+ other answer it is not known whether the agent took the message, and sending
268
+ it again could start the work twice (A2A-HARDEN).
269
+ """
270
+ url = agent["url"]
271
+ order = [version] if version else ["1.0", "0.3"]
272
+ once = method_key == "send"
273
+ unknown = "the agent may have taken the message: ask a2a_task, or a2a_agents, before sending it again"
274
+ last = None
275
+ for v in order:
276
+ d = DIALECTS[v]
277
+ headers = dict(agent.get("headers") or {})
278
+ headers["Content-Type"] = d["content_type"]
279
+ headers.setdefault("A2A-Version", v)
280
+ try:
281
+ out = _post(url, headers, {"jsonrpc": "2.0", "id": 1,
282
+ "method": d[method_key],
283
+ "params": params(d)}, timeout)
284
+ except urllib.error.HTTPError as e:
285
+ last = {"error": f"HTTP {e.code}", "dialect": v}
286
+ if once and e.code not in (400, 404, 405, 415):
287
+ return dict(last, note=unknown)
288
+ continue
289
+ except Exception as e:
290
+ last = {"error": str(e)[:200], "dialect": v}
291
+ if once:
292
+ return dict(last, note=unknown)
293
+ continue
294
+ if not isinstance(out, dict):
295
+ last = {"error": "the agent answered with no JSON-RPC object", "dialect": v}
296
+ if once:
297
+ return dict(last, note=unknown)
298
+ continue
299
+ err = out.get("error") or {}
300
+ if not isinstance(err, dict):
301
+ err = {"message": str(err)[:200]}
302
+ if err.get("code") in (-32601, -32600): # method not found / invalid
303
+ last = {"error": err.get("message", "method not found"), "dialect": v}
304
+ continue
305
+ if err:
306
+ return {"error": err.get("message", "error"), "code": err.get("code"),
307
+ "dialect": v}
308
+ return {"result": out.get("result", out), "dialect": v}
309
+ return last or {"error": "no dialect succeeded"}
310
+
311
+
312
+ def _task_view(res):
313
+ """Flatten a Task from either dialect into one shape."""
314
+ t = res.get("task") or res
315
+ status = t.get("status") or {}
316
+ msg = status.get("message") or {}
317
+ parts = msg.get("parts") or []
318
+ text = " ".join(p.get("text", "") for p in parts if p.get("text")).strip()
319
+ return {"id": t.get("id"), "contextId": t.get("contextId"),
320
+ "state": normalise_state(status.get("state")),
321
+ "message": text or None,
322
+ "artifacts": [{"artifactId": a.get("artifactId"), "name": a.get("name"),
323
+ "text": " ".join(p.get("text", "")
324
+ for p in (a.get("parts") or []))[:4000]}
325
+ for a in (t.get("artifacts") or [])]}
326
+
327
+
328
+ TOOLS = [
329
+ {"name": "a2a_agents",
330
+ "description": "List the configured A2A agents, with the protocol dialect each "
331
+ "one speaks.",
332
+ "inputSchema": {"type": "object", "properties": {}}},
333
+ {"name": "a2a_agent",
334
+ "description": "One agent's card: what it is, and the skills it advertises.",
335
+ "inputSchema": {"type": "object", "required": ["agent"],
336
+ "properties": {"agent": {"type": "string"}}}},
337
+ {"name": "a2a_send",
338
+ "description": "Send a message to an A2A agent. Returns the task, including "
339
+ "state 'input-required' when the agent needs more from you.",
340
+ "inputSchema": {"type": "object", "required": ["agent", "message"],
341
+ "properties": {"agent": {"type": "string"},
342
+ "message": {"type": "string"},
343
+ "taskId": {"type": "string"},
344
+ "contextId": {"type": "string"}}}},
345
+ {"name": "a2a_task",
346
+ "description": "Current state and artifacts of a task you already sent.",
347
+ "inputSchema": {"type": "object", "required": ["agent", "taskId"],
348
+ "properties": {"agent": {"type": "string"},
349
+ "taskId": {"type": "string"}}}},
350
+ {"name": "a2a_cancel",
351
+ "description": "Cancel a task.",
352
+ "inputSchema": {"type": "object", "required": ["agent", "taskId"],
353
+ "properties": {"agent": {"type": "string"},
354
+ "taskId": {"type": "string"}}}},
355
+ ]
356
+
357
+
358
+ def _credentials(reg):
359
+ """Each value a request of the bridge's may carry as a credential, longest first: a variable's value a header names,
360
+ and a credential header's value as it is sent - the machine's file may hold one written out - with each of its
361
+ parts, the token after `Bearer` and each value of `sid=...; csrf=...`, which an answer can echo alone."""
362
+ found = set()
363
+ for agent in reg.values() if isinstance(reg, dict) else []:
364
+ headers = agent.get("headers") if isinstance(agent, dict) else None
365
+ for name, value in headers.items() if isinstance(headers, dict) else []:
366
+ text = str(value)
367
+ for variable in VARIABLE.findall(text):
368
+ held = os.environ.get(variable, "").strip()
369
+ found.update([held] + re.split(r"[\s;,=:&]+", held))
370
+ if credential_header(name):
371
+ sent = VARIABLE.sub(lambda named: os.environ.get(named.group(1), "").strip(), text).strip()
372
+ found.update([sent] + re.split(r"[\s;,=:&]+", sent) + secret_parts(sent))
373
+ # A URL can carry one too: its user, its password, a value of its query (`?access_token=...`).
374
+ from urllib.parse import urlsplit, parse_qsl
375
+ try:
376
+ parts = urlsplit(str((agent or {}).get("url") or "") if isinstance(agent, dict) else "")
377
+ found.update(value for _, value in parse_qsl(parts.query))
378
+ found.update(part for part in (parts.username, parts.password) if part)
379
+ except ValueError:
380
+ pass
381
+ # None shorter than CREDENTIAL_MIN is sent (`resolved`), so none such needs hiding, and hiding every few letters
382
+ # would garble the answer.
383
+ return sorted((value for value in found if len(value) >= CREDENTIAL_MIN), key=len, reverse=True)
384
+
385
+
386
+ def _redacted(value, credentials):
387
+ """`value` with each credential in its text replaced by `[credential]`."""
388
+ if isinstance(value, str):
389
+ for credential in credentials:
390
+ value = value.replace(credential, "[credential]")
391
+ return value
392
+ if isinstance(value, dict):
393
+ return {key: _redacted(item, credentials) for key, item in value.items()}
394
+ if isinstance(value, list):
395
+ return [_redacted(item, credentials) for item in value]
396
+ return value
397
+
398
+
399
+ def call(name, args):
400
+ """A tool's answer, with no credential the bridge sends in it.
401
+
402
+ What an agent answers is its own text, and one that echoed the header it was sent - in an error, a task's
403
+ message, its card - had the bridge hand the person's token to the model that called it, and to the notice the
404
+ bridge records (LEADS-SECRETS). A credential is hidden as it was sent and by each of its parts; an agent the person
405
+ gave one to can still pass it on encoded, which no hiding stops - the guard there is the origin the person bound it
406
+ to (bound_variables), and docs/threat-model.md puts such an agent out of scope.
407
+ """
408
+ # One reading of the registry for the request and for what is hidden in its answer: read twice, a file changed
409
+ # between the two sent a credential the second reading named and the first did not know to hide.
410
+ reg, in_project = registry()
411
+ credentials = _credentials(reg)
412
+ return _redacted(_answer(name, args, credentials, reg, in_project), credentials)
413
+
414
+
415
+ def _answer(name, args, credentials, reg, in_project):
416
+ # The agents are the project's when it has a registry, as the one reading of it said (`registry`).
417
+ bound = bound_variables() if in_project else None
418
+ if name == "a2a_agents":
419
+ out = []
420
+ for aid, a in reg.items():
421
+ a, why = resolved(aid, a, in_project, bound)
422
+ if why:
423
+ out.append({"id": aid, "url": _shown_url(reg[aid].get("url")), "error": why, "reachable": False})
424
+ continue
425
+ card, ver, at = fetch_card(a["url"], a["headers"])
426
+ out.append({"id": aid, "url": _shown_url(a["url"]),
427
+ "name": (card or {}).get("name"),
428
+ "description": (card or {}).get("description"),
429
+ "dialect": a.get("version") or ver or "undeclared",
430
+ "card": _shown_url(at) if at else None, "reachable": card is not None})
431
+ return {"agents": out, "count": len(out),
432
+ "note": "none configured; write .polyctl/a2a-agents.json" if not out else None}
433
+
434
+ a = reg.get(args.get("agent") or "")
435
+ if not a:
436
+ return {"error": f"unknown agent {args.get('agent')!r}",
437
+ "configured": list(reg)}
438
+ a, why = resolved(args["agent"], a, in_project, bound)
439
+ if why:
440
+ return {"error": why}
441
+ version = a.get("version")
442
+
443
+ if name == "a2a_agent":
444
+ card, ver, at = fetch_card(a["url"], a.get("headers"))
445
+ if not card:
446
+ return {"error": "no agent card at " + _shown_url(a["url"])}
447
+ return {"card_url": _shown_url(at), "dialect": version or ver or "undeclared",
448
+ "name": card.get("name"), "description": card.get("description"),
449
+ "skills": [{"id": s.get("id"), "name": s.get("name"),
450
+ "description": s.get("description")}
451
+ for s in card.get("skills") or []]}
452
+
453
+ if name == "a2a_send":
454
+ # One message, whichever dialect carries it: an agent can tell a repeat by its id (A2A-HARDEN).
455
+ message_id = f"polyctl-{os.urandom(8).hex()}"
456
+
457
+ def params(d):
458
+ part = {"text": args["message"]}
459
+ if d["part_kind"]:
460
+ part["kind"] = "text"
461
+ msg = {"role": d["role_user"], "parts": [part], "messageId": message_id}
462
+ for k in ("taskId", "contextId"):
463
+ if args.get(k):
464
+ msg[k] = args[k]
465
+ return {"message": msg}
466
+ r = rpc(a, "send", params, version)
467
+ if "result" not in r:
468
+ return r
469
+ view = _redacted(_task_view(r["result"]), credentials)
470
+ # Remember what we sent, so a task can be followed after the turn that
471
+ # started it has ended — the common case for anything slow.
472
+ A.record_notice(ROOT or os.getcwd(), "a2a", f"{args['agent']} task {view.get('id')} "
473
+ f"{view.get('state')}", sent=False, key="a2a")
474
+ return {**view, "dialect": r["dialect"]}
475
+
476
+ if name in ("a2a_task", "a2a_cancel"):
477
+ key = "get" if name == "a2a_task" else "cancel"
478
+ r = rpc(a, key, lambda d: {"id": args["taskId"]}, version)
479
+ if "result" not in r:
480
+ return r
481
+ return {**_task_view(r["result"]), "dialect": r["dialect"]}
482
+
483
+ return {"error": f"unknown tool {name}"}
484
+
485
+
486
+ def main():
487
+ global ROOT
488
+ # MCP's stdio transport is UTF-8, and each reply below is seven-bit JSON, as polyctl's own server's are (#71).
489
+ A.utf8_streams()
490
+ if "-C" in sys.argv:
491
+ ROOT = os.path.abspath(os.path.expanduser(sys.argv[sys.argv.index("-C") + 1]))
492
+ for line in sys.stdin:
493
+ line = line.strip()
494
+ if not line:
495
+ continue
496
+ try:
497
+ req = json.loads(line)
498
+ except (ValueError, RecursionError):
499
+ # Parser limits must not end the bridge and take every tool away (LEADS-OPEN).
500
+ continue
501
+ if not isinstance(req, dict):
502
+ # A JSON array or a scalar is no request, and reading it as one ended the server (A2A-HARDEN).
503
+ sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": None, "error": {
504
+ "code": -32600, "message": "a request is a JSON object"}}) + "\n")
505
+ sys.stdout.flush()
506
+ continue
507
+ rid, method = req.get("id"), req.get("method")
508
+ # Never dispatch or echo a container id: encoding a deeply nested one ended the server (LEADS-OPEN).
509
+ if (rid is not None and type(rid) not in (str, int, float)) or (
510
+ isinstance(rid, float) and not math.isfinite(rid)):
511
+ sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": None, "error": {
512
+ "code": -32600, "message": "a request id must be a string, finite number or null"}}) + "\n")
513
+ sys.stdout.flush()
514
+ continue
515
+ try:
516
+ if method == "initialize":
517
+ result = {"protocolVersion": PROTOCOL, "capabilities": {"tools": {}},
518
+ "serverInfo": {"name": "polyctl-a2a-mcp", "version": __version__}}
519
+ elif method in ("notifications/initialized", "initialized"):
520
+ continue
521
+ elif method == "tools/list":
522
+ result = {"tools": TOOLS}
523
+ elif method == "tools/call":
524
+ p = req.get("params") or {}
525
+ payload = call(p.get("name"), p.get("arguments") or {})
526
+ result = {"content": [{"type": "text",
527
+ "text": json.dumps(payload, ensure_ascii=False,
528
+ indent=2, default=str)}]}
529
+ elif method == "ping":
530
+ result = {}
531
+ else:
532
+ raise ValueError(f"method not found: {method}")
533
+ except Exception as e:
534
+ sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": rid,
535
+ "error": {"code": -32603,
536
+ "message": str(e)}}) + "\n")
537
+ sys.stdout.flush()
538
+ continue
539
+ if rid is not None:
540
+ # Escaped to ASCII, as the error reply above always was: a write outside the handler must not fail.
541
+ sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": rid, "result": result}, default=str) + "\n")
542
+ sys.stdout.flush()
543
+
544
+
545
+ if __name__ == "__main__":
546
+ main()