Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(mcp): delete native MCP servers from their own config file (#3114)
rkrkrkk17921bf377ee
diff --git a/core/mcp_hub/native.py b/core/mcp_hub/native.pyindex 4cce58c8c..c3d532c37 100644--- a/core/mcp_hub/native.py+++ b/core/mcp_hub/native.py@@ -6,7 +6,9 @@ Hub reads the union of:- Codex ``$CODEX_HOME/config.toml`` (default ``~/.codex``) ``[mcp_servers.<name>]``- OpenCode ``~/.config/opencode/opencode.json`` ``mcp``-as a read-only union. Avibe-added servers live under ``<avibe-home>/mcp``.+as a union. Avibe-added servers live under ``<avibe-home>/mcp``. The Hub+never edits these files except :func:`remove_entry`, which deletes one named+entry and leaves every other byte in place.For a name present in several files the first source in that order is canonical.Avibe sessions never load these servers natively; see:func:`codex_disable_overrides` and :func:`opencode_disabled_mcp`.@@ -17,6 +19,7 @@ from __future__ import annotationsimport jsonimport loggingimport os+import threadingfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Callable, Optional@@ -70,18 +73,7 @@ def _load(source: str) -> tuple[Path, dict[str, Any]]:except (OSError, UnicodeDecodeError, ValueError) as exc:raise _unreadable(source, path, exc) from Nonetry:- if source == CODEX:- try:- import tomllib # type: ignore[attr-defined]- except ImportError: # pragma: no cover - py<3.11- import tomli as tomllib # type: ignore[no-redef]- data = tomllib.loads(text)- elif source == OPENCODE:- from vibe.opencode_config import parse_jsonc_object-- data = parse_jsonc_object(text)- else:- data = json.loads(text)+ data = _parse(source, text)except Exception as exc:raise _unreadable(source, path, exc) from Noneif not isinstance(data, dict):@@ -90,9 +82,22 @@ def _load(source: str) -> tuple[Path, dict[str, Any]]:+def _parse(source: str, text: str) -> Any:+ if source == CODEX:+ try:+ import tomllib # type: ignore[attr-defined]+ except ImportError: # pragma: no cover - py<3.11+ import tomli as tomllib # type: ignore[no-redef]+ return tomllib.loads(text)+ if source == OPENCODE:+ from vibe.opencode_config import parse_jsonc_object++ return parse_jsonc_object(text)+ return json.loads(text)++def _servers(source: str, data: dict[str, Any]) -> dict[str, Any]:- key = {CLAUDE: "mcpServers", CODEX: "mcp_servers", OPENCODE: "mcp"}[source]- value = data.get(key)+ value = data.get(_KEY[source])return value if isinstance(value, dict) else {}@@ -240,6 +245,20 @@ def read_all() -> dict[str, NativeServer]:return servers+def disabled_source(name: str) -> Optional[str]:+ """The first source holding ``name`` as a native ``enabled=false`` entry."""++ for source in SOURCES:+ try:+ _path, data = _load(source)+ except McpHubError:+ continue+ entry = _servers(source, data).get(name)+ if isinstance(entry, dict) and not _native_enabled(source, entry):+ return source+ return None++def disabled_names() -> set[str]:"""Names whose native entry is ``enabled=false``. Hub lists omit these."""@@ -257,6 +276,106 @@ def disabled_names() -> set[str]:+# ---------------------------------------------------------------------------+# Delete: remove one entry from its native file+# ---------------------------------------------------------------------------++_KEY = {CLAUDE: "mcpServers", CODEX: "mcp_servers", OPENCODE: "mcp"}+# One read-modify-write at a time, so two deletes from one file never lose an edit.+_EDIT_LOCK = threading.Lock()+++def _toml_header_path(line: str) -> Optional[tuple[str, ...]]:+ """Key path of a ``[table]`` / ``[[array]]`` header line, else ``None``."""++ stripped = line.strip()+ if not stripped.startswith("["):+ return None+ inner = stripped[2:] if stripped.startswith("[[") else stripped[1:]+ close = inner.find("]]" if stripped.startswith("[[") else "]")+ if close < 0:+ return None+ try:+ node: Any = _parse(CODEX, f"{inner[:close]} = 0")+ except Exception:+ return None+ path: list[str] = []+ while isinstance(node, dict) and len(node) == 1:+ key, node = next(iter(node.items()))+ path.append(key)+ return tuple(path)+++def _remove_codex(text: str, name: str) -> str:+ """Drop ``[mcp_servers.<name>]`` and its sub-tables, line for line."""++ kept: list[str] = []+ dropping = False+ for line in text.splitlines(keepends=True):+ header = _toml_header_path(line)+ if header is not None:+ dropping = header[:2] == (_KEY[CODEX], name)+ if not dropping:+ kept.append(line)+ return "".join(kept)+++def _remove_text(source: str, text: str, name: str) -> str:+ if source == CODEX:+ return _remove_codex(text, name)+ from vibe.opencode_config import remove_jsonc_member++ return remove_jsonc_member(text, _KEY[source], name)+++def remove_entry(source: str, name: str) -> bool:+ """Delete ``name`` from ``source``'s native file; ``False`` if it is already gone.++ Re-reads the file, so an edit since discovery is respected. The result must+ parse to the original minus that one entry, or nothing is written.+ """++ with _EDIT_LOCK:+ return _remove_entry_locked(source, name)+++def _remove_entry_locked(source: str, name: str) -> bool:+ from config.atomic_io import write_atomic++ path, _data = _load(source)+ try:+ text = path.read_text(encoding="utf-8")+ data = _parse(source, text)+ except FileNotFoundError:+ return False+ except Exception as exc:+ raise _unreadable(source, path, exc) from None+ if not isinstance(data, dict) or name not in _servers(source, data):+ return False+ try:+ updated = _remove_text(source, text, name)+ expected = json.loads(json.dumps(data, default=str))+ expected[_KEY[source]].pop(name)+ actual = json.loads(json.dumps(_parse(source, updated), default=str))+ if expected[_KEY[source]] == {} and _KEY[source] not in actual:+ expected.pop(_KEY[source]) # an implicit TOML parent table goes with its last child+ if actual != expected:+ raise ValueError("entry is not a standalone block")+ except Exception as exc:+ raise McpHubError(+ "invalid_native_config",+ f"{source} config {path}: could not remove {name!r} without touching other content ({exc}).",+ hint=f"Remove it from {path} by hand.",+ ) from None++ def unchanged() -> None:+ if path.read_text(encoding="utf-8") != text:+ raise McpHubError("native_config_changed", f"{path} changed while removing {name!r}; try again.")++ write_atomic(path, updated, follow_symlinks=True, mode=path.stat().st_mode & 0o777, before_replace=unchanged)+ return True++# ---------------------------------------------------------------------------# Spawn isolation: Avibe sessions never load native MCP servers# ---------------------------------------------------------------------------diff --git a/core/mcp_hub/repository.py b/core/mcp_hub/repository.pyindex bdba6104a..e8130ca70 100644--- a/core/mcp_hub/repository.py+++ b/core/mcp_hub/repository.py@@ -194,26 +194,26 @@ def write_definition(definition: dict[str, Any]) -> str:def remove_package(name: str) -> str:- """Avibe source: delete artifacts. Native source: hide in Avibe only."""+ """Avibe source: delete artifacts. Native source: delete the entry from its file.++ A native entry already gone from its file only drops Avibe's snapshot.+ """validate_name(name)- mcp_oauth.delete_oauth(name)- if read_avibe_definition(name) is not None:- directory = package_dir(name)- if directory.exists():- shutil.rmtree(directory)- return AVIBE- if name in native.read_all() or name in native.disabled_names():- hide_name(name)- directory = package_dir(name)- if directory.exists():- shutil.rmtree(directory)- return "native"directory = package_dir(name)+ kind = AVIBE if read_avibe_definition(name) is not None else None+ if kind is None:+ server = native.read_all().get(name)+ source = server.source if server is not None else native.disabled_source(name)+ if source is not None:+ native.remove_entry(source, name)+ kind = "native"+ if kind is None and not directory.exists():+ raise _not_found(name)+ mcp_oauth.delete_oauth(name) # only after a refused native edit can no longer happenif directory.exists():shutil.rmtree(directory)- return AVIBE- raise _not_found(name)+ return kind or AVIBEdef delete_artifacts(name: str) -> None:diff --git a/docs/MCP_HUB.md b/docs/MCP_HUB.mdindex d9dc69634..629a877a7 100644--- a/docs/MCP_HUB.md+++ b/docs/MCP_HUB.md@@ -7,9 +7,9 @@ Reachable servers are registered automatically. Two sources share one list:| Source | Where it lives ||---|---|| Avibe | `<avibe-home>/mcp/<name>/definition.json` (page or `vibe mcp-add`) |-| Claude | `~/.claude.json` `mcpServers` (read-only) |-| Codex | `~/.codex/config.toml` `[mcp_servers.<name>]` (read-only) |-| OpenCode | `~/.config/opencode/opencode.json` `mcp` (read-only) |+| Claude | `~/.claude.json` `mcpServers` |+| Codex | `~/.codex/config.toml` `[mcp_servers.<name>]` |+| OpenCode | `~/.config/opencode/opencode.json` `mcp` |Avibe sessions do not load native MCP: Claude, Codex and OpenCode started by Avibe call tools only through `vibe mcp`. Native files are not rewritten for this.@@ -49,7 +49,7 @@ vibe mcp-add --json-stdin < servers.json## Delete- Avibe source: remove the definition and artifacts.-- Native source: hide in Avibe (`<avibe-home>/mcp/.hidden.json`); the native file is unchanged.+- Native source: delete that one entry from the Claude/Codex/OpenCode file listed above (Codex: the `[mcp_servers.<name>]` table and its sub-tables). Everything else in the file — other servers, keys, comments, layout, file mode — is kept. That agent no longer has the server either. If the entry is already gone, only Avibe's snapshot is dropped; if the file cannot be parsed, or the entry is not a standalone block (for example an inline table), nothing is written and the error says to remove it by hand. Names hidden by older versions (`<avibe-home>/mcp/.hidden.json`) stay hidden; new deletes do not write it.```bashvibe mcp docs --removediff --git a/docs/plans/mcp-hub-mvp.md b/docs/plans/mcp-hub-mvp.mdindex e77f7af81..c1d3b9eea 100644--- a/docs/plans/mcp-hub-mvp.md+++ b/docs/plans/mcp-hub-mvp.md@@ -9,7 +9,7 @@Add MCP Hub to the Skills & MCP page. Reachable servers are registered automatically; unreachable ones are simply not listed. Every backend calls tools through `vibe mcp <server> <tool>`; no Skill loader.-**Native MCP is off.** Claude, Codex and OpenCode must not load their own MCP servers in Avibe sessions. Hub **reads** native files as one source and stores Avibe-added servers only under `<avibe-home>/mcp/<name>/definition.json` (add never writes native files):+**Native MCP is off.** Claude, Codex and OpenCode must not load their own MCP servers in Avibe sessions. Hub **reads** native files as one source and stores Avibe-added servers only under `<avibe-home>/mcp/<name>/definition.json` (add never writes native files; delete of a native server removes its entry, §Delete):- Claude: `~/.claude.json` `mcpServers`- Codex: `~/.codex/config.toml` `[mcp_servers.<name>]`@@ -30,7 +30,7 @@ Out of scope: OAuth (now `docs/plans/mcp-hub-oauth.md`), SSE (explicit `unsuppor```text<avibe-home>/mcp/- .hidden.json # names hidden from Avibe lists (native files unchanged)+ .hidden.json # legacy: names hidden by released versions; still honored, no longer written<name>/definition.json # Avibe-owned connection (absent for native-only servers)current.json # pointer to the one published snapshot@@ -41,7 +41,7 @@ Out of scope: OAuth (now `docs/plans/mcp-hub-oauth.md`), SSE (explicit `unsupporcommands.json```-- Native files are a read-only source. Avibe-added servers store `definition.json` here. Hub never writes Claude/Codex/OpenCode files. Every file is written with `config/atomic_io.py` `write_atomic`.+- Native files are a source. Avibe-added servers store `definition.json` here. Hub writes Claude/Codex/OpenCode files only to delete one named entry (see Delete). Every file is written with `config/atomic_io.py` `write_atomic`.- `commands.json` is declarative data interpreted by the shared `vibe mcp` runner, not code.- One published snapshot per server. An unreadable or unknown-`formatVersion` snapshot omits only that package; leftover MVP `state.json` is ignored.@@ -140,7 +140,7 @@ Skills & MCP page, MCP tab. No status badges, enable toggle, or edit dialog.- Row: transport icon, name, command/URL, tool count · transport, source chip (Avibe/Claude/Codex/OpenCode).- Detail: connection, tools, `vibe mcp <name> <tool>`, last refreshed. Footer: 刷新 / 删除.- Add dialog: JSON textarea, 取消 / 添加. Invalid JSON or failed refresh keeps the dialog open.-- Delete: Avibe source removes artifacts. Native source **hides in Avibe only** (`.hidden.json`); the native file is never touched. Owner-confirmed.+- Delete: Avibe source removes artifacts. Native source **removes the entry from its owning native file** (Claude `mcpServers`, Codex `[mcp_servers.<name>]` + sub-tables, OpenCode `mcp`) by a text edit that keeps every other byte, then drops Avibe's snapshot. Owner-confirmed; the dialog names the file and says the other agent loses the server. The result must parse to the original minus that entry, else nothing is written (`invalid_native_config`). An entry already gone only drops the snapshot. Only the canonical (first) source is edited. No backups or undo. *Decision reversed 2026-11-01 (owner): earlier MVP hid native deletes in `.hidden.json`; released `.hidden.json` names stay honored, new deletes no longer write it.*## 6. Discovery and versions@@ -183,7 +183,7 @@ GET /api/mcp/{name}POST /api/mcp # add JSON block → Avibe store + refreshPOST /api/mcp/discoverPOST /api/mcp/{name}/refresh-DELETE /api/mcp/{name} # Avibe: remove; native: hide+DELETE /api/mcp/{name} # Avibe: remove; native: delete entry from its file```Read routes Editor; management Owner. Native async FastAPI → owner IPC.@@ -204,7 +204,7 @@ Acceptance:1. Fresh start with reachable native servers lists and calls them without user action; unreachable ones are absent and `vibe mcp-discover` shows why.2. `vibe mcp-discover` and `vibe mcp <name> --refresh` work from CLI and UI; concurrent passes join. Startup discovery never blocks the controller loop or readiness.3. Add through page/`vibe mcp-add` writes only the Avibe store and the server appears after the call returns.-4. Delete of an Avibe server removes it. Delete of a native server hides it in Avibe only (owner-confirmed); the native file is never touched.+4. Delete of an Avibe server removes it. Delete of a native server removes that entry from its native file (owner-confirmed), preserving the rest of the file.5. Help/list work with the owner down; schema-to-flag contracts hold; injected prompt examples are parser-tested.6. UI matches the Pencil frames; leftover MVP `state.json` enabled flags and drafts load safely (ignored).7. Avibe-spawned sessions do not load native MCP (C3 unchanged).diff --git a/tests/test_mcp_hub_native.py b/tests/test_mcp_hub_native.pyindex d31092f25..36aacf723 100644--- a/tests/test_mcp_hub_native.py+++ b/tests/test_mcp_hub_native.py@@ -2,7 +2,7 @@Contract (docs/plans/mcp-hub-mvp.md §1, acceptance 6): Hub lists the union ofClaude ``.claude.json``, Codex ``config.toml`` and OpenCode ``opencode.json``-servers as a read-only union, stores Avibe-added servers under the Hub,+servers, deletes a native entry from its own file only, stores Avibe-added servers under the Hub,and every spawn path disables the user's native servers.Runs under the hermetic homes ``tests/conftest.py`` provides."""@@ -69,7 +69,7 @@ def test_hub_reads_native_union_without_listing_unpublished(native_files):assert repository.list_packages() == [] # unpublished native entries are not listed-def test_add_writes_avibe_store_and_remove_hides_native(native_files, runtime):+def test_add_writes_avibe_store_without_touching_native(native_files, runtime):claude, _codex, _opencode = native_filesbefore = claude.read_bytes()new = {"name": "fresh", "server": {"command": "/nonexistent/mcp-fresh"}}@@ -79,9 +79,82 @@ def test_add_writes_avibe_store_and_remove_hides_native(native_files, runtime):assert claude.read_bytes() == beforeassert "fresh" not in {item["name"] for item in repository.list_packages()}- assert _run(runtime, "remove", {"name": "shared"})["ok"]- assert claude.read_bytes() == before- assert "shared" in repository.hidden_names()++CODEX_COMMENTED = """# my codex config+model = "gpt-test" # pinned++[mcp_servers.keep]+command = "keep" # stays++# the one to delete+[mcp_servers.gone]+command = "gone"++[mcp_servers.gone.env]+TOKEN = "x"++[profiles.fast]+model = "fast"+"""+++def test_remove_deletes_codex_table_and_subtables_preserving_text(native_files, runtime):+ _claude, codex, _opencode = native_files+ codex.write_text(CODEX_COMMENTED)+ codex.chmod(0o640)+ repository.package_dir("gone").mkdir(parents=True)++ result = _run(runtime, "remove", {"name": "gone"})++ assert result["ok"] and result["kind"] == "native"+ assert codex.read_text() == CODEX_COMMENTED.replace(+ '[mcp_servers.gone]\ncommand = "gone"\n\n[mcp_servers.gone.env]\nTOKEN = "x"\n\n', ""+ )+ assert codex.stat().st_mode & 0o777 == 0o640+ assert not repository.package_dir("gone").exists()+ assert "gone" not in repository.hidden_names()+++def test_remove_deletes_claude_entry_preserving_other_keys_and_layout(native_files, runtime):+ claude, _codex, _opencode = native_files+ claude.write_text(json.dumps(CLAUDE, indent=2) + "\n")++ assert _run(runtime, "remove", {"name": "docs"})["ok"]++ expected = {"numStartups": 7, "mcpServers": {"shared": CLAUDE["mcpServers"]["shared"]}}+ assert claude.read_text() == json.dumps(expected, indent=2) + "\n"+++def test_remove_deletes_last_opencode_entry_keeping_comments(native_files, runtime):+ _claude, _codex, opencode = native_files+ text = '{\n // mine\n "theme": "x",\n "mcp": {\n "keep": {"type": "remote", "url": "https://k.invalid"},\n "oc": {"type": "local", "command": ["node"]}\n }\n}\n'+ opencode.write_text(text)++ assert _run(runtime, "remove", {"name": "oc"})["ok"]++ assert opencode.read_text() == text.replace(',\n "oc": {"type": "local", "command": ["node"]}', "")+++def test_remove_of_entry_already_gone_drops_snapshot(native_files, runtime):+ _claude, codex, _opencode = native_files+ repository.package_dir("vanished").mkdir(parents=True)+ before = codex.read_bytes()++ assert _run(runtime, "remove", {"name": "vanished"})["ok"]++ assert codex.read_bytes() == before+ assert not repository.package_dir("vanished").exists()+++def test_remove_never_writes_a_file_it_cannot_parse(native_files):+ from core.mcp_hub.errors import McpHubError++ _claude, codex, _opencode = native_files+ codex.write_text("[mcp_servers.local]\ncommand = 'srv'\nbroken")+ with pytest.raises(McpHubError) as caught:+ native.remove_entry(native.CODEX, "local")+ assert caught.value.type == "invalid_native_config"+ assert codex.read_text() == "[mcp_servers.local]\ncommand = 'srv'\nbroken"def test_concurrent_hide_keeps_every_name(native_files):@@ -261,3 +334,28 @@ def test_spawns_disable_every_native_server(native_files):))assert only_in_overlay["mcp"]["extra"]["enabled"] is Falseassert only_in_overlay["mcp"]["oc"]["enabled"] is False+++def test_remove_last_codex_server_drops_implicit_parent(native_files):+ _claude, codex, _opencode = native_files+ codex.write_text('model = "m"\n\n[mcp_servers.only]\ncommand = "srv"\n')++ assert native.remove_entry(native.CODEX, "only")++ assert codex.read_text() == 'model = "m"\n\n'+++def test_refused_native_remove_keeps_oauth_login(native_files, runtime):+ from core.mcp_hub import oauth as mcp_oauth++ _claude, codex, _opencode = native_files+ codex.write_text('[mcp_servers]\ninline = { url = "https://i.invalid/mcp" }\n')+ oauth_file = mcp_oauth.oauth_path("inline")+ oauth_file.parent.mkdir(parents=True)+ oauth_file.write_text("{}")++ result = _run(runtime, "remove", {"name": "inline"})++ assert result["ok"] is False and result["error"]["type"] == "invalid_native_config"+ assert oauth_file.exists()+ assert "inline" in codex.read_text()diff --git a/tests/test_mcp_hub_runtime.py b/tests/test_mcp_hub_runtime.pyindex 54f898868..f0a72c2e2 100644--- a/tests/test_mcp_hub_runtime.py+++ b/tests/test_mcp_hub_runtime.py@@ -133,9 +133,7 @@ def test_failed_readd_of_hidden_native_stays_hidden(runtime):claude.write_text(json.dumps({"mcpServers": {"echo": {"type": "stdio", "command": sys.executable, "args": [FIXTURE]},}}))- assert _run(runtime, "discover", {})["ok"]- assert _run(runtime, "remove", {"name": "echo"})["ok"]- assert "echo" in repository.hidden_names()+ repository.hide_name("echo") # hidden by a released version's native deleteresult = _run(runtime, "add", {"servers": [{"name": "echo", "server": {"command": "/nonexistent/mcp-echo"}}]})assert result["ok"] is Falseassert "echo" in repository.hidden_names()@@ -172,9 +170,7 @@ def test_readding_hidden_native_identical_definition_registers_again(runtime):claude.write_text(json.dumps({"mcpServers": {"echo": {"type": "stdio", "command": sys.executable, "args": [FIXTURE]},}}))- assert _run(runtime, "discover", {})["ok"]- assert _run(runtime, "remove", {"name": "echo"})["ok"]- assert "echo" in repository.hidden_names()+ repository.hide_name("echo") # hidden by a released version's native deleteassert repository.read_published("echo") is Noneresult = _run(runtime, "add", {"servers": [_server()]})assert result["ok"] is Truediff --git a/ui/src/components/workbench/skills/McpHubSection.tsx b/ui/src/components/workbench/skills/McpHubSection.tsxindex 0d8d6b456..3b6a6127c 100644--- a/ui/src/components/workbench/skills/McpHubSection.tsx+++ b/ui/src/components/workbench/skills/McpHubSection.tsx@@ -527,7 +527,11 @@ export const McpHubSection: React.FC = () => {<DialogContent className="max-w-md" closeLabel={t('common.close')}><DialogTitle>{t('mcpHub.removeConfirm', { name: confirmDelete?.name ?? '' })}</DialogTitle><DialogDescription>- {confirmDelete?.source === 'avibe' ? t('mcpHub.removeAvibeHint') : t('mcpHub.removeNativeHint')}+ {confirmDelete?.source === 'avibe' ? t('mcpHub.removeAvibeHint') : t('mcpHub.removeNativeHint', {+ name: confirmDelete?.name ?? '',+ path: confirmDelete?.sourcePath ?? '',+ agent: t(`mcpHub.source.${confirmDelete?.source ?? 'avibe'}`),+ })}</DialogDescription><DialogFooter><Button type="button" variant="outline" onClick={() => setConfirmDelete(null)}>{t('common.cancel')}</Button>diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 9ebd79ecf..16d950616 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -6499,7 +6499,7 @@"remove": "Delete","removeConfirm": "Delete MCP server {{name}}?","removeAvibeHint": "This removes the server from Avibe.",- "removeNativeHint": "This hides the server in Avibe. The native config file is not changed.",+ "removeNativeHint": "This removes {{name}} from {{path}}, the {{agent}} config file. {{agent}} will no longer have this server either.","empty": "No MCP server registered. Add one or wait for discovery.","noSearchMatch": "No matching MCP servers.","failed": "MCP operation failed.",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex b09a70487..7bed0f7b1 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -6499,7 +6499,7 @@"remove": "删除","removeConfirm": "删除 MCP 服务器 {{name}}?","removeAvibeHint": "将从 Avibe 中移除该服务器。",- "removeNativeHint": "仅在 Avibe 中隐藏;不会改动原生配置文件。",+ "removeNativeHint": "将从 {{agent}} 的配置文件 {{path}} 中删除 {{name}},{{agent}} 也将不再拥有这个服务器。","empty": "还没有已注册的 MCP 服务器。添加一个,或等待自动发现。","noSearchMatch": "没有匹配的 MCP 服务器。","failed": "MCP 操作失败。",diff --git a/vibe/opencode_config.py b/vibe/opencode_config.pyindex 927547cf9..e0948c692 100644--- a/vibe/opencode_config.py+++ b/vibe/opencode_config.py@@ -376,9 +376,16 @@ def _indent_slice(source: str, line_start: int, token_start: int) -> str:return source[line_start:token_start].replace("\ufeff", "")-def _scan_jsonc_top_level_properties(source: str) -> tuple[int, int, list[_JsoncTopLevelProperty]]:- root_start = 1 if source.startswith("\ufeff") else 0- root_start = _skip_jsonc_whitespace_and_comments(source, root_start)+def _scan_jsonc_top_level_properties(+ source: str, object_start: int | None = None+) -> tuple[int, int, list[_JsoncTopLevelProperty]]:+ """Members of the root object, or of the object starting at ``object_start``."""++ if object_start is None:+ root_start = 1 if source.startswith("\ufeff") else 0+ root_start = _skip_jsonc_whitespace_and_comments(source, root_start)+ else:+ root_start = object_startif root_start >= len(source) or source[root_start] != "{":raise ValueError("root is not a JSON object")@@ -496,6 +503,35 @@ def set_jsonc_top_level_string_property(source: str, key: str, value: str) -> streturn updated_source[:insertion_point] + insertion + updated_source[insertion_point:]+def remove_jsonc_member(source: str, parent_key: str, key: str) -> str:+ """Drop ``parent_key.key`` from the text, leaving every other byte in place."""++ _root_start, _root_end, properties = _scan_jsonc_top_level_properties(source)+ parent = next((prop for prop in reversed(properties) if prop.key == parent_key), None)+ if parent is None or source[parent.value_start] != "{":+ raise ValueError(f"{parent_key} is not an object")+ start, end, members = _scan_jsonc_top_level_properties(source, parent.value_start)+ index = next((i for i in range(len(members) - 1, -1, -1) if members[i].key == key), None)+ if index is None:+ raise KeyError(key)+ member = members[index]+ if len(members) == 1:+ return source[: start + 1] + source[end:]+ if member.delimiter == ",":+ line_start = _line_start(source, member.key_start)+ cut_start = line_start if source[line_start : member.key_start].strip() == "" else member.key_start+ cut_end = member.delimiter_index + 1+ if cut_start == line_start:+ rest = len(source[cut_end:]) - len(source[cut_end:].lstrip(" \t"))+ if source.startswith("\r\n", cut_end + rest) or source.startswith("\n", cut_end + rest):+ cut_end = source.index("\n", cut_end + rest) + 1+ else:+ cut_end += len(source[cut_end:]) - len(source[cut_end:].lstrip(" \t"))+ return source[:cut_start] + source[cut_end:]+ previous = members[index - 1]+ return source[: previous.delimiter_index] + source[member.value_end :]++def load_first_opencode_user_config(*,home: Path | None = None,