entitybind 0.1.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.
@@ -0,0 +1,778 @@
1
+ """Configuration entries for `entitybind mcp add <client>`.
2
+
3
+ Each supported client gets the entry its own documentation describes, a
4
+ target file for `--write`, and the equivalent command for the client's own CLI
5
+ where one exists. With `--auth key` the key is referenced through an
6
+ environment variable and never written into a file unless `--inline-key` is
7
+ given. With `--auth oauth` (Core only) only the URL is configured: the client
8
+ registers itself and the workspace owner approves the connection.
9
+
10
+ Merging preserves everything else in the file and replaces an existing entry
11
+ of the same name only with `--force`. Files that are not plain JSON (for
12
+ example JSON with comments) or TOML forms this module does not rewrite are
13
+ refused rather than reformatted.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import re
20
+ import shlex
21
+ import sys
22
+ from collections.abc import Mapping
23
+ from dataclasses import dataclass, field
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ from entitybind.errors import ConflictError, UsageError
28
+ from entitybind.files import home_dir
29
+ from entitybind.products import Product
30
+
31
+ if sys.version_info >= (3, 11):
32
+ import tomllib
33
+ else: # pragma: no cover - exercised on Python 3.10 only
34
+ tomllib = None
35
+
36
+ CLIENTS = ("claude-code", "codex", "gemini", "cursor", "vscode")
37
+ SCOPES = ("project", "user")
38
+ AUTH_MODES = ("key", "oauth")
39
+ DEFAULT_SCOPES = {
40
+ "claude-code": "project",
41
+ # Codex reads project-scoped .codex/config.toml only in trusted projects;
42
+ # its documented home for MCP servers is ~/.codex/config.toml.
43
+ "codex": "user",
44
+ "gemini": "project",
45
+ "cursor": "project",
46
+ "vscode": "project",
47
+ }
48
+ # Entry keys each client's entry is managed by (beside headers.Authorization).
49
+ # Gemini's `url` is its SSE transport, so it must not linger beside `httpUrl`.
50
+ MANAGED_KEYS = {
51
+ "claude-code": ("type", "url"),
52
+ "codex": ("url", "bearer_token_env_var"),
53
+ "gemini": ("httpUrl", "url"),
54
+ "cursor": ("url",),
55
+ "vscode": ("type", "url"),
56
+ }
57
+ CLIENT_LABELS = {
58
+ "claude-code": "Claude Code",
59
+ "codex": "Codex",
60
+ "gemini": "Gemini CLI",
61
+ "cursor": "Cursor",
62
+ "vscode": "VS Code",
63
+ }
64
+ _SERVER_NAME = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
65
+ _BARE_TOML_KEY = re.compile(r"^[A-Za-z0-9_-]+$")
66
+
67
+
68
+ @dataclass
69
+ class McpTarget:
70
+ client: str
71
+ product: str
72
+ auth: str
73
+ scope: str
74
+ server_name: str
75
+ url: str
76
+ format: str
77
+ path: Path | None = None
78
+ container: str | None = None
79
+ entry: dict[str, Any] | None = None
80
+ toml: str | None = None
81
+ toml_expected: dict[str, Any] | None = None
82
+ env_var: str | None = None
83
+ allow_env: str | None = None
84
+ command: list[str] | None = None
85
+ write_command: list[str] | None = None
86
+ inline_secret: bool = False
87
+ notes: list[str] = field(default_factory=list)
88
+ # Entry keys this CLI controls, besides the Authorization header. Merging
89
+ # compares and replaces only these, so a person's own settings survive.
90
+ managed: tuple[str, ...] = ()
91
+
92
+ def document(self) -> dict[str, Any] | None:
93
+ """The fragment as it appears in the target file."""
94
+ if self.entry is None or self.container is None:
95
+ return None
96
+ doc: dict[str, Any] = {self.container: {self.server_name: self.entry}}
97
+ if self.allow_env:
98
+ doc["security"] = {"environmentVariableRedaction": {"allowed": [self.allow_env]}}
99
+ return doc
100
+
101
+
102
+ def validate_server_name(name: str) -> str:
103
+ if not _SERVER_NAME.match(name):
104
+ raise UsageError(
105
+ f"server name {name!r} must be 1-64 letters, digits, hyphens or underscores"
106
+ )
107
+ return name
108
+
109
+
110
+ def refuse_inline_key_in_project(scope: str) -> None:
111
+ """A raw key never goes into a project file: those are made to be committed."""
112
+ if scope == "project":
113
+ raise UsageError(
114
+ "--inline-key will not write the raw key into a project-scope file, which is "
115
+ "usually committed with the project",
116
+ code="inline_key_project_scope",
117
+ hint="add --scope user to keep it in a file in your home directory, or leave out "
118
+ "--inline-key so the entry reads the key from the environment",
119
+ )
120
+
121
+
122
+ def _header_reference(client: str, env_var: str) -> str:
123
+ if client in ("cursor", "vscode"):
124
+ return f"Bearer ${{env:{env_var}}}"
125
+ return f"Bearer ${{{env_var}}}"
126
+
127
+
128
+ def vscode_user_path(env: Mapping[str, str], platform: str) -> Path:
129
+ home = home_dir(env)
130
+ if platform == "darwin":
131
+ return home / "Library" / "Application Support" / "Code" / "User" / "mcp.json"
132
+ if platform.startswith("win"):
133
+ appdata = env.get("APPDATA")
134
+ root = Path(appdata) if appdata else home / "AppData" / "Roaming"
135
+ return root / "Code" / "User" / "mcp.json"
136
+ xdg = env.get("XDG_CONFIG_HOME")
137
+ root = Path(xdg) if xdg else home / ".config"
138
+ return root / "Code" / "User" / "mcp.json"
139
+
140
+
141
+ def codex_home(env: Mapping[str, str]) -> Path:
142
+ value = env.get("CODEX_HOME")
143
+ return Path(value) if value else home_dir(env) / ".codex"
144
+
145
+
146
+ def toml_string(value: str) -> str:
147
+ escaped = value.replace("\\", "\\\\").replace('"', '\\"')
148
+ escaped = "".join(ch if ch >= " " and ch != "\x7f" else f"\\u{ord(ch):04x}" for ch in escaped)
149
+ return f'"{escaped}"'
150
+
151
+
152
+ def toml_key(value: str) -> str:
153
+ return value if _BARE_TOML_KEY.match(value) else toml_string(value)
154
+
155
+
156
+ def build_target(
157
+ client: str,
158
+ product: Product,
159
+ *,
160
+ base_url: str,
161
+ auth: str,
162
+ scope: str | None,
163
+ server_name: str | None,
164
+ directory: Path,
165
+ env: Mapping[str, str],
166
+ platform: str,
167
+ inline_key: str | None = None,
168
+ ) -> McpTarget:
169
+ if client not in CLIENTS:
170
+ raise UsageError(f"unknown client {client!r}; choose from {', '.join(CLIENTS)}")
171
+ if auth not in AUTH_MODES:
172
+ raise UsageError("--auth must be key or oauth")
173
+ if auth == "oauth" and not product.supports_mcp_oauth:
174
+ raise UsageError(
175
+ f"{product.label} MCP needs an API key; --auth oauth is available for Core only"
176
+ )
177
+ if inline_key is not None and auth != "key":
178
+ raise UsageError("--inline-key applies only to --auth key")
179
+ chosen_scope = scope or DEFAULT_SCOPES[client]
180
+ if chosen_scope not in SCOPES:
181
+ raise UsageError("--scope must be project or user")
182
+ if inline_key is not None:
183
+ refuse_inline_key_in_project(chosen_scope)
184
+ name = validate_server_name(server_name or product.server_name)
185
+ url = product.mcp_url(base_url)
186
+ env_var = product.key_env if auth == "key" and inline_key is None else None
187
+ header: str | None = None
188
+ if inline_key is not None:
189
+ header = f"Bearer {inline_key}"
190
+ elif env_var is not None:
191
+ header = _header_reference(client, env_var)
192
+ home = home_dir(env)
193
+ target = McpTarget(
194
+ client=client,
195
+ product=product.name,
196
+ auth=auth,
197
+ scope=chosen_scope,
198
+ server_name=name,
199
+ url=url,
200
+ format="json",
201
+ env_var=env_var,
202
+ inline_secret=inline_key is not None,
203
+ )
204
+ if client == "claude-code":
205
+ entry: dict[str, Any] = {"type": "http", "url": url}
206
+ if header:
207
+ entry["headers"] = {"Authorization": header}
208
+ target.entry = entry
209
+ target.container = "mcpServers"
210
+ if chosen_scope == "project":
211
+ target.path = directory / ".mcp.json"
212
+ if inline_key is None:
213
+ command = ["claude", "mcp", "add", "--transport", "http", "--scope", "project"]
214
+ command += [name, url]
215
+ if header:
216
+ command += ["--header", f"Authorization: {header}"]
217
+ target.command = command
218
+ else:
219
+ target.format = "command"
220
+ target.write_command = [
221
+ "claude",
222
+ "mcp",
223
+ "add-json",
224
+ "--scope",
225
+ "user",
226
+ name,
227
+ json.dumps(entry, separators=(",", ":")),
228
+ ]
229
+ target.command = target.write_command
230
+ elif client == "codex":
231
+ target.format = "toml"
232
+ root = codex_home(env) if chosen_scope == "user" else directory / ".codex"
233
+ target.path = root / "config.toml"
234
+ lines = [f"[mcp_servers.{toml_key(name)}]", f"url = {toml_string(url)}"]
235
+ expected: dict[str, Any] = {"url": url}
236
+ if inline_key is not None:
237
+ lines.append(
238
+ f'http_headers = {{ "Authorization" = {toml_string(f"Bearer {inline_key}")} }}'
239
+ )
240
+ expected["http_headers"] = {"Authorization": f"Bearer {inline_key}"}
241
+ elif env_var is not None:
242
+ lines.append(f"bearer_token_env_var = {toml_string(env_var)}")
243
+ expected["bearer_token_env_var"] = env_var
244
+ target.toml = "\n".join(lines) + "\n"
245
+ target.toml_expected = expected
246
+ # `codex mcp add` writes only the user configuration.
247
+ if inline_key is None and chosen_scope == "user":
248
+ command = ["codex", "mcp", "add", name, "--url", url]
249
+ if env_var is not None:
250
+ command += ["--bearer-token-env-var", env_var]
251
+ target.command = command
252
+ elif client == "gemini":
253
+ root = home if chosen_scope == "user" else directory
254
+ target.path = root / ".gemini" / "settings.json"
255
+ target.container = "mcpServers"
256
+ entry = {"httpUrl": url}
257
+ if header:
258
+ entry["headers"] = {"Authorization": header}
259
+ target.entry = entry
260
+ if env_var is not None:
261
+ # Gemini CLI blanks variables whose names contain KEY, TOKEN, AUTH or
262
+ # SECRET when it expands headers, unless they are allowlisted here.
263
+ # `gemini mcp add` cannot set that list, so it is offered only for OAuth.
264
+ target.allow_env = env_var
265
+ elif inline_key is None:
266
+ target.command = [
267
+ "gemini",
268
+ "mcp",
269
+ "add",
270
+ "--scope",
271
+ chosen_scope,
272
+ "--transport",
273
+ "http",
274
+ name,
275
+ url,
276
+ ]
277
+ elif client == "cursor":
278
+ root = home if chosen_scope == "user" else directory
279
+ target.path = root / ".cursor" / "mcp.json"
280
+ target.container = "mcpServers"
281
+ entry = {"url": url}
282
+ if header:
283
+ entry["headers"] = {"Authorization": header}
284
+ target.entry = entry
285
+ else: # vscode
286
+ target.path = (
287
+ vscode_user_path(env, platform)
288
+ if chosen_scope == "user"
289
+ else directory / ".vscode" / "mcp.json"
290
+ )
291
+ target.container = "servers"
292
+ entry = {"type": "http", "url": url}
293
+ if header:
294
+ entry["headers"] = {"Authorization": header}
295
+ target.entry = entry
296
+ if chosen_scope == "user" and inline_key is None:
297
+ target.command = [
298
+ "code",
299
+ "--add-mcp",
300
+ json.dumps({"name": name, **entry}, separators=(",", ":")),
301
+ ]
302
+ target.managed = MANAGED_KEYS[client]
303
+ target.notes = _notes(target, product)
304
+ return target
305
+
306
+
307
+ def _notes(target: McpTarget, product: Product) -> list[str]:
308
+ label = CLIENT_LABELS[target.client]
309
+ notes: list[str] = []
310
+ if target.inline_secret:
311
+ notes.append(
312
+ "This entry contains the raw key. Do not commit or share the file; prefer the "
313
+ f"{product.key_env} environment variable."
314
+ )
315
+ elif target.env_var is not None:
316
+ notes.append(
317
+ f"{label} must run with {target.env_var} set in its environment, for that "
318
+ "process or project rather than in your shell profile; "
319
+ "`entitybind login --print-key --no-store` prints a key once."
320
+ )
321
+ if target.client == "gemini":
322
+ notes.append(
323
+ f"Gemini CLI expands {target.env_var} only because it is listed in "
324
+ "security.environmentVariableRedaction.allowed; `gemini mcp add` cannot set "
325
+ "that list, so use --write or add both parts by hand."
326
+ )
327
+ elif target.auth == "oauth":
328
+ how = {
329
+ "claude-code": "run /mcp in Claude Code and choose Authenticate",
330
+ "codex": f"run `codex mcp login {target.server_name}`",
331
+ "gemini": f"run `/mcp auth {target.server_name}` in Gemini CLI",
332
+ "cursor": "open Cursor's MCP settings and sign in when prompted",
333
+ "vscode": "start the server in VS Code and sign in when prompted",
334
+ }[target.client]
335
+ notes.append(
336
+ f"To connect, {how}; the workspace owner approves the connection in the browser."
337
+ )
338
+ if target.client == "codex" and target.scope == "project":
339
+ notes.append("Codex reads .codex/config.toml only in projects you have marked trusted.")
340
+ return notes
341
+
342
+
343
+ def shell_command(argv: list[str]) -> str:
344
+ return shlex.join(argv)
345
+
346
+
347
+ # --- merging ---------------------------------------------------------------
348
+
349
+
350
+ @dataclass
351
+ class MergeResult:
352
+ path: Path
353
+ created: bool
354
+ changed: bool
355
+ content: str
356
+
357
+
358
+ def _indent_of(text: str) -> int | str:
359
+ for line in text.splitlines()[1:]:
360
+ stripped = line.lstrip(" \t")
361
+ if stripped and len(stripped) < len(line):
362
+ prefix = line[: len(line) - len(stripped)]
363
+ return "\t" if prefix.startswith("\t") else len(prefix)
364
+ return 2
365
+
366
+
367
+ def _child_object(parent: dict[str, Any], key: str, where: Path) -> dict[str, Any]:
368
+ value = parent.get(key)
369
+ if value is None:
370
+ value = {}
371
+ parent[key] = value
372
+ if not isinstance(value, dict):
373
+ raise ConflictError(
374
+ f"{key} in {where} is not a JSON object; fix the file or add the entry by hand",
375
+ code="config_conflict",
376
+ )
377
+ return value
378
+
379
+
380
+ def _read_config(path: Path) -> str | None:
381
+ if not path.exists():
382
+ return None
383
+ try:
384
+ return path.read_text(encoding="utf-8")
385
+ except UnicodeDecodeError:
386
+ raise ConflictError(
387
+ f"{path} is not UTF-8 text; add the entry by hand", code="config_unparseable"
388
+ ) from None
389
+
390
+
391
+ AUTHORIZATION = "Authorization"
392
+
393
+
394
+ def _headers(entry: Mapping[str, Any]) -> Mapping[str, Any]:
395
+ headers = entry.get("headers")
396
+ return headers if isinstance(headers, dict) else {}
397
+
398
+
399
+ def _managed_view(entry: Mapping[str, Any], managed: tuple[str, ...]) -> dict[str, Any]:
400
+ """The settings this CLI writes in an entry; everything else is the person's own."""
401
+ view = {key: entry.get(key) for key in managed}
402
+ view[AUTHORIZATION] = _headers(entry).get(AUTHORIZATION)
403
+ return view
404
+
405
+
406
+ def _replace_managed(
407
+ existing: Mapping[str, Any], entry: Mapping[str, Any], managed: tuple[str, ...]
408
+ ) -> dict[str, Any]:
409
+ """`existing` with this CLI's settings taken from `entry` and every other key kept."""
410
+ merged: dict[str, Any] = {}
411
+ for key, value in existing.items():
412
+ if key not in managed:
413
+ merged[key] = value
414
+ elif key in entry:
415
+ merged[key] = entry[key]
416
+ for key in managed:
417
+ if key in entry and key not in merged:
418
+ merged[key] = entry[key]
419
+ headers = dict(_headers(existing))
420
+ wanted = _headers(entry).get(AUTHORIZATION)
421
+ if wanted is None:
422
+ headers.pop(AUTHORIZATION, None)
423
+ else:
424
+ headers[AUTHORIZATION] = wanted
425
+ if headers:
426
+ merged["headers"] = headers
427
+ else:
428
+ merged.pop("headers", None)
429
+ return merged
430
+
431
+
432
+ def merge_json(
433
+ path: Path,
434
+ container: str,
435
+ name: str,
436
+ entry: dict[str, Any],
437
+ *,
438
+ managed: tuple[str, ...] | None = None,
439
+ allow_env: str | None = None,
440
+ force: bool = False,
441
+ ) -> MergeResult:
442
+ """Add the entry, or with `force` update the settings this CLI manages in it.
443
+
444
+ An existing entry whose managed settings already match is left alone, so
445
+ keys a person added (a timeout, tool filters, trust) are never a conflict,
446
+ and `force` keeps them while replacing the URL, transport and the
447
+ Authorization header.
448
+ """
449
+ managed = managed if managed is not None else tuple(key for key in entry if key != "headers")
450
+ original = _read_config(path)
451
+ data: dict[str, Any] = {}
452
+ if original is not None and original.strip():
453
+ try:
454
+ loaded = json.loads(original)
455
+ except ValueError:
456
+ raise ConflictError(
457
+ f"{path} is not plain JSON (it may contain comments); add the entry by hand",
458
+ code="config_unparseable",
459
+ ) from None
460
+ if not isinstance(loaded, dict):
461
+ raise ConflictError(f"{path} does not hold a JSON object", code="config_conflict")
462
+ data = loaded
463
+ servers = _child_object(data, container, path)
464
+ changed = False
465
+ existing = servers.get(name)
466
+ if existing is None:
467
+ servers[name] = entry
468
+ changed = True
469
+ elif not (
470
+ isinstance(existing, dict)
471
+ and _managed_view(existing, managed) == _managed_view(entry, managed)
472
+ ):
473
+ if not force:
474
+ raise ConflictError(
475
+ f"{path} already has an MCP server named {name!r} with different settings",
476
+ code="config_conflict",
477
+ hint="use --force to update its URL and Authorization header (other settings "
478
+ "are kept), or --server-name to add another entry",
479
+ )
480
+ servers[name] = (
481
+ _replace_managed(existing, entry, managed) if isinstance(existing, dict) else entry
482
+ )
483
+ changed = True
484
+ if allow_env:
485
+ security = _child_object(data, "security", path)
486
+ redaction = _child_object(security, "environmentVariableRedaction", path)
487
+ allowed = redaction.get("allowed")
488
+ if allowed is None:
489
+ allowed = []
490
+ redaction["allowed"] = allowed
491
+ if not isinstance(allowed, list):
492
+ raise ConflictError(
493
+ f"security.environmentVariableRedaction.allowed in {path} is not a list",
494
+ code="config_conflict",
495
+ )
496
+ if allow_env not in allowed:
497
+ allowed.append(allow_env)
498
+ changed = True
499
+ indent = _indent_of(original) if original else 2
500
+ content = json.dumps(data, indent=indent, ensure_ascii=False) + "\n"
501
+ return MergeResult(path=path, created=original is None, changed=changed, content=content)
502
+
503
+
504
+ _TABLE_HEADER = re.compile(r"^\s*\[\[?(?P<key>[^\[\]]+)\]\]?\s*(?:#.*)?$")
505
+ _KEY_VALUE = re.compile(r"""^\s*(?P<key>[A-Za-z0-9_\-."' ]+?)\s*=(?P<value>.*)$""")
506
+
507
+
508
+ def _split_dotted(raw: str) -> list[str]:
509
+ parts: list[str] = []
510
+ current = ""
511
+ quote: str | None = None
512
+ for ch in raw.strip():
513
+ if quote:
514
+ if ch == quote:
515
+ quote = None
516
+ else:
517
+ current += ch
518
+ elif ch in ("'", '"'):
519
+ quote = ch
520
+ elif ch == ".":
521
+ parts.append(current.strip())
522
+ current = ""
523
+ else:
524
+ current += ch
525
+ parts.append(current.strip())
526
+ return parts
527
+
528
+
529
+ _TOML_STRING = r"""(?:"(?:[^"\\]|\\.)*"|'[^']*')"""
530
+ _SINGLE_LINE_STRING = re.compile(rf"^{_TOML_STRING}\s*(?:#.*)?$")
531
+ _ONLY_AUTHORIZATION = re.compile(
532
+ rf"""^\{{\s*["']?{AUTHORIZATION}["']?\s*=\s*{_TOML_STRING}\s*\}}\s*(?:#.*)?$"""
533
+ )
534
+
535
+
536
+ @dataclass
537
+ class _TomlPair:
538
+ index: int
539
+ key: list[str]
540
+ value: str
541
+
542
+
543
+ def _pairs(lines: list[str], start: int, stop: int) -> list[_TomlPair]:
544
+ """The `key = value` lines of a table body, as written."""
545
+ found: list[_TomlPair] = []
546
+ for index in range(start, stop):
547
+ line = lines[index]
548
+ pair = _KEY_VALUE.match(line)
549
+ if pair and not line.lstrip().startswith("#"):
550
+ key = _split_dotted(pair.group("key"))
551
+ found.append(_TomlPair(index, key, pair.group("value").strip()))
552
+ return found
553
+
554
+
555
+ def _is_authorization(pair: _TomlPair) -> bool:
556
+ return pair.key == ["http_headers", AUTHORIZATION] or (
557
+ pair.key == ["http_headers"] and AUTHORIZATION in pair.value
558
+ )
559
+
560
+
561
+ def _text_view(pairs: list[_TomlPair]) -> dict[str, str | None]:
562
+ """The managed settings as written, compared when no TOML parser is available."""
563
+ view: dict[str, str | None] = {"url": None, "bearer_token_env_var": None, "authorization": None}
564
+ for pair in pairs:
565
+ if pair.key in (["url"], ["bearer_token_env_var"]):
566
+ view[pair.key[0]] = pair.value
567
+ elif _is_authorization(pair):
568
+ view["authorization"] = pair.value
569
+ return view
570
+
571
+
572
+ def toml_view(server: Mapping[str, Any]) -> dict[str, Any]:
573
+ """The settings this CLI writes in `[mcp_servers.<name>]`; the rest is the person's own."""
574
+ headers = server.get("http_headers")
575
+ return {
576
+ "url": server.get("url"),
577
+ "bearer_token_env_var": server.get("bearer_token_env_var"),
578
+ "authorization": headers.get(AUTHORIZATION) if isinstance(headers, dict) else None,
579
+ }
580
+
581
+
582
+ def _unmanaged(server: Mapping[str, Any]) -> dict[str, Any]:
583
+ kept = {
584
+ key: value
585
+ for key, value in server.items()
586
+ if key not in ("url", "bearer_token_env_var", "http_headers")
587
+ }
588
+ headers = server.get("http_headers")
589
+ if isinstance(headers, dict):
590
+ other = {key: value for key, value in headers.items() if key != AUTHORIZATION}
591
+ if other:
592
+ kept["http_headers"] = other
593
+ elif headers is not None:
594
+ kept["http_headers"] = headers
595
+ return kept
596
+
597
+
598
+ def _without_server(document: Mapping[str, Any], name: str) -> dict[str, Any]:
599
+ rest = {key: value for key, value in document.items() if key != "mcp_servers"}
600
+ servers = document.get("mcp_servers")
601
+ if isinstance(servers, dict):
602
+ others = {key: value for key, value in servers.items() if key != name}
603
+ if others:
604
+ rest["mcp_servers"] = others
605
+ elif servers is not None:
606
+ rest["mcp_servers"] = servers
607
+ return rest
608
+
609
+
610
+ def _parse_toml(text: str, path: Path) -> dict[str, Any] | None:
611
+ if tomllib is None: # Python 3.10
612
+ return None
613
+ try:
614
+ return tomllib.loads(text)
615
+ except tomllib.TOMLDecodeError as exc:
616
+ raise ConflictError(
617
+ f"{path} is not valid TOML ({exc}); fix it or add the entry by hand",
618
+ code="config_unparseable",
619
+ ) from None
620
+
621
+
622
+ def merge_toml(
623
+ path: Path,
624
+ name: str,
625
+ block: str,
626
+ expected: Mapping[str, Any],
627
+ *,
628
+ force: bool = False,
629
+ ) -> MergeResult:
630
+ """Add `[mcp_servers.<name>]`, or with `force` update the settings this CLI manages.
631
+
632
+ Only `url`, `bearer_token_env_var` and the Authorization entry of
633
+ `http_headers` are this CLI's. A table whose managed settings already
634
+ match is left alone; `force` rewrites only those lines and keeps every
635
+ other key and sub-table (approval modes, timeouts, `tools.*`).
636
+ """
637
+ original = _read_config(path) or ""
638
+ before = _parse_toml(original, path)
639
+ lines = original.splitlines(keepends=True)
640
+ start: int | None = None
641
+ end: int | None = None
642
+ main: int | None = None
643
+ main_end: int | None = None
644
+ table: list[str] = []
645
+ for index, line in enumerate(lines):
646
+ header = _TABLE_HEADER.match(line)
647
+ if header:
648
+ table = _split_dotted(header.group("key"))
649
+ ours = table[:2] == ["mcp_servers", name]
650
+ if main is not None and main_end is None:
651
+ main_end = index
652
+ if ours and start is None:
653
+ start = index
654
+ elif ours and end is not None:
655
+ raise ConflictError(
656
+ f"{path} defines [mcp_servers.{name}] in more than one place; edit it by hand",
657
+ code="config_conflict",
658
+ )
659
+ elif not ours and start is not None and end is None:
660
+ end = index
661
+ if table == ["mcp_servers", name]:
662
+ main = index
663
+ continue
664
+ pair = _KEY_VALUE.match(line)
665
+ if not pair or line.lstrip().startswith("#"):
666
+ continue
667
+ keys = table + _split_dotted(pair.group("key"))
668
+ inline_parent = keys == ["mcp_servers"] and name in pair.group("value")
669
+ if (keys[:2] == ["mcp_servers", name] and table[:2] != ["mcp_servers", name]) or (
670
+ inline_parent
671
+ ):
672
+ raise ConflictError(
673
+ f"{path} defines mcp_servers.{name} with dotted keys or an inline table; "
674
+ "edit it by hand",
675
+ code="config_conflict",
676
+ )
677
+ ours_lines = block.splitlines(keepends=True)[1:]
678
+ changed = True
679
+ if start is None:
680
+ prefix = original
681
+ if prefix and not prefix.endswith("\n"):
682
+ prefix += "\n"
683
+ if prefix.strip():
684
+ prefix += "\n"
685
+ content = prefix + block
686
+ elif main is None:
687
+ # Only sub-tables exist, so there is no url yet; the table goes in front of them.
688
+ if not force:
689
+ raise _toml_conflict(path, name)
690
+ content = "".join(lines[:start]) + block + "\n" + "".join(lines[start:])
691
+ else:
692
+ body_end = len(lines) if main_end is None else main_end
693
+ pairs = _pairs(lines, main + 1, body_end)
694
+ if before is not None:
695
+ servers = before.get("mcp_servers")
696
+ server = servers.get(name) if isinstance(servers, dict) else None
697
+ current = toml_view(server if isinstance(server, dict) else {})
698
+ same = current == toml_view(expected)
699
+ else: # Python 3.10, which has no tomllib
700
+ same = _text_view(pairs) == _text_view(_pairs(ours_lines, 0, len(ours_lines)))
701
+ if same:
702
+ content, changed = original, False
703
+ elif not force:
704
+ raise _toml_conflict(path, name)
705
+ else:
706
+ content = _rewrite_managed(path, name, lines, main, body_end, pairs, ours_lines)
707
+ if changed:
708
+ _check_toml_merge(path, name, content, before, expected)
709
+ return MergeResult(path=path, created=not path.exists(), changed=changed, content=content)
710
+
711
+
712
+ def _toml_conflict(path: Path, name: str) -> ConflictError:
713
+ return ConflictError(
714
+ f"{path} already has [mcp_servers.{name}] with different settings",
715
+ code="config_conflict",
716
+ hint="use --force to update its url and credential lines (other settings are kept), "
717
+ "or --server-name to add another entry",
718
+ )
719
+
720
+
721
+ def _rewrite_managed(
722
+ path: Path,
723
+ name: str,
724
+ lines: list[str],
725
+ main: int,
726
+ body_end: int,
727
+ pairs: list[_TomlPair],
728
+ ours: list[str],
729
+ ) -> str:
730
+ """Replace the managed lines of the table body with `ours`, keeping every other line."""
731
+ hand = (
732
+ f"[mcp_servers.{name}] in {path} has a form this client does not rewrite; edit it by hand"
733
+ )
734
+ remove: set[int] = set()
735
+ for pair in pairs:
736
+ if pair.key in (["url"], ["bearer_token_env_var"], ["http_headers", AUTHORIZATION]):
737
+ if not _SINGLE_LINE_STRING.match(pair.value):
738
+ raise ConflictError(hand, code="config_conflict")
739
+ remove.add(pair.index)
740
+ elif pair.key == ["http_headers"] and AUTHORIZATION in pair.value:
741
+ if not _ONLY_AUTHORIZATION.match(pair.value):
742
+ raise ConflictError(hand, code="config_conflict")
743
+ remove.add(pair.index)
744
+ writes_headers = any(line.lstrip().startswith("http_headers") for line in ours)
745
+ keeps_headers = any(pair.key[0] == "http_headers" for pair in pairs if pair.index not in remove)
746
+ if writes_headers and keeps_headers:
747
+ raise ConflictError(hand, code="config_conflict")
748
+ header = lines[main] if lines[main].endswith("\n") else lines[main] + "\n"
749
+ body = [lines[index] for index in range(main + 1, body_end) if index not in remove]
750
+ return "".join([*lines[:main], header, *ours, *body, *lines[body_end:]])
751
+
752
+
753
+ def _check_toml_merge(
754
+ path: Path,
755
+ name: str,
756
+ content: str,
757
+ before: Mapping[str, Any] | None,
758
+ expected: Mapping[str, Any],
759
+ ) -> None:
760
+ """With a TOML parser, prove the merge changed only this CLI's settings."""
761
+ after = _parse_toml(content, path)
762
+ if after is None: # Python 3.10
763
+ return
764
+ servers = after.get("mcp_servers")
765
+ server = servers.get(name) if isinstance(servers, dict) else None
766
+ old_servers = (before or {}).get("mcp_servers")
767
+ old = old_servers.get(name) if isinstance(old_servers, dict) else None
768
+ safe = (
769
+ isinstance(server, dict)
770
+ and toml_view(server) == toml_view(expected)
771
+ and _unmanaged(server) == _unmanaged(old if isinstance(old, dict) else {})
772
+ and _without_server(after, name) == _without_server(before or {}, name)
773
+ )
774
+ if not safe:
775
+ raise ConflictError(
776
+ f"could not merge [mcp_servers.{name}] into {path} safely; edit it by hand",
777
+ code="config_conflict",
778
+ )