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): auto-discover and register MCP Hub servers (#3063)
rkrkrkkda4c291eaa5b
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.pyindex c35704cc4..a4000e3c4 100644--- a/core/agent_auth_service.py+++ b/core/agent_auth_service.py@@ -1650,6 +1650,7 @@ class AgentAuthService:# still get the key into the control-channel SDK client.from vibe.claude_config import (CLAUDE_MEMORY_DISABLED_SETTINGS,+ CLAUDE_NATIVE_MCP_DISABLED,CLAUDE_SETTING_SOURCES,build_claude_subprocess_env,normalize_claude_cli_path,@@ -1677,6 +1678,7 @@ class AgentAuthService:"env": claude_env,"settings": CLAUDE_MEMORY_DISABLED_SETTINGS,"setting_sources": CLAUDE_SETTING_SOURCES,+ **CLAUDE_NATIVE_MCP_DISABLED,"max_buffer_size": CLAUDE_SDK_MAX_BUFFER_SIZE,}permission_mode = getattr(self._resolve_backend_config("claude"), "permission_mode", None)@@ -3175,6 +3177,7 @@ class AgentAuthService:"""Run an isolated turn through the same Claude Agent SDK transport."""from vibe.claude_config import (CLAUDE_MEMORY_DISABLED_SETTINGS,+ CLAUDE_NATIVE_MCP_DISABLED,CLAUDE_SETTING_SOURCES,build_claude_subprocess_env,)@@ -3195,6 +3198,7 @@ class AgentAuthService:"permission_mode": "bypassPermissions","cwd": cwd,"setting_sources": CLAUDE_SETTING_SOURCES,+ **CLAUDE_NATIVE_MCP_DISABLED,"sandbox": {"enabled": False},"tools": [],"max_turns": 1,diff --git a/core/controller.py b/core/controller.pyindex 6139da152..43f3bf0a1 100644--- a/core/controller.py+++ b/core/controller.py@@ -287,6 +287,10 @@ class Controller:self._delivery_recovery_complete = asyncio.Event()self._init_model_hub()+ from core.mcp_hub.runtime import McpRuntime++ # Started lazily on the first MCP request; owns its own thread and loop.+ self.mcp_runtime = McpRuntime()# Initialize core modulesself._init_modules()@@ -336,6 +340,7 @@ class Controller:self.vibey_recovery = VibeyRecovery(self)self.trace_retention_task: Optional[asyncio.Task] = Noneself.web_ui_watchdog_task: Optional[asyncio.Task] = None+ self.mcp_discovery_task: Optional[asyncio.Task] = Noneself._trace_retention_executor: Optional[Any] = Noneself._trace_retention_cancel_event: Optional[threading.Event] = Noneself._trace_retention_future: Optional[Any] = None@@ -1322,6 +1327,21 @@ class Controller:self.web_ui_watchdog_task = asyncio.create_task(watch_web_ui(lambda: self.shutdown_requested))except Exception as e:logger.error("Failed to start the Web UI watchdog: %s", e, exc_info=True)+ try:+ # Off the readiness path: native MCP handshake must not delay startup.+ task = asyncio.create_task(self.mcp_runtime.submit("discover", {}))++ def _log_mcp_discovery(done: asyncio.Task) -> None:+ if done.cancelled():+ return+ exc = done.exception()+ if exc is not None:+ logger.error("MCP Hub discovery failed", exc_info=exc)++ task.add_done_callback(_log_mcp_discovery)+ self.mcp_discovery_task = task+ except Exception as e:+ logger.error("Failed to start MCP Hub discovery: %s", e, exc_info=True)async def _recover_runtime_owners(self) -> None:"""Restore durable execution owners before any producer can admit work."""@@ -2514,6 +2534,10 @@ class Controller:except Exception as e:logger.debug(f"{label} cleanup skipped: {e}")+ mcp_runtime = getattr(self, "mcp_runtime", None)+ if mcp_runtime is not None:+ mcp_runtime.stop()+# Stop update checkertry:update_task = self.update_checker.stop()@@ -2546,6 +2570,16 @@ class Controller:passself.vibey_model_supply_task = None+ async def _cancel_mcp_discovery_task() -> None:+ task = getattr(self, "mcp_discovery_task", None)+ if task is not None and not task.done():+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass+ self.mcp_discovery_task = None+async def _cancel_web_ui_watchdog_task() -> None:task = self.web_ui_watchdog_taskif task and not task.done():@@ -2624,6 +2658,7 @@ class Controller:_stop_loop_coroutine(_cancel_cleanup_task(), "Idle cleanup task")_stop_loop_coroutine(_cancel_vibey_model_supply_task(), "Vibey model supply seed")+ _stop_loop_coroutine(_cancel_mcp_discovery_task(), "MCP Hub discovery")_stop_loop_coroutine(_cancel_web_ui_watchdog_task(), "Web UI watchdog task")# Retention cancellation is cooperative at a delete-batch boundary;# wait for that bounded join instead of abandoning the worker afterdiff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex aceab4c20..8e1d70a7c 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -1720,6 +1720,7 @@ class SessionHandler(BaseHandler):# away from this site's auth_mode handling.from vibe.claude_config import (CLAUDE_MEMORY_DISABLED_SETTINGS,+ CLAUDE_NATIVE_MCP_DISABLED,CLAUDE_SETTING_SOURCES,build_claude_subprocess_env,)@@ -1757,6 +1758,7 @@ class SessionHandler(BaseHandler):"extra_args": extra_args,"settings": claude_settings_for_launch(CLAUDE_MEMORY_DISABLED_SETTINGS, model_hub_launch),"setting_sources": CLAUDE_SETTING_SOURCES,+ **CLAUDE_NATIVE_MCP_DISABLED,"skills": [],"sandbox": CLAUDE_REMOTE_SANDBOX,# Disable interactive-only Claude Code tools that remote IM sessionsdiff --git a/core/internal_server.py b/core/internal_server.pyindex e67dc18bf..b154743f2 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -37,7 +37,7 @@ from types import SimpleNamespacefrom typing import Any, Callable, Optional, TYPE_CHECKINGfrom fastapi import FastAPI, HTTPException, Request-from fastapi.responses import JSONResponse, PlainTextResponse, StreamingResponse+from fastapi.responses import JSONResponse, PlainTextResponse, Response, StreamingResponsefrom config import pathsfrom core import control_ipc@@ -1713,6 +1713,21 @@ def create_app(return JSONResponse(status_code=exc.status, content=response)return {"ok": True, "result": result}+ @app.post("/internal/mcp")+ async def _mcp(request: Request) -> Any:+ """Hand MCP Hub operations to the controller-owned runtime thread."""++ body = await _safe_json(request)+ operation = body.get("operation") if isinstance(body, dict) else None+ payload = body.get("payload") if isinstance(body, dict) else None+ if not isinstance(operation, str) or not isinstance(payload, dict):+ return JSONResponse(status_code=400, content={"ok": False, "error": {"type": "usage"}})+ runtime = getattr(controller, "mcp_runtime", None)+ if runtime is None:+ return JSONResponse(status_code=503, content={"ok": False, "error": {"type": "unavailable"}})+ status, content = await runtime.submit(operation, payload)+ return Response(content=content, status_code=status, media_type="application/json")+@app.get("/internal/events")async def _events() -> Any:"""Long-lived SSE feed of Controller-side inbox events.diff --git a/core/mcp_hub/__init__.py b/core/mcp_hub/__init__.pynew file mode 100644index 000000000..a003dc491--- /dev/null+++ b/core/mcp_hub/__init__.py@@ -0,0 +1 @@+"""MCP Hub: static CLI packages generated from MCP servers (docs/plans/mcp-hub-mvp.md)."""diff --git a/core/mcp_hub/commands.py b/core/mcp_hub/commands.pynew file mode 100644index 000000000..fa8aa7fae--- /dev/null+++ b/core/mcp_hub/commands.py@@ -0,0 +1,241 @@+"""Tool schema -> declarative CLI flags (``commands.json``), argv parsing and validation.++``commands.json`` is data interpreted by the shared ``vibe mcp`` runner: flags map+exact property keys, nothing is aliased, case-converted or defaulted.+"""++from __future__ import annotations++import json+import re+from typing import Any, Optional++from core.mcp_hub.errors import McpHubError++_FLAG_KEY = re.compile(r"^[A-Za-z][A-Za-z0-9_-]*$")+_RESERVED_KEYS = {"args-json", "args-file", "args-stdin", "help"}+_FLAG_KINDS = {"string", "number", "integer", "boolean", "array", "object"}+INPUT_MODES = ("--args-json", "--args-file", "--args-stdin")+++def _validator_for(schema: Any):+ """A JSON Schema validator with remote ``$ref`` retrieval disabled, or ``None``."""++ import jsonschema+ from referencing import Registry+ from referencing.exceptions import NoSuchResource++ def _no_remote(uri: str):+ raise NoSuchResource(ref=uri)++ if not isinstance(schema, dict):+ return None+ try:+ cls = jsonschema.validators.validator_for(schema, default=jsonschema.Draft202012Validator)+ cls.check_schema(schema)+ from referencing.jsonschema import DRAFT202012++ registry = Registry(retrieve=_no_remote).with_resource("", DRAFT202012.create_resource(schema))+ validator = cls(schema, registry=registry)+ validator.is_valid({})+ _assert_refs_resolvable(schema, registry.resolver())+ except Exception:+ return None+ return validator+++def _assert_refs_resolvable(node: Any, resolver) -> None:+ """Walk nested ``$ref`` so an unresolvable optional property is not published as validated."""++ if isinstance(node, dict):+ if "$ref" in node:+ resolver.lookup(node["$ref"])+ for value in node.values():+ _assert_refs_resolvable(value, resolver)+ elif isinstance(node, list):+ for item in node:+ _assert_refs_resolvable(item, resolver)+++def build_command(tool: dict[str, Any]) -> dict[str, Any]:+ """The ``commands.json`` entry for one tool descriptor (``tools/list`` shape)."""++ schema = tool.get("inputSchema")+ validated = _validator_for(schema) is not None+ properties = schema.get("properties") if validated and isinstance(schema, dict) else None+ required = set(schema.get("required") or []) if validated and isinstance(schema, dict) else set()+ flags: list[dict[str, Any]] = []+ json_only_keys: list[str] = []+ if isinstance(properties, dict):+ for key in sorted(properties):+ prop = properties[key] if isinstance(properties[key], dict) else {}+ kind = prop.get("type")+ if (+ isinstance(kind, str)+ and kind in _FLAG_KINDS+ and _FLAG_KEY.match(key)+ and key not in _RESERVED_KEYS+ and not any(word in prop for word in ("anyOf", "oneOf", "allOf", "$ref"))+ ):+ flags.append({+ "flag": f"--{key}",+ "key": key,+ "kind": kind,+ "required": key in required,+ "description": _one_line(prop.get("description")),+ })+ else:+ json_only_keys.append(key)+ return {+ "name": tool["name"],+ "description": _one_line(tool.get("description"), limit=None),+ "validated": validated,+ "flags": flags,+ "jsonOnlyKeys": json_only_keys,+ "requiredJsonOnly": sorted(required & set(json_only_keys)),+ }+++def _one_line(value: object, *, limit: Optional[int] = 200) -> str:+ if not isinstance(value, str):+ return ""+ text = " ".join(value.split())+ return text if limit is None else text[:limit]+++def _usage(message: str, hint: Optional[str] = None) -> McpHubError:+ return McpHubError("usage", message, hint=hint, usage=True)+++def _flag_value(flag: dict[str, Any], raw: str) -> Any:+ kind = flag["kind"]+ if kind == "string":+ return raw+ if kind == "boolean":+ if raw not in {"true", "false"}:+ raise _usage(f"{flag['flag']} expects true or false.")+ return raw == "true"+ try:+ value = json.loads(raw)+ except ValueError:+ raise _usage(f"{flag['flag']} expects a JSON {kind}.") from None+ ok = {+ "number": isinstance(value, (int, float)) and not isinstance(value, bool),+ "integer": isinstance(value, int) and not isinstance(value, bool),+ "array": isinstance(value, list),+ "object": isinstance(value, dict),+ }[kind]+ if not ok:+ raise _usage(f"{flag['flag']} expects a JSON {kind}.")+ return value+++def parse_tool_argv(+ command: dict[str, Any],+ argv: list[str],+ *,+ read_file=None,+ read_stdin=None,+) -> dict[str, Any]:+ """Turn ``vibe mcp <server> <tool>`` arguments into the tool's argument object."""++ flags = {flag["flag"]: flag for flag in command.get("flags") or []}+ arguments: dict[str, Any] = {}+ mode: Optional[str] = None+ payload: Any = None+ index = 0+ while index < len(argv):+ token = argv[index]+ option, eq, inline = token.partition("=")+ if not token.startswith("--"):+ raise _usage(f"Unexpected argument {token!r}.")+ if option in INPUT_MODES:+ if mode is not None or arguments:+ raise _usage("Use one input mode per call: flags, --args-json, --args-file or --args-stdin.")+ mode = option+ if option == "--args-stdin":+ if eq:+ raise _usage("--args-stdin takes no value.")+ payload = read_stdin() if read_stdin else ""+ else:+ if not eq:+ if index + 1 >= len(argv):+ raise _usage(f"{option} requires a value.")+ index += 1+ inline = argv[index]+ payload = inline if option == "--args-json" else (read_file(inline) if read_file else "")+ index += 1+ continue+ flag = flags.get(option)+ if flag is None:+ raise _usage(+ f"Unknown flag {option}.",+ hint="Inspect arguments with --help; keys without a flag need --args-json.",+ )+ if mode is not None:+ raise _usage("Use one input mode per call: flags, --args-json, --args-file or --args-stdin.")+ if flag["key"] in arguments:+ raise _usage(f"{option} was given more than once.")+ if not eq:+ if index + 1 >= len(argv):+ raise _usage(f"{option} requires a value.")+ index += 1+ inline = argv[index]+ arguments[flag["key"]] = _flag_value(flag, inline)+ index += 1+ if mode is None:+ return arguments+ try:+ value = json.loads(payload)+ except (TypeError, ValueError) as exc:+ raise _usage(f"{mode} is not valid JSON: {exc}") from None+ if not isinstance(value, dict):+ raise _usage(f"{mode} must be a JSON object.")+ return value+++def validate_arguments(tool: dict[str, Any], arguments: dict[str, Any]) -> None:+ """Validate against the published input schema; unhandleable schemas are not validated."""++ validator = _validator_for(tool.get("inputSchema"))+ if validator is None:+ return+ errors = sorted(validator.iter_errors(arguments), key=lambda error: list(error.path))+ if errors:+ first = errors[0]+ where = "/".join(str(part) for part in first.path) or "(root)"+ raise McpHubError(+ "invalid_arguments",+ f"Arguments do not match the tool schema at {where}: {first.message}",+ usage=True,+ )+++def render_tool_help(server: str, command: dict[str, Any], escape) -> str:+ lines = [f"vibe mcp {server} {_selector(command['name'])} [flags]"]+ if command.get("description"):+ lines += ["", escape(command["description"])]+ flags = command.get("flags") or []+ if flags:+ lines += ["", "Flags:"]+ for flag in flags:+ required = " (required)" if flag["required"] else ""+ detail = f" {escape(flag['description'])}" if flag["description"] else ""+ lines.append(f" {escape(flag['flag'])} <{flag['kind']}>{required}{detail}")+ if command.get("jsonOnlyKeys"):+ keys = ", ".join(escape(key) for key in command["jsonOnlyKeys"])+ lines += ["", f"Keys only accepted via --args-json/--args-file/--args-stdin: {keys}"]+ if command.get("requiredJsonOnly"):+ lines.append("A required key has no flag: call this tool with --args-json.")+ if not command.get("validated"):+ lines += ["", "This tool's input schema could not be validated locally; pass arguments as JSON."]+ lines += [+ "",+ "Input: flags, or exactly one of --args-json '<object>', --args-file <path>, --args-stdin.",+ f"Schema: vibe mcp {server} --list --format json",+ ]+ return "\n".join(lines)+++def _selector(tool_name: str) -> str:+ return f"-- {tool_name}" if tool_name.startswith("-") else tool_namediff --git a/core/mcp_hub/definition.py b/core/mcp_hub/definition.pynew file mode 100644index 000000000..12488a364--- /dev/null+++ b/core/mcp_hub/definition.py@@ -0,0 +1,329 @@+"""Connection definitions: provider ``mcpServers`` JSON and ``vibe mcp-add`` argv.++Both entry points normalize through :func:`definition_from_provider`, so the page+and the CLI produce identical ``definition.json`` documents. Parsing never runs or+connects to anything.+"""++from __future__ import annotations++import json+import os+import re+from typing import Any, Optional+from urllib.parse import urlsplit++from core.mcp_hub.errors import McpHubError++SCHEMA_VERSION = 1+STDIO = "stdio"+HTTP = "streamable_http"++_STDIO_TYPES = {None, "stdio"}+_HTTP_TYPES = {"http", "streamable-http", "streamable_http"}+_PROVIDER_FIELDS = {"type", "command", "args", "env", "cwd", "url", "headers", "enabled", "description"}+_PLACEHOLDER = re.compile(r"\$\{[^}]*\}")+_ENV_KEY = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")+_HEADER_NAME = re.compile(r"^[!#$%&'*+.^_`|~0-9A-Za-z-]+$")+DESCRIPTION_MAX = 160+++def validate_name(name: object) -> str:+ """Accept any native/user name that can be a directory and a `vibe mcp` token."""++ if not isinstance(name, str) or not name or "\x00" in name or "/" in name or "\\" in name or name in {".", ".."}:+ raise McpHubError(+ "invalid_name",+ "Server names cannot be empty, `.`/`..`, or contain `/`, `\\`, or NUL.",+ field="name",+ usage=True,+ )+ if name in {".hidden.json", "hidden.json"}:+ raise McpHubError(+ "invalid_name",+ "Server name hidden.json is reserved for Avibe MCP Hub metadata.",+ field="name",+ usage=True,+ )+ return name+++def _invalid(field: str, message: str) -> McpHubError:+ return McpHubError("invalid_definition", message, field=field, usage=True)+++def _text(value: object, field: str, *, allow_empty: bool = False) -> str:+ if not isinstance(value, str) or (not allow_empty and not value.strip()):+ raise _invalid(field, f"{field} must be a non-empty string.")+ if "\x00" in value:+ raise _invalid(field, f"{field} must not contain NUL characters.")+ if _PLACEHOLDER.search(value):+ raise _invalid(+ field,+ f"{field} uses a ${{VAR}} placeholder; MCP Hub does not expand variables, enter the literal value.",+ )+ return value+++def _string_map(value: object, field: str, key_pattern: re.Pattern[str]) -> dict[str, str]:+ if value is None:+ return {}+ if not isinstance(value, dict):+ raise _invalid(field, f"{field} must be an object of string values.")+ result: dict[str, str] = {}+ for key, item in value.items():+ if not isinstance(key, str) or not key_pattern.match(key):+ raise _invalid(f"{field}.{key}", f"{field} has an invalid name: {key!r}.")+ result[key] = _text(item, f"{field}.{key}", allow_empty=True)+ return result+++def normalize_description(value: object) -> str:+ """One line, at most 160 characters; used for the prompt index and lists."""++ if value is None:+ return ""+ if not isinstance(value, str):+ raise _invalid("description", "description must be a string.")+ return " ".join(value.split())[:DESCRIPTION_MAX]+++def definition_from_provider(name: str, server: object, *, description: object = None) -> dict[str, Any]:+ """Normalize one provider ``mcpServers`` entry into a persisted definition."""++ validate_name(name)+ if not isinstance(server, dict):+ raise _invalid("server", f"mcpServers.{name} must be an object.")+ # Backend-owned extras (env_vars, timeouts, …) are ignored, not rejected.+ kind = server.get("type")+ if kind == "sse":+ raise McpHubError(+ "unsupported_transport_sse",+ "SSE transport is not supported; use a Streamable HTTP URL.",+ field="type",+ usage=True,+ )+ has_command = "command" in server+ has_url = "url" in server+ if has_command and has_url:+ raise _invalid("url", "Use either command (stdio) or url (Streamable HTTP), not both.")+ if description is None:+ description = server.get("description")+ definition: dict[str, Any] = {+ "schemaVersion": SCHEMA_VERSION,+ "name": name,+ "description": normalize_description(description),+ }+ if has_url or kind in _HTTP_TYPES:+ if kind not in _HTTP_TYPES | {None}:+ raise _invalid("type", f"Unsupported transport type {kind!r}.")+ for field in ("args", "env", "cwd"):+ if field in server:+ raise _invalid(field, f"{field} applies only to stdio servers.")+ definition["transport"] = {+ "type": HTTP,+ "url": _validate_url(server.get("url")),+ "headers": _string_map(server.get("headers"), "headers", _HEADER_NAME),+ }+ return definition+ if kind not in _STDIO_TYPES:+ raise _invalid("type", f"Unsupported transport type {kind!r}.")+ if "headers" in server:+ raise _invalid("headers", "headers apply only to HTTP servers.")+ args = server.get("args", [])+ if not isinstance(args, list):+ raise _invalid("args", "args must be an array of strings.")+ transport: dict[str, Any] = {+ "type": STDIO,+ "command": _text(server.get("command"), "command"),+ "args": [_text(item, f"args[{index}]", allow_empty=True) for index, item in enumerate(args)],+ "env": _string_map(server.get("env"), "env", _ENV_KEY),+ }+ if server.get("cwd") is not None:+ cwd = _text(server["cwd"], "cwd")+ if not os.path.isabs(cwd):+ raise _invalid("cwd", "cwd must be an absolute path.")+ transport["cwd"] = cwd+ definition["transport"] = transport+ return definition+++def _validate_url(value: object) -> str:+ url = _text(value, "url")+ parts = urlsplit(url)+ if parts.scheme not in {"http", "https"} or not parts.hostname:+ raise _invalid("url", "url must be an http(s) URL.")+ if parts.username is not None or parts.password is not None:+ raise _invalid("url", "url must not embed credentials; put them in an Authorization header.")+ return url+++def parse_provider_json(text: str) -> list[dict[str, Any]]:+ """Parse a pasted ``{"mcpServers": {...}}`` block into definitions (sorted by name)."""++ try:+ document = json.loads(text)+ except (TypeError, ValueError) as exc:+ raise _invalid("json", f"Invalid JSON: {exc}") from None+ if not isinstance(document, dict) or not isinstance(document.get("mcpServers"), dict):+ raise _invalid("mcpServers", 'Expected an object with an "mcpServers" map.')+ servers = document["mcpServers"]+ if not servers:+ raise _invalid("mcpServers", "mcpServers is empty.")+ parsed: list[dict[str, Any]] = []+ failures: list[dict[str, str]] = []+ first_error: McpHubError | None = None+ for name in sorted(servers):+ try:+ parsed.append(definition_from_provider(name, servers[name]))+ except McpHubError as cop:+ if first_error is None:+ first_error = cop+ failures.append({"name": str(name), "error": cop.message, "type": cop.type})+ if not parsed:+ if len(failures) == 1 and first_error is not None:+ raise first_error+ raise McpHubError(+ "invalid_definition",+ "; ".join(f"{item['name']}: {item['error']}" for item in failures),+ usage=True,+ )+ return ProviderBatch(parsed, failures)+++class ProviderBatch(list):+ """Parsed definitions plus any entry-level failures that did not abort the document."""++ def __init__(self, definitions: list[dict[str, Any]], failures: list[dict[str, str]]):+ super().__init__(definitions)+ self.failures = failures+++# ---------------------------------------------------------------------------+# ``vibe mcp-add`` (Claude Code ``mcp add`` subset plus Avibe extensions)+# ---------------------------------------------------------------------------++_UNSUPPORTED_ADD_OPTIONS = {"--scope", "-s", "--callback-port", "--client-id", "--client-secret"}+++def parse_add_argv(argv: list[str]) -> tuple[list[dict[str, Any]], bool]:+ """Return ``(definitions, replace)`` for ``vibe mcp-add`` arguments.++ ``--json-stdin`` is resolved by the caller, which passes the stdin text as+ the single token after ``--json-stdin``.+ """++ if "--" in argv:+ split = argv.index("--")+ head, command = argv[:split], argv[split + 1 :]+ else:+ head, command = argv, None+ transport = "stdio"+ env: dict[str, str] = {}+ headers: dict[str, str] = {}+ description: Optional[str] = None+ cwd: Optional[str] = None+ replace = False+ json_text: Optional[str] = None+ positionals: list[str] = []+ index = 0++ def value_of(option: str) -> str:+ nonlocal index+ if index + 1 >= len(head):+ raise McpHubError("usage", f"{option} requires a value.", usage=True)+ index += 1+ return head[index]++ while index < len(head):+ token = head[index]+ option, eq, inline = token.partition("=") if token.startswith("--") else (token, "", "")+ if option in _UNSUPPORTED_ADD_OPTIONS:+ raise McpHubError("unsupported_option", f"{option} is not supported by vibe mcp-add.", usage=True)+ if option in {"--transport", "-t"}:+ transport = inline if eq else value_of(option)+ elif option in {"--env", "-e"}:+ # Claude's --env is variadic: it takes every following KEY=VALUE.+ values = [inline] if eq else []+ while index + 1 < len(head) and "=" in head[index + 1] and not head[index + 1].startswith("-"):+ index += 1+ values.append(head[index])+ if not values:+ raise McpHubError("usage", "--env requires KEY=VALUE.", usage=True)+ for item in values:+ key, sep, val = item.partition("=")+ if not sep:+ raise McpHubError("usage", f"--env expects KEY=VALUE, got {item!r}.", usage=True)+ env[key] = val+ elif option in {"--header", "-H"}:+ item = inline if eq else value_of(option)+ key, sep, val = item.partition(":")+ if not sep:+ raise McpHubError("usage", f"--header expects 'Name: value', got {item!r}.", usage=True)+ headers[key.strip()] = val.strip()+ elif option == "--description":+ description = inline if eq else value_of(option)+ elif option == "--cwd":+ cwd = inline if eq else value_of(option)+ elif option == "--replace":+ replace = True+ elif option == "--json-stdin":+ json_text = value_of(option)+ elif token.startswith("-") and token != "-":+ raise McpHubError("usage", f"Unknown option {token}.", usage=True)+ else:+ positionals.append(token)+ index += 1++ if json_text is not None:+ if positionals or command is not None or env or headers or description or cwd:+ raise McpHubError("usage", "--json-stdin takes no other server arguments.", usage=True)+ return parse_provider_json(json_text), replace+ if not positionals:+ raise McpHubError("usage", "Missing server name.", usage=True)+ name, rest = positionals[0], positionals[1:]+ kind = {"stdio": None, "http": "http", "sse": "sse"}.get(transport)+ if transport not in {"stdio", "http", "sse"}:+ raise McpHubError("usage", f"Unsupported --transport {transport!r}; use stdio or http.", usage=True)+ server: dict[str, Any] = {} if kind is None else {"type": kind}+ if kind is None:+ argv_command = command if command is not None else rest+ if command is not None and rest:+ raise McpHubError("usage", "Put the server command after --.", usage=True)+ if not argv_command:+ raise McpHubError("usage", "Missing server command (vibe mcp-add <name> -- <command> [args...]).", usage=True)+ server.update(command=argv_command[0], args=argv_command[1:])+ if env:+ server["env"] = env+ if cwd is not None:+ server["cwd"] = cwd+ if headers:+ server["headers"] = headers+ else:+ if command is not None or len(rest) != 1:+ raise McpHubError("usage", "HTTP servers take exactly one URL: vibe mcp-add --transport http <name> <url>.", usage=True)+ server["url"] = rest[0]+ if headers:+ server["headers"] = headers+ if env:+ server["env"] = env+ if cwd is not None:+ server["cwd"] = cwd+ return [definition_from_provider(name, server, description=description)], replace+++def provider_entry(definition: dict[str, Any]) -> dict[str, Any]:+ """The provider-shape entry for a definition (inverse of normalization)."""++ transport = definition["transport"]+ if transport["type"] == HTTP:+ entry: dict[str, Any] = {"type": "http", "url": transport["url"]}+ if transport.get("headers"):+ entry["headers"] = transport["headers"]+ return entry+ entry = {"command": transport["command"], "args": list(transport.get("args") or [])}+ for field in ("env", "cwd"):+ if transport.get(field):+ entry[field] = transport[field]+ return entry+diff --git a/core/mcp_hub/errors.py b/core/mcp_hub/errors.pynew file mode 100644index 000000000..279d6cb57--- /dev/null+++ b/core/mcp_hub/errors.py@@ -0,0 +1,48 @@+"""The one error shape every MCP Hub layer raises and serializes."""++from __future__ import annotations++from typing import Any, Optional+++class McpHubError(Exception):+ """A categorized failure: ``type`` is the stable ``error.type`` callers branch on."""++ def __init__(+ self,+ type: str,+ message: str,+ *,+ field: Optional[str] = None,+ hint: Optional[str] = None,+ usage: bool = False,+ ) -> None:+ super().__init__(message)+ self.type = type+ self.message = message+ self.field = field+ self.hint = hint+ # Usage errors exit 2 at the CLI; everything else exits 1.+ self.usage = usage++ def payload(self) -> dict[str, Any]:+ data: dict[str, Any] = {"type": self.type, "message": self.message}+ if self.field:+ data["field"] = self.field+ if self.hint:+ data["hint"] = self.hint+ if self.usage:+ data["usage"] = True+ return data++ @classmethod+ def from_payload(cls, data: Any) -> "McpHubError":+ if not isinstance(data, dict):+ return cls("internal", "Unexpected MCP Hub response")+ return cls(+ str(data.get("type") or "internal"),+ str(data.get("message") or ""),+ field=data.get("field"),+ hint=data.get("hint"),+ usage=data.get("usage") is True,+ )diff --git a/core/mcp_hub/native.py b/core/mcp_hub/native.pynew file mode 100644index 000000000..61e4a818f--- /dev/null+++ b/core/mcp_hub/native.py@@ -0,0 +1,301 @@+"""The backends' own MCP config files are the Hub's connection store.++Hub reads the union of:++- Claude ``~/.claude.json`` (or ``$CLAUDE_CONFIG_DIR/.claude.json``) ``mcpServers``+- 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``.+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`.+"""++from __future__ import annotations++import json+import logging+import os+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Callable, Optional++from core.mcp_hub.definition import definition_from_provider+from core.mcp_hub.errors import McpHubError++logger = logging.getLogger(__name__)++CLAUDE, CODEX, OPENCODE = "claude", "codex", "opencode"+SOURCES = (CLAUDE, CODEX, OPENCODE)++# Native keys that carry no connection meaning for the Hub; kept on rewrite.+_CODEX_KEPT = {"enabled", "startup_timeout_sec", "startup_timeout_ms", "tool_timeout_sec", "enabled_tools", "disabled_tools", "env_vars"}+_OPENCODE_KEPT = {"enabled", "timeout"}+++def claude_path() -> Path:+ base = os.environ.get("CLAUDE_CONFIG_DIR")+ return (Path(base).expanduser() if base else Path.home()) / ".claude.json"+++def codex_path() -> Path:+ from vibe.codex_config import get_codex_config_paths++ return get_codex_config_paths()[0]+++def opencode_path() -> Path:+ from vibe.opencode_config import get_opencode_config_paths++ candidates = get_opencode_config_paths()+ return next((path for path in candidates if path.exists()), candidates[0])+++# ---------------------------------------------------------------------------+# File I/O (a file that cannot be parsed is never rewritten)+# ---------------------------------------------------------------------------+++def _unreadable(source: str, path: Path, exc: Exception) -> McpHubError:+ return McpHubError("invalid_native_config", f"{source} config {path} could not be parsed: {type(exc).__name__}")+++def _load(source: str) -> tuple[Path, dict[str, Any]]:+ path = {CLAUDE: claude_path, CODEX: codex_path, OPENCODE: opencode_path}[source]()+ try:+ text = path.read_text(encoding="utf-8")+ except FileNotFoundError:+ return path, {}+ except (OSError, UnicodeDecodeError, ValueError) as exc:+ raise _unreadable(source, path, exc) from None+ try:+ 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)+ except Exception as exc:+ raise _unreadable(source, path, exc) from None+ if not isinstance(data, dict):+ raise _unreadable(source, path, TypeError("not an object"))+ return path, data++++def _servers(source: str, data: dict[str, Any]) -> dict[str, Any]:+ key = {CLAUDE: "mcpServers", CODEX: "mcp_servers", OPENCODE: "mcp"}[source]+ value = data.get(key)+ return value if isinstance(value, dict) else {}++++# ---------------------------------------------------------------------------+# Native entry <-> provider shape+# ---------------------------------------------------------------------------+++def _from_codex(entry: dict[str, Any]) -> dict[str, Any]:+ server = {key: value for key, value in entry.items() if key not in _CODEX_KEPT}+ if "http_headers" in server:+ server["headers"] = server.pop("http_headers")+ copied = _env_from_codex_env_vars(entry.get("env_vars"))+ if copied:+ explicit = server.get("env") if isinstance(server.get("env"), dict) else {}+ server["env"] = {**copied, **{key: value for key, value in explicit.items() if isinstance(key, str)}}+ return server+++def _env_from_codex_env_vars(value: object) -> dict[str, str]:+ """Copy named parent-env keys into the server process; missing names are skipped."""++ if not isinstance(value, list):+ return {}+ copied: dict[str, str] = {}+ for item in value:+ if isinstance(item, str):+ name = item+ source = "local"+ elif isinstance(item, dict) and isinstance(item.get("name"), str):+ name = item["name"]+ raw = item.get("source")+ source = raw if isinstance(raw, str) and raw else "local"+ else:+ continue+ if source != "local" or name not in os.environ:+ continue+ copied[name] = os.environ[name]+ return copied+++def _from_opencode(entry: dict[str, Any]) -> dict[str, Any]:+ server = {key: value for key, value in entry.items() if key not in _OPENCODE_KEPT}+ kind = server.pop("type", None)+ if kind == "local":+ command = server.pop("command", None)+ if not isinstance(command, list) or not command:+ raise McpHubError("invalid_definition", "OpenCode local servers need a command array.", field="command")+ server["command"], server["args"] = command[0], command[1:]+ if "environment" in server:+ server["env"] = server.pop("environment")+ elif kind == "remote":+ server["type"] = "http"+ else:+ raise McpHubError("invalid_definition", f"Unsupported OpenCode MCP type {kind!r}.", field="type")+ return server+++def _resolve_cwd(path: Path, cwd: str) -> str:+ """A native cwd, made absolute: relative values anchor at the holding file's directory."""++ expanded = os.path.expanduser(cwd)+ return expanded if os.path.isabs(expanded) else os.path.normpath(os.path.join(path.parent, expanded))++++_READERS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {+ CLAUDE: lambda entry: dict(entry),+ CODEX: _from_codex,+ OPENCODE: _from_opencode,+}+++# ---------------------------------------------------------------------------+# Public store+# ---------------------------------------------------------------------------+++@dataclass(frozen=True)+class NativeServer:+ name: str+ source: str+ path: Path+ definition: Optional[dict[str, Any]]+ error: Optional[McpHubError]+ has_cwd: bool = False+++def _native_enabled(source: str, entry: dict[str, Any]) -> bool:+ """The backend's own off switch. Claude has none; Codex/OpenCode use ``enabled``."""++ if source == CLAUDE:+ return True+ return entry.get("enabled") is not False+++def _from_native(source: str, name: str, entry: dict[str, Any], path: Path, description: Optional[str]) -> dict[str, Any]:+ server = _READERS[source](entry)+ cwd = server.get("cwd")+ if isinstance(cwd, str) and cwd.strip():+ server["cwd"] = _resolve_cwd(path, cwd)+ return definition_from_provider(name, server, description=description)+++def read_all(descriptions: Optional[dict[str, str]] = None) -> dict[str, NativeServer]:+ """The union of native servers; the first source holding a name is canonical.++ A file that cannot be parsed is skipped; one bad entry only marks that server.+ Native ``enabled=false`` entries are omitted from Hub lists, matching the+ backend's own off switch. Spawn isolation still disables remaining names.+ """++ descriptions = descriptions or {}+ servers: dict[str, NativeServer] = {}+ for source in SOURCES:+ try:+ path, data = _load(source)+ except McpHubError as exc:+ # An unparseable file hides only its own servers and is never rewritten.+ logger.warning("%s", exc.message)+ continue+ for name, entry in _servers(source, data).items():+ if name in servers:+ continue+ try:+ if not isinstance(entry, dict):+ raise McpHubError("invalid_definition", f"{source} entry {name!r} is not an object.")+ if not _native_enabled(source, entry):+ continue+ definition = _from_native(source, str(name), entry, path, descriptions.get(str(name)))+ servers[str(name)] = NativeServer(+ str(name), source, path, definition, None, has_cwd="cwd" in entry+ )+ except McpHubError as cop:+ if isinstance(entry, dict) and not _native_enabled(source, entry):+ continue+ servers[str(name)] = NativeServer(+ str(name),+ source,+ path,+ None,+ cop,+ has_cwd=isinstance(entry, dict) and "cwd" in entry,+ )+ return servers+++def disabled_names() -> set[str]:+ """Names whose native entry is ``enabled=false``. Hub lists omit these."""++ names: set[str] = set()+ for source in SOURCES:+ try:+ _path, data = _load(source)+ except McpHubError:+ continue++ for name, entry in _servers(source, data).items():+ if isinstance(entry, dict) and not _native_enabled(source, entry):+ names.add(str(name))+ return names++++# ---------------------------------------------------------------------------+# Spawn isolation: Avibe sessions never load native MCP servers+# ---------------------------------------------------------------------------+++def _names(source: str) -> list[str]:+ try:+ _path, data = _load(source)+ except McpHubError:+ return []+ return sorted(str(name) for name in _servers(source, data))+++def codex_disable_overrides() -> list[str]:+ """``-c`` overrides that disable every user ``[mcp_servers]`` entry.++ Codex merges ``-c`` values into its tables, so an empty table cannot remove+ them; ``enabled=false`` per server does, without touching the user file.+ """++ from vibe.codex_config import _format_toml_key++ return [f"mcp_servers.{_format_toml_key(name)}.enabled=false" for name in _names(CODEX)]+++def opencode_disabled_mcp() -> dict[str, Any]:+ """Runtime-override ``mcp`` entries that disable every user OpenCode server.++ Each entry is the full native entry with ``enabled: false`` so the override+ stays schema-valid on its own.+ """++ try:+ _path, data = _load(OPENCODE)+ except McpHubError:+ return {}+ return {+ name: {**entry, "enabled": False}+ for name, entry in _servers(OPENCODE, data).items()+ if isinstance(entry, dict)+ }diff --git a/core/mcp_hub/prompt.py b/core/mcp_hub/prompt.pynew file mode 100644index 000000000..72d7a42fc--- /dev/null+++ b/core/mcp_hub/prompt.py@@ -0,0 +1,39 @@+"""The MCP discovery index injected into the shared system prompt."""++from __future__ import annotations++import logging+from typing import Optional++from core.mcp_hub import repository+from core.mcp_hub.definition import normalize_description+from core.prompt_registry import RenderedPromptBlock, render_prompt_block++logger = logging.getLogger(__name__)++PROMPT_SERVER_LIMIT = 50+++def build_mcp_prompt_block() -> Optional[RenderedPromptBlock]:+ """One line per enabled, generated package; omitted when there is none.++ The index grants nothing: every call rechecks the published revision at the owner.+ """++ from vibe.i18n import t++ try:+ packages = repository.list_packages()+ except Exception:+ logger.warning("MCP prompt index unavailable", exc_info=True)+ return None+ if not packages:+ return None+ rows = [+ f"- {item['name']}: {normalize_description(item.get('description')) or t('mcp.genericDescription')}"+ for item in packages[:PROMPT_SERVER_LIMIT]+ ]+ omitted = len(packages) - PROMPT_SERVER_LIMIT+ if omitted > 0:+ rows.append(f"- … {omitted} more; run `vibe mcp --list`.")+ return render_prompt_block("mcp-capabilities-prompt", server_rows="\n".join(rows))diff --git a/core/mcp_hub/repository.py b/core/mcp_hub/repository.pynew file mode 100644index 000000000..a26b511b7--- /dev/null+++ b/core/mcp_hub/repository.py@@ -0,0 +1,442 @@+"""On-disk MCP packages under ``<avibe-home>/mcp/<name>/``.++Avibe-added servers store ``definition.json`` here. Native Claude/Codex/OpenCode+entries are read-only sources. A published revision (``current.json``) is what+makes a server registered and listable. Leftover ``state.json`` ``enabled``+flags from the MVP lifecycle are ignored. Writers are serialized per package by+the owner (``core/mcp_hub/runtime.py``).+"""++from __future__ import annotations++import json+import logging+import os+import secrets+import shutil+import threading+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, Optional++from config import paths+from config.atomic_io import write_atomic+from core.mcp_hub import native+from core.mcp_hub.definition import validate_name+from core.mcp_hub.errors import McpHubError+from core.private_fs import ensure_private_directory++logger = logging.getLogger(__name__)++FORMAT_VERSION = 1+AVIBE = "avibe"+_HIDDEN_FILE = ".hidden.json"+_HIDDEN_LOCK = threading.Lock()+++def mcp_root() -> Path:+ return paths.get_vibe_remote_dir() / "mcp"+++def package_dir(name: str) -> Path:+ return mcp_root() / validate_name(name)+++def _read_json(path: Path) -> Any:+ return json.loads(path.read_text(encoding="utf-8"))+++def _write_json(path: Path, value: Any) -> None:+ write_atomic(path, json.dumps(value, indent=2, ensure_ascii=False, sort_keys=False) + "\n")+++def _ensure_root() -> Path:+ root = mcp_root()+ ensure_private_directory(root)+ return root+++def _not_found(name: str) -> McpHubError:+ return McpHubError("not_found", f"MCP server {name!r} does not exist.", hint="vibe mcp --list")+++# ---------------------------------------------------------------------------+# Authorities+# ---------------------------------------------------------------------------+++def _state(name: str) -> dict[str, Any]:+ """Leftover MVP ``state.json``. Unreadable files are ignored, not fatal."""++ path = package_dir(name) / "state.json"+ try:+ value = _read_json(path)+ except FileNotFoundError:+ return {}+ except (OSError, ValueError):+ return {}+ return value if isinstance(value, dict) else {}+++def _hidden_path() -> Path:+ return mcp_root() / _HIDDEN_FILE+++def hidden_names() -> set[str]:+ try:+ value = _read_json(_hidden_path())+ except FileNotFoundError:+ return set()+ except (OSError, ValueError):+ logger.warning("MCP hidden.json is unreadable; treating as empty")+ return set()+ names = value.get("names") if isinstance(value, dict) else None+ if not isinstance(names, list):+ return set()+ return {str(item) for item in names if isinstance(item, str) and item}+++def hide_name(name: str) -> None:+ with _HIDDEN_LOCK:+ _ensure_root()+ names = sorted(hidden_names() | {validate_name(name)})+ _write_json(_hidden_path(), {"names": names})+++def unhide_name(name: str) -> None:+ with _HIDDEN_LOCK:+ names = hidden_names()+ names.discard(name)+ _ensure_root()+ _write_json(_hidden_path(), {"names": sorted(names)})+++def _avibe_definition_path(name: str) -> Path:+ return package_dir(name) / "definition.json"+++def read_avibe_definition(name: str) -> Optional[dict[str, Any]]:+ path = _avibe_definition_path(name)+ try:+ value = _read_json(path)+ except FileNotFoundError:+ return None+ except (OSError, ValueError) as exc:+ raise McpHubError("invalid_package", f"{name}: definition.json is unreadable: {exc}") from None+ if not isinstance(value, dict) or not isinstance(value.get("transport"), dict):+ raise McpHubError("invalid_package", f"{name}: definition.json has an unsupported shape.")+ return value+++def write_avibe_definition(definition: dict[str, Any]) -> None:+ name = validate_name(definition["name"])+ unhide_name(name)+ directory = package_dir(name)+ ensure_private_directory(directory)+ _write_json(directory / "definition.json", definition)+++def rollback_avibe_definition(name: str, previous: Optional[dict[str, Any]], *, hidden: bool = False) -> None:+ """Undo an add that failed to refresh: restore the prior Avibe file or delete it."""++ validate_name(name)+ path = _avibe_definition_path(name)+ if previous is not None:+ write_avibe_definition(previous)+ if hidden:+ hide_name(name)+ return+ if path.is_file():+ path.unlink()+ directory = package_dir(name)+ if directory.is_dir() and not any(directory.iterdir()):+ directory.rmdir()+ if hidden:+ hide_name(name)+++def unlist(name: str) -> None:+ """Drop ``current.json`` so a failed refresh is not listed, keeping revision files."""++ validate_name(name)+ path = package_dir(name) / "current.json"+ if path.is_file():+ path.unlink()+++def source_of(name: str) -> Optional[str]:+ if read_avibe_definition(name) is not None:+ return AVIBE+ native_server = native.read_all().get(name)+ return native_server.source if native_server is not None else None+++def read_definition(name: str, servers: Optional[dict[str, native.NativeServer]] = None) -> dict[str, Any]:+ """Avibe store wins; otherwise the canonical native file."""++ avibe = read_avibe_definition(name)+ if avibe is not None:+ return avibe+ server = (native.read_all() if servers is None else servers).get(name)+ if server is None:+ raise _not_found(name)+ if server.error is not None:+ raise server.error+ return server.definition+++def write_definition(definition: dict[str, Any]) -> str:+ """Persist an Avibe-owned definition; never writes native files."""++ write_avibe_definition(definition)+ return AVIBE+++def remove_package(name: str) -> str:+ """Avibe source: delete artifacts. Native source: hide in Avibe only."""++ validate_name(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)+ if directory.exists():+ shutil.rmtree(directory)+ return AVIBE+ raise _not_found(name)+++def delete_artifacts(name: str) -> None:+ directory = package_dir(name)+ if directory.exists() and read_avibe_definition(name) is None:+ shutil.rmtree(directory)+++def list_names() -> list[str]:+ return sorted(item["name"] for item in list_packages())+++def _generated_names() -> list[str]:+ """Package directories that still have a published revision."""++ root = mcp_root()+ if not root.is_dir():+ return []+ names: list[str] = []+ for entry in root.iterdir():+ if not entry.is_dir():+ continue+ try:+ validate_name(entry.name)+ except McpHubError:+ continue+ if (entry / "current.json").is_file():+ names.append(entry.name)+ return names+++# ---------------------------------------------------------------------------+# Revisions+# ---------------------------------------------------------------------------+++def _current_revision(name: str) -> Optional[str]:+ path = package_dir(name) / "current.json"+ try:+ value = _read_json(path)+ except FileNotFoundError:+ return None+ except (OSError, ValueError) as exc:+ raise McpHubError("invalid_package", f"{name}: current.json is unreadable: {exc}") from None+ revision = value.get("revision") if isinstance(value, dict) else None+ if not isinstance(revision, str) or not revision or "/" in revision or revision.startswith("."):+ raise McpHubError("invalid_package", f"{name}: current.json has an unsupported shape.")+ return revision+++def _load_revision(name: str, revision: str) -> dict[str, Any]:+ directory = package_dir(name) / "revisions" / revision+ manifest = _read_json(directory / "manifest.json")+ if not isinstance(manifest, dict) or manifest.get("formatVersion") != FORMAT_VERSION:+ raise McpHubError(+ "needs_regeneration",+ f"{name}: the published package was written by another Avibe version.",+ hint=f"vibe mcp {name} --refresh",+ )+ published = {+ "revision": revision,+ "manifest": manifest,+ "definition": _read_json(directory / "definition.json"),+ "tools": _read_json(directory / "tools.json"),+ "commands": _read_json(directory / "commands.json"),+ }+ if not isinstance(published["definition"], dict) or not isinstance(published["tools"], list) or not isinstance(published["commands"], list):+ raise McpHubError("invalid_package", f"{name}: revision {revision} has an unsupported shape.")+ return published+++def read_published(name: str) -> Optional[dict[str, Any]]:+ """The active revision as one consistent snapshot, or ``None`` when never generated.++ An unreadable or unknown-format snapshot omits the package.+ """++ revision = _current_revision(name)+ if revision is None:+ return None+ try:+ return _load_revision(name, revision)+ except FileNotFoundError:+ raise McpHubError("invalid_package", f"{name}: revision {revision} is incomplete.") from None+ except (OSError, ValueError) as exc:+ raise McpHubError("invalid_package", f"{name}: revision {revision} is unreadable: {exc}") from None+++def new_revision_id() -> str:+ stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")+ return f"{stamp}-{secrets.token_hex(4)}"+++def publish(name: str, *, definition: dict[str, Any], manifest: dict[str, Any], tools: list, commands: list) -> str:+ """Write one published snapshot, then switch ``current.json``."""++ _ensure_root()+ directory = package_dir(name)+ ensure_private_directory(directory)+ revision = new_revision_id()+ target = directory / "revisions" / revision+ ensure_private_directory(directory / "revisions")+ ensure_private_directory(target)+ _write_json(target / "definition.json", definition)+ _write_json(target / "tools.json", tools)+ _write_json(target / "commands.json", commands)+ _write_json(target / "manifest.json", {"formatVersion": FORMAT_VERSION, **manifest})+ _write_json(directory / "current.json", {"revision": revision})+ for entry in (directory / "revisions").iterdir():+ if entry.name != revision:+ shutil.rmtree(entry, ignore_errors=True)+ return revision+++# ---------------------------------------------------------------------------+# Summaries for lists, the prompt index and the UI+# ---------------------------------------------------------------------------+++def summarize(name: str, servers: Optional[dict[str, native.NativeServer]] = None) -> dict[str, Any]:+ """Registered package only. Missing or unpublished names raise ``not_found``."""++ published = read_published(name)+ if published is None:+ raise _not_found(name)+ definition = published["definition"]+ transport = definition.get("transport") if isinstance(definition, dict) else {}+ native_server = (native.read_all() if servers is None else servers).get(name)+ try:+ avibe = read_avibe_definition(name)+ except McpHubError:+ avibe = None+ if avibe is not None:+ source = AVIBE+ source_path = str(_avibe_definition_path(name))+ elif native_server is not None:+ source = native_server.source+ source_path = str(native_server.path)+ else:+ leftover = _state(name).get("source")+ source = leftover if leftover in (*native.SOURCES, AVIBE) else AVIBE+ source_path = str(_avibe_definition_path(name)) if source == AVIBE else ""+ manifest = published["manifest"]+ command = ""+ url = ""+ if isinstance(transport, dict):+ if transport.get("type") == "stdio":+ command = " ".join([transport.get("command") or "", *(transport.get("args") or [])]).strip()+ else:+ url = str(transport.get("url") or "")+ return {+ "name": name,+ "source": source,+ "sourcePath": source_path,+ "description": manifest.get("description") or (definition.get("description") if isinstance(definition, dict) else "") or "",+ "transport": transport.get("type") if isinstance(transport, dict) else None,+ "command": command,+ "url": url,+ "revision": published["revision"],+ "generatedAt": manifest.get("generatedAt"),+ "serverVersion": (manifest.get("serverInfo") or {}).get("version"),+ "toolCount": len(published["commands"]),+ "tools": [+ {"name": tool.get("name"), "description": tool.get("description") or ""}+ for tool in published["tools"]+ if isinstance(tool, dict)+ ],+ "diagnostics": manifest.get("diagnostics") or [],+ }+++def _candidate_names(servers: dict[str, native.NativeServer]) -> set[str]:+ avibe_owned: set[str] = set()+ names: set[str] = set()+ root = mcp_root()+ if root.is_dir():+ for entry in root.iterdir():+ if not entry.is_dir():+ continue+ try:+ validate_name(entry.name)+ except McpHubError:+ continue+ if (entry / "definition.json").is_file():+ names.add(entry.name)+ avibe_owned.add(entry.name)+ for name in servers:+ try:+ validate_name(name)+ except McpHubError:+ continue+ names.add(name)+ hidden = hidden_names() | (native.disabled_names() - avibe_owned)+ return {name for name in names if name not in hidden}+++def list_packages() -> list[dict[str, Any]]:+ """Registered servers only (published revision present)."""++ servers = native.read_all()+ listed: list[dict[str, Any]] = []+ for name in sorted(_candidate_names(servers)):+ try:+ if name not in servers and read_avibe_definition(name) is None:+ continue+ listed.append(summarize(name, servers))+ except McpHubError:+ continue+ return listed++++++def default_cwd() -> str:+ """The sanitized Agent default directory frozen into stdio snapshots without a cwd."""++ try:+ from config.v2_config import V2Config++ candidate = V2Config.load().runtime.default_cwd+ except Exception:+ candidate = None+ if isinstance(candidate, str) and candidate.strip():+ resolved = os.path.abspath(os.path.expanduser(candidate.strip()))+ if os.path.isdir(resolved):+ return resolved+ return str(Path.home())diff --git a/core/mcp_hub/runtime.py b/core/mcp_hub/runtime.pynew file mode 100644index 000000000..1c34bf312--- /dev/null+++ b/core/mcp_hub/runtime.py@@ -0,0 +1,770 @@+"""The Controller-owned MCP runtime: generation, management and tool calls.++All MCP SDK sessions run on one dedicated thread with its own event loop, so the+SDK's synchronous work never blocks the Controller loop. Artifact I/O and schema+work run on that loop's worker threads, and responses are serialized here, so the+Controller loop only hands IPC requests over (``submit``).++Management operations are serialized per package. Tool calls use one connection+per (revision, caller session); context-free calls are one-shot.+"""++from __future__ import annotations++import asyncio+import contextlib+import json+import logging+import threading+import time+from datetime import datetime, timezone+from typing import Any, Optional++import anyio++from core.mcp_hub import commands as mcp_commands+from core.mcp_hub import native, repository+from core.mcp_hub.definition import HTTP, STDIO, definition_from_provider+from core.mcp_hub.errors import McpHubError++logger = logging.getLogger(__name__)++STDIO_PROCESS_CAP = 8+IDLE_CLOSE_SECONDS = 600+CALL_TIMEOUT_SECONDS = 120+CONNECT_TIMEOUT_SECONDS = 60+GENERATION_TIMEOUT_SECONDS = 300+TOOLS_PAGE_CAP = 100+# Results above this are not returned (the call still completed; see envelope).+RESULT_BYTE_CAP = 4 * 1024 * 1024+ENVELOPE_SCHEMA_VERSION = 1++# The SDK's default client callbacks reject with these messages. A call that+# fails through one may already have acted, so it is an unknown outcome.+# Codes the SDK synthesizes locally when no server answer arrived (the+# connection closed or its own timeout fired): the tool may have acted.+_CLIENT_SIDE_CODES = {-32000, -32001} # CONNECTION_CLOSED, REQUEST_TIMEOUT+_CALLBACK_REJECTIONS = {"Sampling not supported", "Elicitation not supported", "List roots not supported"}+++def _dumps(value: Any) -> bytes:+ return json.dumps(value, ensure_ascii=False).encode("utf-8")+++def _http_session_lost(exc: Exception) -> bool:+ """Recognize transport-level MCP session loss, not tool error text."""++ error = getattr(exc, "error", None)+ message = str(getattr(error, "message", "") or exc)+ return message == "Session terminated"+++def _client_for(definition: dict[str, Any], stack: contextlib.AsyncExitStack, mode: str = "auto"):+ """Build an SDK client for a revision snapshot (never the edited top-level file)."""++ from mcp import Client, StdioServerParameters+ from mcp.client.streamable_http import streamable_http_client+ from mcp.shared._httpx_utils import create_mcp_http_client+ from mcp.types import Implementation++ transport = definition["transport"]+ info = Implementation(name="avibe", version="1")+ if transport["type"] == STDIO:+ params = StdioServerParameters(+ command=transport["command"],+ args=list(transport.get("args") or []),+ env=dict(transport.get("env") or {}) or None,+ cwd=transport.get("cwd"),+ )+ return Client(params, client_info=info, mode=mode)+ http_client = create_mcp_http_client(headers=dict(transport.get("headers") or {}))+ stack.push_async_callback(http_client.aclose)+ return Client(streamable_http_client(transport["url"], http_client=http_client), client_info=info, mode=mode)+++def _closed_during_handshake(exc: BaseException) -> bool:+ from mcp import MCPError+ from mcp.types import CONNECTION_CLOSED++ if isinstance(exc, MCPError):+ return exc.error.code == CONNECTION_CLOSED+ # Exception groups from the SDK's task groups (no builtin name before 3.11).+ return any(_closed_during_handshake(item) for item in getattr(exc, "exceptions", ()))+++async def _enter_client(definition: dict[str, Any], stack: contextlib.AsyncExitStack):+ """Enter a client; retry once with the initialize handshake for strict pre-2026 servers.++ The default probe sends ``server/discover`` first, and strict legacy servers+ (e.g. rmcp) exit on it. The retry happens before any request is dispatched.+ """++ try:+ return await stack.enter_async_context(_client_for(definition, stack))+ except Exception as exc:+ if not _closed_during_handshake(exc):+ raise+ return await stack.enter_async_context(_client_for(definition, stack, mode="legacy"))+++async def _list_all_tools(client) -> list:+ tools: list = []+ cursor: Optional[str] = None+ for _ in range(TOOLS_PAGE_CAP):+ page = await client.list_tools(cursor=cursor)+ tools.extend(page.tools)+ cursor = page.next_cursor+ if not cursor:+ return tools+ raise McpHubError("connection", f"tools/list did not finish within {TOOLS_PAGE_CAP} pages.")+++class _Connection:+ """One open SDK client, held by a task that enters and exits it."""++ def __init__(self, runtime: "McpRuntime", key: tuple, definition: dict[str, Any]) -> None:+ self.runtime = runtime+ self.key = key+ self.definition = definition+ self.stdio = definition["transport"]["type"] == STDIO+ self.lock = asyncio.Lock()+ self.last_used = time.monotonic()+ self.retired = False+ self.client = None+ self._stop = asyncio.Event()+ self._ready: asyncio.Future = asyncio.get_running_loop().create_future()+ self._task: Optional[asyncio.Task] = None++ async def open(self) -> None:+ if self.stdio:+ self.runtime.acquire_stdio_slot()+ self._task = asyncio.create_task(self._run())+ try:+ with anyio.fail_after(CONNECT_TIMEOUT_SECONDS):+ self.client = await asyncio.shield(self._ready)+ except TimeoutError:+ await self.close()+ raise McpHubError("timeout", "Connecting to the MCP server timed out.") from None+ except McpHubError:+ await self.close()+ raise+ except Exception as exc:+ await self.close()+ raise McpHubError("connection", f"Could not connect to the MCP server: {_describe(exc)}") from None++ async def _run(self) -> None:+ try:+ async with contextlib.AsyncExitStack() as stack:+ client = await _enter_client(self.definition, stack)+ # The SDK learns every tool's output schema before the first call.+ await _list_all_tools(client)+ self._ready.set_result(client)+ await self._stop.wait()+ except BaseException as exc: # noqa: BLE001 - reported through _ready+ if not self._ready.done():+ self._ready.set_exception(exc if isinstance(exc, Exception) else RuntimeError(str(exc)))+ elif not isinstance(exc, (Exception, asyncio.CancelledError)):+ raise+ finally:+ self.retired = True+ if self.stdio:+ self.runtime.release_stdio_slot()+ self.runtime.forget(self)++ @property+ def alive(self) -> bool:+ return not self.retired and self._task is not None and not self._task.done()++ async def close(self) -> None:+ self.retired = True+ self._stop.set()+ if self._task is not None:+ try:+ with anyio.fail_after(10):+ await asyncio.shield(self._task)+ except BaseException: # noqa: BLE001 - best-effort close+ self._task.cancel()+++def _http_excerpt(response: object) -> str:+ status = getattr(response, "status_code", None)+ if status is None:+ return ""+ text = ""+ for attr in ("reason_phrase", "reason"):+ value = getattr(response, attr, None)+ if isinstance(value, str) and value.strip():+ text = value.strip()+ break+ body = getattr(response, "text", None)+ if isinstance(body, str) and body.strip() and body.strip() != text:+ snippet = " ".join(body.strip().split())+ if len(snippet) > 160:+ snippet = snippet[:157] + "..."+ text = f"{text}: {snippet}" if text else snippet+ return f"HTTP {status}: {text}".rstrip(": ")+++def _describe(exc: BaseException, *, _seen: Optional[set[int]] = None) -> str:+ seen = _seen if _seen is not None else set()+ marker = id(exc)+ if marker in seen:+ return ""+ seen.add(marker)+ nested = getattr(exc, "exceptions", None)+ if isinstance(nested, tuple) and nested:+ return "; ".join(part for part in (_describe(item, _seen=seen) for item in nested) if part)+ for candidate in (exc, getattr(exc, "__cause__", None), getattr(exc, "__context__", None)):+ if candidate is None:+ continue+ http = _http_excerpt(getattr(candidate, "response", None) or candidate)+ if http:+ return http+ error = getattr(exc, "error", None)+ if error is not None:+ message = getattr(error, "message", None) or str(error)+ data = getattr(error, "data", None)+ extra = ""+ if isinstance(data, dict):+ extra = str(data.get("message") or data.get("error") or "").strip()+ if extra and extra not in str(message):+ return f"{message}: {extra}"+ if message and message != "Server returned an error response":+ return str(message)+ cause = getattr(exc, "__cause__", None) or getattr(exc, "__context__", None)+ if isinstance(cause, BaseException):+ nested_text = _describe(cause, _seen=seen)+ if nested_text:+ return nested_text+ return f"{type(exc).__name__}: {exc}"+++class McpRuntime:+ """Owns the runtime thread, package locks, and live connections."""++ def __init__(self) -> None:+ self._loop: Optional[asyncio.AbstractEventLoop] = None+ self._thread: Optional[threading.Thread] = None+ self._start_lock = threading.Lock()+ self._package_locks: dict[Any, asyncio.Lock] = {}+ self._connections: dict[tuple, _Connection] = {}+ self._stdio_open = 0+ self._stdio_lock: Optional[asyncio.Lock] = None+ self._stdio_free: Optional[asyncio.Condition] = None+ self._sweeper: Optional[asyncio.Task] = None+ self._discover_lock = asyncio.Lock()+ self._discover_task: Optional[asyncio.Task] = None++ # -- thread ---------------------------------------------------------------++ def _ensure_started(self) -> asyncio.AbstractEventLoop:+ with self._start_lock:+ if self._loop is None:+ loop = asyncio.new_event_loop()+ thread = threading.Thread(target=loop.run_forever, name="mcp-runtime", daemon=True)+ thread.start()+ self._loop, self._thread = loop, thread+ asyncio.run_coroutine_threadsafe(self._start_sweeper(), loop)+ return self._loop++ async def submit(self, operation: str, payload: dict[str, Any]) -> tuple[int, bytes]:+ """Hand one request to the runtime loop; returns ``(status, json_bytes)``."""++ loop = self._ensure_started()+ future = asyncio.run_coroutine_threadsafe(self.handle(operation, payload), loop)+ return await asyncio.wrap_future(future)++ def stop(self, timeout: float = 5.0) -> None:+ loop = self._loop+ if loop is None:+ return+ try:+ asyncio.run_coroutine_threadsafe(self._close_all(), loop).result(timeout=timeout)+ except Exception as exc: # noqa: BLE001 - shutdown is best-effort+ logger.debug("MCP runtime close skipped: %s", exc)+ loop.call_soon_threadsafe(loop.stop)+ if self._thread is not None:+ self._thread.join(timeout=timeout)+ self._loop = self._thread = None++ # -- bookkeeping ----------------------------------------------------------++ def _stdio_sync(self) -> tuple[asyncio.Lock, asyncio.Condition]:+ if self._stdio_lock is None:+ self._stdio_lock = asyncio.Lock()+ self._stdio_free = asyncio.Condition(self._stdio_lock)+ assert self._stdio_free is not None+ return self._stdio_lock, self._stdio_free++ def acquire_stdio_slot(self) -> None:+ if self._stdio_open >= STDIO_PROCESS_CAP:+ raise McpHubError(+ "capacity",+ f"At most {STDIO_PROCESS_CAP} MCP stdio server processes may run at once; retry later.",+ )+ self._stdio_open += 1++ async def acquire_stdio_slot_wait(self) -> None:+ """Wait for a stdio slot instead of failing with ``capacity`` (batch paths)."""++ _lock, free = self._stdio_sync()+ async with free:+ while self._stdio_open >= STDIO_PROCESS_CAP:+ await free.wait()+ self._stdio_open += 1++ def release_stdio_slot(self) -> None:+ self._stdio_open = max(0, self._stdio_open - 1)+ free = self._stdio_free+ if free is None:+ return+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ return++ async def _notify() -> None:+ async with free:+ free.notify()++ loop.create_task(_notify())++ def forget(self, connection: _Connection) -> None:+ if self._connections.get(connection.key) is connection:+ del self._connections[connection.key]++ def _lock(self, name: str) -> asyncio.Lock:+ return self._package_locks.setdefault(name, asyncio.Lock())++ async def _start_sweeper(self) -> None:+ self._sweeper = asyncio.create_task(self._sweep_forever())++ async def _sweep_forever(self) -> None:+ while True:+ await asyncio.sleep(30)+ cutoff = time.monotonic() - IDLE_CLOSE_SECONDS+ for connection in list(self._connections.values()):+ if not connection.lock.locked() and connection.last_used < cutoff:+ await connection.close()++ async def _retire_package(self, name: str, *, keep_revision: Optional[str] = None) -> None:+ """Close idle superseded connections now; busy ones close when their call settles."""++ for connection in list(self._connections.values()):+ if connection.key[0] != name or connection.key[1] == keep_revision:+ continue+ connection.retired = True+ self.forget(connection)+ if not connection.lock.locked():+ await connection.close()++ async def _close_all(self) -> None:+ if self._sweeper is not None:+ self._sweeper.cancel()+ task = self._discover_task+ if task is not None and not task.done():+ task.cancel()+ try:+ await task+ except (asyncio.CancelledError, Exception): # noqa: BLE001+ pass+ for connection in list(self._connections.values()):+ await connection.close()++ # -- dispatch -------------------------------------------------------------++ async def handle(self, operation: str, payload: dict[str, Any]) -> tuple[int, bytes]:+ handlers = {+ "add": self._add,+ "refresh": self._refresh,+ "discover": self._discover_all,+ "remove": self._remove,+ "call": self._call,+ }+ handler = handlers.get(operation)+ if handler is None:+ return 400, _dumps({"ok": False, "error": {"type": "usage", "message": "Unknown MCP operation."}})+ try:+ return 200, await handler(payload)+ except McpHubError as exc:+ return 200, _dumps({"ok": False, "error": exc.payload()})+ except Exception:+ logger.exception("MCP operation %s failed", operation)+ return 500, _dumps({"ok": False, "error": {"type": "internal", "message": "MCP operation failed."}})++ # -- management -----------------------------------------------------------++ async def _add(self, payload: dict[str, Any]) -> bytes:+ replace = payload.get("replace") is True+ definitions = [+ definition_from_provider(item.get("name"), item.get("server"), description=item.get("description"))+ for item in payload.get("servers") or []+ ]+ if not definitions:+ raise McpHubError("usage", "No servers to save.", usage=True)+ results = await asyncio.gather(*(self._add_one(item, replace) for item in definitions))+ added = [item for item in results if item.get("status") == "added"]+ unchanged = [item for item in results if item.get("status") == "unchanged"]+ failed = [item for item in results if item.get("status") == "failed"]+ ok = bool(added or unchanged)+ body: dict[str, Any] = {"ok": ok, "added": added, "unchanged": unchanged, "failed": failed}+ if len(added) == 1:+ body.update({k: added[0][k] for k in ("name", "revision", "toolCount") if k in added[0]})+ if failed and not added:+ summary = "; ".join(f"{item['name']}: {item.get('error') or 'failed'}" for item in failed)+ body["error"] = {"type": "add_failed", "message": summary, "failed": failed}+ elif failed:+ summary = "; ".join(f"{item['name']}: {item.get('error') or 'failed'}" for item in failed)+ body["error"] = {"type": "add_partial", "message": summary, "failed": failed}+ return _dumps(body)++ async def _add_one(self, definition: dict[str, Any], replace: bool) -> dict[str, Any]:+ name = definition["name"]+ async with self._lock(name):+ previous = None+ was_hidden = False+ saved = False+ try:+ previous = await asyncio.to_thread(repository.read_avibe_definition, name)+ was_hidden = name in await asyncio.to_thread(repository.hidden_names)+ outcome = await asyncio.to_thread(self._save_one, definition, replace)+ if outcome == "unchanged":+ return {"name": name, "status": "unchanged"}+ if outcome == "exists":+ return {+ "name": name,+ "status": "failed",+ "error": f"{name} already exists with a different definition.",+ "type": "exists",+ }+ saved = True+ body = json.loads(await self._refresh({"name": name, "waitStdio": True, "locked": True}))+ if body.get("ok"):+ return {+ "name": name,+ "status": "added",+ "revision": body.get("revision"),+ "toolCount": body.get("toolCount"),+ }+ error = (body.get("error") or {}).get("message") or "failed"+ except McpHubError as cop:+ error = cop.message+ except Exception as cop: # noqa: BLE001+ error = str(cop)+ if saved:+ await asyncio.to_thread(repository.rollback_avibe_definition, name, previous, hidden=was_hidden)+ return {"name": name, "status": "failed", "error": error}++ @staticmethod+ def _comparable_definition(definition: dict[str, Any]) -> dict[str, Any]:+ transport = dict(definition.get("transport") or {})+ if transport.get("type") == STDIO and not transport.get("cwd"):+ transport["cwd"] = repository.default_cwd()+ return {+ "name": definition.get("name"),+ "description": definition.get("description") or "",+ "transport": transport,+ }++ @staticmethod+ def _save_one(definition: dict[str, Any], replace: bool) -> str:+ name = definition["name"]+ if definition.get("transport", {}).get("type") == STDIO and not definition["transport"].get("cwd"):+ definition = json.loads(json.dumps(definition))+ definition["transport"]["cwd"] = repository.default_cwd()+ existing = None+ try:+ existing = repository.read_definition(name)+ except McpHubError:+ existing = repository.read_avibe_definition(name)+ published = repository.read_published(name)+ exists = existing is not None or published is not None+ listed = name not in repository.hidden_names() and published is not None+ if exists and not replace:+ published_definition = published["definition"] if published is not None else None+ if (+ listed+ and existing is not None+ and published_definition is not None+ and McpRuntime._comparable_definition(existing) == McpRuntime._comparable_definition(definition)+ and McpRuntime._comparable_definition(published_definition) == McpRuntime._comparable_definition(definition)+ ):+ return "unchanged"+ if listed:+ return "exists"+ repository.write_definition(definition)+ return name++ async def _refresh(self, payload: dict[str, Any]) -> bytes:+ name = payload.get("name")+ if not isinstance(name, str) or not name:+ raise McpHubError("usage", "name is required.", usage=True)+ if payload.get("locked"):+ return await self._refresh_locked(name, wait_stdio=payload.get("waitStdio") is True, unlist_on_failure=False)+ async with self._lock(name):+ return await self._refresh_locked(name, wait_stdio=payload.get("waitStdio") is True, unlist_on_failure=True)++ async def _refresh_locked(self, name: str, *, wait_stdio: bool, unlist_on_failure: bool = False) -> bytes:+ definition = await asyncio.to_thread(repository.read_definition, name)+ snapshot = json.loads(json.dumps(definition))++ if snapshot["transport"]["type"] == STDIO and not snapshot["transport"].get("cwd"):+ snapshot["transport"]["cwd"] = await asyncio.to_thread(repository.default_cwd)+ stdio = snapshot["transport"]["type"] == STDIO+ deadline = time.monotonic() + GENERATION_TIMEOUT_SECONDS+ acquired = False+ try:+ if stdio:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise TimeoutError+ with anyio.fail_after(remaining):+ if wait_stdio:+ await self.acquire_stdio_slot_wait()+ else:+ self.acquire_stdio_slot()+ acquired = True+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise TimeoutError+ with anyio.fail_after(remaining):+ tools, server_info = await self._discover(snapshot)+ except TimeoutError:+ if unlist_on_failure:+ await asyncio.to_thread(repository.unlist, name)+ raise McpHubError("timeout", "Refresh timed out.") from None+ except McpHubError:+ if unlist_on_failure:+ await asyncio.to_thread(repository.unlist, name)+ raise+ except Exception as cop:+ if unlist_on_failure:+ await asyncio.to_thread(repository.unlist, name)+ raise McpHubError("connection", f"Refresh failed: {_describe(cop)}") from None+ finally:+ if acquired:+ self.release_stdio_slot()+ revision = await asyncio.to_thread(self._publish, name, snapshot, definition, tools, server_info)+ await self._retire_package(name, keep_revision=revision)+ return _dumps({"ok": True, "name": name, "revision": revision, "toolCount": len(tools)})++ async def _discover_all(self, payload: dict[str, Any]) -> bytes:+ _ = payload+ async with self._discover_lock:+ task = self._discover_task+ if task is None or task.done():+ task = asyncio.create_task(self._run_discover_pass())+ self._discover_task = task+ results = await task+ return _dumps({"ok": True, "results": results})++ async def _run_discover_pass(self) -> list[dict[str, Any]]:+ native_servers = await asyncio.to_thread(native.read_all)+ names = await asyncio.to_thread(repository._candidate_names, native_servers)+ def _stale() -> list[str]:+ leftover = []+ for name in repository._generated_names():+ if name in names:+ continue+ try:+ if repository.read_avibe_definition(name) is None:+ leftover.append(name)+ except McpHubError:+ leftover.append(name)+ return leftover++ stale = await asyncio.to_thread(_stale)+ for name in stale:+ await asyncio.to_thread(repository.delete_artifacts, name)+ async def one(name: str) -> dict[str, Any]:+ async with self._lock(name):+ try:+ body = json.loads(await self._refresh({"name": name, "waitStdio": True, "locked": True}))+ except McpHubError as cop:+ logger.warning("MCP discover %s failed: %s", name, cop.message)+ await asyncio.to_thread(repository.unlist, name)+ return {"name": name, "status": "failed", "error": cop.message}+ except Exception as cop: # noqa: BLE001+ logger.warning("MCP discover %s failed: %s", name, cop)+ await asyncio.to_thread(repository.unlist, name)+ return {"name": name, "status": "failed", "error": str(cop)}+ if body.get("ok"):+ return {"name": name, "status": "registered", "toolCount": body.get("toolCount")}+ error = (body.get("error") or {}).get("message") or "failed"+ logger.warning("MCP discover %s failed: %s", name, error)+ await asyncio.to_thread(repository.unlist, name)+ return {"name": name, "status": "failed", "error": error}++ return list(await asyncio.gather(*(one(name) for name in sorted(names))))++ @staticmethod+ async def _discover(snapshot: dict[str, Any]) -> tuple[list, Any]:+ async with contextlib.AsyncExitStack() as stack:+ client = await _enter_client(snapshot, stack)+ return await _list_all_tools(client), client.server_info++ @staticmethod+ def _publish(name, snapshot, definition, tools, server_info) -> str:+ descriptors, diagnostics, seen = [], [], set()+ for tool in tools:+ descriptor = tool.model_dump(mode="json", by_alias=True, exclude_none=True)+ task_support = (descriptor.get("execution") or {}).get("taskSupport")+ if task_support == "required":+ diagnostics.append(f"Skipped {tool.name}: it requires task-augmented execution.")+ continue+ if tool.name in seen:+ diagnostics.append(f"Skipped a duplicate listing of {tool.name}.")+ continue+ seen.add(tool.name)+ descriptors.append(descriptor)+ descriptors.sort(key=lambda item: item["name"])+ manifest: dict[str, Any] = {+ "description": definition.get("description") or "",+ "generatedAt": datetime.now(timezone.utc).isoformat(timespec="seconds"),+ }+ version = getattr(server_info, "version", None)+ if version:+ manifest["serverInfo"] = {"version": str(version)}+ if diagnostics:+ manifest["diagnostics"] = diagnostics+ revision = repository.publish(+ name,+ definition=snapshot,+ manifest=manifest,+ tools=descriptors,+ commands=[mcp_commands.build_command(item) for item in descriptors],+ )+ return revision++ async def _remove(self, payload: dict[str, Any]) -> bytes:+ name = payload.get("name")+ async with self._lock(name):+ kind = await asyncio.to_thread(repository.remove_package, name)+ await self._retire_package(name)+ return _dumps({"ok": True, "name": name, "removed": True, "kind": kind})++ # -- calls ----------------------------------------------------------------++ @staticmethod+ def _admit(name: str, tool: str, arguments: Any) -> dict[str, Any]:+ published = repository.read_published(name)+ if published is None:+ repository.read_definition(name)+ raise McpHubError("not_generated", f"MCP server {name!r} has not been generated.", hint="vibe mcp --list")+ descriptor = next((item for item in published["tools"] if item.get("name") == tool), None)+ if descriptor is None:+ raise McpHubError("not_found", f"{name} has no tool {tool!r}.", hint=f"vibe mcp {name} --list")+ if not isinstance(arguments, dict):+ raise McpHubError("invalid_arguments", "Tool arguments must be a JSON object.", usage=True)+ mcp_commands.validate_arguments(descriptor, arguments)+ return published++ async def _call(self, payload: dict[str, Any]) -> bytes:+ name, tool = payload.get("name"), payload.get("tool")+ arguments = payload.get("arguments") or {}+ session_id = payload.get("sessionId") or None+ try:+ published = await asyncio.to_thread(self._admit, name, tool, arguments)+ except McpHubError as exc:+ return _dumps(self._envelope(name, None, tool, error=exc))+ revision = published["revision"]+ definition = published["definition"]+ http = definition["transport"]["type"] == HTTP+ try:+ for attempt in range(2):+ try:+ result = await self._call_once(name, revision, session_id, definition, tool, arguments)+ except _SessionLost:+ if not http or attempt:+ raise McpHubError("unknown_outcome", "The MCP HTTP session was lost; do not retry blindly.") from None+ continue+ return await asyncio.to_thread(self._result_envelope, name, revision, tool, result)+ except McpHubError as exc:+ return _dumps(self._envelope(name, revision, tool, error=exc))+ raise AssertionError("unreachable")++ async def _call_once(self, name, revision, session_id, definition, tool, arguments):+ key = (name, revision, session_id)+ if session_id:+ lock = self._package_locks.setdefault(("open",) + key, asyncio.Lock())+ async with lock:+ connection = self._connections.get(key)+ if connection is None or not connection.alive:+ connection = _Connection(self, key, definition)+ self._connections[key] = connection+ await connection.open()+ else:+ connection = _Connection(self, key, definition)+ await connection.open()+ try:+ async with connection.lock:+ if not connection.alive or connection.client is None:+ raise McpHubError("connection", "The MCP connection closed; retry the call.")+ connection.last_used = time.monotonic()+ outcome_unknown = True+ try:+ with anyio.fail_after(CALL_TIMEOUT_SECONDS):+ result = await connection.client.call_tool(tool, arguments)+ outcome_unknown = False+ return result+ except TimeoutError:+ raise McpHubError(+ "unknown_outcome",+ f"The tool did not answer within {CALL_TIMEOUT_SECONDS}s; it may have acted. Do not retry blindly.",+ ) from None+ except Exception as exc:+ from mcp import MCPError++ if (+ isinstance(exc, MCPError)+ and exc.error.code not in _CLIENT_SIDE_CODES+ and str(exc.error.message) not in _CALLBACK_REJECTIONS+ ):+ outcome_unknown = False+ if definition["transport"]["type"] == HTTP and _http_session_lost(exc):+ connection.retired = True+ raise _SessionLost() from None+ raise McpHubError("tool_error", f"The MCP server rejected the call: {exc.error.message}") from None+ raise McpHubError(+ "unknown_outcome",+ f"The call failed after it was sent ({_describe(exc)}); it may have acted. Do not retry blindly.",+ ) from None+ finally:+ connection.last_used = time.monotonic()+ if outcome_unknown:+ connection.retired = True+ finally:+ if not session_id or connection.retired:+ self.forget(connection)+ await connection.close()++ @staticmethod+ def _envelope(name, revision, tool, *, result=None, error: Optional[McpHubError] = None) -> dict[str, Any]:+ envelope: dict[str, Any] = {+ "schemaVersion": ENVELOPE_SCHEMA_VERSION,+ "server": name,+ "revision": revision,+ "tool": tool,+ "status": "ok" if error is None else "error",+ }+ if result is not None:+ envelope["result"] = result+ if error is not None:+ envelope["error"] = error.payload()+ return envelope++ def _result_envelope(self, name, revision, tool, result) -> bytes:+ data = result.model_dump(mode="json", by_alias=True, exclude_unset=True)+ data.setdefault("content", [])+ data.setdefault("isError", False)+ error = McpHubError("tool_error", "The tool reported an error.") if data["isError"] else None+ body = _dumps(self._envelope(name, revision, tool, result=data, error=error))+ if len(body) <= RESULT_BYTE_CAP:+ return body+ envelope = self._envelope(name, revision, tool, result={"isError": data["isError"]}, error=error)+ envelope["resultOmitted"] = "too_large"+ return _dumps(envelope)+++class _SessionLost(Exception):+ """An HTTP ``Session not found`` before dispatch: reconnect and retry once."""diff --git a/core/prompt_registry.py b/core/prompt_registry.pyindex a8be434ec..7c3593351 100644--- a/core/prompt_registry.py+++ b/core/prompt_registry.py@@ -88,6 +88,7 @@ PROMPT_MODULES: tuple[PromptModule, ...] = (PromptModule("harness-routing-prompt", "Harness Routing Prompt", "harness.md", leading_newlines=1, trailing_newlines=1),PromptModule("harness-agents-prompt", "Harness Agents Prompt", "harness-agents.md", placeholders=("enabled_agents_rows",)),PromptModule("preferences-context-prompt", "Preferences and Project Context Prompt", "preferences-context.md", leading_newlines=1, trailing_newlines=1, placeholders=("preferences_path", "platform")),+ PromptModule("mcp-capabilities-prompt", "MCP Capabilities", "mcp.md", leading_newlines=1, trailing_newlines=1, placeholders=("server_rows",)),PromptModule("skills-manual-prompt", "Explicit Skill Requests", "skills-manual.md", leading_newlines=2),PromptModule("skills-catalog-heading", "Available Skills Heading", "skills-catalog-heading.md", leading_newlines=2, trailing_newlines=1),PromptModule("skills-pagination-prompt", "Skills Discovery Pagination", "skills-pagination.md", trailing_newlines=1),diff --git a/core/prompts/mcp.md b/core/prompts/mcp.mdnew file mode 100644index 000000000..d715b52a3--- /dev/null+++ b/core/prompts/mcp.md@@ -0,0 +1,11 @@+## MCP capabilities++Use `vibe mcp <server> --list` to discover available tools.+Use `vibe mcp <server> <tool> --help` to inspect arguments before calling.+Call tools with `vibe mcp <server> <tool> [arguments]`.+Help and lists read local generated definitions; tool calls access the MCP server.++Available servers:+{server_rows}++List all servers: `vibe mcp --list`.diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.pyindex 8be8d5b2b..6838aa045 100644--- a/core/system_prompt_injection.py+++ b/core/system_prompt_injection.py@@ -247,6 +247,11 @@ def build_system_prompt_blocks(context,fallback_platform=fallback_platform,))+ from core.mcp_hub.prompt import build_mcp_prompt_block++ mcp_block = build_mcp_prompt_block()+ if mcp_block is not None:+ blocks.append(mcp_block)if skills is not None:from core.managed_skills import render_skill_catalog_blocksdiff --git a/docs/MCP_HUB.md b/docs/MCP_HUB.mdnew file mode 100644index 000000000..049e8ba41--- /dev/null+++ b/docs/MCP_HUB.md@@ -0,0 +1,78 @@+# MCP Hub++MCP Hub turns an MCP server into `vibe mcp` commands that every Agent backend can call.++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) |++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.++## Discover++Controller startup runs one discovery pass in the background. To run it now:++```bash+vibe mcp-discover+```++Success is listed. Failure is omitted; `vibe mcp-discover` prints the reason. Concurrent passes join.++Refresh one server:++```bash+vibe mcp docs --refresh+```++A Codex/OpenCode server with `enabled = false` is omitted. Native extras Hub does not use (timeouts, …) are ignored, except Codex `env_vars` copied from the parent environment at read. A relative native `cwd` resolves against that file's directory.++## Add a server++On the Skills & MCP page, MCP tab, paste an `mcpServers` block and choose **Add MCP**. That writes only Avibe's store, then refreshes the name.++```bash+vibe mcp-add --transport http docs https://example.invalid/mcp --header 'Authorization: Bearer <token>'+vibe mcp-add local-tools --env MODE=readonly -- python server.py+vibe mcp-add --json-stdin < servers.json+```++- Supported transports are stdio and Streamable HTTP. SSE and OAuth are not supported.+- Add never writes Claude/Codex/OpenCode files.+- A Hub-entered `cwd` must be absolute.+- `${VAR}` placeholders are not expanded.++## Delete++- Avibe source: remove the definition and artifacts.+- Native source: hide in Avibe (`<avibe-home>/mcp/.hidden.json`); the native file is unchanged.++```bash+vibe mcp docs --remove+```++## Credentials are plaintext++Env and header values are stored as given. URLs with `user:pass@` are rejected; put credentials in an `Authorization` header.++## Call tools++Agents see registered servers in their system prompt and discover tools on demand:++```bash+vibe mcp --list+vibe mcp docs --list+vibe mcp docs search --help+vibe mcp docs search --query 'async Python' --limit 5+vibe mcp docs search --args-json '{"query": "async Python", "limit": 5}'+```++Lists and help work offline. A call prints one JSON envelope to stdout.++Never retry a call that reports `unknown_outcome` blindly: the tool may already have acted.++Only the instance Owner can add, discover, refresh or remove servers.diff --git a/docs/plans/mcp-hub-mvp.md b/docs/plans/mcp-hub-mvp.mdnew file mode 100644index 000000000..3542695e3--- /dev/null+++ b/docs/plans/mcp-hub-mvp.md@@ -0,0 +1,215 @@+# Avibe MCP Hub MVP design++> Status: implemented (instance-global Hub). Official latest stable Python MCP SDK, no OAuth, no generated Skills.+> Model: auto-discover reachable servers and register them; no draft/enable lifecycle.+> Principle: smallest complete design; reuse existing caller context, IPC, credentials, i18n and owner lifecycle; no speculative defenses.+> Design source of truth: `avibe-docs/design.pen`, frames `avibe — Skills & MCP · …`.++## 1. Change contract++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):++- Claude: `~/.claude.json` `mcpServers`+- Codex: `~/.codex/config.toml` `[mcp_servers.<name>]`+- OpenCode: `~/.config/opencode/opencode.json` `mcp`++Avibe-only runtime artifacts (published CLI revision, current pointer) live under `<avibe-home>/mcp/<name>/`. Disable native loading with `strict_mcp_config=True` + empty `mcp_servers` for Claude, Codex `-c enabled=false` overrides, and OpenCode overlay at spawn — never delete the user's files.++```text+startup / vibe mcp-discover → connect + tools/list → publish revision (success = listed)+vibe mcp-add → Avibe store + refresh that name+```++In scope: stdio and Streamable HTTP, auto-discovery, plaintext env/header configuration, static help/list, shared runtime, structured/multimodal results.++Out of scope: OAuth, SSE (explicit `unsupported_transport_sse` error), project scope, Skill generation, resources/prompts, sampling, update detection, auto-install/upgrade of server software, package sharing/import.++## 2. Package on disk++```text+<avibe-home>/mcp/+ .hidden.json # names hidden from Avibe lists (native files unchanged)+ <name>/+ definition.json # Avibe-owned connection (absent for native-only servers)+ current.json # pointer to the one published snapshot+ revisions/<revision>/ # <revision> = generation timestamp + random suffix+ definition.json # snapshot used to connect+ manifest.json # formatVersion, description, generatedAt, serverInfo.version+ tools.json+ commands.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`.+- `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.++## 3. Prompt injection++The shared system prompt gets a short discovery index (outside `core/managed_skills.py`), only when at least one server is registered:++```text+## MCP capabilities++Use `vibe mcp <server> --list` to discover available tools.+Use `vibe mcp <server> <tool> --help` to inspect arguments before calling.+Call tools with `vibe mcp <server> <tool> [arguments]`.+Help and lists read local generated definitions; tool calls access the MCP server.++Available servers:+- context7: Find current library documentation and code examples.+- github: Work with GitHub repositories, issues, and pull requests.++List all servers: `vibe mcp --list`.+```++- One line per package, sorted by name; description sanitized to one line, max 160 chars.+- Description: from the published snapshot's manifest (user-provided at add/refresh, else a localized generic string). Server-provided text is not used. There is one snapshot per server; there are no pending edits.+- List at most 50 servers; if more exist, append the omitted count and `vibe mcp --list`.+- No tool names, schemas, URLs, commands, credentials or management commands.+- The block has two fixed parts: stable shared instructions (examples must stay parser-valid), then one `<server>: <description>` line per package, where `<server>` is the exact CLI selector.+- Disable/remove takes effect on the next prompt build; new calls are rejected immediately even if a running turn still sees the old list.+- The index grants nothing: every call rechecks the published revision at the owner.++Agents discover details on demand:++```text+prompt index+ → vibe mcp context7 --list+ → vibe mcp context7 resolve-library-id --help+ → vibe mcp context7 resolve-library-id --args-json '{"libraryName":"react","query":"React hooks"}'+```++## 4. CLI++### 4.1 Discover and call++```bash+vibe mcp --list # registered servers+vibe mcp docs --list [--format json]+vibe mcp docs search --help+vibe mcp docs search --query 'async Python' --limit 5+vibe mcp docs search --args-json '{"query":"async Python","limit":5}' # also --args-file, --args-stdin+```++- List/help read local artifacts only; they work offline and with the owner down.+- Lists print all entries, sorted by name. Human-readable output escapes control characters from server-provided text.+- Calls go to the owner, print one JSON document to stdout, diagnostics to stderr.+- Errors point to the next useful command (root list, service list or tool help).++Exit codes: `0` success, `2` usage/argument error, `1` any other failure (including command-admission denial). The JSON `error.type` carries the category (`not_found`, `disabled`, `connection`, `tool_error`, `timeout`, `capacity`, …). `unknown_outcome` marks any failure after `tools/call` was sent other than a returned tool error or a known pre-dispatch rejection; it must not be retried. An IPC timeout or disconnect after the CLI submitted the call to the owner is also `unknown_outcome`, following the existing IPC acceptance-ambiguity handling in `vibe/internal_client.py`.++### 4.2 Schema to flags++| Schema type | Flag |+|---|---|+| string | text as-is |+| number / integer | strict JSON number |+| boolean | explicit `true` / `false` |+| array / object | JSON value |+| union / nullable / complex, or key not matching `[A-Za-z][A-Za-z0-9_-]*` or named `args-json`/`args-file`/`args-stdin`/`help` | only via `--args-*` |++- Exact property keys; no aliases, case conversion or inserted defaults.+- One input mode per call; no input means `{}`.+- A tool whose name starts with `-` is selected after `--`: `vibe mcp docs -- --list --args-json '{}'`.+- Validate with a standard JSON Schema library (no remote refs). A tool whose schema it cannot handle is published as JSON-input-only with unvalidated help, not a failed generation.++### 4.3 Management++`vibe mcp` is reserved for per-server sub-CLIs. Management is:++```bash+vibe mcp-add --transport http docs https://example.invalid/mcp --header 'Accept-Language: en'+vibe mcp-add playwright -- npx -y @playwright/mcp@latest+vibe mcp-add --json-stdin+vibe mcp-discover+vibe mcp docs --refresh+vibe mcp docs --remove+```++- `vibe mcp-add` uses the Claude Code `mcp add` subset plus `--description`, `--cwd`, `--replace`, `--json-stdin`. It writes only the Avibe store, then refreshes that name; the call returns after refresh.+- `vibe mcp-discover` runs one full pass (joins an in-flight pass) and prints registered / failed + reason. Controller startup runs the same pass in the background, off the controller loop.+- Names: empty, `.`/`..`, NUL, `/`/`\\` rejected. Management verbs are not reserved names.+- Owner-only: mcp-add, mcp-discover, `--refresh`, `--remove`. Editor: list/help/call.++## 5. Page configuration++Skills & MCP page, MCP tab. No status badges, enable toggle, or edit dialog.++- Toolbar: 技能 | MCP, search, `+ 添加 MCP`. Header `刷新` = discover all.+- 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.++## 6. Discovery and versions++- Discovery = refresh every Avibe definition and every native source entry (except natively `enabled=false` and Avibe-hidden names). Connect, list tools, publish one snapshot. Success → registered. Failure → not listed; reason in logs and `vibe mcp-discover`.+- Avibe name wins over a native duplicate.+- A native entry removed or set `enabled=false` disappears at the next discovery; leftover artifacts may be deleted then.+- Publish = write one snapshot directory, then atomically replace `current.json`. A failed refresh unlists the name (`current.json` dropped); revision files may remain for a later retry.+- Concurrent discover passes join one in-flight task.+- Keep exactly one published snapshot per server. Tools with `execution.taskSupport: "required"` are skipped with a diagnostic.++## 7. Runtime++- **Owner:** the Controller, over existing control IPC. UI and CLI hold no runtimes.+- **Identity:** existing caller context (`core/caller_context.py`, `AVIBE_SESSION_ID`, …) as used by `vibe task/watch/agent`. No MCP-specific token.+- **Permission:** instance-global. The local OS user has full rights. Management commands (add, discover, refresh, remove) are Owner-only through the existing CLI command admission, because refreshing a stdio definition runs an arbitrary local command; list/help (admission runs before any help is rendered) and tool calls use the same floor as using Skills (Editor), matching who sees the prompt index. Remote-context callers thus get exactly the permissions they have elsewhere. No MCP-specific policy.+- **Connections:** one client connection per (revision, caller session) for every transport — a stdio process, or an HTTP client holding its own `Mcp-Session-Id` (closed with the connection). This matches Claude Code and Codex (one client per session). Context-free calls are one-shot. Calls within one session are serialized on its connection. A connection whose call ends with `unknown_outcome` is closed, never reused. An HTTP `Session not found` (pre-dispatch) closes the client and the call is retried once on a fresh connection.+- **Limits** (constants): at most 8 stdio processes in total, including refresh; batch add/discover wait for a slot, a single tool call fails with `capacity` at the cap. Idle close 10 min; call timeout 120 s; refresh 5 min. HTTP is not capped.+- Servers that lock a shared resource (e.g. Playwright's default persistent profile) need their own isolation flag in the provider config (`--isolated`); Avibe does not rewrite server argv.+- **Schemas at call time:** the CLI parses and validates against the published snapshot only. A new runtime connection lists all `tools/list` pages through the SDK before its first call (same 100-page cap as refresh), so the SDK knows every tool's output schema and header annotations; that list never changes the published package.+- **Calls:** the owner checks a published snapshot, connects or reuses, sends `tools/call` and returns the result with the revision used. Elicitation/sampling/roots are out of scope: the client's callbacks for them reject; since the tool may already have acted, the call ends as `unknown_outcome`. The owner fixes the revision at admission and validates arguments against it.+- **Remove/refresh:** remove blocks new calls; remove and a successful refresh close the package's superseded idle connections at once (busy ones close when their call settles); in-flight work may finish or report unknown outcome.+- **Event loop:** all MCP SDK sessions run on one dedicated runtime thread with its own event loop, owned by the Controller; the SDK's synchronous result validation therefore never blocks the Controller loop. All other MCP work — argument validation, refresh, artifact I/O, result envelope serialization and sizing — also runs off the Controller loop; the Controller loop only hands IPC requests over, per the repo's controller-loop rules.++Result envelope:++```json+{"schemaVersion": 1, "server": "docs", "revision": "<hex>", "tool": "search", "status": "ok",+ "result": {"content": [], "isError": false}}+```++Preserve typed content, `structuredContent`, `isError` and explicit null/false/empty values. Results above a fixed byte cap (set in C0; no shared IPC cap exists) are not returned: the call still completed, so the envelope keeps `isError` and reports `resultOmitted: "too_large"` — success, or the normal tool error when `isError` is true — so Agents never retry a committed call.++## 8. UI / API++No draft/generated/error/pending/nativeDeleted badges. No enable toggle.++```text+GET /api/mcp+GET /api/mcp/{name}+POST /api/mcp # add JSON block → Avibe store + refresh+POST /api/mcp/discover+POST /api/mcp/{name}/refresh+DELETE /api/mcp/{name} # Avibe: remove; native: hide+```++Read routes Editor; management Owner. Native async FastAPI → owner IPC.++## 9. Prior art++CLI shape follows mcporter `generate-cli` (inspected at [`5362d60`](https://github.com/openclaw/mcporter/blob/5362d60d2e17ca5b2dee3d92f48c0fb7b010abc5/docs/cli-generator.md)): discover once, static help, explicit refresh. Differences: one shared Python runner instead of per-server executables; exact keys with no flag normalization or default insertion; one published snapshot, no draft/enable lifecycle.++## 10. Implementation and acceptance++- **C0** (after authorization): pin SDK, confirm caller-context/IPC fit, SDK protocol negotiation, and the result byte cap. Hermetic temp `AVIBE_HOME` and loopback fixtures.+- **C1:** repository + parser, publisher, runtime, CLI, prompt index.+- **C2:** UI/API, i18n, user documentation (adding servers, plaintext credential behavior, refresh, tool invocation), Ruff and UI build; Incus regression on request.+- **C3:** Disable Claude/Codex/OpenCode native MCP in Avibe sessions. Hub **reads** those backends' config files as a source and stores Avibe-added servers under `<avibe-home>/mcp/`. Spawn isolation is unchanged.++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.+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).++## 11. Next action++Owner review, then C0 on explicit authorization.diff --git a/modules/agents/codex/transport.py b/modules/agents/codex/transport.pyindex a60c247c7..9957b3240 100644--- a/modules/agents/codex/transport.py+++ b/modules/agents/codex/transport.py@@ -87,6 +87,14 @@ def _avibe_app_server_config_args() -> list[str]:]+def _native_mcp_disabled_args() -> list[str]:+ """Native MCP is off in Avibe sessions; agents call MCP through ``vibe mcp``."""++ from core.mcp_hub.native import codex_disable_overrides++ return [arg for override in codex_disable_overrides() for arg in ("-c", override)]++class CodexRPCError(RuntimeError):"""A structured server error, distinct from an ambiguous transport failure."""@@ -182,6 +190,7 @@ class CodexTransport:+ self._runtime_args+ self._extra_args+ _avibe_app_server_config_args()+ + await asyncio.to_thread(_native_mcp_disabled_args))if self._model_hub_catalog is not None:# The path actually consumed must be the one we pin, even if adiff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.pyindex 7dd56c45f..75763a8c3 100644--- a/modules/agents/opencode/server.py+++ b/modules/agents/opencode/server.py@@ -30,6 +30,7 @@ import psutilfrom config import pathsfrom config.atomic_io import write_atomicfrom core.handlers.model_hub.identifiers import OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL+from core.mcp_hub.native import opencode_disabled_mcpfrom core.process_isolation import isolated_subprocess_kwargsfrom modules.agents.opencode.caller_context import ensure_plugin_installed, server_environmentfrom vibe import runtime@@ -1758,7 +1759,7 @@ def apply_resource_governance(resource_governor: Any | None, pid: int | None) ->apply_to_pid(pid, label="opencode serve")-def _launch_environment(spec: OpenCodeLaunchSpec, overlay_path: Optional[Path]) -> dict[str, str]:+async def _launch_environment(spec: OpenCodeLaunchSpec, overlay_path: Optional[Path]) -> dict[str, str]:env = os.environ.copy()env[DESKTOP_ROLE_ENV] = DESKTOP_OPENCODE_ROLEenv["OPENCODE_ENABLE_EXA"] = "1"@@ -1777,6 +1778,7 @@ def _launch_environment(spec: OpenCodeLaunchSpec, overlay_path: Optional[Path])# removes OpenCode's independently assembled native Catalog.env["OPENCODE_CONFIG_CONTENT"] = _managed_runtime_config_content(env.get("OPENCODE_CONFIG_CONTENT"),+ await asyncio.to_thread(opencode_disabled_mcp),)return env@@ -1833,7 +1835,7 @@ async def start_generation(overlay_path = generation_records_dir() / f"{generation_id}.overlay.json"overlay_path.parent.mkdir(parents=True, exist_ok=True)write_atomic(overlay_path, spec.overlay_file_content or spec.overlay_inline_content.encode())- env = _launch_environment(spec, overlay_path)+ env = await _launch_environment(spec, overlay_path)exited_pid: int | None = Noneexit_code: int | None = None# A process that survives its stop keeps its record and overlay; itsdiff --git a/modules/claude_client.py b/modules/claude_client.pyindex 204688a89..ff3cab92d 100644--- a/modules/claude_client.py+++ b/modules/claude_client.py@@ -13,6 +13,7 @@ from modules.claude_sdk_compat import (ToolResultBlock,)from config.v2_compat import ClaudeCompatConfig+from vibe.claude_config import CLAUDE_NATIVE_MCP_DISABLEDfrom modules.im.formatters import BaseMarkdownFormatter, SlackFormatter@@ -28,6 +29,7 @@ class ClaudeClient:cwd=config.cwd,system_prompt=config.system_prompt,max_buffer_size=CLAUDE_SDK_MAX_BUFFER_SIZE,+ **CLAUDE_NATIVE_MCP_DISABLED,) # type: ignore[arg-type]def format_message(diff --git a/pyproject.toml b/pyproject.tomlindex 643fc3ab6..7c68c6cc7 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -101,6 +101,8 @@ dependencies = [# (storage/vault_addresses.py); cryptography ships neither."pycryptodome>=3.20","prometheus-client>=0.20.0",+ # MCP Hub client (docs/plans/mcp-hub-mvp.md); 2.x is the current stable line.+ "mcp>=2.3.0,<3",][project.urls]diff --git a/tests/fixtures/mcp_echo_server.py b/tests/fixtures/mcp_echo_server.pynew file mode 100644index 000000000..f3ba4f3cf--- /dev/null+++ b/tests/fixtures/mcp_echo_server.py@@ -0,0 +1,56 @@+"""Loopback MCP test server: ``python mcp_echo_server.py [stdio|http PORT]``."""++import os+import sys+import time++from mcp.server.mcpserver import MCPServer++server = MCPServer("avibe-echo", version="0.1.0")++[email protected](description="Echo text back, optionally repeated.")+def echo(text: str, repeat: int = 1) -> str:+ return text * repeat++[email protected](description="Add two numbers.")+def add(a: float, b: float) -> dict:+ return {"sum": a + b}++[email protected](description="Always fails.")+def fail(reason: str) -> str:+ raise ValueError(reason)++[email protected](description="Reject with a JSON-RPC error.")+def reject() -> str:+ from mcp import MCPError++ raise MCPError(-32602, "rejected by server")++[email protected](description="Return a tool error containing a session phrase.")+def session_text() -> str:+ from mcp import MCPError++ raise MCPError(-32602, "browser session not found")++[email protected](description="Exit the server process mid-call.")+def crash() -> str:+ os._exit(1)++[email protected](description="Sleep for some seconds.")+def nap(seconds: float) -> str:+ time.sleep(seconds)+ return "awake"+++if __name__ == "__main__":+ if len(sys.argv) > 1 and sys.argv[1] == "http":+ server.run("streamable-http", host="127.0.0.1", port=int(sys.argv[2]))+ else:+ server.run("stdio")diff --git a/tests/fixtures/mcp_owner.py b/tests/fixtures/mcp_owner.pynew file mode 100644index 000000000..7ddbbc064--- /dev/null+++ b/tests/fixtures/mcp_owner.py@@ -0,0 +1,27 @@+"""Child test fixture: serve the real control IPC app with only the MCP runtime.++Run with a hermetic ``AVIBE_HOME``; the CLI then reaches this owner exactly as it+reaches the Controller.+"""++import asyncio+import sys+from pathlib import Path+from types import SimpleNamespace++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++from core.internal_server import serve # noqa: E402+from core.mcp_hub.runtime import McpRuntime # noqa: E402+++async def main() -> None:+ controller = SimpleNamespace(mcp_runtime=McpRuntime())+ try:+ await serve(controller)+ finally:+ controller.mcp_runtime.stop()+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/tests/fixtures/mcp_strict_legacy_server.py b/tests/fixtures/mcp_strict_legacy_server.pynew file mode 100644index 000000000..0194d2f9e--- /dev/null+++ b/tests/fixtures/mcp_strict_legacy_server.py@@ -0,0 +1,37 @@+"""Stdio MCP server that, like strict pre-2026 servers (rmcp), exits on ``server/discover``.++Proxies every other line to ``mcp_echo_server.py``.+"""++import json+import subprocess+import sys+import threading+from pathlib import Path++child = subprocess.Popen(+ [sys.executable, str(Path(__file__).with_name("mcp_echo_server.py"))],+ stdin=subprocess.PIPE,+ stdout=sys.stdout.buffer,+)+++def _pump() -> None:+ for line in sys.stdin.buffer:+ try:+ method = json.loads(line).get("method")+ except ValueError:+ method = None+ if method == "server/discover":+ sys.stderr.write("expect initialized request, but received server/discover\n")+ child.kill()+ sys.exit(1)+ child.stdin.write(line)+ child.stdin.flush()+ child.stdin.close()+++thread = threading.Thread(target=_pump, daemon=True)+thread.start()+thread.join()+sys.exit(child.wait())diff --git a/tests/fixtures/member_management_existing_read_roles.json b/tests/fixtures/member_management_existing_read_roles.jsonindex ff7bd8268..af49937b8 100644--- a/tests/fixtures/member_management_existing_read_roles.json+++ b/tests/fixtures/member_management_existing_read_roles.json@@ -35,6 +35,8 @@"GET /api/harness/tasks": "editor","GET /api/harness/watches": "editor","GET /api/inbox": "viewer",+ "GET /api/mcp": "editor",+ "GET /api/mcp/example": "editor","GET /api/media/example": "viewer","GET /api/media/example/meta": "viewer","GET /api/models/agents/example/models": "editor",@@ -129,9 +131,9 @@"POST /api/vault/grants": "editor","POST /api/vault/pubkey-pin": "editor","POST /api/vault/requests/access": "editor",+ "POST /api/vault/requests/example/approve-delete": "editor","POST /api/vault/requests/example/deny": "editor","POST /api/vault/requests/example/fulfill-access": "editor",- "POST /api/vault/requests/example/approve-delete": "editor","POST /api/vault/requests/sign": "editor","POST /api/vault/secrets": "editor","POST /api/vault/secrets/example/reveal-context": "editor",diff --git a/tests/test_backend_registration_contract.py b/tests/test_backend_registration_contract.pyindex f59961b74..fdce36f14 100644--- a/tests/test_backend_registration_contract.py+++ b/tests/test_backend_registration_contract.py@@ -70,6 +70,7 @@ PYTHON_DECLARATIONS = {("vibe/cli_health.py", "Dict", NATIVE): (1, "native", "Backend-specific native CLI version grammars, not another Agent universe."),("vibe/cli_repair.py", "Dict", NATIVE): (2, "native", "npm package and Homebrew formula coordinates for source-preserving native CLI repair."),("vibe/global_agents_md.py", "Dict", NATIVE): (1, "native", "Native global instruction filenames."),+ ("core/mcp_hub/native.py", "Tuple", frozenset({"claude", "codex", "opencode"})): (1, "native", "Native MCP config files Hub reads as the connection store."),("vibe/model_hub_runtime/adapter.py", "Dict", frozenset({"claude", "codex"})): (1, "native_subset", "Native subscription vendors."),("vibe/model_hub_runtime/state.py", "Dict", frozenset({"claude", "codex"})): (1, "native_subset", "Vendor aliases, including provider names."),("storage/alembic/versions/20260529_0007_backfill_scope_agent_names.py", "Set", NATIVE): (1, "native", "Immutable released migration predating Avibe."),@@ -77,6 +78,7 @@ PYTHON_DECLARATIONS = {}TYPESCRIPT_DECLARATIONS = {+ ("ui/src/context/ApiContext.tsx", frozenset({"claude", "codex", "opencode"})): (1, "native", "MCP Hub native source labels."),("ui/src/context/ApiContext.tsx", frozenset({"claude", "codex"})): (4, "native_subset", "Account-level native auth endpoints; OpenCode uses provider auth.",),@@ -186,4 +188,8 @@ def test_backend_universes_are_catalog_owned_and_literals_are_classified():f"Import catalog-derived Agent/native types or classify capability subsets: {locations_ts}")for (_path, members), (_count, relation, reason) in TYPESCRIPT_DECLARATIONS.items():- assert reason and relation == "native_subset" and members < NATIVE+ assert reason+ if relation == "native":+ assert members == NATIVE+ else:+ assert relation == "native_subset" and members < NATIVEdiff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.pyindex 5b7f933d9..375bf82d3 100644--- a/tests/test_claude_cli_path.py+++ b/tests/test_claude_cli_path.py@@ -257,7 +257,7 @@ def test_selected_agent_launch_uses_cli_skill_path_without_computer_use_mcp(assert all("Injected owner policy." in prompt for prompt in rendered_prompts)assert all("Computer use" not in prompt for prompt in rendered_prompts)assert getattr(first.options, "allowed_tools", None) == allowed_tools- assert getattr(first.options, "mcp_servers", None) is None+ assert first.options.mcp_servers == {} # no server at all, native ones includedclass _StubClaudeAgentOptions:@@ -957,6 +957,8 @@ def test_session_handler_preserves_explicit_limits_and_passes_alias_planning_metassert options.env.get(key) == expectedassert key not in json.loads(options.settings).get("env", {})assert options.setting_sources == ["user", "project", "local"]+ # Native MCP is off: agents call MCP through `vibe mcp`.+ assert (options.strict_mcp_config, options.mcp_servers) == (True, {})def test_session_handler_pins_hub_connection_in_launch_settings(monkeypatch, tmp_path: Path) -> None:@@ -995,6 +997,8 @@ def test_session_handler_pins_hub_connection_in_launch_settings(monkeypatch, tmpassert settings["env"]["ANTHROPIC_API_KEY"] == ""assert settings["autoMemoryEnabled"] is Falseassert options.setting_sources == ["user", "project", "local"]+ # Native MCP is off: agents call MCP through `vibe mcp`.+ assert (options.strict_mcp_config, options.mcp_servers) == (True, {})assert options.extra_args["model"] == "claude-opus-5"diff --git a/tests/test_computer_use_backends.py b/tests/test_computer_use_backends.pyindex c0593cee8..6fdd49660 100644--- a/tests/test_computer_use_backends.py+++ b/tests/test_computer_use_backends.py@@ -42,7 +42,7 @@ def test_opencode_runtime_cleanup_removes_stale_computer_use_mcp_only() -> None:)assert payload["mcp"] == {- "notes": {"type": "local", "command": ["notes"]},+ "notes": {"type": "local", "command": ["notes"], "enabled": False},}diff --git a/tests/test_mcp_hub_api.py b/tests/test_mcp_hub_api.pynew file mode 100644index 000000000..ab30cc326--- /dev/null+++ b/tests/test_mcp_hub_api.py@@ -0,0 +1,131 @@+"""``/api/mcp*`` against the real owner runtime and stdio fixture."""++import json+import sys+from pathlib import Path++import pytest++from core.mcp_hub import repository+from core.mcp_hub.runtime import McpRuntime+from tests.ui_server_test_helpers import csrf_headers, save_config+from vibe import internal_client+from vibe.authorization import http_authorization_policy+from vibe.ui_server import app++FIXTURE = str(Path(__file__).parent / "fixtures" / "mcp_echo_server.py")+PASTE = json.dumps({"mcpServers": {"echo": {+ "command": sys.executable, "args": [FIXTURE], "env": {"ECHO_TOKEN": "s3cret-value"}}}})+++def owner(monkeypatch, tmp_path):+ config = save_config(tmp_path)+ config.runtime.default_cwd = str(tmp_path)+ config.save()+ runtime = McpRuntime()++ async def forward(operation, payload, **_kwargs):+ status, body = await runtime.submit(operation, payload)+ assert status == 200+ return json.loads(body)++ monkeypatch.setattr(internal_client, "mcp_request", forward)+ yield runtime+ runtime.stop()+++def test_add_registers_and_delete_removes_through_the_api(owner):+ client = app.test_client()+ headers = csrf_headers(client)++ added = client.post("/api/mcp", json={"text": PASTE}, headers=headers)+ body = added.get_json()+ assert added.status_code == 200 and body["ok"] and body["toolCount"] == 7+ assert "s3cret-value" not in added.text+ assert repository.read_avibe_definition("echo") is not None++ listed = client.get("/api/mcp").get_json()["servers"]+ assert listed[0]["name"] == "echo" and listed[0]["source"] == "avibe"++ owner.stop()+ detail = client.get("/api/mcp/echo").get_json()+ assert detail["server"]["name"] == "echo"+ assert "s3cret-value" not in json.dumps(detail)+ assert any(tool["name"] == "echo" for tool in detail.get("tools") or detail["server"].get("tools") or [])++ assert client.delete("/api/mcp/echo", headers=headers).get_json()["removed"] is True+ assert client.get("/api/mcp/echo").status_code == 404+++def test_all_failed_batch_returns_per_server_reasons_and_identical_readd_is_unchanged(owner):+ client = app.test_client()+ headers = csrf_headers(client)+ first = client.post("/api/mcp", json={"text": PASTE}, headers=headers)+ assert first.status_code == 200 and first.get_json()["ok"]++ again = client.post("/api/mcp", json={"text": PASTE}, headers=headers)+ body = again.get_json()+ assert again.status_code == 200+ assert body["ok"] is True+ assert body["unchanged"][0]["name"] == "echo"+ assert body["failed"] == []+ assert body["added"] == []++ batch = {+ "mcpServers": {+ "echo": {"command": sys.executable, "args": [FIXTURE], "env": {"ECHO_TOKEN": "s3cret-value"}},+ "github": {"command": "/nonexistent/mcp-github"},+ "other": {"command": "/nonexistent/mcp-other"},+ }+ }+ failed = client.post("/api/mcp", json={"text": json.dumps(batch)}, headers=headers)+ payload = failed.get_json()+ assert failed.status_code == 200+ assert payload["ok"] is True # echo is unchanged+ names = {item["name"]: item for item in payload["failed"]}+ assert "github" in names and names["github"]["error"]+ assert "other" in names+ assert payload["unchanged"][0]["name"] == "echo"+ assert payload.get("error", {}).get("message") or names["github"]["error"]++ empty_fail = {+ "mcpServers": {+ "github": {"command": "/nonexistent/mcp-github"},+ "other": {"command": "/nonexistent/mcp-other"},+ }+ }+ none = client.post("/api/mcp", json={"text": json.dumps(empty_fail)}, headers=headers)+ none_body = none.get_json()+ assert none.status_code == 200+ assert none_body["ok"] is False+ assert {item["name"] for item in none_body["failed"]} == {"github", "other"}+ assert none_body["error"]["message"]+ assert "Unexpected MCP Hub response" not in json.dumps(none_body)+++def test_malformed_json_add_returns_top_level_error_without_batch_arrays(owner):+ client = app.test_client()+ headers = csrf_headers(client)+ response = client.post("/api/mcp", json={"text": "{not json"}, headers=headers)+ body = response.get_json()+ assert response.status_code == 400+ assert body["ok"] is False+ assert body.get("error", {}).get("message")+ assert "added" not in body+ assert "failed" not in body+++ ("method", "path", "role"),+ [+ ("GET", "/api/mcp", "editor"),+ ("GET", "/api/mcp/echo", "editor"),+ ("POST", "/api/mcp", "owner"),+ ("POST", "/api/mcp/discover", "owner"),+ ("POST", "/api/mcp/echo/refresh", "owner"),+ ("DELETE", "/api/mcp/echo", "owner"),+ ],+)+def test_route_roles(method, path, role):+ assert http_authorization_policy(method, path).minimum_role == rolediff --git a/tests/test_mcp_hub_commands.py b/tests/test_mcp_hub_commands.pynew file mode 100644index 000000000..abdc7f5c4--- /dev/null+++ b/tests/test_mcp_hub_commands.py@@ -0,0 +1,124 @@+"""Schema -> flag contracts for the shared ``vibe mcp`` runner (plan §4.2).++Exact keys, no aliases or inserted defaults; one input mode per call; schemas the+validator cannot handle publish as JSON-input-only instead of failing generation.+"""++import pytest++from core.mcp_hub.commands import build_command, parse_tool_argv, validate_arguments+from core.mcp_hub.errors import McpHubError++TOOL = {+ "name": "search",+ "inputSchema": {+ "type": "object",+ "properties": {+ "query": {"type": "string"},+ "limit": {"type": "integer"},+ "ratio": {"type": "number"},+ "exact": {"type": "boolean"},+ "tags": {"type": "array", "items": {"type": "string"}},+ "filter": {"type": "object"},+ "maybe": {"type": ["string", "null"]},+ "choice": {"anyOf": [{"type": "string"}, {"type": "integer"}]},+ "bad key": {"type": "string"},+ "help": {"type": "string"},+ "camelCase": {"type": "string"},+ },+ "required": ["query"],+ },+}+++def test_flag_table():+ command = build_command(TOOL)+ assert {flag["key"]: flag["kind"] for flag in command["flags"]} == {+ "query": "string", "limit": "integer", "ratio": "number", "exact": "boolean",+ "tags": "array", "filter": "object", "camelCase": "string",+ }+ assert sorted(command["jsonOnlyKeys"]) == ["bad key", "choice", "help", "maybe"]+ assert command["validated"] is True+++def test_flags_parse_exact_keys_and_strict_values():+ command = build_command(TOOL)+ arguments = parse_tool_argv(command, [+ "--query", "async Python", "--limit=5", "--ratio", "0.5", "--exact", "false",+ "--tags", '["a"]', "--filter", "{}", "--camelCase", "x",+ ])+ assert arguments == {"query": "async Python", "limit": 5, "ratio": 0.5, "exact": False,+ "tags": ["a"], "filter": {}, "camelCase": "x"}+ assert parse_tool_argv(command, []) == {}+++ "argv",+ [+ ["--limit", "5.5"],+ ["--limit", "true"],+ ["--ratio", "NaNx"],+ ["--exact", "yes"],+ ["--tags", "{}"],+ ["--camel-case", "x"],+ ["--query", "a", "--query", "b"],+ ["--query", "a", "--args-json", "{}"],+ ["--args-json", "{}", "--args-json", "{}"],+ ["--args-json", "[]"],+ ["positional"],+ ],+)+def test_usage_errors(argv):+ with pytest.raises(McpHubError) as caught:+ parse_tool_argv(build_command(TOOL), argv)+ assert caught.value.usage+++def test_json_input_modes_reach_flagless_keys():+ command = build_command(TOOL)+ assert parse_tool_argv(command, ["--args-json", '{"choice": 3, "help": "x"}']) == {"choice": 3, "help": "x"}+ assert parse_tool_argv(command, ["--args-stdin"], read_stdin=lambda: '{"maybe": null}') == {"maybe": None}+ assert parse_tool_argv(command, ["--args-file", "p"], read_file=lambda path: '{"query": "q"}') == {"query": "q"}+++def test_validation_uses_the_published_schema():+ validate_arguments(TOOL, {"query": "q", "choice": 1})+ with pytest.raises(McpHubError) as caught:+ validate_arguments(TOOL, {"limit": 1})+ assert caught.value.type == "invalid_arguments"+++def test_unhandleable_schema_is_json_only_and_unvalidated():+ remote = {"name": "remote", "inputSchema": {"$ref": "https://example.invalid/schema.json"}}+ nested = {+ "name": "nested",+ "inputSchema": {+ "type": "object",+ "properties": {"filter": {"$ref": "https://example.invalid/filter.json"}},+ },+ }+ invalid = {"name": "invalid", "inputSchema": {"type": "object", "properties": {"a": {"type": 5}}}}+ for tool in (remote, nested, invalid):+ command = build_command(tool)+ assert command["validated"] is False and command["flags"] == []+ validate_arguments(tool, {"anything": 1}) # not validated, not a failure+++def test_local_defs_ref_stays_validated():+ tool = {+ "name": "count",+ "inputSchema": {+ "type": "object",+ "properties": {+ "label": {"type": "string"},+ "count": {"$ref": "#/$defs/positive"},+ },+ "$defs": {"positive": {"type": "integer", "minimum": 1}},+ "required": ["count"],+ },+ }+ command = build_command(tool)+ assert command["validated"] is True+ assert any(flag["key"] == "label" for flag in command["flags"])+ with pytest.raises(McpHubError):+ validate_arguments(tool, {"count": -1})diff --git a/tests/test_mcp_hub_definition.py b/tests/test_mcp_hub_definition.pynew file mode 100644index 000000000..3bd691d3e--- /dev/null+++ b/tests/test_mcp_hub_definition.py@@ -0,0 +1,134 @@+"""MCP Hub definition parsing: the page JSON and ``vibe mcp-add`` share one shape.++Contract (docs/plans/mcp-hub-mvp.md §4.3, §5): both entry points normalize to the+same ``definition.json``; unsupported transports, options, placeholders and+credential-bearing URLs fail with a field-specific usage error; parsing never+connects.+"""++import json++import pytest++from core.mcp_hub.definition import (+ parse_add_argv,+ parse_provider_json,+)+from core.mcp_hub.errors import McpHubError+++ ("argv", "server"),+ [+ (+ ["--transport", "http", "docs", "https://example.invalid/mcp", "--header", "Accept-Language: en"],+ {"type": "http", "url": "https://example.invalid/mcp", "headers": {"Accept-Language": "en"}},+ ),+ (+ ["playwright", "--", "npx", "-y", "@playwright/mcp@latest", "--isolated"],+ {"command": "npx", "args": ["-y", "@playwright/mcp@latest", "--isolated"]},+ ),+ (+ ["local-tools", "--env", "MODE=readonly", "B=2", "--", "python", "server.py"],+ {"command": "python", "args": ["server.py"], "env": {"MODE": "readonly", "B": "2"}},+ ),+ (+ ["--cwd", "/srv/tools", "tools", "--", "/bin/tool", "--flag=x"],+ {"command": "/bin/tool", "args": ["--flag=x"], "cwd": "/srv/tools"},+ ),+ ],+)+def test_add_argv_and_page_json_produce_identical_definitions(argv, server):+ from_cli, replace = parse_add_argv(argv)+ name = from_cli[0]["name"]+ from_page = parse_provider_json(json.dumps({"mcpServers": {name: server}}))+ assert replace is False+ assert from_cli == from_page+++def test_provider_type_spellings_and_ignored_enabled():+ servers = {+ f"s{index}": {"type": kind, "url": "http://127.0.0.1:1/mcp", "enabled": False}+ for index, kind in enumerate(["http", "streamable-http", "streamable_http"])+ }+ servers["plain"] = {"url": "http://127.0.0.1:1/mcp"}+ servers["local"] = {"type": "stdio", "command": "srv"}+ parsed = {item["name"]: item["transport"]["type"] for item in parse_provider_json(json.dumps({"mcpServers": servers}))}+ assert parsed == {"local": "stdio", "plain": "streamable_http", "s0": "streamable_http",+ "s1": "streamable_http", "s2": "streamable_http"}+++ ("server", "error_type", "field"),+ [+ ({"type": "sse", "url": "http://127.0.0.1:1/sse"}, "unsupported_transport_sse", "type"),+ ({"command": "x", "url": "http://127.0.0.1:1/"}, "invalid_definition", "url"),+ ({"url": "https://user:[email protected]/mcp"}, "invalid_definition", "url"),+ ({"url": "https://example.invalid/mcp", "headers": {"Authorization": "Bearer ${TOKEN}"}},+ "invalid_definition", "headers.Authorization"),+ ({"command": "x", "env": {"K": "${HOME:-/tmp}"}}, "invalid_definition", "env.K"),+ ({"command": "x", "cwd": "relative/dir"}, "invalid_definition", "cwd"),+ ({"url": "https://example.invalid/mcp", "args": ["a"]}, "invalid_definition", "args"),+ ],+)+def test_page_rejects_unsupported_input_with_field(server, error_type, field):+ with pytest.raises(McpHubError) as caught:+ parse_provider_json(json.dumps({"mcpServers": {"bad": server}}))+ assert (caught.value.type, caught.value.field, caught.value.usage) == (error_type, field, True)+++def test_json_batch_keeps_valid_neighbors_when_one_entry_is_invalid():+ parsed = parse_provider_json(json.dumps({"mcpServers": {+ "ok": {"command": "srv"},+ "bad": {"type": "sse", "url": "http://127.0.0.1:1/sse"},+ }}))+ assert [item["name"] for item in parsed] == ["ok"]+ assert parsed.failures[0]["name"] == "bad"++[email protected]("name", ["hidden.json", ".hidden.json"])+def test_hidden_registry_name_is_reserved(name):+ with pytest.raises(McpHubError) as caught:+ parse_provider_json(json.dumps({"mcpServers": {name: {"command": "srv"}}}))+ assert caught.value.type == "invalid_name"++[email protected]("name", ["", ".", "..", "a/b", "a\\b", "a\x00b"])+def test_invalid_names_are_rejected(name):+ with pytest.raises(McpHubError) as caught:+ parse_add_argv([name, "--", "srv"])+ assert caught.value.type == "invalid_name"++[email protected]("name", ["iphone_use", "node_repl", "Upper", "1abc", "con"])+def test_native_style_names_are_accepted(name):+ definitions, _replace = parse_add_argv([name, "--", "srv"])+ assert definitions[0]["name"] == name+++ "argv",+ [+ ["--scope", "user", "x", "--", "srv"],+ ["--transport", "sse", "x", "http://127.0.0.1:1/sse"],+ ["--client-id", "abc", "--transport", "http", "x", "http://127.0.0.1:1/"],+ ],+)+def test_add_rejects_scope_sse_and_oauth_options(argv):+ with pytest.raises(McpHubError) as caught:+ parse_add_argv(argv)+ assert caught.value.usage+++def test_json_stdin_after_command_separator_is_a_server_argument():+ definitions, _replace = parse_add_argv(["local", "--", "server", "--json-stdin"])+ assert definitions[0]["transport"]["command"] == "server"+ assert definitions[0]["transport"]["args"] == ["--json-stdin"]+++def test_json_stdin_and_replace():+ text = json.dumps({"mcpServers": {"b": {"command": "srv"}, "a": {"url": "http://127.0.0.1:1/mcp"}}})+ definitions, replace = parse_add_argv(["--replace", "--json-stdin", text])+ assert [item["name"] for item in definitions] == ["a", "b"] and replace is True++diff --git a/tests/test_mcp_hub_native.py b/tests/test_mcp_hub_native.pynew file mode 100644index 000000000..9a6628eb2--- /dev/null+++ b/tests/test_mcp_hub_native.py@@ -0,0 +1,264 @@+"""Native MCP configs are the Hub's connection store, and Avibe sessions never load them.++Contract (docs/plans/mcp-hub-mvp.md §1, acceptance 6): Hub lists the union of+Claude ``.claude.json``, Codex ``config.toml`` and OpenCode ``opencode.json``+servers as a read-only union, 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.+"""++import asyncio+import json+import tomllib++import pytest++from core.mcp_hub import native, repository+from core.mcp_hub.runtime import McpRuntime++CLAUDE = {"numStartups": 7, "mcpServers": {+ "docs": {"type": "http", "url": "https://example.invalid/mcp", "headers": {"Authorization": "Bearer c"}},+ "shared": {"type": "stdio", "command": "claude-wins", "args": []},+}}+CODEX = """model = "gpt-test"++[mcp_servers.local]+command = "srv"+args = ["--read-only"]+startup_timeout_sec = 30++[mcp_servers.local.env]+MODE = "ro"++[mcp_servers.shared]+command = "codex-loses"+"""+OPENCODE = {"$schema": "https://opencode.ai/config.json", "mcp": {+ "oc": {"type": "local", "command": ["node", "oc.js"], "environment": {"K": "v"}, "enabled": True},+}}+++def native_files():+ claude, codex, opencode = native.claude_path(), native.codex_path(), native.opencode_path()+ for path in (claude, codex, opencode):+ path.parent.mkdir(parents=True, exist_ok=True)+ claude.write_text(json.dumps(CLAUDE))+ codex.write_text(CODEX)+ opencode.write_text(json.dumps(OPENCODE))+ return claude, codex, opencode+++def runtime():+ owner = McpRuntime()+ yield owner+ owner.stop()+++def _run(runtime, operation, payload):+ return json.loads(asyncio.run(runtime.submit(operation, payload))[1])+++def test_hub_reads_native_union_without_listing_unpublished(native_files):+ assert repository.read_definition("shared")["transport"]["command"] == "claude-wins"+ assert repository.read_definition("local")["transport"] == {+ "type": "stdio", "command": "srv", "args": ["--read-only"], "env": {"MODE": "ro"}}+ assert repository.read_definition("oc")["transport"] == {+ "type": "stdio", "command": "node", "args": ["oc.js"], "env": {"K": "v"}}+ assert repository.list_packages() == [] # unpublished native entries are not listed+++def test_add_writes_avibe_store_and_remove_hides_native(native_files, runtime):+ claude, _codex, _opencode = native_files+ before = claude.read_bytes()+ new = {"name": "fresh", "server": {"command": "/nonexistent/mcp-fresh"}, "description": "Fresh"}+ result = _run(runtime, "add", {"servers": [new]})+ assert result["ok"] is False # http fixture is unreachable; add rolls back+ assert repository.read_avibe_definition("fresh") is None+ assert claude.read_bytes() == before+ assert "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()+++def test_concurrent_hide_keeps_every_name(native_files):+ from concurrent.futures import ThreadPoolExecutor++ names = ["shared", "docs", "local"]+ with ThreadPoolExecutor(max_workers=3) as pool:+ list(pool.map(repository.hide_name, names))+ assert set(names) <= repository.hidden_names()+++def test_unparseable_native_file_is_skipped_and_never_rewritten(native_files):+ _claude, codex, _opencode = native_files+ codex.write_text("[mcp_servers.local\nbroken")+ assert "local" not in native.read_all()+ assert "docs" in native.read_all()+ assert repository.list_packages() == []+ assert native.codex_path().read_text() == "[mcp_servers.local\nbroken"+++def test_unreadable_native_bytes_are_skipped_without_aborting_neighbors(native_files):+ _claude, codex, _opencode = native_files+ codex.write_bytes(b"\xff\xfe not utf-8")+ names = native.read_all()+ assert "local" not in names+ assert "docs" in names+ assert repository.list_packages() == []+++def test_underscore_names_and_natively_disabled_relative_cwd(native_files):+ _claude, codex, _opencode = native_files+ codex.write_text(+ CODEX+ + """+[mcp_servers.iphone_use]+command = "python3"+args = ["iphone_use.py"]++[mcp_servers.computer-use]+command = "./Codex Computer Use.app/bin"+args = ["mcp"]+cwd = "."+enabled = false+"""+ )+ assert "iphone_use" in native.read_all()+ assert "computer-use" not in native.read_all()+ assert "computer-use" in native.disabled_names()+ assert repository.list_packages() == []+++def test_codex_backend_extras_are_ignored_not_errors(native_files, monkeypatch):+ _claude, codex, _opencode = native_files+ extra = """+[mcp_servers.node_repl]+command = "/bin/node_repl"+args = []+startup_timeout_sec = 120+env_vars = ["HUB_TEST_PRESENT", "HUB_TEST_MISSING"]++[mcp_servers.node_repl.env]+CODEX_HOME = "/tmp/codex"+"""+ monkeypatch.setenv("HUB_TEST_PRESENT", "from-parent")+ monkeypatch.delenv("HUB_TEST_MISSING", raising=False)+ codex.write_text(CODEX + extra)+ transport = repository.read_definition("node_repl")["transport"]+ assert transport["command"] == "/bin/node_repl"+ assert transport["env"] == {"HUB_TEST_PRESENT": "from-parent", "CODEX_HOME": "/tmp/codex"}+ stored = tomllib.loads(codex.read_text())["mcp_servers"]["node_repl"]+ assert stored["startup_timeout_sec"] == 120+ assert stored["env_vars"] == ["HUB_TEST_PRESENT", "HUB_TEST_MISSING"]+++def test_opencode_local_cwd_is_resolved_from_native_file(native_files):+ _claude, _codex, opencode = native_files+ data = json.loads(opencode.read_text())+ data["mcp"]["local-cwd"] = {"type": "local", "command": ["./server"], "cwd": "."}+ opencode.write_text(json.dumps(data))+ definition = repository.read_definition("local-cwd")+ assert definition["transport"]["cwd"] == str(opencode.parent)+ assert definition["transport"]["command"] == "./server"+++def test_natively_disabled_entry_is_omitted_from_hub_lists(native_files):+ import sys+ from pathlib import Path++ _claude, codex, _opencode = native_files+ fixture = str(Path(__file__).parent / "fixtures" / "mcp_echo_server.py")+ codex.write_text(CODEX + f'\n[mcp_servers.off]\ncommand = {json.dumps(sys.executable)}\nargs = [{json.dumps(fixture)}]\nenabled = false\n')+ names = {item["name"] for item in repository.list_packages()}+ assert "off" not in names+ assert "off" in native.disabled_names()+++def test_relative_native_cwd_resolves_against_its_file_and_generates(native_files, runtime):+ import shutil+ import sys+ from pathlib import Path++ claude, codex, opencode = native_files+ fixture = Path(__file__).parent / "fixtures" / "mcp_echo_server.py"+ for path in native_files:+ shutil.copy(fixture, path.parent / "rel_echo.py") # found only if cwd is the file's dir+ data = json.loads(claude.read_text())+ data["mcpServers"]["rel-claude"] = {"command": sys.executable, "args": ["rel_echo.py"], "cwd": "."}+ claude.write_text(json.dumps(data))+ codex.write_text(CODEX + f'\n[mcp_servers.rel-codex]\ncommand = {json.dumps(sys.executable)}\nargs = ["rel_echo.py"]\ncwd = "."\n')+ data = json.loads(opencode.read_text())+ data["mcp"]["rel-opencode"] = {"type": "local", "command": [sys.executable, "rel_echo.py"], "cwd": "."}+ opencode.write_text(json.dumps(data))++ for name, path in (("rel-claude", claude), ("rel-codex", codex), ("rel-opencode", opencode)):+ assert repository.read_definition(name)["transport"]["cwd"] == str(path.parent)+ result = _run(runtime, "refresh", {"name": name})+ assert result["ok"] and result["toolCount"] == 7, (name, result)+++def test_native_delete_hides_and_may_drop_artifacts(native_files):+ from core.mcp_hub.commands import build_command++ claude, _codex, _opencode = native_files+ definition = {+ "schemaVersion": 1,+ "name": "docs",+ "description": "Search",+ "transport": {"type": "streamable_http", "url": "https://example.invalid/mcp", "headers": {}},+ }+ tool = {"name": "search", "description": "", "inputSchema": {"type": "object", "properties": {}}}+ repository.publish(+ "docs",+ definition=definition,+ manifest={"description": "Search", "generatedAt": "2026-01-01T00:00:00+00:00"},+ tools=[tool],+ commands=[build_command(tool)],+ )+ data = json.loads(claude.read_text())+ del data["mcpServers"]["docs"]+ claude.write_text(json.dumps(data))+ assert "docs" not in {item["name"] for item in repository.list_packages()}+ return++def test_native_entries_needing_env_expansion_are_marked_not_dropped(native_files):+ claude, _codex, _opencode = native_files+ data = json.loads(claude.read_text())+ data["mcpServers"]["templated"] = {"command": "srv", "env": {"TOKEN": "${TOKEN}"}}+ claude.write_text(json.dumps(data))+ assert "templated" not in native.read_all() or native.read_all()["templated"].error is not None+ assert "templated" not in {item["name"] for item in repository.list_packages()}+++def test_spawns_disable_every_native_server(native_files):+ from claude_agent_sdk import ClaudeAgentOptions+ from claude_agent_sdk._internal.transport.subprocess_cli import SubprocessCLITransport++ from modules.agents.codex.transport import _native_mcp_disabled_args+ from vibe.claude_config import CLAUDE_NATIVE_MCP_DISABLED+ from vibe.opencode_config import managed_opencode_runtime_config_content++ command = SubprocessCLITransport(prompt="x", options=ClaudeAgentOptions(cli_path="/bin/claude", **CLAUDE_NATIVE_MCP_DISABLED))._build_command()+ assert "--strict-mcp-config" in command and "--mcp-config" not in command+ from config.v2_compat import ClaudeCompatConfig+ from modules.claude_client import ClaudeClient++ client = ClaudeClient(ClaudeCompatConfig(enabled=True, permission_mode="default", cwd="/tmp"))+ assert client.options.strict_mcp_config and client.options.mcp_servers == {}++ assert _native_mcp_disabled_args() == [+ "-c", "mcp_servers.local.enabled=false", "-c", "mcp_servers.shared.enabled=false"]++ overlay = json.loads(managed_opencode_runtime_config_content(None, native.opencode_disabled_mcp()))+ assert overlay["mcp"] == {"oc": {**OPENCODE["mcp"]["oc"], "enabled": False}}++ only_in_overlay = json.loads(managed_opencode_runtime_config_content(+ json.dumps({"mcp": {"extra": {"type": "local", "command": ["node"], "enabled": True}}}),+ native.opencode_disabled_mcp(),+ ))+ assert only_in_overlay["mcp"]["extra"]["enabled"] is False+ assert only_in_overlay["mcp"]["oc"]["enabled"] is Falsediff --git a/tests/test_mcp_hub_runtime.py b/tests/test_mcp_hub_runtime.pynew file mode 100644index 000000000..d43d19a88--- /dev/null+++ b/tests/test_mcp_hub_runtime.py@@ -0,0 +1,489 @@+"""MCP Hub owner path against a real loopback stdio server (plan §6, §7, acceptance 2-5).++Runs the real SDK, runtime thread, repository and CLI under the per-test hermetic+``AVIBE_HOME`` that ``tests/conftest.py`` provides.+"""++import asyncio+import json+import re+import shlex+import sys+from pathlib import Path++import pytest++from core.mcp_hub import repository+from core.mcp_hub import runtime as mcp_runtime+from core.mcp_hub.prompt import build_mcp_prompt_block+from core.mcp_hub.runtime import McpRuntime+from tests.ui_server_test_helpers import save_config+++FIXTURE = str(Path(__file__).parent / "fixtures" / "mcp_echo_server.py")+++def _run(runtime: McpRuntime, operation: str, payload: dict) -> dict:+ status, body = asyncio.run(runtime.submit(operation, payload))+ assert status == 200+ return json.loads(body)+++def _server(command: str = sys.executable) -> dict:+ return {"name": "echo", "server": {"command": command, "args": [FIXTURE]}, "description": "Echo tools"}+++def runtime(tmp_path):+ config = save_config(tmp_path)+ config.runtime.default_cwd = str(tmp_path)+ config.save()+ owner = McpRuntime()+ yield owner+ owner.stop()+++def generated(runtime):+ assert _run(runtime, "add", {"servers": [_server()]})["ok"]+ return runtime+++def test_describe_walks_cause_chain_for_http_status():+ class Response:+ status_code = 400+ reason = "Bad Request"+ text = '{"message":"Bad credentials"}'++ class HttpError(Exception):+ def __init__(self):+ super().__init__("boom")+ self.response = Response()++ outer = Exception("Server returned an error response")+ outer.__cause__ = HttpError()+ assert mcp_runtime._describe(outer).startswith("HTTP 400:")+ assert "Bad Request" in mcp_runtime._describe(outer)+++def test_add_writes_avibe_store_and_registers(runtime):+ first = _run(runtime, "add", {"servers": [_server()]})+ assert first["ok"] and first["toolCount"] == 7+ assert first["added"][0]["name"] == "echo"+ assert repository.read_avibe_definition("echo") is not None+ assert first.get("failed") == []+++def test_batch_add_registers_neighbors_and_rolls_back_the_failure(runtime):+ """One failing server in the middle must not block or leave an invisible definition."""++ good = _server()+ bad = {"name": "github", "server": {"command": "/nonexistent/mcp-github"}}+ other = {"name": "zeta", "server": {"command": sys.executable, "args": [FIXTURE]}, "description": "Z"}+ result = _run(runtime, "add", {"servers": [good, bad, other]})+ names = {item["name"] for item in result["added"]}+ failed = {item["name"]: item["error"] for item in result["failed"]}+ assert result["ok"] is True+ assert names == {"echo", "zeta"}+ assert "github" in failed and failed["github"]+ assert repository.read_avibe_definition("github") is None+ assert "github" not in {item["name"] for item in repository.list_packages()}+ assert repository.read_published("echo") is not None+ assert repository.read_published("zeta") is not None+ published = repository.read_published("echo")+ assert [tool["name"] for tool in published["tools"]] == ["add", "crash", "echo", "fail", "nap", "reject", "session_text"]+ assert repository.summarize("echo")["source"] == "avibe"+++def test_refresh_keeps_one_published_snapshot(generated):+ revisions = [_run(generated, "refresh", {"name": "echo"})["revision"] for _ in range(3)]+ kept = sorted(path.name for path in (repository.package_dir("echo") / "revisions").iterdir())+ assert kept == [revisions[-1]]+++def test_failed_replace_add_restores_previous_avibe_definition(generated):+ before = repository.read_published("echo")["revision"]+ previous = repository.read_avibe_definition("echo")+ result = _run(generated, "add", {"servers": [_server("/nonexistent/mcp-server")], "replace": True})+ assert result["ok"] is False+ assert result["failed"][0]["name"] == "echo"+ assert repository.read_published("echo")["revision"] == before+ assert repository.read_avibe_definition("echo") == previous+++def test_malformed_existing_definition_does_not_abort_batch_add(runtime):+ path = repository.package_dir("broken") / "definition.json"+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("{not json")+ result = _run(runtime, "add", {"servers": [{"name": "broken", "server": {"command": "/nonexistent/x"}}, _server()]})+ assert result["ok"] is True+ assert {item["name"] for item in result["added"]} == {"echo"}+ assert any(item["name"] == "broken" for item in result["failed"])+++def test_failed_readd_of_hidden_native_stays_hidden(runtime):+ from core.mcp_hub import native++ claude = native.claude_path()+ claude.parent.mkdir(parents=True, exist_ok=True)+ 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()+ result = _run(runtime, "add", {"servers": [{"name": "echo", "server": {"command": "/nonexistent/mcp-echo"}}]})+ assert result["ok"] is False+ assert "echo" in repository.hidden_names()+ assert repository.read_published("echo") is None+++def test_failed_explicit_refresh_unlists_the_server(generated):+ repository.write_avibe_definition({+ "name": "echo",+ "description": "Echo tools",+ "transport": {"type": "stdio", "command": "/nonexistent/mcp-echo", "args": [FIXTURE]},+ })+ result = _run(generated, "refresh", {"name": "echo", "waitStdio": True})+ assert result["ok"] is False+ assert "echo" not in {item["name"] for item in repository.list_packages()}+++def test_failed_discover_unlists_previous_revision(generated):+ repository.write_avibe_definition({+ "name": "echo",+ "description": "Echo tools",+ "transport": {"type": "stdio", "command": "/nonexistent/mcp-echo", "args": [FIXTURE]},+ })+ result = _run(generated, "discover", {})+ by_name = {item["name"]: item for item in result["results"]}+ assert by_name["echo"]["status"] == "failed"+ assert "echo" not in {item["name"] for item in repository.list_packages()}+ assert (repository.package_dir("echo") / "revisions").exists()+++def test_readding_hidden_native_identical_definition_registers_again(runtime):+ from core.mcp_hub import native++ claude = native.claude_path()+ claude.parent.mkdir(parents=True, exist_ok=True)+ 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()+ assert repository.read_published("echo") is None+ result = _run(runtime, "add", {"servers": [_server()]})+ assert result["ok"] is True+ assert result["added"][0]["name"] == "echo"+ assert "echo" not in repository.hidden_names()+ assert repository.read_published("echo") is not None+++def test_native_definition_change_is_not_unchanged_until_published(runtime):+ from core.mcp_hub import native++ claude = native.claude_path()+ claude.parent.mkdir(parents=True, exist_ok=True)+ claude.write_text(json.dumps({"mcpServers": {+ "echo": {"type": "stdio", "command": sys.executable, "args": [FIXTURE]},+ }}))+ assert _run(runtime, "discover", {})["ok"]+ claude.write_text(json.dumps({"mcpServers": {+ "echo": {"type": "stdio", "command": sys.executable, "args": [FIXTURE, "--other"]},+ }}))+ pasted = {+ "name": "echo",+ "server": {"command": sys.executable, "args": [FIXTURE, "--other"]},+ "description": "Echo tools",+ }+ blocked = _run(runtime, "add", {"servers": [pasted]})+ assert blocked["ok"] is False+ assert blocked["failed"][0]["type"] == "exists"+ replaced = _run(runtime, "add", {"servers": [pasted], "replace": True})+ assert replaced["ok"] is True+ assert replaced["added"][0]["name"] == "echo"+ published = repository.read_published("echo")["definition"]+ assert published["transport"]["args"] == [FIXTURE, "--other"]+++def test_identical_native_readd_without_cwd_is_unchanged(runtime):+ from core.mcp_hub import native++ claude = native.claude_path()+ claude.parent.mkdir(parents=True, exist_ok=True)+ claude.write_text(json.dumps({"mcpServers": {+ "echo": {"type": "stdio", "command": sys.executable, "args": [FIXTURE]},+ }}))+ assert _run(runtime, "discover", {})["ok"]+ result = _run(runtime, "add", {"servers": [{+ "name": "echo",+ "server": {"command": sys.executable, "args": [FIXTURE]},+ }]})+ assert result["ok"] is True+ assert result["unchanged"][0]["name"] == "echo"+++def test_explicit_cwd_difference_is_exists_not_unchanged(generated):+ same_command = {+ "name": "echo",+ "server": {"command": sys.executable, "args": [FIXTURE], "cwd": "/tmp/mcp-other-cwd"},+ "description": "Echo tools",+ }+ result = _run(generated, "add", {"servers": [same_command]})+ assert result["ok"] is False+ assert result["failed"][0]["type"] == "exists"+ assert repository.read_avibe_definition("echo")["transport"].get("cwd") != "/tmp/mcp-other-cwd"+++def test_discover_keeps_neighbors_when_one_native_refresh_fails(runtime):+ from core.mcp_hub import native++ claude = native.claude_path()+ claude.parent.mkdir(parents=True, exist_ok=True)+ claude.write_text(json.dumps({"mcpServers": {+ "echo": {"type": "stdio", "command": sys.executable, "args": [FIXTURE]},+ "dead": {"type": "stdio", "command": "/nonexistent/mcp-dead"},+ }}))+ result = _run(runtime, "discover", {})+ by_name = {item["name"]: item for item in result["results"]}+ assert result["ok"] is True+ assert by_name["echo"]["status"] == "registered"+ assert by_name["dead"]["status"] == "failed"+++def test_avibe_owned_server_is_listed_even_if_codex_disables_the_same_name(generated):+ from core.mcp_hub import native++ path = native.codex_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text('[mcp_servers.echo]\ncommand = "codex-echo"\nenabled = false\n')+ names = {item["name"] for item in repository.list_packages()}+ assert "echo" in names+ assert repository.summarize("echo")["source"] == "avibe"+++def test_calls_return_envelopes(generated):+ ok = _run(generated, "call", {"name": "echo", "tool": "echo", "arguments": {"text": "hi", "repeat": 2},+ "sessionId": "ses-1"})+ assert ok["status"] == "ok" and ok["revision"] == repository.read_published("echo")["revision"]+ assert ok["result"]["content"] == [{"type": "text", "text": "hihi"}]+ assert ok["result"]["structuredContent"] == {"result": "hihi"} and ok["result"]["isError"] is False++ failed = _run(generated, "call", {"name": "echo", "tool": "fail", "arguments": {"reason": "x"}})+ assert failed["status"] == "error" and failed["error"]["type"] == "tool_error"+ assert failed["result"]["isError"] is True++ invalid = _run(generated, "call", {"name": "echo", "tool": "add", "arguments": {"a": "x", "b": 1}})+ assert invalid["error"]["type"] == "invalid_arguments"++++def test_concurrent_first_calls_in_one_session_share_the_open(generated):+ async def both():+ first = generated.submit("call", {"name": "echo", "tool": "echo", "arguments": {"text": "a"}, "sessionId": "ses-race"})+ second = generated.submit("call", {"name": "echo", "tool": "echo", "arguments": {"text": "b"}, "sessionId": "ses-race"})+ return await asyncio.gather(first, second)++ bodies = [json.loads(body) for _status, body in asyncio.run(both())]+ assert all(item["status"] == "ok" for item in bodies), bodies+++def test_stdio_process_cap_reports_capacity(generated, monkeypatch):+ monkeypatch.setattr(mcp_runtime, "STDIO_PROCESS_CAP", 0)+ result = _run(generated, "call", {"name": "echo", "tool": "echo", "arguments": {"text": "x"}})+ assert result["error"]["type"] == "capacity"+++def test_oversized_result_is_omitted_but_reported_complete(generated, monkeypatch):+ monkeypatch.setattr(mcp_runtime, "RESULT_BYTE_CAP", 64)+ result = _run(generated, "call", {"name": "echo", "tool": "echo", "arguments": {"text": "x" * 100}})+ assert result["status"] == "ok" and result["resultOmitted"] == "too_large"+ assert result["result"] == {"isError": False}+++def test_malformed_avibe_definition_is_omitted_from_the_list(generated):+ path = repository.package_dir("broken") / "definition.json"+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("{not json")+ names = {item["name"] for item in repository.list_packages()}+ assert "echo" in names+ assert "broken" not in names+++def test_future_format_revision_is_not_listed(generated):+ published = repository.read_published("echo")+ manifest = repository.package_dir("echo") / "revisions" / published["revision"] / "manifest.json"+ manifest.write_text(json.dumps({"formatVersion": 99}))+ assert "echo" not in {item["name"] for item in repository.list_packages()}+ assert build_mcp_prompt_block() is None+++def test_cli_list_and_help_work_with_the_owner_down(generated, capsys):+ from vibe import mcp_cli++ generated.stop()+ assert mcp_cli.main(["--list"]) == 0+ assert "echo Echo tools" in capsys.readouterr().out+ assert mcp_cli.main(["echo", "--list"]) == 0+ assert "echo Echo text back" in capsys.readouterr().out+ assert mcp_cli.main(["echo", "echo", "--help"]) == 0+ assert "--text <string> (required)" in capsys.readouterr().out+ assert mcp_cli.main(["echo", "echo", "--text", "x"]) == 1+ assert "not running" in capsys.readouterr().err+ assert mcp_cli.main(["echo", "echo", "--bogus", "x"]) == 2+++def test_cli_treats_help_as_a_server_name(generated, capsys):+ from vibe import mcp_cli++ added = _run(generated, "add", {"servers": [{**_server(), "name": "help"}]})+ assert added["ok"] is True+ generated.stop()+ assert mcp_cli.main(["help", "--list"]) == 0+ assert "echo Echo text back" in capsys.readouterr().out+ assert mcp_cli.main(["-h"]) == 0+ assert "usage:" in capsys.readouterr().out+++def test_mcp_add_and_discover_are_listed_and_print_usage(capsys):+ from vibe import cli, mcp_cli++ parser = cli.build_parser()+ help_text = parser.format_help()+ assert "mcp-add" in help_text and "mcp-discover" in help_text+ assert mcp_cli.add_main(["--help"]) == 0+ assert "vibe mcp-add" in capsys.readouterr().out+ assert mcp_cli.discover_main(["--help"]) == 0+ assert "vibe mcp-discover" in capsys.readouterr().out+++def test_mcp_add_does_not_treat_json_stdin_after_separator_as_avibe_option(monkeypatch):+ from vibe import mcp_cli++ consumed = []++ class FakeStdin:+ def read(self):+ consumed.append(True)+ return "{}"++ captured = []++ def fake_owner(operation, payload):+ captured.append((operation, payload))+ return 0++ monkeypatch.setattr(sys, "stdin", FakeStdin())+ monkeypatch.setattr(mcp_cli, "_owner", fake_owner)+ monkeypatch.setattr(mcp_cli, "_admit", lambda _floor: None)+ assert mcp_cli.add_main(["local", "--", "server", "--json-stdin"]) == 0+ assert consumed == []+ servers = captured[0][1]["servers"]+ assert servers[0]["server"]["command"] == "server"+ assert servers[0]["server"]["args"] == ["--json-stdin"]+++def test_prompt_index_lists_enabled_servers_and_its_examples_parse(generated, capsys, monkeypatch):+ from vibe import mcp_cli++ text = build_mcp_prompt_block().text+ assert "- echo: Echo tools" in text+ examples = re.findall(r"`(vibe mcp[^`]*)`", text)+ assert examples+ sent = []+ monkeypatch.setattr(mcp_cli, "_call", lambda name, tool, arguments: sent.append((name, tool)) or 0)+ for example in examples:+ argv = shlex.split(example.replace("<server>", "echo").replace("<tool>", "echo")+ .replace("[arguments]", "--text x"))[2:]+ assert mcp_cli.main(argv) == 0, example+ assert sent == [("echo", "echo")]+++[email protected](("argv", "allowed"), [(["--list"], True), (["echo", "--refresh"], False)])+def test_editor_discovers_but_cannot_manage(generated, argv, allowed, capsys):+ from vibe import mcp_cli+ from vibe.authorization import AuthorizationContext, invocation_authority++ editor = AuthorizationContext(instance_role="editor", is_remote=True, instance_kind="organization")+ with invocation_authority(editor):+ code = mcp_cli.main(argv)+ assert (code == 0) is allowed+ if not allowed:+ assert "owner" in capsys.readouterr().err+++ ("tool", "arguments", "error_type"),+ [+ ("reject", {}, "tool_error"), # a JSON-RPC error the server returned+ ("crash", {}, "unknown_outcome"), # transport died after tools/call was sent+ ("nap", {"seconds": 5}, "unknown_outcome"), # call timeout+ ],+)+def test_call_failure_classification_and_reconnect(generated, monkeypatch, tool, arguments, error_type):+ monkeypatch.setattr(mcp_runtime, "CALL_TIMEOUT_SECONDS", 1)+ payload = {"name": "echo", "tool": tool, "arguments": arguments, "sessionId": "ses-1"}+ assert _run(generated, "call", payload)["error"]["type"] == error_type+ # An unknown-outcome connection is closed, so the session's next call reconnects.+ again = _run(generated, "call", {"name": "echo", "tool": "echo", "arguments": {"text": "x"}, "sessionId": "ses-1"})+ assert again["status"] == "ok"+++def test_streamable_http_generate_and_call(runtime):+ import socket+ import subprocess+ import time++ with socket.socket() as probe:+ probe.bind(("127.0.0.1", 0))+ port = probe.getsockname()[1]+ server = subprocess.Popen([sys.executable, FIXTURE, "http", str(port)],+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ try:+ deadline = time.monotonic() + 20+ while time.monotonic() < deadline:+ with socket.socket() as attempt:+ if attempt.connect_ex(("127.0.0.1", port)) == 0:+ break+ time.sleep(0.1)+ _run(runtime, "add", {"servers": [{"name": "web", "server": {+ "type": "http", "url": f"http://127.0.0.1:{port}/mcp", "headers": {"X-Test": "v"}}}]})+ assert _run(runtime, "refresh", {"name": "web"})["toolCount"] == 7+ for text in ("one", "two"):+ result = _run(runtime, "call", {"name": "web", "tool": "echo", "arguments": {"text": text},+ "sessionId": "ses-http"})+ assert result["result"]["content"] == [{"type": "text", "text": text}]+ assert _run(runtime, "call", {"name": "web", "tool": "reject", "arguments": {}})["error"]["type"] == "tool_error"+ session_text = _run(runtime, "call", {"name": "web", "tool": "session_text", "arguments": {}})+ assert session_text["error"]["type"] == "tool_error"+ finally:+ server.terminate()+ server.wait(timeout=10)+++def test_malformed_revision_file_disables_only_that_package(generated, capsys):+ from vibe import mcp_cli++ _run(generated, "add", {"servers": [{**_server(), "name": "other"}]})+ revision = repository.read_published("echo")["revision"]+ path = repository.package_dir("echo") / "revisions" / revision / "tools.json"+ path.write_text("{not json")+ names = {item["name"] for item in repository.list_packages()}+ assert "echo" not in names+ assert "other" in names+ assert mcp_cli.main(["--list"]) == 0+ assert mcp_cli.main(["echo", "--list"]) == 1+ call = _run(generated, "call", {"name": "echo", "tool": "echo", "arguments": {"text": "x"}})+ assert call["error"]["type"] == "invalid_package"+++def test_strict_legacy_server_that_exits_on_discover_still_generates(runtime):+ strict = str(Path(__file__).parent / "fixtures" / "mcp_strict_legacy_server.py")+ result = _run(runtime, "add", {"servers": [{"name": "strict", "server": {"command": sys.executable, "args": [strict]}}]})+ assert result["ok"], result+ assert result["toolCount"] == 7+ call = _run(runtime, "call", {"name": "strict", "tool": "echo", "arguments": {"text": "hi"}})+ assert call["status"] == "ok", calldiff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.pyindex 41ca98dd7..bfa0a2f9e 100644--- a/tests/test_member_management_parity.py+++ b/tests/test_member_management_parity.py@@ -93,6 +93,11 @@ def management_http(tmp_path, monkeypatch):# This inventory describes retained effects independently of the policy rules.# A newly registered Owner-only management route must be consciously classified._RETAINED_OWNER_ROUTES = {+ # MCP Hub management runs arbitrary local commands: Owner-only (plan §7).+ ("POST", "/api/mcp"),+ ("POST", "/api/mcp/discover"),+ ("POST", "/api/mcp/{name}/refresh"),+ ("DELETE", "/api/mcp/{name}"),("PUT", "/api/permissions/authorized-users"),("PUT", "/api/permissions/projects/{project_id}/access"),("PUT", "/api/permissions/resources/{resource_kind}/{resource_id}/access"),@@ -118,7 +123,7 @@ def test_complete_registered_api_management_inventory():for method in (getattr(route, "methods", None) or ())if method not in {"HEAD", "OPTIONS"}}- assert len(endpoints) == 297+ assert len(endpoints) == 303 # master 297 + 6 MCP Hub routes, classified in tests/test_mcp_hub_api.py# Editors who use Vault read avault's authorization state; the handler admits only# instance managers to raise the Keychain dialog on the host.for method in ("GET", "POST"):diff --git a/tests/test_prompt_render_export.py b/tests/test_prompt_render_export.pyindex 41ae3ce9d..79465dbf8 100644--- a/tests/test_prompt_render_export.py+++ b/tests/test_prompt_render_export.py@@ -12,6 +12,7 @@ import pytestfrom markdown_it import MarkdownItfrom config import paths+from core.mcp_hub import repository as mcp_repositoryfrom core import managed_skills, show_gitfrom core.managed_skills import ManagedSkillfrom core.prompt_registry import PROMPT_MODULES, prompt_text@@ -120,6 +121,7 @@ def _environment(monkeypatch, history="managed", skill_mode="pages"):for name in names] if skill_mode != "empty" else []monkeypatch.setattr(managed_skills, "resolve_skills", lambda *_args, **_kwargs: skills)+ monkeypatch.setattr(mcp_repository, "list_packages", lambda: [{"name": "docs", "description": "Docs"}])@pytest.mark.parametrize("backend,history,skill_mode", itertools.product(@@ -552,6 +554,8 @@ def test_approved_guidance_changes_preserve_all_other_injection_bytes(monkeypatc"skills-prompt","skills-manual-prompt","codex-skill-reuse",+ # New MCP Hub discovery index (docs/plans/mcp-hub-mvp.md §3).+ "mcp-capabilities-prompt",}for backend, history, skill_mode in itertools.product(("claude", "codex", "opencode"), ("off", "managed", "self-managed"), ("empty", "manual", "pages"),diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.pyindex c1c8a485e..6b5d52eec 100644--- a/tests/test_web_oauth_flow.py+++ b/tests/test_web_oauth_flow.py@@ -1915,6 +1915,7 @@ def test_test_web_auth_claude_oauth_env_removes_stale_anthropic_vars(assert options.cli_path == "/usr/bin/echo"assert options.permission_mode == "bypassPermissions"assert options.setting_sources == ["user", "project", "local"]+ assert (options.strict_mcp_config, options.mcp_servers) == (True, {})assert options.tools == []assert options.env["ANTHROPIC_API_KEY"] == ""assert options.env["ANTHROPIC_AUTH_TOKEN"] == ""diff --git a/ui/src/components/workbench/SkillsPage.tsx b/ui/src/components/workbench/SkillsPage.tsxindex f0d2ca67a..57da4d9ad 100644--- a/ui/src/components/workbench/SkillsPage.tsx+++ b/ui/src/components/workbench/SkillsPage.tsx@@ -15,6 +15,7 @@ import { SkillDetailPanel } from './skills/SkillDetailPanel';import { ProjectPicker } from './skills/ProjectPicker';import { AddSkillDialog } from './skills/AddSkillDialog';import { BrowseRegistryDialog } from './skills/BrowseRegistryDialog';+import { McpHubSection } from './skills/McpHubSection';import { errorMessage } from '@/lib/errorMessage';import { Badge } from '../ui/badge';import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';@@ -28,7 +29,9 @@ export const SkillsPage: React.FC = () => {const { capabilities } = useInstanceAuthorization();const canManage = capabilities.can_use_skills;+ const [pageTab, setPageTab] = useState<'skills' | 'mcp'>('skills');const [scope, setScope] = useState<SkillScope>('global');+ const showMcp = pageTab === 'mcp';const [projects, setProjects] = useState<WorkbenchProject[]>([]);const [projectId, setProjectId] = useState<string | null>(null);const [skills, setSkills] = useState<SkillBrief[]>([]);@@ -228,7 +231,7 @@ export const SkillsPage: React.FC = () => {<CapabilityTabs /><WorkbenchPageHeadericon={<WandSparkles className="size-5" />}- title={t('skills.title')}+ title={t('skills.pageTitle')}subtitle={t('skills.subtitle')}actions={<Button type="button" variant="outline" size="xs" onClick={() => refresh()} disabled={loading}>@@ -239,6 +242,16 @@ export const SkillsPage: React.FC = () => {/><div className="flex flex-wrap items-center gap-2.5">+ <SegmentedRadio<'skills' | 'mcp'>+ value={pageTab}+ onChange={setPageTab}+ ariaLabel={t('skills.pageTitle')}+ options={[+ { id: 'skills', label: t('skills.tabSkills') },+ { id: 'mcp', label: t('skills.tabMcp') },+ ]}+ />+ {showMcp ? null : (<SegmentedRadio<SkillScope>value={scope}onChange={setScope}@@ -248,6 +261,9 @@ export const SkillsPage: React.FC = () => {{ id: 'project', label: t('skills.scopeProject') },]}/>+ )}+ {showMcp ? null : (+ <>{scope === 'project' && projects.length > 0 ? (<ProjectPicker projects={projects} value={projectId} onChange={setProjectId} />) : null}@@ -279,6 +295,8 @@ export const SkillsPage: React.FC = () => {{t('skills.remoteReadOnly')}</Badge>) : null}+ </>+ )}</div>{scope === 'project' && activeProject?.folder_path ? (@@ -290,6 +308,8 @@ export const SkillsPage: React.FC = () => {</div>) : null}+ {showMcp ? <McpHubSection /> : (+ <>{error ? (<div className="rounded-md border border-destructive/40 bg-destructive/[0.06] px-3 py-2 text-[12px] text-destructive-ink">{error}</div>) : null}@@ -389,6 +409,8 @@ export const SkillsPage: React.FC = () => {) : null}</div>)}+ </>+ )}{projectCanManage && showAdd ? (<AddSkillDialogdiff --git a/ui/src/components/workbench/skills/McpHubSection.tsx b/ui/src/components/workbench/skills/McpHubSection.tsxnew file mode 100644index 000000000..7f198c63e--- /dev/null+++ b/ui/src/components/workbench/skills/McpHubSection.tsx@@ -0,0 +1,382 @@+import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { ChevronDown, ChevronRight, Globe, Loader2, Plus, RefreshCw, Search, Terminal, Trash2, X } from 'lucide-react';+import clsx from 'clsx';++import { useApi } from '../../../context/ApiContext';+import type { McpError, McpServerSummary } from '../../../context/ApiContext';+import { useToast } from '../../../context/ToastContext';+import { useInstanceAuthorization } from '../../../context/InstanceAuthorizationContext';+import { Badge } from '../../ui/badge';+import { Button } from '../../ui/button';+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogTitle } from '../../ui/dialog';+import { Textarea } from '../../ui/textarea';++const SOURCE_CHIP: Record<string, string> = {+ avibe: 'border-gold/40 bg-gold/[0.12] text-gold-ink',+ claude: 'border-mint/40 bg-mint-soft text-mint-ink',+ codex: 'border-violet/40 bg-violet/10 text-violet',+ opencode: 'border-cyan/40 bg-cyan/10 text-cyan-ink',+};++function McpToolCard({+ name,+ description,+ expanded,+ onToggle,+}: {+ name: string;+ description?: string;+ expanded: boolean;+ onToggle: () => void;+}) {+ const textRef = useRef<HTMLParagraphElement>(null);+ const [truncated, setTruncated] = useState(false);++ useLayoutEffect(() => {+ const node = textRef.current;+ if (!node || expanded) return;+ setTruncated(node.scrollHeight > node.clientHeight + 1);+ }, [description, expanded]);++ if (!description) {+ return (+ <div className="rounded-[10px] border border-border bg-surface-3 px-3 py-2">+ <div className="font-mono text-[12px] text-foreground">{name}</div>+ </div>+ );+ }++ const interactive = truncated || expanded;+ return (+ <button+ type="button"+ disabled={!interactive}+ aria-expanded={interactive ? expanded : undefined}+ onClick={() => interactive && onToggle()}+ className={clsx(+ 'w-full rounded-[10px] border border-border bg-surface-3 px-3 py-2 text-left',+ interactive ? 'hover:border-border-strong' : 'cursor-default',+ )}+ >+ <div className="flex items-start gap-2">+ <div className="min-w-0 flex-1">+ <div className="font-mono text-[12px] text-foreground">{name}</div>+ <p ref={textRef} className={clsx('text-[11px] text-muted', !expanded && 'line-clamp-2')}>+ {description}+ </p>+ </div>+ {interactive ? (+ <ChevronDown className={clsx('mt-0.5 size-3.5 shrink-0 text-muted transition-transform', expanded && 'rotate-180')} />+ ) : null}+ </div>+ </button>+ );+}++export const McpHubSection: React.FC = () => {+ const { t } = useTranslation();+ const api = useApi();+ const { showToast } = useToast();+ const { capabilities } = useInstanceAuthorization();+ const canManage = capabilities.is_instance_owner;+ const [servers, setServers] = useState<McpServerSummary[]>([]);+ const [search, setSearch] = useState('');+ const [selected, setSelected] = useState<string | null>(null);+ const [expandedFor, setExpandedFor] = useState<string | null>(null);+ const [expandedTools, setExpandedTools] = useState<Record<string, boolean>>({});+ const [busy, setBusy] = useState<string | null>(null);+ const [showAdd, setShowAdd] = useState(false);+ const [addText, setAddText] = useState('');+ const [addError, setAddError] = useState<string | null>(null);+ const [confirmDelete, setConfirmDelete] = useState<McpServerSummary | null>(null);+ if (expandedFor !== selected) {+ setExpandedFor(selected);+ setExpandedTools({});+ }++ const describe = useCallback(+ (error?: McpError) => (error ? t(`mcpHub.errors.${error.type}`, { defaultValue: error.message, message: error.message }) : t('mcpHub.failed')),+ [t],+ );++ const load = useCallback(async () => {+ try {+ const res = await api.listMcpServers();+ if (res.ok) setServers(res.servers ?? []);+ else showToast(describe(res.error), 'error');+ } catch {+ showToast(t('mcpHub.failed'), 'error');+ }+ }, [api, describe, showToast, t]);++ const [listed, setListed] = useState(false);+ if (!listed) {+ setListed(true);+ void load();+ }++ const filtered = useMemo(() => {+ const q = search.trim().toLowerCase();+ if (!q) return servers;+ return servers.filter((item) => item.name.toLowerCase().includes(q) || (item.description || '').toLowerCase().includes(q));+ }, [search, servers]);++ const current = servers.find((item) => item.name === selected) ?? null;++ const onDiscover = async () => {+ if (!canManage) return;+ setBusy('discover');+ try {+ const res = await api.discoverMcp();+ if (!res.ok) showToast(describe(res.error), 'error');+ await load();+ } finally {+ setBusy(null);+ }+ };++ const onRefreshOne = async (name: string) => {+ setBusy(`refresh:${name}`);+ try {+ const res = await api.refreshMcp(name);+ if (!res.ok) {+ showToast(describe(res.error), 'error');+ return;+ }+ showToast(t('mcpHub.refreshed', { name, count: res.toolCount ?? 0 }), 'success');+ await load();+ } finally {+ setBusy(null);+ }+ };++ const onAdd = async () => {+ setBusy('add');+ setAddError(null);+ try {+ const res = await api.addMcp(addText);+ const added = res.added ?? [];+ const unchanged = res.unchanged ?? [];+ const failed = res.failed ?? [];+ const succeeded = added.length + unchanged.length;+ const failedLines = failed.map((item) =>+ t('mcpHub.failedLine', {+ name: item.name,+ error: item.type ? t(`mcpHub.errors.${item.type}`, { defaultValue: item.error || '', message: item.error || '', name: item.name }) : (item.error || ''),+ }),+ );+ const inline = [+ t('mcpHub.succeededCount', { count: succeeded }),+ failed.length ? t('mcpHub.failedCount', { count: failed.length }) : null,+ ...failedLines,+ ].filter(Boolean).join('\n');+ const toast = inline;+ const hasBatch = Boolean(res.added || res.unchanged || res.failed);+ if (!succeeded) {+ setAddError(hasBatch ? inline : describe(res.error));+ return;+ }+ setShowAdd(false);+ setAddText('');+ if (failed.length) {+ showToast(toast, 'error', { label: t('common.close'), onClick: () => undefined });+ } else {+ showToast(t('mcpHub.succeededCount', { count: succeeded }), 'success');+ }+ await load();+ } finally {+ setBusy(null);+ }+ };++ const onDelete = async () => {+ if (!confirmDelete) return;+ const name = confirmDelete.name;+ setBusy(`remove:${name}`);+ try {+ const res = await api.removeMcp(name);+ if (!res.ok) {+ showToast(describe(res.error), 'error');+ return;+ }+ setConfirmDelete(null);+ if (selected === name) setSelected(null);+ await load();+ } finally {+ setBusy(null);+ }+ };++ const transportLabel = (server: McpServerSummary) =>+ server.transport === 'stdio' ? t('mcpHub.transportStdio') : t('mcpHub.transportHttp');++ return (+ <div className="flex flex-col gap-3">+ <div className="flex flex-wrap items-center gap-2.5">+ <div className="flex min-w-[220px] flex-1 items-center gap-2 rounded-md border border-border-strong bg-surface px-3 py-2">+ <Search className="size-3.5 shrink-0 text-muted" />+ <input+ value={search}+ onChange={(event) => setSearch(event.target.value)}+ placeholder={t('mcpHub.searchPlaceholder')}+ className="flex-1 bg-transparent text-[12px] text-foreground outline-none placeholder:text-muted"+ />+ </div>+ {canManage ? (+ <>+ <Button type="button" variant="outline" size="xs" disabled={busy !== null} onClick={() => void onDiscover()}>+ {busy === 'discover' ? <Loader2 className="size-3.5 animate-spin" /> : <RefreshCw className="size-3.5" />}+ {t('mcpHub.refreshAll')}+ </Button>+ <Button type="button" variant="brand" size="xs" onClick={() => { setShowAdd(true); setAddError(null); }}>+ <Plus className="size-3.5" />+ {t('mcpHub.add')}+ </Button>+ </>+ ) : null}+ </div>++ <div className={clsx('grid gap-5', current ? 'lg:grid-cols-[minmax(0,1fr)_400px]' : 'grid-cols-1')}>+ <div className="flex min-w-0 flex-col gap-2">+ {filtered.length === 0 ? (+ <div className="flex flex-col items-center gap-3 rounded-xl border border-dashed border-border bg-surface px-6 py-12 text-center">+ <p className="text-[13px] text-muted">{servers.length === 0 ? t('mcpHub.empty') : t('mcpHub.noSearchMatch')}</p>+ {canManage && servers.length === 0 ? (+ <Button type="button" variant="brand" size="sm" onClick={() => setShowAdd(true)}>+ <Plus className="size-3.5" />+ {t('mcpHub.add')}+ </Button>+ ) : null}+ </div>+ ) : (+ filtered.map((server) => (+ <button+ key={server.name}+ type="button"+ onClick={() => setSelected(server.name)}+ className={clsx(+ 'group flex w-full items-center gap-3 rounded-lg border px-[14px] py-3 text-left transition',+ selected === server.name+ ? 'border-mint/40 bg-mint-soft shadow-glow-sm-mint'+ : 'border-border bg-surface hover:border-border-strong hover:bg-surface-2',+ )}+ >+ <span className="flex size-9 shrink-0 items-center justify-center rounded-[9px] border border-border bg-surface-3 text-muted">+ {server.transport === 'stdio' ? <Terminal className="size-4" /> : <Globe className="size-4" />}+ </span>+ <span className="flex min-w-0 flex-1 flex-col gap-1">+ <span className="flex items-center gap-2">+ <span className="truncate font-mono text-[13px] font-semibold text-foreground">{server.name}</span>+ <Badge className={clsx('font-mono text-[9px] uppercase', SOURCE_CHIP[server.source ?? 'avibe'])}>+ {t(`mcpHub.source.${server.source ?? 'avibe'}`)}+ </Badge>+ </span>+ <span className="truncate font-mono text-[11px] text-muted" title={server.command || server.url || server.description || undefined}>+ {server.command || server.url || server.description}+ </span>+ <span className="font-mono text-[10px] text-muted">+ {t('mcpHub.toolMeta', { count: server.toolCount ?? 0, transport: transportLabel(server) })}+ </span>+ </span>+ <ChevronRight className="size-3.5 text-muted" />+ </button>+ ))+ )}+ </div>++ {current ? (+ <div className="flex flex-col gap-3.5 self-start rounded-2xl border border-border-strong bg-surface p-5">+ <div className="flex items-start gap-3">+ <span className="flex size-10 shrink-0 items-center justify-center rounded-[10px] border border-border bg-surface-3">+ {current.transport === 'stdio' ? <Terminal className="size-5" /> : <Globe className="size-5" />}+ </span>+ <div className="flex min-w-0 flex-1 flex-col">+ <div className="flex items-center gap-2">+ <span className="truncate font-mono text-[16px] font-bold text-foreground">{current.name}</span>+ <Badge className={clsx('font-mono text-[9px] uppercase', SOURCE_CHIP[current.source ?? 'avibe'])}>+ {t(`mcpHub.source.${current.source ?? 'avibe'}`)}+ </Badge>+ </div>+ <div className="truncate font-mono text-[11px] text-muted" title={current.command || current.url || undefined}>+ {current.command || current.url}+ </div>+ </div>+ <Button type="button" variant="ghost" size="icon" className="size-6" onClick={() => setSelected(null)} aria-label={t('common.close')}>+ <X className="size-3.5" />+ </Button>+ </div>+ <div className="flex flex-col gap-1.5">+ <span className="font-mono text-[10px] font-bold uppercase tracking-[0.12em] text-muted">{t('mcpHub.tools')}</span>+ {(current.tools ?? []).map((tool) => (+ <McpToolCard+ key={tool.name}+ name={tool.name}+ description={tool.description}+ expanded={Boolean(expandedTools[tool.name])}+ onToggle={() => setExpandedTools((prev) => ({ ...prev, [tool.name]: !prev[tool.name] }))}+ />+ ))}+ </div>+ <div className="rounded-[10px] border border-border bg-surface-3 px-3 py-2.5 font-mono text-[11px] text-muted">+ {t('mcpHub.callHint', { name: current.name })}+ </div>+ <div className="font-mono text-[10px] text-muted">+ {current.generatedAt && current.serverVersion+ ? t('mcpHub.generatedAtWithVersion', { time: current.generatedAt, version: current.serverVersion })+ : current.generatedAt+ ? t('mcpHub.generatedAt', { time: current.generatedAt })+ : current.serverVersion+ ? t('mcpHub.serverVersion', { version: current.serverVersion })+ : null}+ </div>+ {canManage ? (+ <div className="flex items-center gap-2 pt-1">+ <Button type="button" variant="outline" size="xs" disabled={busy !== null} onClick={() => void onRefreshOne(current.name)}>+ {busy === `refresh:${current.name}` ? <Loader2 className="size-3.5 animate-spin" /> : <RefreshCw className="size-3.5" />}+ {t('mcpHub.refresh')}+ </Button>+ <Button type="button" variant="ghost" size="xs" onClick={() => setConfirmDelete(current)}>+ <Trash2 className="size-3.5" />+ {t('mcpHub.remove')}+ </Button>+ </div>+ ) : null}+ </div>+ ) : null}+ </div>++ <Dialog open={showAdd} onOpenChange={(open) => (!open ? setShowAdd(false) : undefined)}>+ <DialogContent className="max-w-lg" closeLabel={t('common.close')}>+ <DialogTitle>{t('mcpHub.addTitle')}</DialogTitle>+ <DialogDescription>{t('mcpHub.addSubtitle')}</DialogDescription>+ <Textarea value={addText} onChange={(event) => setAddText(event.target.value)} className="min-h-40 font-mono text-[12px]" placeholder={t('mcpHub.pastePlaceholder')} />+ <p className="text-[11px] text-muted">{t('mcpHub.pasteHint')}</p>+ {addError ? <div className="whitespace-pre-wrap text-[12px] text-destructive-ink">{addError}</div> : null}+ <DialogFooter>+ <Button type="button" variant="outline" onClick={() => setShowAdd(false)}>{t('common.cancel')}</Button>+ <Button type="button" disabled={busy !== null || !addText.trim()} onClick={() => void onAdd()}>+ {busy === 'add' ? <Loader2 className="size-3.5 animate-spin" /> : null}+ {t('mcpHub.add')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ <Dialog open={confirmDelete !== null} onOpenChange={(open) => (!open ? setConfirmDelete(null) : undefined)}>+ <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')}+ </DialogDescription>+ <DialogFooter>+ <Button type="button" variant="outline" onClick={() => setConfirmDelete(null)}>{t('common.cancel')}</Button>+ <Button type="button" variant="destructive" disabled={busy !== null} onClick={() => void onDelete()}>+ {t('mcpHub.remove')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </div>+ );+};diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 915bdaa4b..626a8df67 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -557,6 +557,43 @@ export type TunnelConnectivityDiagnostics = {error?: string;};+// MCP Hub (/api/mcp*): static packages generated from MCP servers.+export interface McpServerSummary {+ name: string;+ description?: string;+ transport?: string;+ source?: 'avibe' | 'claude' | 'codex' | 'opencode';+ sourcePath?: string;+ command?: string;+ url?: string;+ revision?: string | null;+ generatedAt?: string;+ serverVersion?: string;+ toolCount?: number;+ tools?: { name: string; description?: string }[];+ diagnostics?: string[];+}+export interface McpError { type: string; message: string; field?: string; hint?: string }+/** Masked definition from GET /api/mcp/{name}: env/header values are always blank. */+export interface McpDefinition {+ name: string;+ description?: string;+ transport: {+ type: 'stdio' | 'streamable_http';+ command?: string;+ args?: string[];+ cwd?: string;+ url?: string;+ env?: Record<string, string>;+ headers?: Record<string, string>;+ has_env?: Record<string, boolean>;+ has_headers?: Record<string, boolean>;+ };+}+export interface McpResult { ok: boolean; error?: McpError }+export interface McpParsedServer { name: string; exists: boolean; transport?: { type: string } }+export interface McpTool { name: string; description?: string; inputSchema?: unknown; flags: { flag: string; kind: string; required: boolean }[] }+export type ApiContextType = {/** `cache: false` reads past the 30-second config cache, for a surface (the* desktop pet) that must see a setup another window just finished. */@@ -903,6 +940,19 @@ export type ApiContextType = {importVibeAgents: (payload: { from?: NativeCliBackend; name?: string; all?: boolean; file?: string; backend?: string }) => Promise<{ ok: boolean; imported?: any[]; skipped?: any[]; error?: string; code?: string; message?: string }>;// Agent Skills — thin shells over the askill CLI (see /api/skills*).listSkills: (params?: { scope?: SkillScope | 'all'; projectId?: string; backends?: string[] }) => Promise<SkillsListResult>;+ listMcpServers: () => Promise<McpResult & { servers?: McpServerSummary[] }>;+ addMcp: (text: string) => Promise<McpResult & {+ saved?: string[];+ name?: string;+ toolCount?: number;+ added?: { name: string; toolCount?: number }[];+ unchanged?: { name: string }[];+ failed?: { name: string; error?: string; type?: string }[];+ }>;+ discoverMcp: () => Promise<McpResult & { results?: { name: string; status: string; error?: string; toolCount?: number }[] }>;+ refreshMcp: (name: string) => Promise<McpResult & { name?: string; toolCount?: number }>;+ removeMcp: (name: string) => Promise<McpResult>;+ getMcpServer: (name: string) => Promise<McpResult & { server?: McpServerSummary; tools?: McpTool[] }>;previewSkillSource: (source: string, params?: { projectId?: string }) => Promise<SkillsPreviewResult>;addSkill: (payload: { source: string; scope: SkillScope; projectId?: string; backends?: string[]; all?: boolean; skill?: string; copy?: boolean }) => Promise<SkillsMutationResult>;removeSkill: (name: string, params?: { scope?: SkillScope; projectId?: string; backends?: string[] }) => Promise<SkillsMutationResult>;@@ -4281,6 +4331,12 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenconst qs = search.toString();return getCachedJson(qs ? `/api/skills?${qs}` : '/api/skills', 5_000);},+ listMcpServers: () => getJson('/api/mcp', { handleError: false }),+ addMcp: (text) => postJson('/api/mcp', { text }, { handleError: false }),+ discoverMcp: () => postJson('/api/mcp/discover', {}, { handleError: false }),+ refreshMcp: (name) => postJson(`/api/mcp/${encodeURIComponent(name)}/refresh`, {}, { handleError: false }),+ removeMcp: (name) => deleteJson(`/api/mcp/${encodeURIComponent(name)}`, undefined, { handleError: false }),+ getMcpServer: (name) => getJson(`/api/mcp/${encodeURIComponent(name)}`, { handleError: false }),previewSkillSource: (source, params) =>postJson('/api/skills/preview', { source, project_id: params?.projectId }),addSkill: (payload) =>diff --git a/ui/src/context/ToastProvider.tsx b/ui/src/context/ToastProvider.tsxindex cdd14bfbc..e52ca5c5c 100644--- a/ui/src/context/ToastProvider.tsx+++ b/ui/src/context/ToastProvider.tsx@@ -150,7 +150,7 @@ export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ childre) : (<XCircle size={18} />)}- <span className="text-sm font-medium">{toast.message}</span>+ <span className="max-w-sm whitespace-pre-wrap text-sm font-medium">{toast.message}</span>{toast.repeats > 0 && (<span className="ml-1 rounded-full bg-current/15 px-1.5 py-0.5 text-[10px] font-semibold tabular-nums opacity-80">×{toast.repeats + 1}diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 43f6a7b31..1612056f0 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -2445,7 +2445,11 @@"generate": "Generate"},"tool": {- "web_fetch": {"name": "Web fetch", "inline": "web fetch", "description": "Read one page for the model; content past the cap is explicitly truncated."},+ "web_fetch": {+ "name": "Web fetch",+ "inline": "web fetch",+ "description": "Read one page for the model; content past the cap is explicitly truncated."+ },"web_search": {"name": "Web search","inline": "web search",@@ -2566,20 +2570,51 @@"clearUnconfirmed": "Couldn't confirm whether the {{toolInline}} refusal was cleared. It's being re-read from the server; check it before trying again."},"webFetch": {- "dialogTitle": "Add search / fetch service", "dialogDescription": "Search and fetch share service keys, but their switches and execution orders are independent. Built-in free executors need no setup.", "noModels": "Provides search and web fetch, not models.",- "endpoints": {"tavily": "https://api.tavily.com/extract", "exa": "https://api.exa.ai/contents", "deepseek": "https://api.deepseek.com/v1/tools/fetch", "exa-mcp": "https://mcp.exa.ai/mcp", "jina-reader": "https://r.jina.ai/"},- "order": "Fetch order", "caption": "When the model calls web_fetch, try in this order; move on after failure. Default: local → configured services → Exa (free) → Jina Reader (free); reorder as needed.",- "use": "Use for web fetch", "unused": "Not used for web fetch", "kind": "Fetch service", "local": "Local", "add": "Add fetch service",- "searchBadge": "Search", "fetchBadge": "Fetch", "viewOrder": "View fetch order", "price": "${{usd}} / 1k pages",+ "dialogTitle": "Add search / fetch service",+ "dialogDescription": "Search and fetch share service keys, but their switches and execution orders are independent. Built-in free executors need no setup.",+ "noModels": "Provides search and web fetch, not models.",+ "endpoints": {+ "tavily": "https://api.tavily.com/extract",+ "exa": "https://api.exa.ai/contents",+ "deepseek": "https://api.deepseek.com/v1/tools/fetch",+ "exa-mcp": "https://mcp.exa.ai/mcp",+ "jina-reader": "https://r.jina.ai/"+ },+ "order": "Fetch order",+ "caption": "When the model calls web_fetch, try in this order; move on after failure. Default: local → configured services → Exa (free) → Jina Reader (free); reorder as needed.",+ "use": "Use for web fetch",+ "unused": "Not used for web fetch",+ "kind": "Fetch service",+ "local": "Local",+ "add": "Add fetch service",+ "searchBadge": "Search",+ "fetchBadge": "Fetch",+ "viewOrder": "View fetch order",+ "price": "${{usd}} / 1k pages","egress": "Local reads leave this Avibe runtime directly: the site sees its egress IP and browser-like requests. Services receive the submitted URL when they read it.","custody": "Configured service keys stay with the gateway; Local, Exa (free) and Jina Reader (free) need no key.",- "vendorName": {"local": "Local", "exa-mcp": "Exa (free)", "jina-reader": "Jina Reader (free)"},- "row": {"local": "Chrome 150 fingerprint · HTML / PDF / text · no JS", "tavily": "Uses the Tavily key · basic Extract", "exa": "Uses the Exa key · Contents", "deepseek": "Uses the official DeepSeek key · Fetch", "exa-mcp": "Shares IP limits with web search", "jina-reader": "20 per minute · Jina renders JS · default last fallback"},+ "vendorName": {+ "local": "Local",+ "exa-mcp": "Exa (free)",+ "jina-reader": "Jina Reader (free)"+ },+ "row": {+ "local": "Chrome 150 fingerprint · HTML / PDF / text · no JS",+ "tavily": "Uses the Tavily key · basic Extract",+ "exa": "Uses the Exa key · Contents",+ "deepseek": "Uses the official DeepSeek key · Fetch",+ "exa-mcp": "Shares IP limits with web search",+ "jina-reader": "20 per minute · Jina renders JS · default last fallback"+ },"localDetail": "Defaults to the Chrome 150 browser profile and HTTP/2. If native transport cannot load, plain HTTP/2 is used and the call records the reason. No JavaScript execution, user cookies or login credentials. Supports HTML, PDF, plain text, Markdown and JSON.","limits": "180 seconds per chain, 30 seconds per attempt; local text up to 16 MiB, PDF 32 MiB. The complete model-facing result is capped at 12,000 estimated tokens (48,000 UTF-8 bytes); any cut is explicit.","exaDetail": "Search and fetch share Exa's IP limits and cooldown; their switches are independent. No key required.","jinaDetail": "20 requests per minute without a key (2026-10-24). Jina processes JavaScript server-side; availability also depends on shared egress limits. Last by default, not fixed after reordering.",- "terms": "Jina / Elastic terms", "endpoint": "Endpoint", "tavilyPrice": "1 credit per 5 URLs (amortized)", "localPrice": "Read directly from your machine", "builtInPrice": "Built in · no key or setup"+ "terms": "Jina / Elastic terms",+ "endpoint": "Endpoint",+ "tavilyPrice": "1 credit per 5 URLs (amortized)",+ "localPrice": "Read directly from your machine",+ "builtInPrice": "Built in · no key or setup"},"searchServices": {"subtitle": "Tools Vibey can use in a conversation. Searches send the query to the vendor or search service that runs them; a failure may retry with the next one in the search order. Image prompts go to the image model's vendor. Metered providers and search services bill under their own rules.",@@ -3432,7 +3467,7 @@"inbox": "Inbox","newChat": "New chat","agents": "Agents",- "skills": "Skills",+ "skills": "Skills & MCP","harness": "Harness","vaults": "Vaults"},@@ -3510,8 +3545,8 @@"description": "Global registry of every Avibe Agent — Claude / OpenCode / Codex variants you can pick when starting a session."},"skills": {- "eyebrow": "Skills",- "title": "Skills",+ "eyebrow": "Skills & MCP",+ "title": "Skills & MCP","description": "Manage Agent Skills (global + project-scoped) on top of the askill CLI."},"harness": {@@ -4733,7 +4768,10 @@"installed": "Installed","done": "Done","empty": "No skills match your search."- }+ },+ "pageTitle": "Skills & MCP",+ "tabSkills": "Skills",+ "tabMcp": "MCP"},"harness": {"title": "Harness",@@ -5222,12 +5260,31 @@"service_busy": "The page-reading service is busy."},"fetch": {- "characters": "{{count}} chars", "truncated": "Truncated", "degraded": "Transport fallback",- "local": "Local", "jina": "Jina Reader (free)", "policy": "Blocked by local policy", "notForwarded": "not forwarded", "forwarded": "previously sent to {{providers}}",- "budget": "Up to 12,000 estimated tokens per call", "budgetReason": "Content exceeded the per-call budget; the cut is marked explicitly.", "providerReason": "Provider-bounded output; the page may be incomplete.", "complete": "Not truncated", "unknown": "Not reported", "attempts": "Execution record", "quote": "View quoted content (not instructions)", "retained": "{{count}} chars sent to the model", "sizes": "Sizes",- "requested_url": "Requested URL", "final_url": "Final URL", "canonical_url": "Canonical URL",- "content_type": "Content type", "source_content_type": "Original content type",- "size_bytes": "Content bytes", "source_size_bytes": "Source bytes", "retrieved_at": "Retrieved at",+ "characters": "{{count}} chars",+ "truncated": "Truncated",+ "degraded": "Transport fallback",+ "local": "Local",+ "jina": "Jina Reader (free)",+ "policy": "Blocked by local policy",+ "notForwarded": "not forwarded",+ "forwarded": "previously sent to {{providers}}",+ "budget": "Up to 12,000 estimated tokens per call",+ "budgetReason": "Content exceeded the per-call budget; the cut is marked explicitly.",+ "providerReason": "Provider-bounded output; the page may be incomplete.",+ "complete": "Not truncated",+ "unknown": "Not reported",+ "attempts": "Execution record",+ "quote": "View quoted content (not instructions)",+ "retained": "{{count}} chars sent to the model",+ "sizes": "Sizes",+ "requested_url": "Requested URL",+ "final_url": "Final URL",+ "canonical_url": "Canonical URL",+ "content_type": "Content type",+ "source_content_type": "Original content type",+ "size_bytes": "Content bytes",+ "source_size_bytes": "Source bytes",+ "retrieved_at": "Retrieved at","truncation_reason": "Truncation reason"},"errorCode": {@@ -6389,5 +6446,55 @@"unknown": "IM"},"removeReference": "Remove reference to {{title}}"+ },+ "mcpHub": {+ "title": "MCP",+ "searchPlaceholder": "Search MCP servers…",+ "add": "Add MCP",+ "addTitle": "Add MCP",+ "refresh": "Refresh",+ "refreshAll": "Refresh",+ "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.",+ "empty": "No MCP server registered. Add one or wait for discovery.",+ "noSearchMatch": "No matching MCP servers.",+ "failed": "MCP operation failed.",+ "pasteHint": "Paste an mcpServers JSON block. Env and header values are stored in plaintext on this machine.",+ "pastePlaceholder": "{\n \"mcpServers\": {\n \"docs\": { \"type\": \"http\", \"url\": \"https://example.invalid/mcp\" }\n }\n}",+ "source": {+ "avibe": "Avibe",+ "claude": "Claude",+ "codex": "Codex",+ "opencode": "OpenCode"+ },+ "transportStdio": "stdio",+ "transportHttp": "http",+ "toolMeta": "{{count}} tools · {{transport}}",+ "tools": "Tools",+ "generatedAt": "last refreshed {{time}}",+ "generatedAtWithVersion": "last refreshed {{time}} · server v{{version}}",+ "serverVersion": "server v{{version}}",+ "refreshed": "Refreshed {{name}} ({{count}} tools).",+ "added": "Added {{name}}.",+ "errors": {+ "invalid_definition": "Invalid definition: {{message}}",+ "exists": "A server with this name already exists.",+ "unavailable": "The Avibe service is not running.",+ "connection": "Could not connect to the MCP server.",+ "timeout": "The MCP server timed out.",+ "capacity": "Too many MCP server processes are running; try again later.",+ "not_found": "Unknown MCP server.",+ "unsupported_transport_sse": "SSE is not supported; use a Streamable HTTP URL."+ },+ "addedCount": "Added {{count}} MCP servers.",+ "addedPartial": "Added {{count}}; failed: {{failed}}",+ "addSubtitle": "Paste MCP config JSON. Avibe registers it so every Agent can call vibe mcp.",+ "unchangedCount": "{{count}} already present.",+ "succeededCount": "{{count}} succeeded",+ "failedCount": "{{count}} failed:",+ "failedLine": "{{name}} — {{error}}",+ "callHint": "vibe mcp {{name}} <tool>"}}diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex e6963b586..8def6b80e 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -2445,7 +2445,11 @@"generate": "生成"},"tool": {- "web_fetch": {"name": "网页读取", "inline": "网页读取", "description": "读取一个网页的正文交给模型;超出上限会截断并注明。"},+ "web_fetch": {+ "name": "网页读取",+ "inline": "网页读取",+ "description": "读取一个网页的正文交给模型;超出上限会截断并注明。"+ },"web_search": {"name": "网页搜索","inline": "网页搜索",@@ -2566,20 +2570,51 @@"clearUnconfirmed": "无法确认{{toolInline}}拒绝记录是否已清除,正在从服务器重新读取,请确认后再重试。"},"webFetch": {- "dialogTitle": "添加搜索 / 读取服务", "dialogDescription": "搜索与读取共用服务密钥,但开关和执行顺序彼此独立。内置的免费执行者无需添加。", "noModels": "提供搜索与网页读取,不提供模型。",- "endpoints": {"tavily": "https://api.tavily.com/extract", "exa": "https://api.exa.ai/contents", "deepseek": "https://api.deepseek.com/v1/tools/fetch", "exa-mcp": "https://mcp.exa.ai/mcp", "jina-reader": "https://r.jina.ai/"},- "order": "读取顺序", "caption": "模型调用 web_fetch 时按这个顺序读取;失败自动换下一个。默认:本机 → 已配置服务 → Exa(免费) → Jina Reader(免费);可调整顺序。",- "use": "用于网页读取", "unused": "未用于网页读取", "kind": "读取服务", "local": "本机", "add": "添加读取服务",- "searchBadge": "搜索", "fetchBadge": "读取", "viewOrder": "查看读取顺序", "price": "${{usd}} / 千页",+ "dialogTitle": "添加搜索 / 读取服务",+ "dialogDescription": "搜索与读取共用服务密钥,但开关和执行顺序彼此独立。内置的免费执行者无需添加。",+ "noModels": "提供搜索与网页读取,不提供模型。",+ "endpoints": {+ "tavily": "https://api.tavily.com/extract",+ "exa": "https://api.exa.ai/contents",+ "deepseek": "https://api.deepseek.com/v1/tools/fetch",+ "exa-mcp": "https://mcp.exa.ai/mcp",+ "jina-reader": "https://r.jina.ai/"+ },+ "order": "读取顺序",+ "caption": "模型调用 web_fetch 时按这个顺序读取;失败自动换下一个。默认:本机 → 已配置服务 → Exa(免费) → Jina Reader(免费);可调整顺序。",+ "use": "用于网页读取",+ "unused": "未用于网页读取",+ "kind": "读取服务",+ "local": "本机",+ "add": "添加读取服务",+ "searchBadge": "搜索",+ "fetchBadge": "读取",+ "viewOrder": "查看读取顺序",+ "price": "${{usd}} / 千页","egress": "本机读取直接从此 Avibe 运行时访问网页,网站会看到它的出口 IP 和浏览器式请求;交给服务读取时,服务会收到网址。","custody": "已配置服务的密钥由网关保管;本机、Exa(免费)和 Jina Reader(免费)都不需要密钥。",- "vendorName": {"local": "本机", "exa-mcp": "Exa(免费)", "jina-reader": "Jina Reader(免费)"},- "row": {"local": "Chrome 150 指纹 · HTML / PDF / 文本 · 不执行 JS", "tavily": "用 Tavily 的密钥 · Extract 基础", "exa": "用 Exa 的密钥 · Contents", "deepseek": "用官方 DeepSeek 的密钥 · Fetch", "exa-mcp": "与网页搜索共用按 IP 的限流", "jina-reader": "每分钟 20 次 · 由 Jina 渲染 JS · 默认最后兜底"},+ "vendorName": {+ "local": "本机",+ "exa-mcp": "Exa(免费)",+ "jina-reader": "Jina Reader(免费)"+ },+ "row": {+ "local": "Chrome 150 指纹 · HTML / PDF / 文本 · 不执行 JS",+ "tavily": "用 Tavily 的密钥 · Extract 基础",+ "exa": "用 Exa 的密钥 · Contents",+ "deepseek": "用官方 DeepSeek 的密钥 · Fetch",+ "exa-mcp": "与网页搜索共用按 IP 的限流",+ "jina-reader": "每分钟 20 次 · 由 Jina 渲染 JS · 默认最后兜底"+ },"localDetail": "默认使用 Chrome 150 浏览器画像、HTTP/2。原生传输无法加载时改用普通 HTTP/2,并在调用记录中标记原因。不执行 JavaScript,不读取用户 Cookie 或登录凭据。支持 HTML、PDF、纯文本、Markdown 和 JSON。","limits": "整条调用最长 180 秒,每次尝试 30 秒;本机文本上限 16 MiB,PDF 32 MiB;给模型的完整结果最多 12,000 估算 token(48,000 UTF-8 字节),超出会明确截断。","exaDetail": "搜索与读取共用 Exa 的 IP 限流和冷却;两项开关独立。无须密钥。","jinaDetail": "无密钥每分钟 20 次(2026-10-24)。Jina 在其服务端处理 JavaScript;实际可用性与共享出口限流有关。默认最后兜底,调整顺序后按新位置执行。",- "terms": "Jina / Elastic 条款", "endpoint": "接口", "tavilyPrice": "5 个网址 1 credit(摊算)", "localPrice": "从你的机器直接读取", "builtInPrice": "内置 · 无需密钥或设置"+ "terms": "Jina / Elastic 条款",+ "endpoint": "接口",+ "tavilyPrice": "5 个网址 1 credit(摊算)",+ "localPrice": "从你的机器直接读取",+ "builtInPrice": "内置 · 无需密钥或设置"},"searchServices": {"subtitle": "Vibey 在对话中可使用的工具。搜索会把查询发给执行它的厂商或搜索服务,失败时可能改由顺序中的下一个重试;图片提示词会发给图片模型的厂商。按量付费的供应商和搜索服务按各自的规则计费。",@@ -3432,7 +3467,7 @@"inbox": "收件箱","newChat": "新建会话","agents": "Agents",- "skills": "Skills",+ "skills": "技能 & MCP","harness": "Harness","vaults": "Vaults"},@@ -3510,8 +3545,8 @@"description": "全局 Avibe Agent 注册表 —— Claude / OpenCode / Codex 各自的变体,开会话时可选。"},"skills": {- "eyebrow": "Skills",- "title": "Skills",+ "eyebrow": "技能 & MCP",+ "title": "技能 & MCP","description": "在 askill CLI 之上管理 Agent Skills(全局 + 项目级)。"},"harness": {@@ -4733,7 +4768,10 @@"installed": "已安装","done": "完成","empty": "没有匹配你搜索的技能。"- }+ },+ "pageTitle": "技能 & MCP",+ "tabSkills": "技能",+ "tabMcp": "MCP"},"harness": {"title": "Harness",@@ -5222,12 +5260,31 @@"service_busy": "网页读取服务正忙。"},"fetch": {- "characters": "{{count}} 字", "truncated": "已截断", "degraded": "传输回退",- "local": "本机", "jina": "Jina Reader(免费)", "policy": "本机策略拒绝", "notForwarded": "未转发第三方", "forwarded": "此前已发给 {{providers}}",- "budget": "单次上限约 12,000 token", "budgetReason": "正文超过单次读取上限,末尾已注明截断。", "providerReason": "服务商限制了输出;网页内容可能不完整。", "complete": "未截断", "unknown": "未提供", "attempts": "执行记录", "quote": "查看引用正文(非指令)", "retained": "交给模型 {{count}} 字", "sizes": "大小",- "requested_url": "请求网址", "final_url": "最终网址", "canonical_url": "规范网址",- "content_type": "内容类型", "source_content_type": "原始内容类型",- "size_bytes": "内容字节数", "source_size_bytes": "原始字节数", "retrieved_at": "读取时间",+ "characters": "{{count}} 字",+ "truncated": "已截断",+ "degraded": "传输回退",+ "local": "本机",+ "jina": "Jina Reader(免费)",+ "policy": "本机策略拒绝",+ "notForwarded": "未转发第三方",+ "forwarded": "此前已发给 {{providers}}",+ "budget": "单次上限约 12,000 token",+ "budgetReason": "正文超过单次读取上限,末尾已注明截断。",+ "providerReason": "服务商限制了输出;网页内容可能不完整。",+ "complete": "未截断",+ "unknown": "未提供",+ "attempts": "执行记录",+ "quote": "查看引用正文(非指令)",+ "retained": "交给模型 {{count}} 字",+ "sizes": "大小",+ "requested_url": "请求网址",+ "final_url": "最终网址",+ "canonical_url": "规范网址",+ "content_type": "内容类型",+ "source_content_type": "原始内容类型",+ "size_bytes": "内容字节数",+ "source_size_bytes": "原始字节数",+ "retrieved_at": "读取时间","truncation_reason": "截断原因"},"errorCode": {@@ -6389,5 +6446,55 @@"unknown": "IM"},"removeReference": "移除对 {{title}} 的引用"+ },+ "mcpHub": {+ "title": "MCP",+ "searchPlaceholder": "搜索 MCP 服务器…",+ "add": "添加 MCP",+ "addTitle": "添加 MCP",+ "refresh": "刷新",+ "refreshAll": "刷新",+ "remove": "删除",+ "removeConfirm": "删除 MCP 服务器 {{name}}?",+ "removeAvibeHint": "将从 Avibe 中移除该服务器。",+ "removeNativeHint": "仅在 Avibe 中隐藏;不会改动原生配置文件。",+ "empty": "还没有已注册的 MCP 服务器。添加一个,或等待自动发现。",+ "noSearchMatch": "没有匹配的 MCP 服务器。",+ "failed": "MCP 操作失败。",+ "pasteHint": "粘贴 mcpServers JSON。环境变量和请求头的值会以明文保存在本机。",+ "pastePlaceholder": "{\n \"mcpServers\": {\n \"docs\": { \"type\": \"http\", \"url\": \"https://example.invalid/mcp\" }\n }\n}",+ "source": {+ "avibe": "Avibe",+ "claude": "Claude",+ "codex": "Codex",+ "opencode": "OpenCode"+ },+ "transportStdio": "stdio",+ "transportHttp": "http",+ "toolMeta": "{{count}} 个工具 · {{transport}}",+ "tools": "工具",+ "generatedAt": "最近刷新 {{time}}",+ "generatedAtWithVersion": "最近刷新 {{time}} · 服务端 v{{version}}",+ "serverVersion": "服务端 v{{version}}",+ "refreshed": "已刷新 {{name}}({{count}} 个工具)。",+ "added": "已添加 {{name}}。",+ "errors": {+ "invalid_definition": "配置无效:{{message}}",+ "exists": "同名服务器已存在。",+ "unavailable": "Avibe 服务未运行。",+ "connection": "无法连接 MCP 服务器。",+ "timeout": "MCP 服务器超时。",+ "capacity": "运行中的 MCP 服务器进程过多,请稍后重试。",+ "not_found": "未知 MCP 服务器。",+ "unsupported_transport_sse": "不支持 SSE;请使用 Streamable HTTP 地址。"+ },+ "addedCount": "已添加 {{count}} 个。",+ "addedPartial": "已添加 {{count}} 个;失败:{{failed}}",+ "addSubtitle": "粘贴 MCP 配置 JSON,添加到 Avibe 后自动注册,所有 Agent 可用 vibe mcp 调用",+ "unchangedCount": "{{count}} 个已存在。",+ "succeededCount": "成功 {{count}} 个",+ "failedCount": "失败 {{count}} 个:",+ "failedLine": "{{name}} — {{error}}",+ "callHint": "vibe mcp {{name}} <tool>"}}diff --git a/uv.lock b/uv.lockindex 3a7687f11..23d251d54 100644--- a/uv.lock+++ b/uv.lock@@ -1,5 +1,5 @@version = 1-revision = 5+revision = 3requires-python = ">=3.10"resolution-markers = ["python_full_version >= '3.14' and sys_platform == 'win32'",@@ -389,6 +389,7 @@ dependencies = [{ name = "lark-oapi" },{ name = "markdown-it-py" },{ name = "markdown-to-mrkdwn" },+ { name = "mcp" },{ name = "packaging" },{ name = "pillow", version = "12.3.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },{ name = "pillow", version = "13.0.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },@@ -442,6 +443,7 @@ requires-dist = [{ name = "lark-oapi", specifier = ">=1.4.0" },{ name = "markdown-it-py", specifier = ">=4.2.0" },{ name = "markdown-to-mrkdwn", specifier = ">=0.2.0" },+ { name = "mcp", specifier = ">=2.3.0,<3" },{ name = "packaging", specifier = ">=23.0" },{ name = "pillow", specifier = ">=11.0" },{ name = "prometheus-client", specifier = ">=0.20.0" },@@ -753,11 +755,11 @@ resolution-markers = ["python_full_version < '3.11' and sys_platform == 'win32'",]dependencies = [- { name = "anyio" },- { name = "jsonschema" },- { name = "mcp" },- { name = "sniffio" },- { name = "typing-extensions", marker = "python_full_version < '3.11'" },+ { name = "anyio", marker = "sys_platform == 'win32'" },+ { name = "jsonschema", marker = "sys_platform == 'win32'" },+ { name = "mcp", marker = "sys_platform == 'win32'" },+ { name = "sniffio", marker = "sys_platform == 'win32'" },+ { name = "typing-extensions", marker = "python_full_version < '3.11' and sys_platform == 'win32'" },]sdist = { url = "https://files.pythonhosted.org/packages/db/b2/81eb389ace55434f0119b99b62c10a7ac206def6c92ee0768eb389b0c900/claude_agent_sdk-0.2.159.tar.gz", hash = "sha256:e1905e2637b27971bb561bb6ad317aeb3d50619be5261bfa7ff2e9c2be0f0fd1", size = 354571, upload-time = "2026-09-23T20:26:37.386Z" }wheels = [@@ -780,11 +782,11 @@ resolution-markers = ["(python_full_version < '3.11' and platform_machine != 'x86_64' and sys_platform == 'darwin') or (python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'win32')",]dependencies = [- { name = "anyio" },- { name = "jsonschema" },- { name = "mcp" },- { name = "sniffio" },- { name = "typing-extensions", marker = "python_full_version < '3.11'" },+ { name = "anyio", marker = "sys_platform != 'win32'" },+ { name = "jsonschema", marker = "sys_platform != 'win32'" },+ { name = "mcp", marker = "sys_platform != 'win32'" },+ { name = "sniffio", marker = "sys_platform != 'win32'" },+ { name = "typing-extensions", marker = "python_full_version < '3.11' and sys_platform != 'win32'" },]sdist = { url = "https://files.pythonhosted.org/packages/78/a3/d31886d0723593228797c96eb54d07a19e561931a2771ed40b4a105bedc9/claude_agent_sdk-0.2.162.tar.gz", hash = "sha256:e4cf92f04f934d3b87d42be9ecbeb75c1a3d487a8dc8a299f7fed1ad9d0b476f", size = 365167, upload-time = "2026-09-29T20:06:54.593Z" }wheels = [@@ -840,8 +842,8 @@ resolution-markers = ["python_full_version < '3.11' and platform_machine == 'x86_64' and sys_platform == 'darwin'",]dependencies = [- { name = "cffi", marker = "platform_python_implementation != 'PyPy'" },- { name = "typing-extensions", marker = "python_full_version < '3.11'" },+ { name = "cffi", marker = "platform_machine == 'x86_64' and platform_python_implementation != 'PyPy' and sys_platform == 'darwin'" },+ { name = "typing-extensions", marker = "python_full_version < '3.11' and platform_machine == 'x86_64' and sys_platform == 'darwin'" },]sdist = { url = "https://files.pythonhosted.org/packages/12/45/870e7f4bef50e5f53b9f51d4428aee5290eedf58ba443f16b1ebb7ab8e66/cryptography-48.0.1.tar.gz", hash = "sha256:266f4ee051abb2f725b74ef8072b521ce1feacf685a3364fa6a6b45548db791a", size = 832989, upload-time = "2026-06-09T22:32:31.8Z" }wheels = [@@ -866,8 +868,8 @@ resolution-markers = ["(python_full_version < '3.11' and platform_machine != 'x86_64' and sys_platform == 'darwin') or (python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'win32')",]dependencies = [- { name = "cffi", marker = "platform_python_implementation != 'PyPy'" },- { name = "typing-extensions", marker = "python_full_version < '3.11'" },+ { name = "cffi", marker = "(platform_machine != 'x86_64' and platform_python_implementation != 'PyPy') or (platform_python_implementation != 'PyPy' and sys_platform != 'darwin')" },+ { name = "typing-extensions", marker = "(python_full_version < '3.11' and platform_machine != 'x86_64') or (python_full_version < '3.11' and sys_platform != 'darwin')" },]sdist = { url = "https://files.pythonhosted.org/packages/9d/af/182eb91b0df3fe75c4d9f26fe70684569566745f6ba7e5c9c73a862c5252/cryptography-50.0.2.tar.gz", hash = "sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5", size = 880623, upload-time = "2026-09-30T15:30:04.884Z" }wheels = [@@ -936,8 +938,8 @@ name = "curl-cffi"version = "0.16.3"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "certifi" },- { name = "cffi" },+ { name = "certifi", marker = "python_full_version != '3.12.*' or sys_platform != 'emscripten'" },+ { name = "cffi", marker = "python_full_version != '3.12.*' or sys_platform != 'emscripten'" },]sdist = { url = "https://files.pythonhosted.org/packages/82/e1/730125c43e3e331d98e17af3cb310ba526b3f1101b7635ca23d976ebfcf5/curl_cffi-0.16.3.tar.gz", hash = "sha256:d15d0c2a35f2d75bec430c28946c2a833f421c85773bdb0795182cc5c515665b", size = 239020, upload-time = "2026-09-02T11:58:23.266Z" }wheels = [@@ -945,6 +947,8 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/4c/86/e21b8ed384db26401a4438f20f01c7bcd9c3a6f8ceede458344e2d62775c/curl_cffi-0.16.3-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:f3b63da797912bc82911e34dfe449725514e4281527fb516931fc457087cfb44", size = 2784023, upload-time = "2026-09-02T11:57:40.986Z" },{ url = "https://files.pythonhosted.org/packages/97/2d/25b106e64178829be1ce171b6cd45ba354ab7a2a5169001866b38d4c440f/curl_cffi-0.16.3-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d5a4103f2baa1fcf619ec3101b419827d367044ba106b206228137cc71a5a9c5", size = 12834219, upload-time = "2026-09-02T11:57:42.711Z" },{ url = "https://files.pythonhosted.org/packages/72/01/2bbf141baa0fc3921d31a90de5465b7a94188845a8fe84dee86bf7bd90f1/curl_cffi-0.16.3-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a875a661e2f9a949be29454880bbb9553307a487c4c08819738298cf5c1622e2", size = 13484311, upload-time = "2026-09-02T11:57:47.58Z" },+ { url = "https://files.pythonhosted.org/packages/bb/d4/745ca299a2a223ee18574ec7cff75de620a92ce69b3cb09490db8fba614b/curl_cffi-0.16.3-cp310-abi3-manylinux_2_28_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0851e710608122a2716bdee35788bbd7e9d4a0fd42899b2bca9181277095af8e", size = 12840616, upload-time = "2026-09-02T11:57:50.016Z" },+ { url = "https://files.pythonhosted.org/packages/5e/bf/98d72d7a081cc155a71ab66bde6a18640d4ac5d4f6766f729a92cb4257c0/curl_cffi-0.16.3-cp310-abi3-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:1d7e553442cefec100dfd1fca4ae7035ab6c094457244bf60a38670b8ac8185d", size = 12612602, upload-time = "2026-09-02T11:57:52.584Z" },{ url = "https://files.pythonhosted.org/packages/36/cf/2fdaff71fd6f39c5994495af8378e6e26bca8e447d94d2f75a76337908c8/curl_cffi-0.16.3-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:60621b3f561346046dd62be33abfb50c8b88a8007699d6b11d39ad4755312c4a", size = 12588697, upload-time = "2026-09-02T11:57:55.138Z" },{ url = "https://files.pythonhosted.org/packages/74/55/68c399019bc24ea6ac783c98139a2555f88589631f3d127fe6b9073f019b/curl_cffi-0.16.3-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:20a7b1b473371cfaf2118958034977e457c6fa279fbd11543c9e0ab58be9eedd", size = 13253555, upload-time = "2026-09-02T11:57:57.524Z" },{ url = "https://files.pythonhosted.org/packages/9b/72/1732a24ef4a2aeba994b80ec163debe8deda403c07e4abbc0443bca078b8/curl_cffi-0.16.3-cp310-abi3-win_amd64.whl", hash = "sha256:fe87b66e324ed7318166698e02169f3208dbda32b872a27d2bc61a9c19b335eb", size = 1978602, upload-time = "2026-09-02T11:58:00.033Z" },@@ -992,7 +996,7 @@ name = "exceptiongroup"version = "1.3.1"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "typing-extensions" },+ { name = "typing-extensions", marker = "python_full_version < '3.11'" },]sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" }wheels = [@@ -1147,14 +1151,18 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/b0/03/84359833f7e1d49a883e92777637c592306030e30cee5e2b1e6476f95c88/greenlet-3.5.0-cp310-cp310-macosx_11_0_universal2.whl", hash = "sha256:29ea813b2e1f45fa9649a17853b2b5465c4072fbcb072e5af6cd3a288216574a", size = 283502, upload-time = "2026-04-27T12:20:55.213Z" },{ url = "https://files.pythonhosted.org/packages/25/ce/6f9f008266273aa14a2e011945797ac5802b97b8b40efe7afe1ee6c1afc9/greenlet-3.5.0-cp310-cp310-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:804a70b328e706b785c6ef16187051c394a63dd1a906d89be24b6ad77759f13f", size = 600508, upload-time = "2026-04-27T12:52:37.876Z" },{ url = "https://files.pythonhosted.org/packages/e0/6d/b0f3272c2368ea2c1aa19a5ad70db0be8f8dff6e6d3d1eb82efa00cbcf19/greenlet-3.5.0-cp310-cp310-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:884f649de075b84739713d41dd4dfd41e2b910bfb769c4a3ea02ec1da52cd9bb", size = 613283, upload-time = "2026-04-27T12:59:37.957Z" },+ { url = "https://files.pythonhosted.org/packages/e5/ae/1db979ff6ae7958d80b288f63d5f6c30df96682700ea9fc340ce994d94a1/greenlet-3.5.0-cp310-cp310-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4d0eadc7e4d9ffb2af4247b606cae307be8e448911e5a0d0b16d72fc3d224cfd", size = 619894, upload-time = "2026-04-27T13:02:35.13Z" },{ url = "https://files.pythonhosted.org/packages/ed/ac/0b509b6fb93551ce5a01612ee1acda7f7dda4bbb66c99aeb2ab403d205dc/greenlet-3.5.0-cp310-cp310-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4b28037cb07768933c54d81bfe47a85f9f402f57d7d69743b991a713b63954eb", size = 613418, upload-time = "2026-04-27T12:25:23.852Z" },+ { url = "https://files.pythonhosted.org/packages/ce/94/b0590e3d1978f02419f30502341c40d72f77eb0a2198119fe27df47714ee/greenlet-3.5.0-cp310-cp310-manylinux_2_39_riscv64.whl", hash = "sha256:f8c30c2225f40dd76c50790f0eb3b5c7c18431efb299e2782083e1981feed243", size = 415681, upload-time = "2026-04-27T13:05:11.494Z" },{ url = "https://files.pythonhosted.org/packages/03/03/2b2b680ec87aaa97998fb5b8d76658d4d3560386864f17efab33ba7c2e24/greenlet-3.5.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:cda05425526240807408156b6960a17a79a0c760b813573b67027823be760977", size = 1572229, upload-time = "2026-04-27T12:53:23.509Z" },{ url = "https://files.pythonhosted.org/packages/61/e4/42b259e7a19aff1a270a4bd82caf6353109ed6860c9454e18f37162b83ae/greenlet-3.5.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:9c615f869163e14bb1ced20322d8038fb680b08236521ac3f30cd4c1288785a0", size = 1639886, upload-time = "2026-04-27T12:25:22.325Z" },{ url = "https://files.pythonhosted.org/packages/6f/b4/733ca47b883b67c57f90d3ecb21055c9ec753597d10754ac201644061f9d/greenlet-3.5.0-cp310-cp310-win_amd64.whl", hash = "sha256:ba8f0bdc2fae6ce915dfd0c16d2d00bca7e4247c1eae4416e06430e522137858", size = 237795, upload-time = "2026-04-27T12:21:40.118Z" },{ url = "https://files.pythonhosted.org/packages/8b/0f/a91f143f356523ff682309732b175765a9bc2836fd7c081c2c67fedc1ad4/greenlet-3.5.0-cp311-cp311-macosx_11_0_universal2.whl", hash = "sha256:8f1cc966c126639cd152fdaa52624d2655f492faa79e013fea161de3e6dda082", size = 284726, upload-time = "2026-04-27T12:20:51.402Z" },{ url = "https://files.pythonhosted.org/packages/95/82/800646c7ffc5dbabd75ddd2f6b519bb898c0c9c969e5d0473bfe5d20bcce/greenlet-3.5.0-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:362624e6a8e5bca3b8233e45eef33903a100e9539a2b995c364d595dbc4018b3", size = 604264, upload-time = "2026-04-27T12:52:39.494Z" },{ url = "https://files.pythonhosted.org/packages/ca/ac/354867c0bba812fc33b15bc55aedafedd0aee3c7dd91dfca22444157dc0c/greenlet-3.5.0-cp311-cp311-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5ecd83806b0f4c2f53b1018e0005cd82269ea01d42befc0368730028d850ed1c", size = 616099, upload-time = "2026-04-27T12:59:39.623Z" },+ { url = "https://files.pythonhosted.org/packages/c9/ab/192090c4a5b30df148c22bf4b8895457d739a7c7c5a7b9c41e5dd7f537f2/greenlet-3.5.0-cp311-cp311-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:fa94cb2288681e3a11645958f1871d48ee9211bd2f66628fdace505927d6e564", size = 623976, upload-time = "2026-04-27T13:02:37.363Z" },{ url = "https://files.pythonhosted.org/packages/ff/b0/815bece7399e01cadb69014219eebd0042339875c59a59b0820a46ece356/greenlet-3.5.0-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0ff251e9a0279522e62f6176412869395a64ddf2b5c5f782ff609a8216a4e662", size = 615198, upload-time = "2026-04-27T12:25:25.928Z" },+ { url = "https://files.pythonhosted.org/packages/24/11/05eb2b9b188c6df7d68a89c99134d644a7af616a40b9808e8e6ced315d5d/greenlet-3.5.0-cp311-cp311-manylinux_2_39_riscv64.whl", hash = "sha256:64d6ac45f7271f48e45f67c95b54ef73534c52ec041fcda8edf520c6d811f4bc", size = 418379, upload-time = "2026-04-27T13:05:12.755Z" },{ url = "https://files.pythonhosted.org/packages/10/80/3b2c0a895d6698f6ddb31b07942ebfa982f3e30888bc5546a5b5990de8b2/greenlet-3.5.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6d874e79afd41a96e11ff4c5d0bc90a80973e476fda1c2c64985667397df432b", size = 1574927, upload-time = "2026-04-27T12:53:25.81Z" },{ url = "https://files.pythonhosted.org/packages/44/0e/f354af514a4c61454dbc68e44d47544a5a4d6317e30b77ddfa3a09f4c5f3/greenlet-3.5.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:0ed006e4b86c59de7467eb2601cd1b77b5a7d657d1ee55e30fe30d76451edba4", size = 1642683, upload-time = "2026-04-27T12:25:23.9Z" },{ url = "https://files.pythonhosted.org/packages/fa/6a/87f38255201e993a1915265ebb80cd7c2c78b04a45744995abbf6b259fd8/greenlet-3.5.0-cp311-cp311-win_amd64.whl", hash = "sha256:703cb211b820dbffbbc55a16bfc6e4583a6e6e990f33a119d2cc8b83211119c8", size = 238115, upload-time = "2026-04-27T12:21:48.845Z" },@@ -1162,7 +1170,9 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/ef/32/f2ce6d4cac3e55bc6173f92dbe627e782e1850f89d986c3606feb63aafa7/greenlet-3.5.0-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:db2910d3c809444e0a20147361f343fe2798e106af8d9d8506f5305302655a9f", size = 286228, upload-time = "2026-04-27T12:20:34.421Z" },{ url = "https://files.pythonhosted.org/packages/b7/aa/caed9e5adf742315fc7be2a84196373aab4816e540e38ba0d76cb7584d68/greenlet-3.5.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3ec9ea74e7268ace7f9aab1b1a4e730193fc661b39a993cd91c606c32d4a3628", size = 601775, upload-time = "2026-04-27T12:52:41.045Z" },{ url = "https://files.pythonhosted.org/packages/c7/af/90ae08497400a941595d12774447f752d3dfe0fbb012e35b76bc5c0ff37e/greenlet-3.5.0-cp312-cp312-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:54d243512da35485fc7a6bf3c178fdda6327a9d6506fcdd62b1abd1e41b2927b", size = 614436, upload-time = "2026-04-27T12:59:41.595Z" },+ { url = "https://files.pythonhosted.org/packages/3f/e9/4eeadf8cb3403ac274245ba75f07844abc7fa5f6787583fc9156ba741e0f/greenlet-3.5.0-cp312-cp312-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:41353ec2ecedf7aa8f682753a41919f8718031a6edac46b8d3dc7ed9e1ceb136", size = 620610, upload-time = "2026-04-27T13:02:39.194Z" },{ url = "https://files.pythonhosted.org/packages/2b/e0/2e13df68f367e2f9960616927d60857dd7e56aaadd59a47c644216b2f920/greenlet-3.5.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9d280a7f5c331622c69f97eb167f33577ff2d1df282c41cd15907fc0a3ca198c", size = 611388, upload-time = "2026-04-27T12:25:28.008Z" },+ { url = "https://files.pythonhosted.org/packages/ee/ef/f913b3c0eb7d26d86a2401c5e1546c9d46b657efee724b06f6f4ac5d8824/greenlet-3.5.0-cp312-cp312-manylinux_2_39_riscv64.whl", hash = "sha256:58c1c374fe2b3d852f9b6b11a7dff4c85404e51b9a596fd9e89cf904eb09866d", size = 422775, upload-time = "2026-04-27T13:05:14.261Z" },{ url = "https://files.pythonhosted.org/packages/82/f7/393c64055132ac0d488ef6be549253b7e6274194863967ddc0bc8f5b87b8/greenlet-3.5.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:1eb67d5adefb5bd2e182d42678a328979a209e4e82eb93575708185d31d1f588", size = 1570768, upload-time = "2026-04-27T12:53:28.099Z" },{ url = "https://files.pythonhosted.org/packages/b8/4b/eaf7735253522cf56d1b74d672a58f54fc114702ceaf05def59aae72f6e1/greenlet-3.5.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2628d6c86f6cb0cb45e0c3c54058bbec559f57eaae699447748cb3928150577e", size = 1635983, upload-time = "2026-04-27T12:25:26.903Z" },{ url = "https://files.pythonhosted.org/packages/4c/fe/4fb3a0805bd5165da5ebf858da7cc01cce8061674106d2cf5bdab32cbfde/greenlet-3.5.0-cp312-cp312-win_amd64.whl", hash = "sha256:d4d9f0624c775f2dfc56ba54d515a8c771044346852a918b405914f6b19d7fd8", size = 238840, upload-time = "2026-04-27T12:23:54.806Z" },@@ -1170,7 +1180,9 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/0c/58/fc576f99037ce19c5aa16628e4c3226b6d1419f72a62c79f5f40576e6eb3/greenlet-3.5.0-cp313-cp313-macosx_11_0_universal2.whl", hash = "sha256:5a5ed18de6a0f6cc7087f1563f6bd93fc7df1c19165ca01e9bde5a5dc281d106", size = 285066, upload-time = "2026-04-27T12:23:05.033Z" },{ url = "https://files.pythonhosted.org/packages/4a/ba/b28ddbe6bfad6a8ac196ef0e8cff37bc65b79735995b9e410923fffeeb70/greenlet-3.5.0-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3a717fbc46d8a354fa675f7c1e813485b6ba3885f9bef0cd56e5ba27d758ff5b", size = 604414, upload-time = "2026-04-27T12:52:42.358Z" },{ url = "https://files.pythonhosted.org/packages/09/06/4b69f8f0b67603a8be2790e55107a190b376f2627fe0eaf5695d85ffb3cd/greenlet-3.5.0-cp313-cp313-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ddc090c5c1792b10246a78e8c2163ebbe04cf877f9d785c230a7b27b39ad038e", size = 617349, upload-time = "2026-04-27T12:59:43.32Z" },+ { url = "https://files.pythonhosted.org/packages/6a/15/a643b4ecd09969e30b8a150d5919960caae0abe4f5af75ab040b1ab85e78/greenlet-3.5.0-cp313-cp313-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4964101b8585c144cbda5532b1aa644255126c08a265dae90c16e7a0e63aaa9d", size = 623234, upload-time = "2026-04-27T13:02:40.611Z" },{ url = "https://files.pythonhosted.org/packages/8a/17/a3918541fd0ddefe024a69de6d16aa7b46d36ac19562adaa63c7fa180eff/greenlet-3.5.0-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2094acd54b272cb6eae8c03dd87b3fa1820a4cef18d6889c378d503500a1dc13", size = 613927, upload-time = "2026-04-27T12:25:30.28Z" },+ { url = "https://files.pythonhosted.org/packages/77/18/3b13d5ef1275b0ffaf933b05efa21408ac4ca95823c7411d79682e4fdcff/greenlet-3.5.0-cp313-cp313-manylinux_2_39_riscv64.whl", hash = "sha256:7022615368890680e67b9965d33f5773aade330d5343bbe25560135aaa849eae", size = 425243, upload-time = "2026-04-27T13:05:15.689Z" },{ url = "https://files.pythonhosted.org/packages/ee/e1/bd0af6213c7dd33175d8a462d4c1fe1175124ebed4855bc1475a5b5242c2/greenlet-3.5.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:5e05ba267789ea87b5a155cf0e810b1ab88bf18e9e8740813945ceb8ee4350ba", size = 1570893, upload-time = "2026-04-27T12:53:29.483Z" },{ url = "https://files.pythonhosted.org/packages/9b/2a/0789702f864f5382cb476b93d7a9c823c10472658102ccd65f415747d2e2/greenlet-3.5.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:0ecec963079cd58cbd14723582384f11f166fd58883c15dcbfb342e0bc9b5846", size = 1636060, upload-time = "2026-04-27T12:25:28.845Z" },{ url = "https://files.pythonhosted.org/packages/b2/8f/22bf9df92bbff0eb07842b60f7e63bf7675a9742df628437a9f02d09137f/greenlet-3.5.0-cp313-cp313-win_amd64.whl", hash = "sha256:728d9667d8f2f586644b748dbd9bb67e50d6a9381767d1357714ea6825bb3bf5", size = 238740, upload-time = "2026-04-27T12:24:01.341Z" },@@ -1178,7 +1190,9 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/94/5e/a70f31e3e8d961c4ce589c15b28e4225d63704e431a23932a3808cbcc867/greenlet-3.5.0-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:f35807464c4c58c55f0d31dfa83c541a5615d825c2fe3d2b95360cf7c4e3c0a8", size = 285564, upload-time = "2026-04-27T12:23:08.555Z" },{ url = "https://files.pythonhosted.org/packages/af/a6/046c0a28e21833e4086918218cfb3d8bed51c075a1b700f20b9d7861c0f4/greenlet-3.5.0-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:55fa7ea52771be44af0de27d8b80c02cd18c2c3cddde6c847ecebdf72418b6a1", size = 651166, upload-time = "2026-04-27T12:52:43.644Z" },{ url = "https://files.pythonhosted.org/packages/47/f8/4af27f71c5ff32a7fbc516adb46370d9c4ae2bc7bd3dc7d066ac542b4b15/greenlet-3.5.0-cp314-cp314-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a97e4821aa710603f94de0da25f25096454d78ffdace5dc77f3a006bc01abba3", size = 663792, upload-time = "2026-04-27T12:59:44.93Z" },+ { url = "https://files.pythonhosted.org/packages/fb/89/2dadb89793c37ee8b4c237857188293e9060dc085f19845c292e00f8e091/greenlet-3.5.0-cp314-cp314-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:bf2d8a80bec89ab46221ae45c5373d5ba0bd36c19aa8508e85c6cd7e5106cd37", size = 668086, upload-time = "2026-04-27T13:02:42.314Z" },{ url = "https://files.pythonhosted.org/packages/a3/59/1bd6d7428d6ed9106efbb8c52310c60fd04f6672490f452aeaa3829aa436/greenlet-3.5.0-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8f52a464e4ed91780bdfbbdd2b97197f3accaa629b98c200f4dffada759f3ae7", size = 660933, upload-time = "2026-04-27T12:25:33.276Z" },+ { url = "https://files.pythonhosted.org/packages/82/35/75722be7e26a2af4cbd2dc35b0ed382dacf9394b7e75551f76ed1abe87f2/greenlet-3.5.0-cp314-cp314-manylinux_2_39_riscv64.whl", hash = "sha256:1bae92a1dd94c5f9d9493c3a212dd874c202442047cf96446412c862feca83a2", size = 470799, upload-time = "2026-04-27T13:05:17.094Z" },{ url = "https://files.pythonhosted.org/packages/83/e4/b903e5a5fae1e8a28cdd32a0cfbfd560b668c25b692f67768822ddc5f40f/greenlet-3.5.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:762612baf1161ccb8437c0161c668a688223cba28e1bf038f4eb47b13e39ccdf", size = 1618401, upload-time = "2026-04-27T12:53:31.062Z" },{ url = "https://files.pythonhosted.org/packages/0e/e3/5ec408a329acb854fb607a122e1ee5fb3ff649f9a97952948a90803c0d8e/greenlet-3.5.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:57a43c6079a89713522bc4bcb9f75070ecf5d3dbad7792bfe42239362cbf2a16", size = 1682038, upload-time = "2026-04-27T12:25:31.838Z" },{ url = "https://files.pythonhosted.org/packages/91/20/6b165108058767ee643c55c5c4904d591a830ee2b3c7dbd359828fbc829f/greenlet-3.5.0-cp314-cp314-win_amd64.whl", hash = "sha256:3bc59be3945ae9750b9e7d45067d01ae3fe90ea5f9ade99239dabdd6e28a5033", size = 239835, upload-time = "2026-04-27T12:24:54.136Z" },@@ -1186,7 +1200,9 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/78/a8/4522939255bb5409af4e87132f915446bf3622c2c292d14d3c38d128ae82/greenlet-3.5.0-cp314-cp314t-macosx_11_0_universal2.whl", hash = "sha256:a10a732421ab4fec934783ce3e54763470d0181db6e3468f9103a275c3ed1853", size = 293614, upload-time = "2026-04-27T12:24:12.874Z" },{ url = "https://files.pythonhosted.org/packages/15/5e/8744c52e2c027b5a8772a01561934c8835f869733e101f62075c60430340/greenlet-3.5.0-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7fc391b1566f2907d17aaebe78f8855dc45675159a775fcf9e61f8ee0078e87f", size = 650723, upload-time = "2026-04-27T12:52:45.412Z" },{ url = "https://files.pythonhosted.org/packages/00/ef/7b4c39c03cf46ceca512c5d3f914afd85aa30b2cc9a93015b0dd73e4be6c/greenlet-3.5.0-cp314-cp314t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:680bd0e7ad5e8daa8a4aa89f68fd6adc834b8a8036dc256533f7e08f4a4b01f7", size = 656529, upload-time = "2026-04-27T12:59:46.295Z" },+ { url = "https://files.pythonhosted.org/packages/5f/5c/0602239503b124b70e39355cbdb39361ecfe65b87a5f2f63752c32f5286f/greenlet-3.5.0-cp314-cp314t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1aa4ce8debcd4ea7fb2e150f3036588c41493d1d52c43538924ae1819003f4ce", size = 657015, upload-time = "2026-04-27T13:02:43.973Z" },{ url = "https://files.pythonhosted.org/packages/0b/b5/c7768f352f5c010f92064d0063f987e7dc0cd290a6d92a34109015ce4aa1/greenlet-3.5.0-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ddb36c7d6c9c0a65f18c7258634e0c416c6ab59caac8c987b96f80c2ebda0112", size = 654364, upload-time = "2026-04-27T12:25:35.64Z" },+ { url = "https://files.pythonhosted.org/packages/38/51/8699f865f125dc952384cb432b0f7138aa4d8f2969a7d12d0df5b94d054d/greenlet-3.5.0-cp314-cp314t-manylinux_2_39_riscv64.whl", hash = "sha256:728a73687e39ae9ca34e4694cbf2f049d3fbc7174639468d0f67200a97d8f9e2", size = 488275, upload-time = "2026-04-27T13:05:18.28Z" },{ url = "https://files.pythonhosted.org/packages/ef/d0/079ebe12e4b1fc758857ce5be1a5e73f06870f2101e52611d1e71925ce54/greenlet-3.5.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e5ddf316ced87539144621453c3aef229575825fe60c604e62bedc4003f372b2", size = 1614204, upload-time = "2026-04-27T12:53:32.618Z" },{ url = "https://files.pythonhosted.org/packages/6d/89/6c2fb63df3596552d20e58fb4d96669243388cf680cff222758812c7bfaa/greenlet-3.5.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:4a448128607be0de65342dc9b31be7f948ef4cc0bc8832069350abefd310a8f2", size = 1675480, upload-time = "2026-04-27T12:25:34.168Z" },{ url = "https://files.pythonhosted.org/packages/15/32/77ee8a6c1564fc345a491a4e85b3bf360e4cf26eac98c4532d2fdb96e01f/greenlet-3.5.0-cp314-cp314t-win_amd64.whl", hash = "sha256:d60097128cb0a1cab9ea541186ea13cd7b847b8449a7787c2e2350da0cb82d86", size = 245324, upload-time = "2026-04-27T12:24:40.295Z" },@@ -1272,8 +1288,8 @@ resolution-markers = ["(python_full_version < '3.11' and platform_machine != 'x86_64' and sys_platform == 'darwin') or (python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'win32')",]dependencies = [- { name = "h11" },- { name = "truststore" },+ { name = "h11", marker = "python_full_version < '3.11'" },+ { name = "truststore", marker = "python_full_version < '3.11'" },]sdist = { url = "https://files.pythonhosted.org/packages/30/ff/b53af1b49bb2cb5fa97c92215614b173ca5c1a99ded80e2d52f15a94fa6d/httpcore2-2.14.0.tar.gz", hash = "sha256:4f57a1a8249fe6af589d935cfd456f1d13bbdcb0f0fc72af9142368fc94811d7", size = 69096, upload-time = "2026-10-18T16:29:21.898Z" }wheels = [@@ -1296,8 +1312,8 @@ resolution-markers = ["(python_full_version >= '3.11' and python_full_version < '3.13' and platform_machine != 'x86_64' and sys_platform == 'darwin') or (python_full_version >= '3.11' and python_full_version < '3.13' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'win32') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')",]dependencies = [- { name = "h11" },- { name = "truststore" },+ { name = "h11", marker = "(python_full_version >= '3.11' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten') or (python_full_version >= '3.13' and sys_platform == 'emscripten')" },+ { name = "truststore", marker = "(python_full_version >= '3.11' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten') or (python_full_version >= '3.13' and sys_platform == 'emscripten')" },]sdist = { url = "https://files.pythonhosted.org/packages/c0/61/afa9d6b7452f9eca73f73d45324eb0bb52f098fd5e6049bf6b8263be9b4e/httpcore2-2.16.0.tar.gz", hash = "sha256:c72cd0413563b17e1cd8354677dff887466f8ec2551679759e93126534428643", size = 69886, upload-time = "2026-10-21T07:09:45.31Z" }wheels = [@@ -1380,11 +1396,11 @@ resolution-markers = ["(python_full_version < '3.11' and platform_machine != 'x86_64' and sys_platform == 'darwin') or (python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'win32')",]dependencies = [- { name = "anyio", marker = "sys_platform != 'emscripten'" },- { name = "httpcore2", version = "2.14.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'emscripten'" },- { name = "idna" },- { name = "truststore", marker = "sys_platform != 'emscripten'" },- { name = "typing-extensions" },+ { name = "anyio", marker = "python_full_version < '3.11' and sys_platform != 'emscripten'" },+ { name = "httpcore2", version = "2.14.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11' and sys_platform != 'emscripten'" },+ { name = "idna", marker = "python_full_version < '3.11'" },+ { name = "truststore", marker = "python_full_version < '3.11' and sys_platform != 'emscripten'" },+ { name = "typing-extensions", marker = "python_full_version < '3.11'" },]sdist = { url = "https://files.pythonhosted.org/packages/e8/67/58353f1848b4ba568e1ec22ea1e0d8e039f0bca5fde7e2d1f07739fd83e7/httpx2-2.14.0.tar.gz", hash = "sha256:47ad61a3c40282cd8d0dc96311531f00f5bfc71a066c6fe3b36d8f63fb9e4f6e", size = 102036, upload-time = "2026-10-18T16:29:22.627Z" }wheels = [@@ -1408,12 +1424,12 @@ resolution-markers = ["(python_full_version >= '3.11' and python_full_version < '3.13' and platform_machine != 'x86_64' and sys_platform == 'darwin') or (python_full_version >= '3.11' and python_full_version < '3.13' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'win32') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')",]dependencies = [- { name = "anyio", marker = "sys_platform != 'emscripten'" },- { name = "httpcore2", version = "2.16.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'emscripten'" },+ { name = "anyio", marker = "python_full_version >= '3.11' and sys_platform != 'emscripten'" },+ { name = "httpcore2", version = "2.16.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11' and sys_platform != 'emscripten'" },{ name = "httpx2-jsfetch", marker = "python_full_version >= '3.12' and sys_platform == 'emscripten'" },- { name = "idna" },- { name = "truststore", marker = "sys_platform != 'emscripten'" },- { name = "typing-extensions", marker = "python_full_version < '3.13'" },+ { name = "idna", marker = "python_full_version >= '3.11'" },+ { name = "truststore", marker = "python_full_version >= '3.11' and sys_platform != 'emscripten'" },+ { name = "typing-extensions", marker = "python_full_version >= '3.11' and python_full_version < '3.13'" },]sdist = { url = "https://files.pythonhosted.org/packages/43/73/5ca2cedf5e4e50423d1c258877865a6b62793633b561c58499f8aeb33b7e/httpx2-2.16.0.tar.gz", hash = "sha256:0d54c98128e8f2ff7fbbde0fca8c359e5f032edeaaaac443cdb7f31f685bcd7f", size = 103116, upload-time = "2026-10-21T07:09:46.348Z" }wheels = [@@ -3294,8 +3310,8 @@ resolution-markers = ["(python_full_version < '3.11' and platform_machine != 'x86_64' and sys_platform == 'darwin') or (python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'win32')",]dependencies = [- { name = "greenlet", marker = "platform_machine == 'AMD64' or platform_machine == 'WIN32' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'ppc64le' or platform_machine == 'win32' or platform_machine == 'x86_64'" },- { name = "typing-extensions" },+ { name = "greenlet", marker = "(python_full_version < '3.11' and platform_machine == 'AMD64') or (python_full_version < '3.11' and platform_machine == 'WIN32') or (python_full_version < '3.11' and platform_machine == 'aarch64') or (python_full_version < '3.11' and platform_machine == 'amd64') or (python_full_version < '3.11' and platform_machine == 'ppc64le') or (python_full_version < '3.11' and platform_machine == 'win32') or (python_full_version < '3.11' and platform_machine == 'x86_64')" },+ { name = "typing-extensions", marker = "python_full_version < '3.11'" },]sdist = { url = "https://files.pythonhosted.org/packages/a5/bd/08864ddfffbb8914ee13b0c887d84b4b13bc8dd8da3077c0dace5a87699c/sqlalchemy-2.0.55.tar.gz", hash = "sha256:ae40c563bc10a8d56f1fd1f39f069aeb5eb85ca26913b2314dd8d190139258fa", size = 9997689, upload-time = "2026-10-16T20:45:32.724Z" }wheels = [@@ -3361,7 +3377,7 @@ resolution-markers = ["(python_full_version >= '3.11' and python_full_version < '3.13' and platform_machine != 'x86_64' and sys_platform == 'darwin') or (python_full_version >= '3.11' and python_full_version < '3.13' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'win32') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')",]dependencies = [- { name = "typing-extensions" },+ { name = "typing-extensions", marker = "python_full_version >= '3.11'" },]sdist = { url = "https://files.pythonhosted.org/packages/ba/29/8de56a7f78fb0d71fe4f91ee43401a24ba8777e6d4f72683f268c9e0c72e/sqlalchemy-2.1.0.tar.gz", hash = "sha256:37600e4641c435a7e4549f4e6df79d9dfc096bb9712a10dba8925921bc87bc3c", size = 10502427, upload-time = "2026-09-24T20:12:49.737Z" }wheels = [@@ -3462,8 +3478,8 @@ resolution-markers = ["(python_full_version < '3.11' and platform_machine != 'x86_64' and sys_platform == 'darwin') or (python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'win32')",]dependencies = [- { name = "anyio" },- { name = "typing-extensions" },+ { name = "anyio", marker = "python_full_version < '3.11'" },+ { name = "typing-extensions", marker = "python_full_version < '3.11'" },]sdist = { url = "https://files.pythonhosted.org/packages/7b/2b/3850dc6bf7ef71b088962eba31dafc6cffd2f96e577ebb0bb316df96da3e/starlette-1.7.0.tar.gz", hash = "sha256:c79f74ea63cff761804fbbfb182f1e0b440c2d07b164d24700c5a1bab5d6ff5d", size = 2736246, upload-time = "2026-09-23T07:30:26.35Z" }wheels = [@@ -3487,8 +3503,8 @@ resolution-markers = ["(python_full_version >= '3.11' and python_full_version < '3.13' and platform_machine != 'x86_64' and sys_platform == 'darwin') or (python_full_version >= '3.11' and python_full_version < '3.13' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'win32') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')",]dependencies = [- { name = "anyio" },- { name = "typing-extensions", marker = "python_full_version < '3.13'" },+ { name = "anyio", marker = "python_full_version >= '3.11'" },+ { name = "typing-extensions", marker = "python_full_version >= '3.11' and python_full_version < '3.13'" },]sdist = { url = "https://files.pythonhosted.org/packages/ad/eb/4e197bf26b023abafc5e9043ec8710d7de0fcb032d0969045236d72aa0b1/starlette-1.9.0.tar.gz", hash = "sha256:3d931de246ed870e35ce605974440816ef895e592f255d1396cfdf191d4c4318", size = 2732466, upload-time = "2026-10-18T15:50:33.189Z" }wheels = [diff --git a/vibe/authorization.py b/vibe/authorization.pyindex e4c971a59..8142e8de1 100644--- a/vibe/authorization.py+++ b/vibe/authorization.py@@ -650,6 +650,9 @@ _EDITOR_HTTP_RULES = tuple(for method, pattern in (("GET", r"^/api/agents$"),("GET", r"^/api/agents/[^/]+$"),+ # MCP Hub reads match Skills; its management routes stay Owner-only.+ ("GET", r"^/api/mcp$"),+ ("GET", r"^/api/mcp/[^/]+$"),("GET", r"^/api/agents-graph$"),("GET", r"^/api/agent-backends$"),# Read-only model catalogs. Chat's route picker is an editor surface anddiff --git a/vibe/claude_config.py b/vibe/claude_config.pyindex 0a2f869bd..10a468974 100644--- a/vibe/claude_config.py+++ b/vibe/claude_config.py@@ -50,6 +50,11 @@ CLAUDE_MEMORY_DISABLED_SETTINGS = '{"autoMemoryEnabled":false}'# override, which outranks each of these sources.CLAUDE_SETTING_SOURCES = ["user", "project", "local"]+# Native MCP is off in Avibe sessions: agents call MCP through ``vibe mcp``.+# ``--strict-mcp-config`` with no ``--mcp-config`` loads no server from any+# settings source, without touching the user's files.+CLAUDE_NATIVE_MCP_DISABLED = {"strict_mcp_config": True, "mcp_servers": {}}+# Keys we recognise inside ``~/.claude/settings.json``'s ``env`` block.# Claude Code assigns header semantics from the selected variable, independently# from ``ANTHROPIC_BASE_URL``. Avibe preserves that native distinction insteaddiff --git a/vibe/cli.py b/vibe/cli.pyindex 0f1beafa9..507e723d3 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -16860,6 +16860,11 @@ def _cmd_restart_with_delay(delay_seconds: float) -> int:def build_parser():parser = VibeArgumentParser(prog="vibe")subparsers = parser.add_subparsers(dest="command")+ # ``vibe mcp`` is dispatched from raw argv in ``main`` (server and tool names+ # are dynamic); this entry only lists it in ``vibe --help``.+ subparsers.add_parser("mcp", help="Discover and call generated MCP server tools (vibe mcp --help)", add_help=False)+ subparsers.add_parser("mcp-add", help="Add MCP servers to the Avibe Hub (vibe mcp-add --help)", add_help=False)+ subparsers.add_parser("mcp-discover", help="Discover native MCP servers and register reachable ones", add_help=False)stop_parser = subparsers.add_parser("stop", help="Stop all services")stop_parser.add_argument(@@ -19004,6 +19009,13 @@ _CLI_COMMAND_FLOORS: dict[tuple[str, ...], Optional[str]] = {("data", "query"): "editor",("data", "skill-usage"): "editor",("data", "retention"): "member",+ # ``vibe mcp`` admits itself from raw argv (vibe/mcp_cli.py): discovery and+ # calls at Editor like Skills, management Owner-only. This floor is reached+ # only if argparse ever dispatches it. ``mcp-add`` / ``mcp-discover`` are+ # listed in ``vibe --help`` with add_help=False and also dispatched from argv.+ ("mcp",): "owner",+ ("mcp-add",): "owner",+ ("mcp-discover",): "owner",}#: Argv-level entry points the supervisor and the installer use. They are not@@ -19122,6 +19134,18 @@ def main():sys.exit(_dispatch_deferred_upgrade_activation(argv[1:]))if argv and argv[0] == "__activate-install":sys.exit(_dispatch_installer_activation(argv[1:]))+ if argv and argv[0] == "mcp":+ from vibe import mcp_cli++ sys.exit(mcp_cli.main(argv[1:]))+ if argv and argv[0] == "mcp-add":+ from vibe import mcp_cli++ sys.exit(mcp_cli.add_main(argv[1:]))+ if argv and argv[0] == "mcp-discover":+ from vibe import mcp_cli++ sys.exit(mcp_cli.discover_main(argv[1:]))parser = build_parser()args = parser.parse_args()_require_command_admission(parser, args)diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex c11beab0a..b187a5695 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -1789,5 +1789,8 @@"unsupported": "The reference image {path} is {mime}, which cannot be sent."}}+ },+ "mcp": {+ "genericDescription": "Tools from an MCP server."}}diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex e1245c62b..2a1bfa8f0 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -1789,5 +1789,8 @@"unsupported": "参考图片 {path} 是 {mime},无法发送。"}}+ },+ "mcp": {+ "genericDescription": "来自 MCP 服务器的工具。"}}diff --git a/vibe/internal_client.py b/vibe/internal_client.pyindex 509c10ab4..0a0cc95d6 100644--- a/vibe/internal_client.py+++ b/vibe/internal_client.py@@ -384,6 +384,68 @@ def computer_use_sync(return {"status_code": response.status_code, "body": body}+def mcp_request_sync(+ operation: str,+ payload: dict[str, Any],+ *,+ socket_path: Optional[Path] = None,+) -> dict[str, Any]:+ """Run one Controller-owned MCP Hub operation (``core/mcp_hub/runtime.py``).++ The owner bounds every operation itself (connect, call and generation+ timeouts), so the read waits for its definitive answer. Once IPC connected,+ a transport failure is acceptance-ambiguous and raises+ ``InternalServerTimeout``.+ """++ endpoint = _resolve_endpoint(socket_path)+ try:+ with httpx.Client(+ transport=_sync_transport(endpoint),+ base_url=endpoint.base_url,+ headers=endpoint.headers,+ timeout=httpx.Timeout(None, connect=5.0),+ ) as client:+ response = client.post("/internal/mcp", json={"operation": operation, "payload": payload})+ _validate_response(response, endpoint)+ body = response.json() if response.content else {}+ except _SOCKET_CONNECT_ERRORS as exc:+ raise InternalServerUnavailable(str(exc)) from exc+ except httpx.TransportError as exc:+ raise InternalServerTimeout(str(exc)) from exc+ if not isinstance(body, dict):+ raise InternalServerUnavailable("mcp endpoint returned invalid JSON")+ return body+++async def mcp_request(+ operation: str,+ payload: dict[str, Any],+ *,+ socket_path: Optional[Path] = None,+) -> dict[str, Any]:+ """Async twin of :func:`mcp_request_sync` for the Web UI process."""++ endpoint = await _resolve_endpoint_async(socket_path)+ try:+ async with httpx.AsyncClient(+ transport=_async_transport(endpoint),+ base_url=endpoint.base_url,+ headers=endpoint.headers,+ timeout=httpx.Timeout(None, connect=5.0),+ ) as client:+ response = await client.post("/internal/mcp", json={"operation": operation, "payload": payload})+ _validate_response(response, endpoint)+ except _SOCKET_CONNECT_ERRORS as exc:+ raise InternalServerUnavailable(str(exc)) from exc+ except httpx.TransportError as exc:+ raise InternalServerTimeout(str(exc)) from exc+ body = response.json() if response.content else {}+ if not isinstance(body, dict):+ raise InternalServerUnavailable("mcp endpoint returned invalid JSON")+ return body++def resolve_computer_script_endpoint(socket_path: Optional[Path] = None,) -> control_ipc.ControlIpcClientEndpoint:diff --git a/vibe/mcp_api.py b/vibe/mcp_api.pynew file mode 100644index 000000000..66b06408a--- /dev/null+++ b/vibe/mcp_api.py@@ -0,0 +1,99 @@+"""Web API for MCP Hub (``/api/mcp*``).++Reads come from published artifacts. Mutations are Controller-owned operations+over control IPC. Env/header values never leave the owner files.+"""++from __future__ import annotations++import asyncio+from typing import Any++from core.mcp_hub import repository+from core.mcp_hub.definition import parse_provider_json, provider_entry+from core.mcp_hub.errors import McpHubError++_STATUS = {"usage": 400, "not_found": 404, "exists": 409, "unavailable": 503, "unknown_outcome": 502}+++def _error(exc: McpHubError) -> tuple[dict[str, Any], int]:+ status = _STATUS.get(exc.type, 400)+ return {"ok": False, "error": exc.payload()}, status+++async def _owner(operation: str, payload: dict[str, Any]) -> dict[str, Any]:+ from vibe import internal_client++ try:+ response = await internal_client.mcp_request(operation, payload)+ except internal_client.InternalServerUnavailable:+ raise McpHubError("unavailable", "The Avibe service is not running.") from None+ except internal_client.InternalServerTimeout:+ raise McpHubError("unknown_outcome", "The Avibe service connection broke; refresh to see the result.") from None+ if not response.get("ok"):+ if operation == "add" and (response.get("failed") or response.get("unchanged") is not None):+ return response+ raise McpHubError.from_payload(response.get("error"))+ return response+++def _servers_payload(definitions: list[dict[str, Any]]) -> list[dict[str, Any]]:+ return [+ {"name": item["name"], "server": provider_entry(item), "description": item.get("description")}+ for item in definitions+ ]+++async def run(handler, *args) -> tuple[dict[str, Any], int]:+ try:+ return await handler(*args), 200+ except McpHubError as cop:+ return _error(cop)+++async def list_servers() -> dict[str, Any]:+ return {"ok": True, "servers": await asyncio.to_thread(repository.list_packages)}+++async def add(body: dict[str, Any]) -> dict[str, Any]:+ definitions = parse_provider_json(str(body.get("text") or ""))+ payload = {"replace": body.get("replace") is True, "servers": _servers_payload(definitions)}+ response = await _owner("add", payload)+ parse_failed = getattr(definitions, "failures", None) or []+ if parse_failed:+ failed = list(response.get("failed") or []) + parse_failed+ response = {**response, "failed": failed, "ok": bool(response.get("added") or response.get("unchanged"))}+ if failed and not response.get("added"):+ summary = "; ".join(f"{item['name']}: {item.get('error') or 'failed'}" for item in failed)+ response["error"] = {"type": "add_failed" if not response.get("unchanged") else "add_partial", "message": summary, "failed": failed}+ elif failed:+ summary = "; ".join(f"{item['name']}: {item.get('error') or 'failed'}" for item in failed)+ response["error"] = {"type": "add_partial", "message": summary, "failed": failed}+ return response+++async def detail(name: str) -> dict[str, Any]:+ def _read() -> dict[str, Any]:+ summary = repository.summarize(name)+ published = repository.read_published(name)+ payload: dict[str, Any] = {"ok": True, "server": summary}+ if published is not None:+ payload["tools"] = [+ {"name": tool.get("name"), "description": tool.get("description") or ""}+ for tool in published["tools"]+ ]+ return payload++ return await asyncio.to_thread(_read)+++async def discover() -> dict[str, Any]:+ return await _owner("discover", {})+++async def refresh(name: str) -> dict[str, Any]:+ return await _owner("refresh", {"name": name, "waitStdio": True})+++async def remove(name: str) -> dict[str, Any]:+ return await _owner("remove", {"name": name})diff --git a/vibe/mcp_cli.py b/vibe/mcp_cli.pynew file mode 100644index 000000000..55f782b69--- /dev/null+++ b/vibe/mcp_cli.py@@ -0,0 +1,316 @@+"""``vibe mcp``: per-server discovery and calls. Management is ``vibe mcp-add`` / ``vibe mcp-discover``.++List and help read local artifacts only. Calls and management go to the Controller+over control IPC.++Exit codes: 0 success, 2 usage/argument error, 1 any other failure.+"""++from __future__ import annotations++import json+import sys+from pathlib import Path+from typing import Any, Optional++from core.mcp_hub import commands as mcp_commands+from core.mcp_hub import repository+from core.mcp_hub.definition import parse_add_argv, provider_entry+from core.mcp_hub.errors import McpHubError++USAGE = """\+usage:+ vibe mcp --list [--format json]+ vibe mcp <server> --list [--format json]+ vibe mcp <server> --refresh+ vibe mcp <server> --remove+ vibe mcp <server> <tool> --help+ vibe mcp <server> <tool> [--<key> <value> ...]+ vibe mcp <server> <tool> --args-json '<object>' | --args-file <path> | --args-stdin+ vibe mcp <server> -- <tool-starting-with-dash> ...++management (Owner):+ vibe mcp-add [--transport stdio|http] [--env KEY=VALUE ...] [--header 'Name: value' ...]+ [--description TEXT] [--cwd DIR] [--replace] <name> -- <command> [args...]+ vibe mcp-add --transport http <name> <url>+ vibe mcp-add --json-stdin [--replace]+ vibe mcp-discover+"""+++def escape(text: object) -> str:+ """Escape control characters in server-provided text for terminal output."""++ return "".join(+ char if char.isprintable() or char == " " else char.encode("unicode_escape").decode("ascii")+ for char in str(text)+ )+++def _fail(error: McpHubError) -> int:+ print(f"error: {error.message}", file=sys.stderr)+ if error.hint:+ print(f"hint: {error.hint}", file=sys.stderr)+ return 2 if error.usage else 1+++def _admit(floor: str) -> Optional[int]:+ from vibe.authorization import InstanceAuthorizationError, require_instance_role++ try:+ require_instance_role(None, floor)+ except InstanceAuthorizationError as cop:+ return _fail(McpHubError(cop.code, str(cop)))+ return None+++def main(argv: list[str]) -> int:+ denied = _admit("editor")+ if denied is not None:+ return denied+ try:+ return _dispatch(argv)+ except McpHubError as cop:+ return _fail(cop)+++def add_main(argv: list[str]) -> int:+ if argv and argv[0] in {"-h", "--help"}:+ print(USAGE, end="")+ return 0+ denied = _admit("owner")+ if denied is not None:+ return denied+ try:+ return _add(argv)+ except McpHubError as cop:+ return _fail(cop)+++def discover_main(argv: list[str]) -> int:+ if argv and argv[0] in {"-h", "--help"}:+ print("usage: vibe mcp-discover\n", end="")+ return 0+ denied = _admit("owner")+ if denied is not None:+ return denied+ if argv:+ raise_or = McpHubError("usage", "usage: vibe mcp-discover", usage=True)+ return _fail(raise_or)+ try:+ return _owner("discover", {})+ except McpHubError as cop:+ return _fail(cop)+++def _dispatch(argv: list[str]) -> int:+ if not argv or argv[0] in {"-h", "--help"}:+ print(USAGE, end="")+ return 0 if argv else 2+ head = argv[0]+ if head == "--list":+ return _root_list(argv)+ if head.startswith("-"):+ raise McpHubError("usage", f"Unknown option {head}.", hint="vibe mcp --help", usage=True)+ return _server(head, argv[1:])+++def _format_json(options: list[str], allowed: set[str]) -> bool:+ as_json = False+ index = 0+ while index < len(options):+ option = options[index]+ if option == "--format" and index + 1 < len(options):+ if options[index + 1] not in {"json", "text"}:+ raise McpHubError("usage", "--format accepts json or text.", usage=True)+ as_json = options[index + 1] == "json"+ index += 2+ continue+ if option not in allowed:+ raise McpHubError("usage", f"Unexpected argument {option}.", hint="vibe mcp --help", usage=True)+ index += 1+ return as_json+++def _root_list(argv: list[str]) -> int:+ as_json = _format_json(argv, {"--list"})+ packages = repository.list_packages()+ if as_json:+ print(json.dumps({"servers": packages}, ensure_ascii=False, indent=2))+ return 0+ if not packages:+ print("No MCP servers.")+ return 0+ for item in packages:+ extra = f" [{item.get('source') or 'avibe'}]" if item.get("source") else ""+ print(f"{item['name']} {escape(item.get('description') or '')}{extra}".rstrip())+ print("\nNext: vibe mcp <server> --list")+ return 0+++def _owner(operation: str, payload: dict[str, Any]) -> int:+ from vibe import internal_client++ try:+ response = internal_client.mcp_request_sync(operation, payload)+ except internal_client.InternalServerUnavailable:+ raise McpHubError("unavailable", "The Avibe service is not running.", hint="vibe start") from None+ except internal_client.InternalServerTimeout:+ raise McpHubError("unknown_outcome", "The Avibe service connection broke; check vibe mcp --list.") from None+ if not response.get("ok") and not (operation in {"add", "save"} and "failed" in response):+ raise McpHubError.from_payload(response.get("error"))+ if operation == "discover":+ for item in response.get("results") or []:+ if item.get("status") == "registered":+ print(f"{item['name']}: registered ({item.get('toolCount', 0)} tools)")+ else:+ print(f"{item['name']}: failed — {item.get('error') or 'unknown'}", file=sys.stderr)+ return 0+ if operation in {"add", "save"}:+ added = response.get("added") or []+ failed = response.get("failed") or []+ unchanged = response.get("unchanged") or []+ for item in added:+ print(f"{item['name']}: added ({item.get('toolCount', 0)} tools)")+ for item in unchanged:+ print(f"{item['name']}: unchanged")+ for item in failed:+ print(f"{item['name']}: failed — {item.get('error') or 'unknown'}", file=sys.stderr)+ succeeded = len(added) + len(unchanged)+ print(f"{succeeded} succeeded, {len(failed)} failed")+ if not added and not failed and not unchanged:+ names = ", ".join(response.get("saved") or [response.get("name") or ""])+ print(f"Registered {names} ({response.get('toolCount', 0)} tools).")+ return 0 if added or unchanged or response.get("ok") else 1+ elif operation == "refresh":+ print(f"Refreshed {response['name']} ({response.get('toolCount', 0)} tools).")+ elif operation == "remove":+ kind = response.get("kind")+ extra = " (hidden in Avibe)" if kind == "native" else ""+ print(f"Removed {response['name']}{extra}.")+ return 0+++def _add(args: list[str]) -> int:+ split = args.index("--") if "--" in args else len(args)+ if "--json-stdin" in args[:split]:+ position = args.index("--json-stdin")+ args = args[: position + 1] + [sys.stdin.read()] + args[position + 1 :]+ definitions, replace = parse_add_argv(args)+ payload = {+ "replace": replace,+ "servers": [+ {"name": item["name"], "server": provider_entry(item), "description": item.get("description")}+ for item in definitions+ ],+ }+ code = _owner("add", payload)+ parse_failed = getattr(definitions, "failures", None) or []+ if parse_failed:+ for item in parse_failed:+ print(f"error: {item['name']}: {item['error']}", file=sys.stderr)+ if code == 0:+ return 1+ return code+++def _published(name: str) -> dict[str, Any]:+ published = repository.read_published(name)+ if published is None:+ raise McpHubError("not_found", f"Unknown MCP server {name!r}.", hint="vibe mcp --list")+ return published+++def _server(name: str, args: list[str]) -> int:+ from core.mcp_hub.definition import validate_name++ try:+ validate_name(name)+ except McpHubError:+ raise McpHubError("not_found", f"Unknown MCP server {name!r}.", hint="vibe mcp --list") from None+ if args and args[0] == "--refresh":+ denied = _admit("owner")+ if denied is not None:+ return denied+ if len(args) != 1:+ raise McpHubError("usage", "usage: vibe mcp <server> --refresh", usage=True)+ return _owner("refresh", {"name": name, "waitStdio": True})+ if args and args[0] == "--remove":+ denied = _admit("owner")+ if denied is not None:+ return denied+ if len(args) != 1:+ raise McpHubError("usage", "usage: vibe mcp <server> --remove", usage=True)+ return _owner("remove", {"name": name})+ if not args or args[0] in {"--list", "--help", "-h", "--format"}:+ return _server_list(name, args)+ if args[0] == "--":+ if len(args) < 2:+ raise McpHubError("usage", "Missing tool name after --.", usage=True)+ tool, rest = args[1], args[2:]+ elif args[0].startswith("-"):+ raise McpHubError("usage", f"Unexpected option {args[0]}.", hint=f"vibe mcp {name} --list", usage=True)+ else:+ tool, rest = args[0], args[1:]+ published = _published(name)+ command = next((item for item in published["commands"] if item["name"] == tool), None)+ if command is None:+ raise McpHubError("not_found", f"{name} has no tool {tool!r}.", hint=f"vibe mcp {name} --list")+ if rest in (["--help"], ["-h"]):+ print(mcp_commands.render_tool_help(name, command, escape))+ return 0+ arguments = mcp_commands.parse_tool_argv(+ command,+ rest,+ read_file=lambda path: Path(path).read_text(encoding="utf-8"),+ read_stdin=sys.stdin.read,+ )+ descriptor = next(item for item in published["tools"] if item["name"] == tool)+ mcp_commands.validate_arguments(descriptor, arguments)+ return _call(name, tool, arguments)+++def _server_list(name: str, args: list[str]) -> int:+ as_json = _format_json(args, {"--list", "--help", "-h"})+ published = _published(name)+ if as_json:+ print(json.dumps({+ "server": name,+ "revision": published["revision"],+ "tools": [+ {**tool, "flags": command["flags"], "validated": command["validated"]}+ for tool, command in zip(published["tools"], published["commands"])+ ],+ }, ensure_ascii=False, indent=2))+ return 0+ for command in published["commands"]:+ print(f"{escape(command['name'])} {escape(command['description'])[:200]}".rstrip())+ print(f"\nNext: vibe mcp {name} <tool> --help")+ return 0+++def _call(name: str, tool: str, arguments: dict[str, Any]) -> int:+ from core.caller_context import caller_context_from_env+ from vibe import internal_client++ caller = caller_context_from_env()+ payload = {"name": name, "tool": tool, "arguments": arguments, "sessionId": caller.session_id if caller else None}+ try:+ envelope = internal_client.mcp_request_sync("call", payload)+ except internal_client.InternalServerUnavailable:+ raise McpHubError("unavailable", "The Avibe service is not running; the call was not sent.", hint="vibe start") from None+ except internal_client.InternalServerTimeout:+ envelope = {+ "schemaVersion": 1, "server": name, "revision": None, "tool": tool, "status": "error",+ "error": {"type": "unknown_outcome",+ "message": "The connection to the Avibe service broke after the call was submitted; do not retry blindly."},+ }+ if "status" not in envelope:+ raise McpHubError.from_payload(envelope.get("error"))+ print(json.dumps(envelope, ensure_ascii=False))+ if envelope["status"] == "ok":+ return 0+ error = envelope.get("error") or {}+ if error.get("hint"):+ print(f"hint: {error['hint']}", file=sys.stderr)+ return 2 if error.get("usage") else 1diff --git a/vibe/opencode_config.py b/vibe/opencode_config.pyindex 92fbeed7b..927547cf9 100644--- a/vibe/opencode_config.py+++ b/vibe/opencode_config.py@@ -80,6 +80,7 @@ class OpenCodeRuntimeConfigInvalidError(RuntimeError):def managed_opencode_runtime_config_content(raw: str | bytes | None,+ disabled_mcp: Dict[str, Any] | None = None,) -> str:"""Apply Avibe-owned OpenCode runtime policy without mutating user config."""@@ -124,6 +125,14 @@ def managed_opencode_runtime_config_content(# Computer Use is exposed through ``vibe computer`` and must never be# reintroduced from a stale user or runtime configuration.managed_mcp.pop("avibe_computer", None)+ # Native MCP is off in Avibe sessions; agents call MCP through ``vibe mcp``+ # (core/mcp_hub/native.py supplies the user's entries with enabled=false).+ for name, entry in (disabled_mcp or {}).items():+ current = managed_mcp.get(name)+ managed_mcp[name] = {**(current if isinstance(current, dict) else entry), "enabled": False}+ for name, entry in list(managed_mcp.items()):+ if isinstance(entry, dict):+ managed_mcp[name] = {**entry, "enabled": False}if managed_mcp:payload["mcp"] = managed_mcpelse:diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 659e22ed8..cf4d51684 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -9489,6 +9489,66 @@ def global_prompts_save():return jsonify({"ok": True, "backends": result})+# MCP Hub (docs/plans/mcp-hub-mvp.md §8): reads come from published artifacts,+# mutations are the Controller-owned operations the CLI uses. Read routes are+# Editor and management routes Owner in vibe/authorization.py.+def _mcp_body() -> dict:+ payload = request.json+ return payload if isinstance(payload, dict) else {}+++async def _mcp_route(starlette_request: FastAPIRequest, handler, *args):+ async def run():+ from vibe import mcp_api++ body, status = await mcp_api.run(handler, *args)+ return jsonify(body), status++ return await _dispatch_native_ui_request(starlette_request, run)++[email protected]("/api/mcp", include_in_schema=False)+async def mcp_list(starlette_request: FastAPIRequest):+ from vibe import mcp_api++ return await _mcp_route(starlette_request, mcp_api.list_servers)++[email protected]("/api/mcp", include_in_schema=False)+async def mcp_add(starlette_request: FastAPIRequest):+ from vibe import mcp_api++ return await _mcp_route(starlette_request, lambda: mcp_api.add(_mcp_body()))++[email protected]("/api/mcp/discover", include_in_schema=False)+async def mcp_discover(starlette_request: FastAPIRequest):+ from vibe import mcp_api++ return await _mcp_route(starlette_request, mcp_api.discover)++[email protected]("/api/mcp/{name}", include_in_schema=False)+async def mcp_detail(name: str, starlette_request: FastAPIRequest):+ from vibe import mcp_api++ return await _mcp_route(starlette_request, mcp_api.detail, name)++[email protected]("/api/mcp/{name}/refresh", include_in_schema=False)+async def mcp_refresh(name: str, starlette_request: FastAPIRequest):+ from vibe import mcp_api++ return await _mcp_route(starlette_request, mcp_api.refresh, name)++[email protected]("/api/mcp/{name}", include_in_schema=False)+async def mcp_remove(name: str, starlette_request: FastAPIRequest):+ from vibe import mcp_api++ return await _mcp_route(starlette_request, mcp_api.remove, name)++# Agent Skills — thin shells over api.* (which wraps the askill CLI). Pure# data CRUD, so it stays in the UI-server process via core/services (no# dispatch-socket round-trip). See docs/plans/workbench-skills-page.md.