phiward 0.2.0b1__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 (53) hide show
  1. phiward/__init__.py +8 -0
  2. phiward/__main__.py +5 -0
  3. phiward/_toml.py +211 -0
  4. phiward/adapters/__init__.py +105 -0
  5. phiward/adapters/claude.py +429 -0
  6. phiward/broker.py +831 -0
  7. phiward/carryover.py +1613 -0
  8. phiward/claude_settings.py +1307 -0
  9. phiward/cli.py +110 -0
  10. phiward/config.py +936 -0
  11. phiward/confine.py +476 -0
  12. phiward/copying.py +533 -0
  13. phiward/core.py +105 -0
  14. phiward/data/agents-section.md +43 -0
  15. phiward/doctor.py +1132 -0
  16. phiward/fasthook.py +70 -0
  17. phiward/fsinfo.py +241 -0
  18. phiward/gateway.py +159 -0
  19. phiward/githooks.py +248 -0
  20. phiward/guards/__init__.py +0 -0
  21. phiward/guards/protected_paths.py +1138 -0
  22. phiward/hidden.py +281 -0
  23. phiward/init.py +155 -0
  24. phiward/install.py +828 -0
  25. phiward/inventory.py +173 -0
  26. phiward/mcp.py +186 -0
  27. phiward/mcp_config.py +1736 -0
  28. phiward/names.py +5 -0
  29. phiward/packs/dates.toml +17 -0
  30. phiward/packs/genomics.toml +51 -0
  31. phiward/packs/msk.toml +32 -0
  32. phiward/pathid.py +403 -0
  33. phiward/pathmatch.py +98 -0
  34. phiward/paths.py +942 -0
  35. phiward/pin.py +214 -0
  36. phiward/procinfo.py +73 -0
  37. phiward/remote.py +448 -0
  38. phiward/run.py +788 -0
  39. phiward/safeio.py +84 -0
  40. phiward/sanitize.py +691 -0
  41. phiward/selfcheck.py +1506 -0
  42. phiward/service.py +321 -0
  43. phiward/session_note.py +86 -0
  44. phiward/setup_cmd.py +886 -0
  45. phiward/shell.py +504 -0
  46. phiward/wholetool.py +1463 -0
  47. phiward-0.2.0b1.dist-info/METADATA +147 -0
  48. phiward-0.2.0b1.dist-info/RECORD +53 -0
  49. phiward-0.2.0b1.dist-info/WHEEL +5 -0
  50. phiward-0.2.0b1.dist-info/entry_points.txt +3 -0
  51. phiward-0.2.0b1.dist-info/licenses/LICENSE +662 -0
  52. phiward-0.2.0b1.dist-info/licenses/NOTICE +16 -0
  53. phiward-0.2.0b1.dist-info/top_level.txt +1 -0
phiward/mcp_config.py ADDED
@@ -0,0 +1,1736 @@
1
+ """The MCP servers Claude Code may start here, read from its config files: the user's
2
+ `.claude.json` (in `$CLAUDE_CONFIG_DIR` when that is set, else the home folder; top level, and
3
+ this project's entry for local scope) and the project's `.mcp.json`. A server is **wrapped**
4
+ when its command runs it under `phiward launch [OPTIONS] -- ...` and nothing in its entry
5
+ changes what runs (`env` PATH, HOME, PHIWARD_*, ...; a `cwd`): then it runs in phiward's kernel
6
+ profile, and its tools are confined. A remote server (`type` http, sse or ws, and no
7
+ `command`) runs nothing here. Every other local server runs with the operator's rights.
8
+
9
+ The hook finds a tool's server by the hook input's `mcp_server` (`classify`: the scope Claude
10
+ Code names, the exact name; plugins from their installed files; `sdk` and the sources phiward
11
+ does not read are bare). Without it (Claude Code older than 2.1.274, Copilot), by name in the
12
+ operator's own config only (`server_of(..., trust_project=False)`).
13
+
14
+ When a name is defined more than once (scopes, files, a duplicate key), it is wrapped only when
15
+ every definition is. The hook trusts these files, so the agent must not write them: they are on
16
+ the hidden list or guard files for the file tools, and Claude Code's sandbox keeps Bash from
17
+ them."""
18
+
19
+ import functools
20
+ import json
21
+ import os
22
+ import re
23
+ import shlex
24
+ import shutil
25
+ import stat
26
+ import sys
27
+ from dataclasses import dataclass, field, replace
28
+ from typing import Any, Dict, List, Optional, Tuple
29
+
30
+ from phiward import claude_settings, pathid
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class Server:
35
+ name: str
36
+ wrapped: bool # runs under `phiward launch --` (or is remote)
37
+ remote: bool = False
38
+ # where Claude Code says its definition came from (hook input `mcp_server.source`); "" when
39
+ # found by name (an older Claude Code, Copilot)
40
+ source: str = ""
41
+ # its entries as phiward read them (filled in, as JSON text); none: not found
42
+ specs: Tuple[str, ...] = field(default=(), compare=False)
43
+ # reached by a URL on this machine (an IDE's server): not remote, and cannot be wrapped
44
+ here: bool = False
45
+ # no command phiward can wrap (none, empty, not text), and not remote
46
+ unwrappable: bool = False
47
+ # defined only where phiward does not trust it (the project's `.mcp.json`, without a source)
48
+ untrusted: bool = False
49
+ # for a plugin's server: (registry key, install folder) of each entry in `specs`
50
+ copies: Tuple[Tuple[str, str], ...] = field(default=(), compare=False)
51
+
52
+
53
+ # env keys that change which program runs, or what `phiward launch` reads
54
+ _ENV_CHANGES = ("PATH", "HOME", "CLAUDE_CONFIG_DIR", "TMPDIR",
55
+ # what tells a plugin's launcher from a configured one's (`plugin_hash`)
56
+ "CLAUDE_PLUGIN_ROOT", "CLAUDE_PLUGIN_DATA")
57
+ _ENV_PREFIXES = ("PHIWARD_", "XDG_", "PYTHON", "LD_", "DYLD_")
58
+
59
+
60
+ def user_file(home: str, env: Optional[Dict[str, str]] = None) -> str:
61
+ """The `.claude.json` Claude Code reads: in `$CLAUDE_CONFIG_DIR` when that is set."""
62
+ env = os.environ if env is None else env
63
+ conf = env.get("CLAUDE_CONFIG_DIR")
64
+ return os.path.join(conf, ".claude.json") if conf else os.path.join(home, ".claude.json")
65
+
66
+
67
+ def _command(spec: dict) -> List[str]:
68
+ """The command line of a server entry. `command` is split on spaces only when there are no
69
+ `args` and it is not, as given, an existing file (`/Applications/My App/srv` stays whole)."""
70
+ first = spec.get("command", "")
71
+ args = spec.get("args", []) or []
72
+ if not isinstance(first, str) or not isinstance(args, list) or \
73
+ not all(isinstance(a, (str, int, float)) and not isinstance(a, bool) for a in args):
74
+ return [] # malformed: not a command phiward can read (it counts as bare)
75
+ args = [str(a) for a in args]
76
+ if "\0" in first or any("\0" in a for a in args):
77
+ return []
78
+ if " " in first and not args and not os.path.exists(first):
79
+ try:
80
+ return shlex.split(first)
81
+ except ValueError:
82
+ return [first]
83
+ return [first] + args
84
+
85
+
86
+ def _is_remote(spec: dict) -> bool:
87
+ """Runs nothing here: no `command`, an http, sse or ws `type` (or only a `url`), and a `url`
88
+ whose host is another machine. A server at this machine's own address (`127.0.0.1`,
89
+ `localhost`, its host name) is a local program, such as an IDE's, and counts as local."""
90
+ if spec.get("command"):
91
+ return False
92
+ t = spec.get("type")
93
+ if not (t in ("http", "sse", "ws") or (t is None and bool(spec.get("url")))):
94
+ return False
95
+ return _elsewhere(spec.get("url"))
96
+
97
+
98
+ HOSTS_FILE = "/etc/hosts"
99
+
100
+ # a URL phiward reads strictly: printable ASCII only (checked before), no `\\`, no user part,
101
+ # a host of letters, digits, dots and dashes or a bracketed IPv6 address, an optional port
102
+ _STRICT_URL = re.compile(r"(?i)(?:https?|wss?)://(?P<host>[a-z0-9.-]+|\[[0-9a-f:.]+\])"
103
+ r"(?::[0-9]{1,5})?(?:[/?#][\x21-\x7e]*)?")
104
+
105
+
106
+ def _elsewhere(url: Any) -> bool:
107
+ """Whether `url` surely names another machine. Claude Code reads it with Node's WHATWG URL
108
+ parser, which turns `\\` into `/`, decodes `%31` in the host, maps full-width characters
109
+ and reads `0177.1` as octal; so a URL counts only when it is plain (`_STRICT_URL`) and its
110
+ host is not this machine (`_host_elsewhere`). Anything else counts as this machine."""
111
+ if not isinstance(url, str) or not url.isascii() or "\\" in url:
112
+ return False
113
+ m = _STRICT_URL.fullmatch(url)
114
+ return bool(m) and _host_elsewhere(m.group("host"))
115
+
116
+
117
+ def _host_elsewhere(host: str) -> bool:
118
+ """Whether a host, as a URL parser gives it (lower case, IPv6 in brackets or not), names
119
+ another machine: not loopback, unspecified or link-local (IPv4 in any WHATWG spelling,
120
+ IPv6 also as `::ffff:a.b.c.d` or `::a.b.c.d`), not `localhost` or `*.localhost`, not this
121
+ machine's host name (or with `.local`), not a name /etc/hosts maps to such an address."""
122
+ import ipaddress
123
+ host = host.casefold()
124
+ if host.startswith("[") or ":" in host:
125
+ try:
126
+ ip6 = ipaddress.IPv6Address(host.strip("[]"))
127
+ except ValueError:
128
+ return False
129
+ return not _here_ip(ip6)
130
+ if host.endswith("."):
131
+ host = host[:-1]
132
+ labels = host.split(".")
133
+ if not host or "" in labels or not re.fullmatch(r"[a-z0-9.-]+", host):
134
+ return False
135
+ last = labels[-1]
136
+ if re.fullmatch(r"[0-9]+|0x[0-9a-f]*", last): # WHATWG: "ends in a number": an IPv4 host
137
+ ip4 = _whatwg_ipv4(labels)
138
+ return ip4 is not None and not _here_ip(ip4)
139
+ if host == "localhost" or host.endswith(".localhost"):
140
+ return False
141
+ import socket
142
+ me = socket.gethostname().rstrip(".").casefold()
143
+ short = me.split(".")[0]
144
+ if host in {me, short, me + ".local", short + ".local"} or host in _loopback_names():
145
+ return False
146
+ return True
147
+
148
+
149
+ def _whatwg_ipv4(labels: List[str]) -> Any:
150
+ """The IPv4 address of a host's labels by the WHATWG rules (decimal, `0` octal, `0x` hex
151
+ parts; the last one fills the rest), or None where Node refuses the URL."""
152
+ import ipaddress
153
+ if len(labels) > 4:
154
+ return None
155
+ nums = []
156
+ for part in labels:
157
+ base = 10
158
+ if part[:2] in ("0x", "0X"):
159
+ base, part = 16, part[2:]
160
+ elif len(part) > 1 and part.startswith("0"):
161
+ base, part = 8, part[1:]
162
+ if part == "":
163
+ nums.append(0)
164
+ continue
165
+ if not re.fullmatch({10: r"[0-9]+", 8: r"[0-7]+", 16: r"[0-9a-fA-F]+"}[base], part):
166
+ return None # Node refuses the URL (`-1`, `08`, `0x1g`)
167
+ part = part.lstrip("0") or "0" # Node allows any number of leading zeros
168
+ if len(part) > 11:
169
+ return None # 2**32 or more: Node refuses the URL (and int() may refuse it too)
170
+ nums.append(int(part, base))
171
+ if any(n > 255 for n in nums[:-1]) or nums[-1] >= 256 ** (5 - len(nums)):
172
+ return None
173
+ value = nums[-1]
174
+ for i, n in enumerate(nums[:-1]):
175
+ value += n * 256 ** (3 - i)
176
+ return ipaddress.IPv4Address(value)
177
+
178
+
179
+ def _here_ip(ip: Any) -> bool:
180
+ import ipaddress
181
+ if ip.version == 6:
182
+ if ip.ipv4_mapped is not None:
183
+ ip = ip.ipv4_mapped
184
+ elif int(ip) >> 32 == 0 and int(ip) > 1: # `::a.b.c.d` (IPv4-compatible)
185
+ ip = ipaddress.IPv4Address(int(ip))
186
+ return ip.is_loopback or ip.is_unspecified or ip.is_link_local
187
+
188
+
189
+ @functools.lru_cache(maxsize=1)
190
+ def _loopback_names() -> frozenset:
191
+ """The names /etc/hosts maps to a loopback, unspecified or link-local address."""
192
+ import ipaddress
193
+ out = set()
194
+ try:
195
+ with open(HOSTS_FILE, encoding="utf-8", errors="replace") as fh:
196
+ text = fh.read(1024 * 1024)
197
+ except OSError:
198
+ return frozenset()
199
+ for line in text.splitlines():
200
+ words = line.split("#", 1)[0].split()
201
+ if len(words) < 2:
202
+ continue
203
+ try:
204
+ ip = ipaddress.ip_address(words[0].split("%")[0])
205
+ except ValueError:
206
+ continue
207
+ if _here_ip(ip):
208
+ out.update(w.rstrip(".").casefold() for w in words[1:])
209
+ return frozenset(out)
210
+
211
+
212
+ def _has_command(spec: dict) -> bool:
213
+ c = spec.get("command") if isinstance(spec, dict) else None
214
+ return isinstance(c, str) and bool(c.strip())
215
+
216
+
217
+ def _listens_here(spec: dict) -> bool:
218
+ """An entry with no command that Claude Code reaches by a URL on this machine (an IDE's
219
+ server, say): phiward cannot wrap it, and it is not remote."""
220
+ if not isinstance(spec, dict) or spec.get("command"):
221
+ return False
222
+ t, url = spec.get("type"), spec.get("url")
223
+ return (t in ("http", "sse", "ws") or (t is None and bool(url))) and isinstance(url, str) \
224
+ and bool(url) and not _elsewhere(url)
225
+
226
+
227
+ def _changes_what_runs(spec: dict) -> bool:
228
+ """An entry whose `env` sets what chooses the program or what it loads (also every variable
229
+ the hooks clear: install.CLEARED_PREFIXES and CLEARED_NAMES), or that has a `cwd`."""
230
+ return bool(_changed_by(spec))
231
+
232
+
233
+ def _changed_by(spec: dict) -> List[str]:
234
+ """What in an entry changes what runs (`_changes_what_runs`), as the operator would remove it:
235
+ `cwd`, `env` PATH, ..."""
236
+ from phiward import install
237
+ names = set(_ENV_CHANGES) | set(install.CLEARED_NAMES)
238
+ prefixes = _ENV_PREFIXES + install.CLEARED_PREFIXES
239
+ out = []
240
+ if "cwd" in spec:
241
+ out.append("`cwd`")
242
+ env = spec.get("env")
243
+ if env is not None and not isinstance(env, dict):
244
+ out.append("an `env` that is not an object") # malformed: not known what it sets
245
+ elif isinstance(env, dict):
246
+ out += [f"`env` {shown(k)}" for k in env
247
+ if isinstance(k, str) and (k in names or k.startswith(prefixes))]
248
+ return out
249
+
250
+
251
+ def entry_wrapped(spec: Any, project: str, home: str) -> bool:
252
+ """The one answer to "is this configured entry wrapped", for `mcp list`, `doctor`, the hook
253
+ and `wrap`: `placed_state` is `wrapped` (the launcher file, its own entry id, no copy)."""
254
+ return placed_state(spec, project, home) == "wrapped"
255
+
256
+
257
+ def placed_state(spec: Any, project: str, home: str) -> str:
258
+ """`entry_state` of an entry as it sits in the config files: `copied` when it is wrapped but
259
+ its entry id is in another string of them too (a copy of the entry), so its launcher could
260
+ be the copy's; `wrap` gives it an id of its own."""
261
+ st = entry_state(spec)
262
+ if st == "wrapped":
263
+ eid = entry_id(_command(spec))
264
+ if eid and id_count(eid, project, home) > 1:
265
+ return "copied"
266
+ return st
267
+
268
+
269
+ def entry_state(spec: Any) -> str:
270
+ """What one entry is, and so what `phiward mcp wrap` would do with it. The one answer that
271
+ `mcp list`, `doctor`, the hook's advice and `wrap` all use:
272
+ - `wrapped`: runs under `phiward launch --entry ID --` (its own id: `entry_id`);
273
+ - `remote`: runs nothing here;
274
+ - `bare`: a command `wrap` can wrap;
275
+ - `runner`: starts phiward through another program (`uvx`, `env`, `uv run`, `pipx run`, Python
276
+ with `-m phiward`): the operator edits it (`RUNNER_STEP`); `wrap` never rewrites it;
277
+ - `changed`: wrapped, but its `cwd` or an `env` key changes what runs (the operator removes
278
+ that; wrapping again would not help);
279
+ - `here`: no command, reached by a URL on this machine (it runs outside Claude Code);
280
+ - `no-command`: no command phiward can read.
281
+ `here` and `no-command` cannot be wrapped."""
282
+ if not isinstance(spec, dict):
283
+ return "no-command"
284
+ if _is_remote(spec):
285
+ return "remote"
286
+ if not _has_command(spec):
287
+ return "here" if _listens_here(spec) else "no-command"
288
+ cmd = _command(spec)
289
+ if not cmd or not cmd[0]:
290
+ return "no-command"
291
+ if is_wrapped(cmd, spec):
292
+ # a configured entry without its own id (an older wrap) is not wrapped: `wrap` adds one
293
+ return "wrapped" if entry_id(cmd) else "bare"
294
+ if is_wrapped(cmd):
295
+ return "changed"
296
+ if _launch_shaped(cmd) and os.path.basename(cmd[0]) not in LAUNCHER_NAMES:
297
+ return "runner"
298
+ return "bare"
299
+
300
+
301
+ @dataclass(frozen=True)
302
+ class Entry:
303
+ name: str
304
+ path: str # the config file
305
+ scope: str # user, local (this project's entry in the user file) or project
306
+ spec: Any = field(compare=False)
307
+ state: str = ""
308
+
309
+
310
+ def entries(project: str, home: str) -> List[Entry]:
311
+ """Every server entry of the config files phiward reads, one per definition, in file order
312
+ (a file that cannot be read strictly has none here: `problems` names it)."""
313
+ out: List[Entry] = []
314
+ mcp_json = os.path.join(project, ".mcp.json")
315
+ for path in _files(project, home):
316
+ data, _why = _load(path)
317
+ if not isinstance(data, dict):
318
+ continue
319
+ if _same_place(path, mcp_json):
320
+ groups = [("project", data.get("mcpServers"))]
321
+ else:
322
+ groups = [("user", data.get("mcpServers"))]
323
+ projects = data.get("projects") if isinstance(data.get("projects"), dict) else {}
324
+ groups += [("local", e.get("mcpServers")) for k, e in projects.items()
325
+ if isinstance(k, str) and isinstance(e, dict) and _same_place(k, project)]
326
+ for scope, group in groups:
327
+ if isinstance(group, dict):
328
+ out += [Entry(str(n), path, scope, spec, placed_state(spec, project, home))
329
+ for n, spec in group.items()]
330
+ return out
331
+
332
+
333
+ def _changed_step(spec: dict) -> str:
334
+ """What to do about a `changed` entry, by what it sets."""
335
+ keys = _changed_by(spec)
336
+ if keys == ["`cwd`"]:
337
+ return "remove `cwd` and give the server absolute paths"
338
+ if keys == ["`env` PATH"]:
339
+ return "name the command by its full path and remove PATH from `env`"
340
+ return "remove that from the entry"
341
+
342
+
343
+ def where(path: str, scope: str, home: str) -> str:
344
+ """A config file as the operator knows it: `~/.claude.json`, `.mcp.json`."""
345
+ if scope == "project":
346
+ return ".mcp.json"
347
+ h = os.path.join(home, "")
348
+ shown_path = "~/" + path[len(h):] if path.startswith(h) else path
349
+ return shown_path + (", this project" if scope == "local" else "")
350
+
351
+
352
+ def name_states(project: str, home: str) -> Dict[str, set]:
353
+ """name -> the states of its entries (`entry_state`)."""
354
+ out: Dict[str, set] = {}
355
+ for e in entries(project, home):
356
+ out.setdefault(e.name, set()).add(e.state)
357
+ return out
358
+
359
+
360
+ def cannot_wrap_why(states: set) -> str:
361
+ """Why a name whose entries `wrap` cannot change stays not wrapped, or "" when `wrap` can
362
+ change one of them."""
363
+ if "bare" in states:
364
+ return ""
365
+ if "here" in states:
366
+ return "listens on this machine at its URL and runs outside Claude Code"
367
+ if "no-command" in states:
368
+ return "has no command phiward can read"
369
+ if "runner" in states:
370
+ return ("starts phiward through another program (env, uv, uvx, pipx or python -m): "
371
+ + RUNNER_STEP + ", then run `phiward mcp wrap`")
372
+ if "changed" in states:
373
+ return "its entry sets a `cwd` or an `env` key that changes what runs (remove it)"
374
+ return ""
375
+
376
+
377
+ LAUNCHER_NAMES = ("phiward", "agent-guards")
378
+
379
+
380
+ def _safe_path(path: str, project: str = "", inputs=None) -> str:
381
+ """`path` with only the folders the agent cannot write (`service._safe_path_entries`, and
382
+ none inside Claude Code's project, `$CLAUDE_PROJECT_DIR`, also when this runs elsewhere): a
383
+ project's `.venv/bin` or `node_modules/.bin` could hold another `phiward`."""
384
+ from phiward import service
385
+ project = project or os.environ.get("CLAUDE_PROJECT_DIR", "")
386
+ top = os.path.realpath(project) if project else ""
387
+ keep = [e for e in service.path_entries(path, inputs or service.path_inputs())
388
+ if not top or not (os.path.realpath(e) + "/").startswith(top.rstrip("/") + "/")]
389
+ return ":".join(keep)
390
+
391
+
392
+ @functools.lru_cache(maxsize=8)
393
+ def _launchers_on(path: str, project: str, inputs: tuple) -> frozenset:
394
+ safe = _safe_path(path, project, inputs)
395
+ return frozenset(os.path.realpath(p) for p in (shutil.which(n, path=safe)
396
+ for n in LAUNCHER_NAMES) if p)
397
+
398
+
399
+ def _launcher_exes(path: str) -> frozenset:
400
+ """Where the installed `phiward` and its alias lead, found only on the folders of `path` the
401
+ agent cannot write (looked up once per PATH, project and `service.path_inputs()`: a hook
402
+ call may read many entries; the key is what the PATH filter reads, so a changed setting is
403
+ seen at once)."""
404
+ from phiward import service
405
+ return _launchers_on(path, os.environ.get("CLAUDE_PROJECT_DIR", ""), service.path_inputs())
406
+
407
+
408
+ _launcher_exes.cache_clear = _launchers_on.cache_clear # type: ignore[attr-defined]
409
+
410
+
411
+ def _recorded_launchers() -> Optional[frozenset]:
412
+ """The launcher files phiward's install record lists (`selfcheck.launcher_scripts`), or
413
+ None for a source checkout or an editable install, which keep the PATH rule
414
+ (`_launcher_exes`). A record that cannot be read gives no launcher at all."""
415
+ from phiward import selfcheck
416
+ try:
417
+ return selfcheck.launcher_scripts()
418
+ except Exception: # noqa: BLE001 - fail closed: nothing counts as the launcher
419
+ return frozenset()
420
+
421
+
422
+ def _file_id(path: str) -> str:
423
+ """A path with its folders resolved but not its last part: the file an entry names, as the
424
+ record lists it (a link on PATH to it is another file, which another program may replace)."""
425
+ return os.path.join(os.path.realpath(os.path.dirname(path)), os.path.basename(path))
426
+
427
+
428
+ def _is_launcher(path: str) -> bool:
429
+ """Whether an entry's command, an absolute path, is the installed launcher: the file
430
+ phiward's install record lists; without a record, the `phiward` found on the PATH folders
431
+ the agent cannot write."""
432
+ rec = _recorded_launchers()
433
+ if rec is not None:
434
+ return _file_id(path) in rec
435
+ return os.path.realpath(path) in _launcher_exes(os.environ.get("PATH", ""))
436
+
437
+
438
+ def installed_launcher() -> Optional[str]:
439
+ """The installed `phiward` as `wrap` writes it into an entry: the file the install record
440
+ lists; without a record, found on PATH folders the agent cannot write; None when there is
441
+ none."""
442
+ rec = _recorded_launchers()
443
+ if rec is not None:
444
+ return next((p for p in sorted(rec) if os.path.basename(p) == "phiward"), None)
445
+ return shutil.which("phiward", path=_safe_path(os.environ.get("PATH", "")))
446
+
447
+
448
+ # programs that start the words after them as a command (uvx, env, uv run, pipx run, ...): an
449
+ # entry that starts phiward's launcher through one is named and rewritten, never trusted
450
+ _RUNNERS = frozenset({"uvx", "env", "uv", "pipx", "nice", "nohup", "time", "exec", "command",
451
+ "stdbuf", "timeout", "ionice", "chrt", "taskset"})
452
+ # Python options that take the next word as their value
453
+ _PY_VALUE_OPTS = frozenset({"-W", "-X", "-Q", "--check-hash-based-pycs"})
454
+
455
+
456
+ def _launch_tail(cmd: List[str]) -> Optional[List[str]]:
457
+ """The words from `launch` on, for any spelling that starts phiward's launcher: the launcher
458
+ (or the alias) by any path; one started through a runner (`uvx [--from X] phiward launch`,
459
+ `env K=V phiward launch`, `uv run phiward launch`); or a Python whose words before `-m
460
+ phiward` are all its own options. Well formed or not; None for any other command. For naming
461
+ and rewriting an entry, never for trusting one (`_launch_rest`)."""
462
+ if not cmd or not cmd[0]:
463
+ return None
464
+ first = os.path.basename(cmd[0])
465
+ rest: Optional[List[str]] = None
466
+ if first in LAUNCHER_NAMES:
467
+ rest = cmd[1:]
468
+ elif first.startswith("python") and "-m" in cmd[1:]:
469
+ i = cmd.index("-m", 1)
470
+ before, ok, k = cmd[1:i], True, 0
471
+ while k < len(before):
472
+ if not before[k].startswith("-"):
473
+ ok = False
474
+ break
475
+ k += 2 if before[k] in _PY_VALUE_OPTS else 1
476
+ if ok and cmd[i + 1:i + 2] == ["phiward"]:
477
+ rest = cmd[i + 2:]
478
+ elif first in _RUNNERS:
479
+ at = next((k for k in range(1, len(cmd) - 1)
480
+ if os.path.basename(cmd[k]) in LAUNCHER_NAMES and cmd[k + 1] == "launch"),
481
+ None)
482
+ if at is not None:
483
+ rest = cmd[at + 1:]
484
+ return rest if rest is not None and rest[:1] == ["launch"] else None
485
+
486
+
487
+ def _well_formed(rest: Optional[List[str]]) -> bool:
488
+ """`launch [OPTIONS] -- PROGRAM ...`: a `--` and a program after it."""
489
+ return rest is not None and "--" in rest and len(rest) > rest.index("--") + 1
490
+
491
+
492
+ def _launch_rest(cmd: List[str]) -> Optional[List[str]]:
493
+ """What follows the launcher in `phiward launch [OPTIONS] -- PROGRAM ...`, from `launch` on,
494
+ when the command is the launcher file itself (or the alias): never a Python with `-m
495
+ phiward`, which imports the folder it starts in (the project) before phiward. None for any
496
+ other command, or a `launch` without `--` and a program."""
497
+ if not cmd or os.path.basename(cmd[0]) not in LAUNCHER_NAMES:
498
+ return None
499
+ rest = _launch_tail(cmd)
500
+ return rest if _well_formed(rest) else None
501
+
502
+
503
+ def _launch_options(cmd: List[str]) -> List[str]:
504
+ """The options between `launch` and `--` of a well-formed launcher entry ([] otherwise)."""
505
+ rest = _launch_tail(cmd)
506
+ return rest[1:rest.index("--")] if _well_formed(rest) and rest is not None else []
507
+
508
+
509
+ def _exact_options(cmd: List[str]) -> bool:
510
+ """A wrapped entry takes exactly `--entry ID` before `--`: no `--tool`, `--memory` or
511
+ `--report` (an entry the agent or a repository wrote must not carry them into what the
512
+ operator's `wrap` makes trusted; `--report` writes before the launcher confines)."""
513
+ opts = _launch_options(cmd)
514
+ return len(opts) == 2 and opts[0] == "--entry" and bool(ENTRY_ID.fullmatch(opts[1]))
515
+
516
+
517
+ # what a `runner` entry needs (`entry_state`): the words in front of phiward mean something
518
+ # different for each runner, so `wrap` does not guess them
519
+ RUNNER_STEP = "edit the entry so its command is the server program itself"
520
+
521
+
522
+ def _launch_shaped(cmd: List[str]) -> bool:
523
+ """Any spelling that starts phiward's launcher (`_launch_tail`), well formed or not."""
524
+ return _launch_tail(cmd) is not None
525
+
526
+
527
+ ENTRY_ID = re.compile(r"[0-9a-f]{16}")
528
+
529
+
530
+ def entry_id(cmd: List[str]) -> Optional[str]:
531
+ """The id `wrap` gives an entry (`phiward launch --entry ID -- ...`), or None."""
532
+ rest = _launch_rest(cmd)
533
+ if rest is None:
534
+ return None
535
+ opts = rest[1:rest.index("--")]
536
+ for i, o in enumerate(opts[:-1]):
537
+ if o == "--entry" and ENTRY_ID.fullmatch(opts[i + 1]):
538
+ return opts[i + 1]
539
+ return None
540
+
541
+
542
+ def new_entry_id() -> str:
543
+ import secrets
544
+ return secrets.token_hex(8)
545
+
546
+
547
+ def _relaunch_args(cmd: List[str]) -> Tuple[List[str], List[str]]:
548
+ """A launcher entry by the launcher's name, in the one form a wrapped entry has: (`launch
549
+ --entry NEW -- PROGRAM ...`, the options it dropped, any old id aside)."""
550
+ rest = _launch_tail(cmd) or []
551
+ cut = rest.index("--")
552
+ opts, prog = rest[1:cut], rest[cut + 1:]
553
+ dropped: List[str] = []
554
+ i = 0
555
+ while i < len(opts):
556
+ if opts[i] == "--entry":
557
+ i += 2
558
+ continue
559
+ dropped.append(opts[i])
560
+ i += 1
561
+ return ["launch", "--entry", new_entry_id(), "--"] + prog, dropped
562
+
563
+
564
+ def launcher_problem(spec: Any) -> str:
565
+ """For an entry that starts `phiward launch` but is not wrapped: why, as `list` says it
566
+ ("" for any other entry)."""
567
+ cmd = _command(spec) if isinstance(spec, dict) else []
568
+ if not _launch_shaped(cmd):
569
+ return ""
570
+ if not _well_formed(_launch_tail(cmd)):
571
+ return "its `phiward launch` has no `--` and a program after it"
572
+ first = os.path.basename(cmd[0])
573
+ if first not in LAUNCHER_NAMES:
574
+ return (f"it starts phiward through `{shown(first)}`, not as the server program itself: "
575
+ f"{RUNNER_STEP}")
576
+ if not os.path.isabs(cmd[0]):
577
+ return "it names `phiward` without its path"
578
+ if not _is_launcher(cmd[0]):
579
+ return "its `phiward` is not the installed launcher"
580
+ if entry_id(cmd) is None:
581
+ return "it was wrapped without an entry id (an older phiward)"
582
+ if not _exact_options(cmd):
583
+ return ("it has options before `--` that wrapped entries do not take ("
584
+ + " ".join(shown(o) for o in _launch_options(cmd)) + ")")
585
+ return ""
586
+
587
+
588
+ def is_wrapped(cmd: List[str], spec: Optional[dict] = None) -> bool:
589
+ """`phiward launch [OPTIONS] -- PROGRAM ...` (or the alias) with the installed launcher file
590
+ by its full path (`_is_launcher`): only that exact shape counts, not a shell around it, not
591
+ `phiward` by name (Claude Code looks a name up on its PATH, where a folder the agent can
592
+ write may come first), not a Python with `-m phiward` (it imports the project folder first),
593
+ and only when the entry (`spec`) does not change what runs."""
594
+ if not cmd or not cmd[0] or (spec is not None and _changes_what_runs(spec)):
595
+ return False
596
+ if not os.path.isabs(cmd[0]) or _launch_rest(cmd) is None:
597
+ return False
598
+ return _is_launcher(cmd[0]) and (entry_id(cmd) is None or _exact_options(cmd))
599
+
600
+
601
+ def _load(path: str) -> Tuple[Optional[dict], str]:
602
+ """A config file as a dict (`claude_settings.read_json`), or (None, why). A key given twice
603
+ makes it unreadable here: which of two server entries Claude Code starts is then not worth
604
+ trusting, so its servers count as bare."""
605
+ data, why, twice = claude_settings.read_json(path)
606
+ if twice:
607
+ return None, "a key is given twice (" + ", ".join(twice[:3]) + ")"
608
+ return data, why
609
+
610
+
611
+ def _same_place(a: str, b: str) -> bool:
612
+ try:
613
+ x, y = os.path.realpath(os.path.normpath(a)), os.path.realpath(os.path.normpath(b))
614
+ except (TypeError, ValueError): # a NUL in a path: not a place
615
+ return False
616
+ if sys.platform == "darwin":
617
+ x, y = x.casefold(), y.casefold()
618
+ return x == y
619
+
620
+
621
+ def problems(project: str, home: str) -> List[str]:
622
+ """The config files that cannot be read strictly (their servers then count as bare)."""
623
+ out = []
624
+ for path in _files(project, home):
625
+ _d, why = _load(path)
626
+ if why:
627
+ out.append(f"{path}: {why}")
628
+ return out
629
+
630
+
631
+ def _files(project: str, home: str) -> List[str]:
632
+ # the one user file Claude Code reads (`$CLAUDE_CONFIG_DIR/.claude.json` in place of
633
+ # `~/.claude.json` when that is set), and the project's
634
+ files = [user_file(home), os.path.join(project, ".mcp.json")]
635
+ return list(dict.fromkeys(files))
636
+
637
+
638
+ def servers(project: str, home: str, trust_project: bool = True) -> Dict[str, Server]:
639
+ """Every MCP server of the user's and this project's config. A name defined more than once
640
+ is wrapped only when every definition is. A file that cannot be read strictly makes every
641
+ server it may name bare: its names are not known, so a marker records the failure.
642
+ `trust_project` False: a server of the project's `.mcp.json` counts as bare (a repository
643
+ wrote it, and the agent's Bash may rewrite it), and so does every name it defines."""
644
+ found: Dict[str, Server] = {}
645
+ mcp_json = os.path.join(project, ".mcp.json")
646
+ for path in _files(project, home):
647
+ own = trust_project or not _same_place(path, mcp_json)
648
+ data, why = _load(path)
649
+ if not isinstance(data, dict):
650
+ if why:
651
+ found["\0unreadable"] = Server("\0unreadable", False)
652
+ # the names it may hold: read leniently, only to mark them bare
653
+ try:
654
+ with open(path, encoding="utf-8") as fh:
655
+ loose = json.loads(fh.read())
656
+ except (OSError, ValueError):
657
+ loose = None
658
+ for name in _names(loose, project):
659
+ found[name] = Server(name, False)
660
+ continue
661
+ groups = [data.get("mcpServers")]
662
+ projects = data.get("projects") if isinstance(data.get("projects"), dict) else {}
663
+ for key, entry in projects.items():
664
+ if isinstance(key, str) and isinstance(entry, dict) and _same_place(key, project):
665
+ groups.append(entry.get("mcpServers")) # this project's only (local scope)
666
+ for group in groups:
667
+ if not isinstance(group, dict):
668
+ continue
669
+ for name, spec in group.items():
670
+ if not isinstance(spec, dict):
671
+ continue
672
+ remote = own and _is_remote(spec)
673
+ s = Server(str(name), own and (remote or entry_wrapped(spec, project, home)), remote,
674
+ here=_listens_here(spec),
675
+ unwrappable=not _is_remote(spec) and not _has_command(spec),
676
+ untrusted=not own)
677
+ old = found.get(s.name)
678
+ if old is not None:
679
+ # `here`: an entry on this machine keeps the name bare whatever `wrap` does;
680
+ # `unwrappable`: no entry has a command `wrap` could wrap;
681
+ # `untrusted`: any entry of the project's `.mcp.json` (without a source) keeps
682
+ # the name bare, whatever the other entries are
683
+ s = Server(s.name, old.wrapped and s.wrapped, old.remote and s.remote,
684
+ here=old.here or s.here,
685
+ unwrappable=old.unwrappable and s.unwrappable,
686
+ untrusted=old.untrusted or s.untrusted)
687
+ found[s.name] = s
688
+ return found
689
+
690
+
691
+ def _names(data: Any, project: str) -> List[str]:
692
+ out: List[str] = []
693
+ if not isinstance(data, dict):
694
+ return out
695
+ groups = [data.get("mcpServers")]
696
+ projects = data.get("projects") if isinstance(data.get("projects"), dict) else {}
697
+ groups += [e.get("mcpServers") for k, e in projects.items()
698
+ if isinstance(k, str) and isinstance(e, dict) and _same_place(k, project)]
699
+ for g in groups:
700
+ if isinstance(g, dict):
701
+ out += [str(n) for n in g]
702
+ return out
703
+
704
+
705
+ def _tool_prefix(name: str) -> str:
706
+ """The `mcp__<server>__` prefix Claude Code gives a server's tools (other characters as
707
+ `_`)."""
708
+ return "mcp__" + re.sub(r"[^A-Za-z0-9_-]", "_", name) + "__"
709
+
710
+
711
+ def server_of(tool: str, project: str, home: str,
712
+ trust_project: bool = True) -> Optional[Server]:
713
+ """The configured server whose tool `tool` is, by its name only, or None (not an MCP tool, a
714
+ plugin's or managed server, or unknown). Only for a hook input without `mcp_server` (an
715
+ older Claude Code, Copilot): then the hook passes `trust_project` False, since a server of
716
+ the app's own may have any name, `.mcp.json` too. The rest of the name after the server's
717
+ prefix must hold no `__` (else it may be another server's tool, whose name begins the same
718
+ way). When several names give the same prefix, the result is wrapped only if all are."""
719
+ if not tool.startswith("mcp__"):
720
+ return None
721
+ every = servers(project, home, trust_project)
722
+ hits = [s for s in every.values()
723
+ if not s.name.startswith("\0") and tool.startswith(_tool_prefix(s.name))
724
+ and "__" not in tool[len(_tool_prefix(s.name)):]]
725
+ if not hits:
726
+ return None
727
+ unreadable = "\0unreadable" in every # a config file whose servers are not all known
728
+ if len(hits) == 1 and not unreadable:
729
+ return hits[0]
730
+ wrapped = all(s.wrapped for s in hits) and not unreadable
731
+ # the entries of every name the tool may belong to: each needs its own launcher
732
+ specs = tuple(x for s in hits for x in _by_name_specs(s.name, project, home)) if wrapped \
733
+ else ()
734
+ return Server(hits[0].name, wrapped and bool(specs),
735
+ all(s.remote for s in hits) and not unreadable, specs=specs)
736
+
737
+
738
+ # --- by the source Claude Code reports (hook input `mcp_server`, Claude Code 2.1.274 and newer) -----
739
+ #
740
+ # Claude Code names the server and where its definition came from, and uses only the entry of the
741
+ # highest scope (local, project, user, then plugins and connectors). phiward looks the entry up in
742
+ # exactly that scope, by its exact name. Docs: "Base trust decisions on `source` rather than on
743
+ # `name` or the `mcp__<server>__` tool-name prefix"; a configured server never reports `sdk`; an
744
+ # unknown source is a configured one phiward cannot read (bare).
745
+
746
+ MIN_SOURCE_VERSION = (2, 1, 274)
747
+ CONFIG_SOURCES = ("user", "local", "project")
748
+ _PLACEHOLDER = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}")
749
+
750
+
751
+ def _expand(value: Any, env: Dict[str, str]) -> Any:
752
+ """`${VAR}` and `${VAR:-default}` filled in, in every string of an entry, as Claude Code does
753
+ before it starts the server; an unset variable without a default stays as written."""
754
+ if isinstance(value, str):
755
+ def one(m: "re.Match[str]") -> str:
756
+ if m.group(1) in env:
757
+ return env[m.group(1)]
758
+ return m.group(2) if m.group(2) is not None else m.group(0)
759
+ return _PLACEHOLDER.sub(one, value)
760
+ if isinstance(value, list):
761
+ return [_expand(v, env) for v in value]
762
+ if isinstance(value, dict):
763
+ return {k: _expand(v, env) for k, v in value.items()}
764
+ return value
765
+
766
+
767
+ def shown(name: Any) -> str:
768
+ """A server name as a refusal may show it: printable, without backticks, short (the docs:
769
+ for any source other than `sdk`, `name` is untrusted text)."""
770
+ text = re.sub(r"[^\x20-\x7e]", "?", str(name)).replace("`", "'")
771
+ return text[:80] + ("..." if len(text) > 80 else "")
772
+
773
+
774
+ def _user_files(home: str) -> List[str]:
775
+ return [user_file(home)] # the one Claude Code reads
776
+
777
+
778
+ def _scope_specs(source: str, name: str, project: str, home: str
779
+ ) -> Optional[List[Tuple[dict, Dict[str, str]]]]:
780
+ """The entries of `name` in the scope `source` (each with the placeholders it may use), or
781
+ None when a file of that scope cannot be read strictly (then nothing of it is known)."""
782
+ if source == "project":
783
+ places = [(os.path.join(project, ".mcp.json"), ("mcpServers",))]
784
+ elif source == "user":
785
+ places = [(f, ("mcpServers",)) for f in _user_files(home)]
786
+ else:
787
+ places = [(f, ("projects", None, "mcpServers")) for f in _user_files(home)]
788
+ out: List[Tuple[dict, Dict[str, str]]] = []
789
+ for path, keys in places:
790
+ data, why = _load(path)
791
+ if why:
792
+ return None
793
+ for group in _groups(data, keys, project) if data is not None else []:
794
+ if name in group:
795
+ if not isinstance(group[name], dict):
796
+ return None
797
+ out.append((group[name], {}))
798
+ return out
799
+
800
+
801
+ def plugins_file(home: str, env: Optional[Dict[str, str]] = None) -> str:
802
+ return os.path.join(claude_settings.user_dir(home, env), "plugins", "installed_plugins.json")
803
+
804
+
805
+ def _fill_env(project: str, env: Optional[Dict[str, str]] = None) -> Dict[str, str]:
806
+ """What Claude Code fills an entry's `${VAR}` from: the environment, without the hook's own
807
+ plugin variables (the hook may run as a plugin's), with this project."""
808
+ base = os.environ if env is None else env
809
+ out = {k: v for k, v in base.items() if not k.startswith("CLAUDE_PLUGIN_")}
810
+ out["CLAUDE_PROJECT_DIR"] = project
811
+ return out
812
+
813
+
814
+ def _plugin_env(home: str, key: str, root: str) -> Dict[str, str]:
815
+ """The plugin variables Claude Code gives a copy of plugin `key` installed at `root`: its
816
+ folder and its data folder (`~/.claude/plugins/data/<id>`, every character of the id other
817
+ than a letter, digit, `_` or `-` made `-`)."""
818
+ data = os.path.join(os.path.dirname(plugins_file(home)), "data",
819
+ re.sub(r"[^A-Za-z0-9_-]", "-", key))
820
+ return {"CLAUDE_PLUGIN_ROOT": root, "CLAUDE_PLUGIN_DATA": data}
821
+
822
+
823
+ def _plugin_group(root: str) -> Optional[Dict[str, Any]]:
824
+ """The `mcpServers` a plugin installed at `root` declares (its `.mcp.json`, and `mcpServers`
825
+ in its `plugin.json`: an object, or a file relative to the plugin), or None when one cannot
826
+ be read."""
827
+ group: Dict[str, Any] = {}
828
+ data, why = _load(os.path.join(root, ".mcp.json"))
829
+ if why:
830
+ return None
831
+ if data:
832
+ servers = data.get("mcpServers", data)
833
+ if not isinstance(servers, dict):
834
+ return None
835
+ group.update(servers)
836
+ meta, why = _load(os.path.join(root, ".claude-plugin", "plugin.json"))
837
+ if why:
838
+ return None
839
+ inline = (meta or {}).get("mcpServers")
840
+ if isinstance(inline, str):
841
+ path = os.path.normpath(os.path.join(root, inline))
842
+ if not path.startswith(os.path.normpath(root) + os.sep):
843
+ return None
844
+ more, why = _load(path)
845
+ if why or more is None:
846
+ return None
847
+ inline = more.get("mcpServers", more)
848
+ if isinstance(inline, dict):
849
+ for k, v in inline.items():
850
+ if k in group and group[k] != v:
851
+ return None # two different entries for one name: not known which runs
852
+ group[k] = v
853
+ elif inline is not None:
854
+ return None
855
+ return group
856
+
857
+
858
+ _PLUGIN_RANK = {"local": 0, "project": 1} # the more specific install wins; user and others: 2
859
+
860
+
861
+ def _plugin_roots(home: str, env: Dict[str, str], project: str, plugin: str
862
+ ) -> Optional[Dict[str, List[str]]]:
863
+ """registry key (`plugin@market`) -> the install folders of the copies of `plugin` that apply
864
+ to `project`: a copy made for another project (`projectPath`) does not; of the rest, only
865
+ the most specific scope (local, then project, then the others). None when the registry, or
866
+ an entry of this plugin, cannot be read. Other plugins' entries are not looked at."""
867
+ reg, why = _load(plugins_file(home, env))
868
+ if why or not isinstance(reg, dict) or not isinstance(reg.get("plugins"), dict):
869
+ return None
870
+ out: Dict[str, List[str]] = {}
871
+ for key, installs in reg["plugins"].items():
872
+ if not isinstance(key, str) or key.split("@", 1)[0] != plugin:
873
+ continue
874
+ ranked: List[Tuple[int, str]] = []
875
+ for inst in installs if isinstance(installs, list) else [installs]:
876
+ root = inst.get("installPath") if isinstance(inst, dict) else None
877
+ if not isinstance(root, str) or not os.path.isabs(root) or "\0" in root:
878
+ return None
879
+ where = inst.get("projectPath")
880
+ if where is not None and not isinstance(where, str):
881
+ return None
882
+ if where and not _same_place(where, project):
883
+ continue
884
+ scope = inst.get("scope")
885
+ ranked.append((_PLUGIN_RANK.get(scope, 2) if isinstance(scope, str) else 2, root))
886
+ if ranked:
887
+ best = min(r for r, _ in ranked)
888
+ out[key] = list(dict.fromkeys(root for r, root in ranked if r == best))
889
+ return out
890
+
891
+
892
+ def _plugin_specs(name: str, home: str, env: Dict[str, str], project: str = ""
893
+ ) -> Optional[List[Tuple[dict, Dict[str, str]]]]:
894
+ """The entries of a plugin's server (`plugin:<plugin>:<server>`) in every installed copy of
895
+ that plugin that applies to `project`, each with `${CLAUDE_PLUGIN_ROOT}`; None when unknown
896
+ or not readable."""
897
+ parts = name.split(":")
898
+ if len(parts) != 3 or parts[0] != "plugin" or not parts[1] or not parts[2]:
899
+ return None
900
+ plugin, server = parts[1], parts[2]
901
+ keys = _plugin_roots(home, env, project or env.get("CLAUDE_PROJECT_DIR") or os.getcwd(),
902
+ plugin)
903
+ if keys is None:
904
+ return None
905
+ out: List[Tuple[dict, Dict[str, str]]] = []
906
+ for key, roots in keys.items():
907
+ for root in roots:
908
+ group = _plugin_group(root)
909
+ if group is None:
910
+ return None
911
+ if server in group:
912
+ if not isinstance(group[server], dict):
913
+ return None
914
+ out.append((group[server], dict(_plugin_env(home, key, root), **{"\0key": key})))
915
+ return out
916
+
917
+
918
+ def _segment(name: str, source: str) -> str:
919
+ """The server part of its tools' names: `plugin_<plugin>_<server>` for a plugin's."""
920
+ if source == "plugin":
921
+ parts = name.split(":")
922
+ if len(parts) == 3 and parts[0] == "plugin":
923
+ return f"plugin_{parts[1]}_{parts[2]}"
924
+ return name
925
+
926
+
927
+ def classify(mcp_server: Any, tool: str, project: str, home: str,
928
+ env: Optional[Dict[str, str]] = None) -> Server:
929
+ """The server of `tool` as the hook input's `mcp_server` names it, read from exactly that
930
+ source. Bare unless it is found there and every entry for it is wrapped (or remote):
931
+ `claudeai` connectors are remote; `sdk` and every source phiward does not read are bare.
932
+ (The agent cannot rewrite these files during a session: the file tools refuse them, and
933
+ Claude Code's sandbox denies `.mcp.json` and `~/.claude.json` to Bash.)"""
934
+ env = _fill_env(project, env)
935
+ if not isinstance(mcp_server, dict) or not isinstance(mcp_server.get("name"), str):
936
+ return Server("?", False, False, "?")
937
+ name = mcp_server["name"]
938
+ source = mcp_server.get("source") if isinstance(mcp_server.get("source"), str) else "?"
939
+ bare = Server(name, False, False, source)
940
+ prefix = _tool_prefix(_segment(name, source))
941
+ if not tool.startswith(prefix) or "__" in tool[len(prefix):] or not tool[len(prefix):]:
942
+ return bare # the tool is not this server's
943
+ if source == "claudeai":
944
+ return Server(name, True, True, source)
945
+ if source in CONFIG_SOURCES:
946
+ found = _scope_specs(source, name, project, home)
947
+ elif source == "plugin":
948
+ found = _plugin_specs(name, home, env, project)
949
+ else:
950
+ return bare
951
+ if not found:
952
+ return bare
953
+ env["CLAUDE_PROJECT_DIR"] = project
954
+ specs = [_expand(spec, dict(env, **extra)) for spec, extra in found]
955
+ copies = tuple((extra.get("\0key", ""), extra.get("CLAUDE_PLUGIN_ROOT", ""))
956
+ for _spec, extra in found) if source == "plugin" else ()
957
+ if not all(isinstance(s, dict) for s in specs):
958
+ return bare
959
+ try:
960
+ texts = tuple(json.dumps(s, sort_keys=True) for s in specs)
961
+ remote = all(_is_remote(s) for s in specs)
962
+ # a configured entry by the one answer (its own id, not copied); a plugin's by its shape
963
+ wrapped = remote or all(entry_wrapped(s, project, home) if source in CONFIG_SOURCES
964
+ else is_wrapped(_command(s), s) for s in specs)
965
+ here = any(_listens_here(s) for s in specs)
966
+ except (TypeError, ValueError, OSError):
967
+ return bare # an entry phiward cannot read
968
+ return Server(name, wrapped, remote, source, texts, here=here, copies=copies,
969
+ unwrappable=not remote and not any(_has_command(x) for x in specs))
970
+
971
+
972
+ # --- the launcher's record: which wrapped servers really run ------------------------------------
973
+ #
974
+ # Claude Code starts its servers when a session starts (and again on `/mcp` reconnect): a server
975
+ # wrapped in the config after that still runs bare. So the config alone is not enough. Each
976
+ # `phiward launch` writes a record of its own process (pid, start time, parent, a hash of what it
977
+ # was told to run) in a folder the agent cannot write (a guard file; the confined child cannot
978
+ # reach it either), and removes it when it ends. The hook trusts a wrapped entry only when a live
979
+ # launcher of that command is a child of the hook's own Claude Code process: the nearest of the
980
+ # hook's ancestors that has launcher children. A launcher the agent starts from Bash has the
981
+ # sandboxed shell as its parent, never an ancestor of the hook, and could not write the record.
982
+
983
+ LAUNCHED_MAX = 512
984
+
985
+
986
+ def backups_root(home: str) -> str:
987
+ """Where `wrap` keeps its backups: phiward's own folder, a guard file (config.guard_files)."""
988
+ return os.path.join(home, ".phiward", "backups")
989
+
990
+
991
+ def backup_dir(path: str, home: str) -> str:
992
+ """The backups of one config file: `original` (before phiward first changed it, never
993
+ overwritten) and `last` (before the latest change), in a folder named by the file and a hash
994
+ of where it really is."""
995
+ import hashlib
996
+ real = os.path.realpath(path)
997
+ tag = hashlib.sha256(real.encode("utf-8", "surrogatepass")).hexdigest()[:12]
998
+ return os.path.join(backups_root(home), f"{os.path.basename(path).lstrip('.')}-{tag}")
999
+
1000
+
1001
+ def _backup_folder(path: str, home: str) -> Tuple[str, str]:
1002
+ """The backup folder of `path`, made private (0700) and checked: (folder, "") or ("", why).
1003
+ Never through a link, and only folders of the operator's."""
1004
+ root = backups_root(home)
1005
+ folder = backup_dir(path, home)
1006
+ for d in (os.path.dirname(root), root, folder):
1007
+ try:
1008
+ os.mkdir(d, 0o700)
1009
+ except FileExistsError:
1010
+ pass
1011
+ except OSError as exc:
1012
+ return "", f"{d} cannot be made ({exc.strerror})"
1013
+ try:
1014
+ st = os.lstat(d)
1015
+ except OSError as exc:
1016
+ return "", f"{d} cannot be read ({exc.strerror})"
1017
+ if not stat.S_ISDIR(st.st_mode) or st.st_uid != os.getuid():
1018
+ return "", f"{d} is a link or not your own folder"
1019
+ try:
1020
+ os.chmod(root, 0o700)
1021
+ os.chmod(folder, 0o700)
1022
+ except OSError as exc:
1023
+ return "", f"{folder} cannot be made private ({exc.strerror})"
1024
+ return folder, ""
1025
+
1026
+
1027
+ def launched_dir(env: Optional[Dict[str, str]] = None) -> str:
1028
+ env = os.environ if env is None else env
1029
+ return os.path.join(pathid.home(env), ".phiward", "launched")
1030
+
1031
+
1032
+ def _private_folder(folder: str) -> bool:
1033
+ """`folder` and the one above it (`~/.phiward`) are real folders of the operator's, not
1034
+ links, and `folder` is private: the records are trusted only there."""
1035
+ try:
1036
+ for path in (os.path.dirname(folder), folder):
1037
+ st = os.lstat(path)
1038
+ if not stat.S_ISDIR(st.st_mode) or st.st_uid != os.getuid():
1039
+ return False
1040
+ return not os.lstat(folder).st_mode & 0o077
1041
+ except OSError:
1042
+ return False
1043
+
1044
+
1045
+ def plugin_hash(root: Optional[str]) -> str:
1046
+ """What the record keeps of the launcher's `CLAUDE_PLUGIN_ROOT` (Claude Code exports it to a
1047
+ plugin's stdio server, never to a configured one's): "" without one."""
1048
+ import hashlib
1049
+ if not root:
1050
+ return ""
1051
+ try:
1052
+ root = os.path.realpath(root) # `/var` and `/private/var`, a trailing `/`
1053
+ except (TypeError, ValueError):
1054
+ return "?"
1055
+ return hashlib.sha256(root.encode("utf-8", "surrogatepass")).hexdigest()
1056
+
1057
+
1058
+ def _launcher_owner(env: Dict[str, str]) -> str:
1059
+ """The record's `plugin` for a launcher with environment `env`: "" only when it has no
1060
+ plugin variable at all (a configured server's); a plugin's folder hash; "?" (trusted for
1061
+ nothing) when a plugin variable is there but the folder is not."""
1062
+ if not any(k.startswith("CLAUDE_PLUGIN_") for k in env):
1063
+ return ""
1064
+ return plugin_hash(env.get("CLAUDE_PLUGIN_ROOT")) or "?"
1065
+
1066
+
1067
+ def launch_hash(argv: List[str]) -> str:
1068
+ """What a launcher was told to run (its arguments after `launch`), as one hash."""
1069
+ import hashlib
1070
+ return hashlib.sha256(json.dumps([str(a) for a in argv]).encode()).hexdigest()
1071
+
1072
+
1073
+ def _spec_hash(spec: dict) -> Optional[str]:
1074
+ """The launch hash of a wrapped entry (filled in), or None when it is not wrapped."""
1075
+ cmd = _command(spec)
1076
+ if not is_wrapped(cmd, spec):
1077
+ return None
1078
+ return launch_hash((_launch_rest(cmd) or [])[1:])
1079
+
1080
+
1081
+ def view_hash(env: Dict[str, str], cwd: str) -> str:
1082
+ """A hash of what a launch profile is built from, derived as `launch` derives it: the hidden
1083
+ list, the protected roots and patterns. The launcher records it; the hook trusts the record
1084
+ only when its own is the same, so an entry's `env` (`KRB5CCNAME`, `KRB5_CONFIG`) or a change
1085
+ since the start cannot leave a wrapped server with a narrower profile. "" when the config
1086
+ cannot be used."""
1087
+ import hashlib
1088
+ from phiward import config, hidden
1089
+ try:
1090
+ cfg = config.load(cwd, env=env)
1091
+ if cfg.problem:
1092
+ return ""
1093
+ data = {"hidden": sorted(hidden.credentials(env, cfg)), "roots": sorted(cfg.all_roots),
1094
+ "patterns": sorted(cfg.patterns)}
1095
+ except (OSError, ValueError):
1096
+ return ""
1097
+ return hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest()
1098
+
1099
+
1100
+ def record_launch(argv: List[str]) -> Optional[str]:
1101
+ """Called by `phiward launch` before it starts the tool: this process's record, or None when
1102
+ it cannot be written (then the server is just not trusted as wrapped). Never raises."""
1103
+ from phiward import procinfo, safeio
1104
+ try:
1105
+ me = os.getpid()
1106
+ got = procinfo.info(me)
1107
+ if got is None:
1108
+ return None
1109
+ folder = launched_dir()
1110
+ os.makedirs(folder, mode=0o700, exist_ok=True)
1111
+ st = os.lstat(folder)
1112
+ if not stat.S_ISDIR(st.st_mode) or st.st_uid != os.getuid():
1113
+ return None
1114
+ os.chmod(folder, 0o700)
1115
+ if not _private_folder(folder):
1116
+ return None
1117
+ _prune(folder)
1118
+ path = os.path.join(folder, f"{me}.json")
1119
+ safeio.write_new(path, json.dumps({"pid": me, "ppid": got[0], "start": got[1],
1120
+ "argv": launch_hash(argv),
1121
+ "plugin": _launcher_owner(dict(os.environ)),
1122
+ "view": view_hash(dict(os.environ), os.getcwd())}),
1123
+ mode=0o600)
1124
+ return path
1125
+ except (OSError, ValueError):
1126
+ return None
1127
+
1128
+
1129
+ def end_launch(path: Optional[str]) -> None:
1130
+ if path:
1131
+ try:
1132
+ os.unlink(path)
1133
+ except OSError:
1134
+ pass
1135
+
1136
+
1137
+ def _records(folder: str) -> List[dict]:
1138
+ """The records of live launchers: plain private files of the operator's, whose process still
1139
+ runs with the same parent and start time."""
1140
+ from phiward import procinfo, safeio
1141
+ out: List[dict] = []
1142
+ try:
1143
+ if not _private_folder(folder):
1144
+ return out
1145
+ # records only count toward the cap (a writer's hidden temp name sorts first)
1146
+ names = sorted(n for n in os.listdir(folder)
1147
+ if n.endswith(".json") and not n.startswith("."))[:LAUNCHED_MAX]
1148
+ except OSError:
1149
+ return out
1150
+ for name in names:
1151
+ if not name.endswith(".json"):
1152
+ continue
1153
+ path = os.path.join(folder, name)
1154
+ try:
1155
+ st = os.lstat(path)
1156
+ if not stat.S_ISREG(st.st_mode) or st.st_uid != os.getuid() or st.st_mode & 0o077:
1157
+ continue
1158
+ rec = json.loads(safeio.read_text(path, limit=4096))
1159
+ except (OSError, ValueError):
1160
+ continue
1161
+ if not isinstance(rec, dict) or name != f"{rec.get('pid')}.json":
1162
+ continue
1163
+ pid, ppid, start = rec.get("pid"), rec.get("ppid"), rec.get("start")
1164
+ if not all(isinstance(x, int) and not isinstance(x, bool) for x in (pid, ppid, start)):
1165
+ continue
1166
+ if procinfo.info(pid) != (ppid, start) or not isinstance(rec.get("argv"), str):
1167
+ continue
1168
+ if not isinstance(rec.get("plugin"), str) or not isinstance(rec.get("view"), str):
1169
+ continue # a record without them (an older or development build's): trusted for nothing
1170
+ out.append(rec)
1171
+ return out
1172
+
1173
+
1174
+ def _prune(folder: str) -> None:
1175
+ """Remove the records of launchers that are gone."""
1176
+ from phiward import procinfo
1177
+ try:
1178
+ names = os.listdir(folder)
1179
+ except OSError:
1180
+ return
1181
+ import time
1182
+ for name in names[:4 * LAUNCHED_MAX]:
1183
+ path = os.path.join(folder, name)
1184
+ if not re.fullmatch(r"[0-9]+\.json", name):
1185
+ # another launcher's record being written (safeio's temporary name): only when old
1186
+ try:
1187
+ alive = time.time() - os.lstat(path).st_mtime < 60
1188
+ except OSError:
1189
+ continue
1190
+ else:
1191
+ try:
1192
+ with open(path, encoding="utf-8") as fh:
1193
+ rec = json.loads(fh.read(4096))
1194
+ alive = procinfo.info(rec["pid"]) == (rec["ppid"], rec["start"])
1195
+ except (OSError, ValueError, KeyError, TypeError):
1196
+ alive = False
1197
+ if not alive:
1198
+ try:
1199
+ os.unlink(path)
1200
+ except OSError:
1201
+ pass
1202
+
1203
+
1204
+ def _hash_of(spec: Any, env: Dict[str, str]) -> Optional[str]:
1205
+ """The launch hash of an entry filled in with `env`; None when not wrapped or malformed."""
1206
+ if not isinstance(spec, dict):
1207
+ return None
1208
+ try:
1209
+ return _spec_hash(_expand(spec, env))
1210
+ except (TypeError, ValueError, OSError):
1211
+ return None
1212
+
1213
+
1214
+ def _segments(text: str) -> List[List[str]]:
1215
+ """The simple commands of a shell text (`sh -c "..."`), as words, split at `;`, `&&`, `|`."""
1216
+ try:
1217
+ lex = shlex.shlex(text, posix=True, punctuation_chars=True)
1218
+ lex.whitespace_split = True
1219
+ words = list(lex)
1220
+ except ValueError:
1221
+ words = text.split()
1222
+ out: List[List[str]] = [[]]
1223
+ for w in words:
1224
+ if w and all(c in "();<>|&" for c in w):
1225
+ out.append([])
1226
+ else:
1227
+ out[-1].append(w)
1228
+ return [seg for seg in out if seg]
1229
+
1230
+
1231
+ def _launch_tails(words: List[str], depth: int = 0) -> List[List[str]]:
1232
+ """What follows each `launch` word, in the words and in any shell text among them (`nice
1233
+ phiward launch -- srv`, `env K=V phiward launch ...`, `sh -c "exec phiward launch -- srv"`)."""
1234
+ out = [words[i + 1:] for i in range(1, len(words)) if words[i] == "launch"]
1235
+ if depth < 3:
1236
+ for w in words:
1237
+ if any(c in w for c in " \t\n;&|"):
1238
+ for seg in _segments(w):
1239
+ out += _launch_tails(seg, depth + 1)
1240
+ return out
1241
+
1242
+
1243
+ def _twin_hashes(spec: Any, env: Dict[str, str]) -> set:
1244
+ """The launch hashes of an entry that may start a launcher, filled in with `env`, whatever
1245
+ else the entry sets and however it starts it (directly, through `nice` or `env`, or in a
1246
+ shell's text): for counting the entries that share a command. An entry that changes what
1247
+ runs (a `cwd`, an `env` key) or starts the launcher through another program is bare itself,
1248
+ yet its launcher has the same command and could vouch for another entry. Counting more than
1249
+ run only asks for more launchers (never trusts more)."""
1250
+ if not isinstance(spec, dict):
1251
+ return set()
1252
+ try:
1253
+ cmd = _command(_expand(spec, env))
1254
+ except (TypeError, ValueError, OSError):
1255
+ return set()
1256
+ return {launch_hash(t) for t in _launch_tails(cmd)}
1257
+
1258
+
1259
+ def _strings(data: Any) -> List[str]:
1260
+ """Every string of a JSON value (decoded: an escape cannot hide one), keys too."""
1261
+ out: List[str] = []
1262
+ stack = [data]
1263
+ while stack:
1264
+ d = stack.pop()
1265
+ if isinstance(d, str):
1266
+ out.append(d)
1267
+ elif isinstance(d, dict):
1268
+ stack += list(d.keys()) + list(d.values())
1269
+ elif isinstance(d, list):
1270
+ stack += d
1271
+ return out
1272
+
1273
+
1274
+ _STRINGS_CACHE: Dict[str, Tuple[tuple, List[str]]] = {}
1275
+
1276
+
1277
+ def _server_strings(path: str) -> List[str]:
1278
+ """The strings of every `mcpServers` object of a config file (the top-level one and every
1279
+ project's), decoded; cached by the file's identity, size and change time, so one hook call
1280
+ reads a large `.claude.json` once."""
1281
+ try:
1282
+ st = os.stat(path)
1283
+ except OSError:
1284
+ return []
1285
+ key = (st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns)
1286
+ hit = _STRINGS_CACHE.get(path)
1287
+ if hit and hit[0] == key:
1288
+ return hit[1]
1289
+ data, _why = _load(path)
1290
+ groups: List[Any] = []
1291
+ if isinstance(data, dict):
1292
+ groups.append(data.get("mcpServers"))
1293
+ projects = data.get("projects")
1294
+ if isinstance(projects, dict):
1295
+ groups += [e.get("mcpServers") for e in projects.values() if isinstance(e, dict)]
1296
+ out = _strings([g for g in groups if isinstance(g, dict)])
1297
+ _STRINGS_CACHE[path] = (key, out)
1298
+ return out
1299
+
1300
+
1301
+ def id_count(eid: str, project: str, home: str) -> int:
1302
+ """How often an entry id occurs in the server entries of the config files Claude Code reads
1303
+ (every scope, every project's part of the user file): 1 for an entry no other copies. Only
1304
+ `mcpServers` objects count: an id in a prompt history the file also holds is no copy."""
1305
+ seen, n = set(), 0
1306
+ for path in _files(project, home):
1307
+ real = os.path.realpath(path)
1308
+ if real in seen:
1309
+ continue
1310
+ seen.add(real)
1311
+ n += sum(x.count(eid) for x in _server_strings(path))
1312
+ return n
1313
+
1314
+
1315
+ def vouched(server: Server, project: str, home: str) -> bool:
1316
+ """Whether live launchers, children of this hook's Claude Code process, run the command of
1317
+ `server`'s wrapped entry. A configured server needs, for each of its entries, a launcher
1318
+ without a plugin folder started with that entry's own id (`entry_id`), an id no other
1319
+ string of the config files holds. A plugin's server needs, for each registry key, a launcher of one of its copies,
1320
+ with that copy's folder, one for each server of the copy with that command."""
1321
+ from phiward import procinfo
1322
+ specs: List[dict] = []
1323
+ for text in server.specs:
1324
+ try:
1325
+ specs.append(json.loads(text))
1326
+ except ValueError:
1327
+ return False
1328
+ if not specs:
1329
+ return False
1330
+ hashes = [_hash_of(s, {}) for s in specs]
1331
+ if None in hashes:
1332
+ return False
1333
+ live = _records(launched_dir())
1334
+ parents = {r["ppid"] for r in live}
1335
+ claude = next((a for a in procinfo.ancestors(depth=4) if a in parents), None)
1336
+ if claude is None:
1337
+ return False
1338
+ # the same profile as this hook would build: from the same hidden list, roots and patterns
1339
+ own = view_hash(dict(os.environ), project)
1340
+ mine = [(r["argv"], r["plugin"]) for r in live
1341
+ if r["ppid"] == claude and own and r["view"] == own]
1342
+ if not server.copies:
1343
+ # each entry has its own id, so its own launch hash: a launcher vouches for the one
1344
+ # entry whose id it was started with, and an id found twice (a copy of the entry, any
1345
+ # wrapper around it) is trusted for nothing
1346
+ for spec in specs:
1347
+ eid = entry_id(_command(spec))
1348
+ if eid is None or id_count(eid, project, home) != 1:
1349
+ return False
1350
+ return all(mine.count((h, "")) >= 1 for h in set(hashes))
1351
+ if len(server.copies) != len(hashes):
1352
+ return False
1353
+ by_key: Dict[str, List[Tuple[str, str]]] = {}
1354
+ for h, (key, root) in zip(hashes, server.copies):
1355
+ if not root:
1356
+ return False
1357
+ by_key.setdefault(key, []).append((h, root))
1358
+ for key, options in by_key.items():
1359
+ # filled in exactly as Claude Code fills it: the folder as the registry has it, the data
1360
+ # folder without a trailing `/` (another spelling may name another file)
1361
+ if not any(mine.count((h, plugin_hash(root))) >= _in_copy(root, h, dict(
1362
+ _fill_env(project), **_plugin_env(home, key, root))) for h, root in options):
1363
+ return False
1364
+ return True
1365
+
1366
+
1367
+ def _in_copy(root: str, h: str, env: Dict[str, str]) -> float:
1368
+ """How many servers of the plugin copy at `root` run the command of launch hash `h`, filled
1369
+ in with `env` (at least 1); infinite when the copy cannot be read."""
1370
+ group = _plugin_group(root)
1371
+ if group is None:
1372
+ return float("inf")
1373
+ n = sum(1 for spec in group.values() if h in _twin_hashes(spec, env))
1374
+ return max(1, n)
1375
+
1376
+
1377
+ def _by_name_specs(name: str, project: str, home: str) -> Tuple[str, ...]:
1378
+ """The entries of `name` in the operator's own scopes (user, local), filled in: for a hook
1379
+ input without `mcp_server`."""
1380
+ env = _fill_env(project)
1381
+ out: List[str] = []
1382
+ for scope in ("user", "local"):
1383
+ for spec, _extra in _scope_specs(scope, name, project, home) or []:
1384
+ out.append(json.dumps(_expand(spec, env), sort_keys=True))
1385
+ return tuple(out)
1386
+
1387
+
1388
+ def trusted(server: Optional[Server], project: str, home: str) -> Optional[Server]:
1389
+ """`server` as the hook may trust it: a remote server as it is; a wrapped one only when a
1390
+ live launcher of its command runs for this Claude Code (`vouched`)."""
1391
+ if server is None or not server.wrapped or server.remote:
1392
+ return server
1393
+ if not server.specs:
1394
+ server = replace(server, specs=_by_name_specs(server.name, project, home))
1395
+ return server if vouched(server, project, home) else replace(server, wrapped=False)
1396
+
1397
+
1398
+ # --- `phiward mcp wrap|unwrap|list`: the operator's command ----------------------------------------
1399
+
1400
+ USAGE = ("Run your local MCP servers in phiward's kernel profile (wrap), or as they were (unwrap);\n"
1401
+ "list says which are wrapped and the command for each that is not.\n"
1402
+ "usage: phiward mcp wrap NAME...|--all [--yes|-y]\n"
1403
+ " phiward mcp unwrap NAME... [--yes|-y] (only in your own terminal, even with "
1404
+ "--yes)\n"
1405
+ " phiward mcp list\n")
1406
+ _FLAGS = {"wrap": ("--yes", "-y", "--all"), "unwrap": ("--yes", "-y"), "list": ()}
1407
+
1408
+
1409
+ def _places(project: str, home: str) -> List[tuple]:
1410
+ """(file, key path) of each `mcpServers` object phiward may change: the user's and this
1411
+ project's (local scope) in ~/.claude.json, and the project's .mcp.json."""
1412
+ user = user_file(home)
1413
+ return [(user, ("mcpServers",)), (user, ("projects", None, "mcpServers")),
1414
+ (os.path.join(project, ".mcp.json"), ("mcpServers",))]
1415
+
1416
+
1417
+ def _groups(data: Any, keys: tuple, project: str) -> List[dict]:
1418
+ """The `mcpServers` objects at `keys`; None there stands for every project key that names
1419
+ this project (in any spelling)."""
1420
+ level = [data]
1421
+ for k in keys:
1422
+ nxt = []
1423
+ for d in level:
1424
+ if not isinstance(d, dict):
1425
+ continue
1426
+ if k is None:
1427
+ nxt += [v for key, v in d.items() if isinstance(key, str) and _same_place(key, project)]
1428
+ else:
1429
+ nxt.append(d.get(k))
1430
+ level = nxt
1431
+ return [g for g in level if isinstance(g, dict)]
1432
+
1433
+
1434
+ def _wrapped_spec(spec: dict, exe: str) -> dict:
1435
+ new = dict(spec)
1436
+ new["command"] = exe
1437
+ new["args"] = ["launch", "--entry", new_entry_id(), "--"] + _command(spec)
1438
+ return new
1439
+
1440
+
1441
+ def _unwrapped_spec(spec: dict) -> Optional[dict]:
1442
+ cmd = _command(spec)
1443
+ if not _well_formed(_launch_tail(cmd)) or os.path.basename(cmd[0]) not in LAUNCHER_NAMES:
1444
+ # any `phiward launch -- PROGRAM` by the launcher's name (another path too); a runner's
1445
+ # words would be lost (`entry_state` `runner`: the operator edits it)
1446
+ return None
1447
+ inner = cmd[cmd.index("--") + 1:]
1448
+ new = dict(spec)
1449
+ new["command"], new["args"] = inner[0], inner[1:]
1450
+ return new
1451
+
1452
+
1453
+ def _say(cmd: List[str]) -> str:
1454
+ """A command line as the operator reads it: each word quoted, control characters shown as
1455
+ escapes (an entry from a repository's `.mcp.json` must not steer the terminal)."""
1456
+ return " ".join(shlex.quote(re.sub(r"[\x00-\x1f\x7f-\x9f]", "?", str(w))) for w in cmd)
1457
+
1458
+
1459
+ def entry_text(e: Entry, home: str, others: List[Entry] = ()) -> str:
1460
+ """What one entry is, and what to do about it, in a line of `mcp list` (`others`: the other
1461
+ entries of the same name)."""
1462
+ name = shown(e.name)
1463
+ if e.state == "wrapped":
1464
+ return "wrapped"
1465
+ if e.state == "copied":
1466
+ return (f"not wrapped: its entry id is also in another entry (a copy), so a launcher "
1467
+ f"cannot tell them apart; `phiward mcp wrap {name}` gives it an id of its own")
1468
+ if e.state == "runner":
1469
+ return "not wrapped: " + launcher_problem(e.spec) + f", then run `phiward mcp wrap {name}`"
1470
+ why = launcher_problem(e.spec) if e.state == "bare" else ""
1471
+ if why and not _well_formed(_launch_tail(_command(e.spec))):
1472
+ return f"not wrapped: {why}; fix the entry, or remove it and add the server again"
1473
+ if why:
1474
+ return (f"not wrapped: {why}; `phiward mcp wrap {name}` writes the installed launcher's "
1475
+ "full path")
1476
+ if e.state == "remote":
1477
+ if isinstance(e.spec, dict) and e.spec.get("headersHelper"):
1478
+ return ("remote, but its `headersHelper` runs a command here with your rights each "
1479
+ "time Claude Code connects: keep that command a file no session can write")
1480
+ return "remote (runs nothing here)"
1481
+ gateway = "; its command tools may make only gateway calls"
1482
+ if e.state == "here":
1483
+ url = e.spec.get("url") if isinstance(e.spec, dict) else ""
1484
+ return (f"not wrapped: listens on this machine ({shown(url)}) and runs outside Claude "
1485
+ "Code, so it cannot be wrapped" + gateway)
1486
+ if e.state == "no-command":
1487
+ return "not wrapped: no command phiward can read, so it cannot be wrapped" + gateway
1488
+ if e.state == "changed":
1489
+ return ("not wrapped: wrapped, but its entry sets " + ", ".join(_changed_by(e.spec)) +
1490
+ ", which changes what runs; " + _changed_step(e.spec))
1491
+ text = f"not wrapped (runs with your rights): `phiward mcp wrap {name}`"
1492
+ stuck = [o for o in others if o.state in ("here", "no-command")]
1493
+ if stuck:
1494
+ text += (f"; the name stays not wrapped while its entry in "
1495
+ f"{where(stuck[0].path, stuck[0].scope, home)} cannot be wrapped")
1496
+ return text
1497
+
1498
+
1499
+ def _list(project: str, home: str) -> int:
1500
+ found = entries(project, home)
1501
+ for why in problems(project, home):
1502
+ print(f"{why}: its servers count as not wrapped until it can be read")
1503
+ if not found:
1504
+ if not problems(project, home):
1505
+ print(f"no MCP servers in {where(user_file(home), 'user', home)} or ./.mcp.json")
1506
+ return 0
1507
+ by_name: Dict[str, List[Entry]] = {}
1508
+ for e in found:
1509
+ by_name.setdefault(e.name, []).append(e)
1510
+ for name in sorted(by_name):
1511
+ group = by_name[name]
1512
+ for e in group:
1513
+ others = [o for o in group if o is not e]
1514
+ print(f"{shown(name)} ({where(e.path, e.scope, home)}): {entry_text(e, home, others)}")
1515
+ return 0
1516
+
1517
+
1518
+ def main(argv: List[str]) -> int:
1519
+ import json
1520
+ from phiward import safeio
1521
+ if "-h" in argv or "--help" in argv:
1522
+ sys.stdout.write(USAGE)
1523
+ return 0
1524
+ if not argv or argv[0] not in ("wrap", "unwrap", "list"):
1525
+ sys.stderr.write(USAGE)
1526
+ return 2
1527
+ what, rest = argv[0], argv[1:]
1528
+ odd = [a for a in rest if a.startswith("-") and a not in _FLAGS[what]]
1529
+ if odd:
1530
+ sys.stderr.write(f"mcp {what}: unknown option {odd[0]}\n" + USAGE)
1531
+ return 2
1532
+ yes = "--yes" in rest or "-y" in rest
1533
+ names = [a for a in rest if not a.startswith("-")]
1534
+ every = "--all" in rest
1535
+ home = pathid.home()
1536
+ project = os.getcwd()
1537
+ if what == "list":
1538
+ return _list(project, home)
1539
+ try:
1540
+ tty = sys.stdin.isatty()
1541
+ except (AttributeError, ValueError):
1542
+ tty = False
1543
+ if what == "unwrap" and not tty:
1544
+ sys.stderr.write("mcp unwrap: run it in your own terminal (unwrapping gives the server "
1545
+ "your full rights). Nothing was changed.\n")
1546
+ return 2
1547
+ if not names and not every:
1548
+ sys.stderr.write(USAGE)
1549
+ return 2
1550
+ exe = installed_launcher()
1551
+ if what == "wrap" and not exe:
1552
+ if _recorded_launchers() is not None:
1553
+ sys.stderr.write("mcp wrap: phiward's install record lists no `phiward` launcher; "
1554
+ "reinstall it (uv tool install, pipx). Nothing was changed.\n")
1555
+ elif shutil.which("phiward"):
1556
+ sys.stderr.write("mcp wrap: phiward is found only in a PATH folder that the agent "
1557
+ "or another account can write (a project's `.venv/bin`, a "
1558
+ "group-writable folder), so it cannot be the launcher; install it "
1559
+ "with uv tool or pipx, or make its folder writable by you alone "
1560
+ "(`phiward doctor` names the folders phiward does not search). "
1561
+ "Nothing was changed.\n")
1562
+ else:
1563
+ sys.stderr.write("mcp wrap: phiward is not on PATH; install it (uv tool, pipx) so "
1564
+ "Claude Code can start `phiward launch`. Nothing was changed.\n")
1565
+ return 2
1566
+ known = servers(project, home)
1567
+ for n in names:
1568
+ if n not in known:
1569
+ sys.stderr.write(f"mcp {what}: no MCP server named {n} in ~/.claude.json or "
1570
+ ".mcp.json. Nothing was changed.\n")
1571
+ return 2
1572
+ changes: Dict[str, tuple] = {} # file -> (before text, data, [lines])
1573
+ env_keys: List[str] = []
1574
+ # a file that is a link or not a plain file is read where it leads, and never written: only
1575
+ # one that holds an entry to change stops the command (below)
1576
+ odd = set()
1577
+ twice: Dict[str, List[str]] = {} # a file with a key given twice is never rewritten
1578
+ for path, keys in _places(project, home):
1579
+ if os.path.islink(path) or (os.path.lexists(path) and not os.path.isfile(path)):
1580
+ odd.add(path)
1581
+ if path in changes:
1582
+ text, data, lines = changes[path]
1583
+ else:
1584
+ try:
1585
+ text = safeio.read_text(path, limit=64 * 1024 * 1024, follow=path in odd)
1586
+ twice[path] = claude_settings.read_json(path)[2]
1587
+ data = json.loads(text)
1588
+ except FileNotFoundError:
1589
+ continue
1590
+ except (OSError, ValueError) as exc:
1591
+ sys.stderr.write(f"mcp {what}: {path} cannot be read ({type(exc).__name__}). "
1592
+ "Nothing was changed.\n")
1593
+ return 3
1594
+ lines = []
1595
+ found_groups = _groups(data, keys, project)
1596
+ if not found_groups:
1597
+ changes.setdefault(path, (text, data, lines))
1598
+ continue
1599
+ scope = ("project" if keys == ("mcpServers",) and path.endswith(".mcp.json") else
1600
+ "local" if keys[0] == "projects" else "user")
1601
+ for group in found_groups:
1602
+ for name, spec in list(group.items()):
1603
+ if not isinstance(spec, dict) or not (every or name in names):
1604
+ continue
1605
+ st = placed_state(spec, project, home)
1606
+ at = f"{shown(name)} ({where(path, scope, home)})"
1607
+ if st == "remote":
1608
+ print(f"{at}: remote (runs nothing here); left as it is")
1609
+ continue
1610
+ if st == "runner":
1611
+ print(f"{at}: {entry_text(Entry(name, path, scope, spec, st), home)}; left "
1612
+ "as it is")
1613
+ continue
1614
+ if st in ("here", "no-command"):
1615
+ if what != "wrap":
1616
+ print(f"{at}: not wrapped; left as it is")
1617
+ else:
1618
+ print(f"{at}: {entry_text(Entry(name, path, scope, spec, st), home)}; "
1619
+ "left as it is")
1620
+ continue
1621
+ cmd = _command(spec)
1622
+ if what == "wrap" and st == "bare" and launcher_problem(spec) and \
1623
+ not _well_formed(_launch_tail(cmd)):
1624
+ print(f"{at}: not wrapped: {launcher_problem(spec)}; left as it is (fix the "
1625
+ "entry)")
1626
+ continue
1627
+ if what == "wrap" and (st == "copied" or st == "bare" and launcher_problem(spec)):
1628
+ # its launcher by name, or one that is not the installed phiward: the
1629
+ # installed one's full path, not a second wrap
1630
+ new = dict(spec)
1631
+ new["command"], (new["args"], dropped) = exe, _relaunch_args(cmd)
1632
+ group[name] = new
1633
+ lines.append(f" {shown(name)} ({os.path.basename(path)}): {_say(cmd)}\n"
1634
+ f" -> {_say(_command(new))}")
1635
+ if dropped:
1636
+ lines.append(f" dropped: {_say(dropped)} (wrapped entries do not take "
1637
+ "options)")
1638
+ continue
1639
+ if what == "wrap" and st == "wrapped":
1640
+ print(f"{at}: wrapped already")
1641
+ continue
1642
+ if what == "wrap" and st == "changed":
1643
+ print(f"{at}: runs under `phiward launch`, but its entry sets "
1644
+ + ", ".join(_changed_by(spec)) + ", which changes what runs: phiward "
1645
+ "counts it as not wrapped until you remove that from the entry")
1646
+ continue
1647
+ # the installed launcher's full path in every file: by name, a folder on PATH
1648
+ # the agent can write (a project's `.venv/bin`) could supply another one
1649
+ new = _wrapped_spec(spec, exe or "") if what == "wrap" else _unwrapped_spec(spec)
1650
+ if new is None:
1651
+ print(f"{at}: not wrapped; left as it is")
1652
+ continue
1653
+ if what == "wrap" and _changes_what_runs(new):
1654
+ print(f"{at}: its entry sets " + ", ".join(_changed_by(new)) + ", which "
1655
+ "changes what runs: phiward counts it as not wrapped until you remove "
1656
+ "that from the entry")
1657
+ group[name] = new
1658
+ lines.append(f" {shown(name)} ({os.path.basename(path)}): {_say(_command(spec))}\n"
1659
+ f" -> {_say(_command(new))}")
1660
+ if what == "wrap" and isinstance(spec.get("env"), dict):
1661
+ env_keys += [k for k in spec["env"] if k not in env_keys]
1662
+ changes[path] = (text, data, lines)
1663
+ todo = {p: c for p, c in changes.items() if c[2]}
1664
+ for p in todo:
1665
+ if twice.get(p):
1666
+ sys.stderr.write(f"mcp {what}: {p} gives a key twice ({', '.join(twice[p][:3])}); "
1667
+ "Claude Code reads the last one, and a rewrite would drop the "
1668
+ "other: remove one yourself, then run `phiward mcp "
1669
+ f"{what}` again. Nothing was changed.\n")
1670
+ return 3
1671
+ if p in odd:
1672
+ # never written through a link (it could point anywhere): the operator edits the
1673
+ # file it leads to
1674
+ sys.stderr.write(f"mcp {what}: {p} is a link or not a plain file (it leads to "
1675
+ f"{os.path.realpath(p)}); edit the entry there yourself, or make "
1676
+ f"{p} a plain file and run `phiward mcp {what}` again. Nothing was "
1677
+ "changed.\n")
1678
+ return 3
1679
+ if not todo:
1680
+ print(f"mcp {what}: nothing to change.")
1681
+ return 0
1682
+ print("Close Claude Code first: it writes ~/.claude.json too, and a running session keeps "
1683
+ "each server as it started it.")
1684
+ for p, (_t, _d, lines) in todo.items():
1685
+ print(f"{p}:")
1686
+ for ln in lines:
1687
+ print(ln)
1688
+ if what == "wrap":
1689
+ print("Wrapped servers run in phiward's kernel profile: they cannot read protected "
1690
+ "data or your keys, and write only the project. Start Claude Code again once this "
1691
+ "is written: it starts each server as the file then says.")
1692
+ if env_keys:
1693
+ print("Their `env` keys reach a wrapped server only when `[launch] pass_env` in your "
1694
+ "user config lists them: " + ", ".join(env_keys))
1695
+ if not yes:
1696
+ if not tty:
1697
+ print(f"mcp {what}: not written. Run it in your own terminal, or add --yes.")
1698
+ return 1
1699
+ if input("Write these changes? [y/N] ").strip().lower() not in ("y", "yes"):
1700
+ print(f"mcp {what}: not written.")
1701
+ return 1
1702
+ folders: Dict[str, str] = {}
1703
+ for p in todo:
1704
+ # the backups live only in phiward's own guarded folder, never beside the file (one
1705
+ # there could be the agent's): checked before anything is written
1706
+ folder, why = _backup_folder(p, home)
1707
+ if not folder:
1708
+ sys.stderr.write(f"mcp {what}: the backups folder: {why}. Nothing was changed.\n")
1709
+ return 3
1710
+ folders[p] = folder
1711
+ for p, (before, data, _lines) in todo.items():
1712
+ try:
1713
+ if safeio.read_text(p, limit=64 * 1024 * 1024) != before:
1714
+ sys.stderr.write(f"mcp {what}: {p} changed while this ran (Claude Code writes it "
1715
+ "too); run it again, best with Claude Code closed.\n")
1716
+ return 3
1717
+ mode = stat.S_IMODE(os.stat(p).st_mode)
1718
+ folder = folders[p]
1719
+ original = os.path.join(folder, "original")
1720
+ if not os.path.lexists(original):
1721
+ # the file before phiward first changed it: never overwritten
1722
+ safeio.write_new(original, before, mode=0o600)
1723
+ safeio.write_new(os.path.join(folder, "last"), before, mode=0o600)
1724
+ safeio.write_new(p, json.dumps(data, indent=2) + "\n", mode=mode)
1725
+ except OSError as exc:
1726
+ sys.stderr.write(f"mcp {what}: {p} cannot be written ({exc})\n")
1727
+ return 3
1728
+ base = os.path.basename(p)
1729
+ shown_folder = "~/" + os.path.relpath(folders[p], home)
1730
+ print(f"mcp {what}: wrote {p} (backups in {shown_folder}: `last`, before this change; "
1731
+ "`original`, before phiward first changed it)")
1732
+ if _same_place(p, os.path.join(project, ".mcp.json")):
1733
+ print(f" {base} is shared with the repository and now names this machine's "
1734
+ f"phiward ({exe}): a contributor whose phiward is elsewhere runs `phiward mcp "
1735
+ "wrap` again.")
1736
+ return 0