From 1db5ca6bc1d6011a058ea6036207f366080e91f5 Mon Sep 17 00:00:00 2001 From: LizheChen <574118090@qq.com> Date: Thu, 15 Oct 2026 03:24:43 +0800 Subject: [PATCH] Harden local MCP transport and simplify standalone client lifecycle --- README.md | 8 +- README.zh-CN.md | 8 +- package/editor/infernux_mcp/adapter.py | 18 +- package/editor/infernux_mcp/bridge.py | 19 ++ package/editor/infernux_mcp/capabilities.py | 5 + package/editor/infernux_mcp/client.py | 35 ++- package/editor/infernux_mcp/credentials.py | 108 +++++++++ package/editor/infernux_mcp/server.py | 224 ++++++++---------- package/editor/infernux_mcp/session.py | 2 +- .../editor/infernux_mcp/supervisor_utils.py | 3 +- .../editor/infernux_mcp/transport_security.py | 32 +++ package/plugin_pages/operations.md | 18 ++ package/plugin_pages/operations.zh-CN.md | 6 + package/plugin_pages/trust.md | 5 +- package/plugin_pages/trust.zh-CN.md | 6 +- package/requirements.txt | 4 +- test/test_client_transport.py | 35 ++- 17 files changed, 366 insertions(+), 170 deletions(-) create mode 100644 package/editor/infernux_mcp/bridge.py create mode 100644 package/editor/infernux_mcp/credentials.py create mode 100644 package/editor/infernux_mcp/transport_security.py diff --git a/README.md b/README.md index 7ada1d3..ad458bb 100644 --- a/README.md +++ b/README.md @@ -17,13 +17,13 @@ The official Model Context Protocol plugin for [Infernux](https://github.com/Che | Package | Version | Compatible engine | Endpoint | | --- | --- | --- | --- | -| `infernux/mcp` | 0.1.2 | Infernux 0.4.x | `http://127.0.0.1:9713/mcp` | +| `infernux/mcp` | 0.1.19 | Infernux >=0.4.2 | `http://127.0.0.1:9713/mcp` | ## Install and connect New Infernux projects include this official plugin by default. Existing projects can install or update it from the Editor's **Plugins** window. You can disable or uninstall it there when agent access is not needed. -Point an MCP-compatible client to `http://127.0.0.1:9713/mcp`. The server accepts localhost connections only. Set `INFERNUX_MCP_PORT` before starting the Editor to choose another port. +The Editor writes standard stdio client configurations for Cursor, Claude Code, VS Code, Trae and Gemini. Their small proxy forwards to `http://127.0.0.1:9713/mcp` and reads the current user's private credential for every request, including after an Editor restart. It does not initialize the engine. Direct HTTP clients must send a bearer credential; the built-in Python client handles this automatically. No credential is stored in project files, process arguments, or environment variables. Set `INFERNUX_MCP_PORT` before starting the Editor to choose another loopback port. Start a session with `host_session_status`, then read `operation_schema_list`. Search the catalog with `operation_schema_search`, inspect the exact schema you need, and call it through `operation_command_execute`. Long-running builds belong in `operation_job_submit`; known ordered calls can be grouped with `operation_batch_execute`. @@ -49,7 +49,7 @@ changes retain the existing gateway APIs and capability gates; no extra grants or automatic retries are introduced. The published package version is unchanged until a release is tagged. -## Compute diagnostics (041) +## Compute diagnostics Search the operation catalog for `runtime.compute`. Read `statistics` for the engine's cumulative upload/readback bytes, dispatches, submissions and CPU waits; @@ -57,7 +57,7 @@ engine's cumulative upload/readback bytes, dispatches, submissions and CPU waits to collect native GPU timestamps, and disable it after measuring. Toggling it may wait for in-flight compute. GPU time describes the latest completed submission, not an entire frame; use the separate `runtime.performance` window for frame -percentiles. These operations require the matching 041 engine host. +percentiles. These operations require the matching engine host. ## Repository guide diff --git a/README.zh-CN.md b/README.zh-CN.md index d3fea0a..24b4e84 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -17,13 +17,13 @@ | 包标识 | 版本 | 适配引擎 | 默认地址 | | --- | --- | --- | --- | -| `infernux/mcp` | 0.1.2 | Infernux 0.4.x | `http://127.0.0.1:9713/mcp` | +| `infernux/mcp` | 0.1.19 | Infernux >=0.4.2 | `http://127.0.0.1:9713/mcp` | ## 安装与连接 Infernux 新项目默认带有这个官方插件。已有项目可以在编辑器的**插件**窗口中安装或更新;不需要 Agent 操作时,也可以在同一位置禁用或卸载。 -把支持 MCP 的客户端连接到 `http://127.0.0.1:9713/mcp` 即可。服务只接受本机连接。如需更换端口,请在启动编辑器前设置 `INFERNUX_MCP_PORT`。 +编辑器为 Cursor、Claude Code、VS Code、Trae 和 Gemini 生成标准 stdio 配置。轻量代理把请求转发至 `http://127.0.0.1:9713/mcp`,每次请求读取当前用户的私有凭据,编辑器重启后也会使用新凭据;代理不会初始化引擎。直接连接 HTTP 的客户端必须携带 bearer 凭据,内置 Python 客户端会自动处理。凭据不会写入项目文件、进程参数或环境变量。如需更换端口,请在启动编辑器前设置 `INFERNUX_MCP_PORT`。 Agent 应先调用 `host_session_status`,再读取 `operation_schema_list`。通过 `operation_schema_search` 找到所需能力、读取准确 schema,最后用 `operation_command_execute` 执行。构建等耗时任务使用 `operation_job_submit`,一组顺序明确的操作可以交给 `operation_batch_execute`,减少通信往返。 @@ -40,9 +40,9 @@ Python 客户端新增 `session` 模式:每行输入一个 JSON 请求,复 [客户端工作流与耗时诊断](package/plugin_pages/operations.zh-CN.md#python-客户端)说明了协议、超时边界和只读基准测试。现有 gateway API、能力白名单与确认要求保持不变,不会自动重试命令。源码改进将在后续打标签发布时进入新安装包,当前发布版本号不变。 -## Compute 性能诊断(041) +## Compute 性能诊断 -在操作目录中搜索 `runtime.compute`。`statistics` 读取引擎已有的上传/回读字节数、派发与提交次数、CPU 等待时间;`reset_statistics` 开始新的计数区间。需要 GPU 时间戳时显式启用 `profiling`,测量完关闭;切换时可能等待在途任务。GPU 耗时只代表最近完成的一次提交,不是整帧耗时;完整帧的百分位仍通过 `runtime.performance` 获取。这些操作需要配套的 041 引擎宿主。 +在操作目录中搜索 `runtime.compute`。`statistics` 读取引擎已有的上传/回读字节数、派发与提交次数、CPU 等待时间;`reset_statistics` 开始新的计数区间。需要 GPU 时间戳时显式启用 `profiling`,测量完关闭;切换时可能等待在途任务。GPU 耗时只代表最近完成的一次提交,不是整帧耗时;完整帧的百分位仍通过 `runtime.performance` 获取。这些操作需要配套的引擎宿主。 ## 仓库说明 diff --git a/package/editor/infernux_mcp/adapter.py b/package/editor/infernux_mcp/adapter.py index 52af655..97607d8 100644 --- a/package/editor/infernux_mcp/adapter.py +++ b/package/editor/infernux_mcp/adapter.py @@ -47,7 +47,6 @@ def register_gateways( with _state_lock: registration_started = time.perf_counter() shutdown_adapter() - _command_owner = CommandOwner(OWNER) _config = dict(config or {}) registry = OperationRegistry.instance() registry.unregister_owner(OWNER) @@ -59,6 +58,8 @@ def register_gateways( _config = capabilities.configure(project_path, write_default=False) else: _config = capabilities.apply_config(project_path, dict(config)) + _command_owner = CommandOwner(OWNER) + _command_owner.timeout_ms = _config["limits"]["main_thread_timeout_ms"] from infernux_mcp import session # Registration defines a new plugin lifetime and policy session. session.configure(project_path, dict(_config)) @@ -67,7 +68,8 @@ def register_gateways( _operation_ids.clear() for operation in build_operations(project_path): registry.register(operation) - _operation_ids.add(operation.schema.id) + if registry.get(operation.schema.id).owner == OWNER: + _operation_ids.add(operation.schema.id) _registry = registry _jobs = OperationJobRegistry(registry) _started_at = time.time() @@ -154,9 +156,13 @@ def gateway(name: str): _gateway_names.add(name) def decorate(fn): @wraps(fn) - def invoke(*args, **kwargs): + def invoke_sync(*args, **kwargs): with command_owner_scope(command_owner): return fn(*args, **kwargs) + @wraps(invoke_sync) + async def invoke(*args, **kwargs): + import anyio + return await anyio.to_thread.run_sync(partial(invoke_sync, *args, **kwargs)) return mcp.tool(name=name)(invoke) return decorate @@ -412,10 +418,10 @@ def _compact_schema(value: Mapping[str, object]) -> dict[str, object]: def _granted_capabilities() -> tuple[str, ...]: - configured = _config.get("granted_capabilities", ["*"]) + configured = _config.get("granted_capabilities", ()) if not isinstance(configured, (list, tuple)): - return ("*",) - return tuple(str(item) for item in configured) + return () + return tuple(configured) def _execute( diff --git a/package/editor/infernux_mcp/bridge.py b/package/editor/infernux_mcp/bridge.py new file mode 100644 index 0000000..1453bf3 --- /dev/null +++ b/package/editor/infernux_mcp/bridge.py @@ -0,0 +1,19 @@ +"""Standard stdio MCP entry point; forwards to the authenticated Editor HTTP host.""" + +import argparse + +from client import create_loopback_client + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--endpoint", required=True) + args = parser.parse_args() + from fastmcp.server import create_proxy + + proxy = create_proxy(create_loopback_client(args.endpoint), name="Infernux Editor") + proxy.run(transport="stdio", show_banner=False) + + +if __name__ == "__main__": + main() diff --git a/package/editor/infernux_mcp/capabilities.py b/package/editor/infernux_mcp/capabilities.py index a0292ff..0f0c148 100644 --- a/package/editor/infernux_mcp/capabilities.py +++ b/package/editor/infernux_mcp/capabilities.py @@ -236,6 +236,7 @@ def _normalized_config(config: dict[str, Any]) -> dict[str, Any]: raise ValueError("configuration must be a JSON object") source = config normalized = copy.deepcopy(DEFAULT_CAPABILITY_CONFIG) + normalized["granted_capabilities"] = [] for key in ("enabled", "write_default_config_on_bootstrap"): if key in source: _validate_value(key, source[key], bool) @@ -260,6 +261,10 @@ def _normalized_config(config: dict[str, Any]) -> dict[str, Any]: for key, expected in schema.items(): if key in values: _validate_value(f"{section}.{key}", values[key], expected) + if section == "session" and key == "session_id" and values[key]: + from infernux_mcp.checkpoints import normalize_checkpoint_id + + normalize_checkpoint_id(values[key]) if section == "limits": minimum = 1 if key in {"main_thread_timeout_ms", "batch_max_steps"} else 0 if values[key] < minimum: diff --git a/package/editor/infernux_mcp/client.py b/package/editor/infernux_mcp/client.py index 176c4c0..47f68a3 100644 --- a/package/editor/infernux_mcp/client.py +++ b/package/editor/infernux_mcp/client.py @@ -33,17 +33,29 @@ def create_loopback_client(endpoint: str, *, timeout_seconds: float | None = Non import httpx from fastmcp import Client from fastmcp.client.transports.http import StreamableHttpTransport + if __package__: + from .credentials import load_token + else: + from credentials import load_token + + class EditorCredentialAuth(httpx.Auth): + async def async_auth_flow(self, request): + request.headers["Authorization"] = f"Bearer {load_token(endpoint)}" + yield request def http_client_factory(headers=None, auth=None, follow_redirects=True, timeout=None): return httpx.AsyncClient( headers=headers, auth=auth, - follow_redirects=follow_redirects, + follow_redirects=False, timeout=timeout or httpx.Timeout(30.0, read=300.0), trust_env=False, ) - transport = StreamableHttpTransport(str(endpoint), httpx_client_factory=http_client_factory) + transport = StreamableHttpTransport( + str(endpoint), auth=EditorCredentialAuth(), + httpx_client_factory=http_client_factory, + ) return Client(transport, timeout=timeout_seconds, init_timeout=timeout_seconds) @@ -165,12 +177,18 @@ async def _run_cli(args: argparse.Namespace) -> Any: matches = [tool for tool in tools if tool.name == args.tool] if not matches: raise ValueError(f"MCP tool not found: {args.tool}") - return _json_value(matches[0]) - query = str(args.match or "").casefold() - if query: - tools = [tool for tool in tools if query in tool.name.casefold()] - return _json_value(tools) - return await _call(client, args, args.tool, tool_args) + value = _json_value(matches[0]) + else: + query = str(args.match or "").casefold() + if query: + tools = [tool for tool in tools if query in tool.name.casefold()] + value = _json_value(tools) + else: + value = await _call(client, args, args.tool, tool_args) + # Publish the completed response before transport cleanup. A cleanup + # error goes to stderr and must not erase the request's stdout result. + _write_json(args, value) + return value async def _stdin_lines(): @@ -285,7 +303,6 @@ def main(argv: list[str] | None = None) -> int: if args.command == "session": return asyncio.run(_run_session(args)) value = asyncio.run(_run_cli(args)) - _write_json(args, value) return int(_failed(value, tool=getattr(args, "tool", ""))) except KeyboardInterrupt: return 130 diff --git a/package/editor/infernux_mcp/credentials.py b/package/editor/infernux_mcp/credentials.py new file mode 100644 index 0000000..c19f977 --- /dev/null +++ b/package/editor/infernux_mcp/credentials.py @@ -0,0 +1,108 @@ +"""Per-user credentials for the loopback Editor transport.""" + +from __future__ import annotations + +import ctypes +import json +import os +from pathlib import Path +import secrets +from urllib.parse import urlsplit + + +def credential_path(endpoint: str) -> Path: + parsed = urlsplit(endpoint) + if (parsed.scheme != "http" or parsed.hostname not in {"127.0.0.1", "localhost"} + or parsed.path != "/mcp" or parsed.username or parsed.password + or parsed.query or parsed.fragment or not parsed.port): + raise ValueError("MCP credentials require a loopback HTTP /mcp endpoint") + if os.name == "nt": + directory = Path(os.environ["LOCALAPPDATA"]) / "Infernux" / "MCP" + else: + directory = Path(os.environ.get("XDG_STATE_HOME", Path.home() / ".local/state")) / "infernux/mcp" + return directory / f"{parsed.port}.json" + + +def _protect_directory(path: Path) -> None: + if os.name != "nt": + path.chmod(0o700) + return + from ctypes import wintypes + + kernel = ctypes.WinDLL("kernel32", use_last_error=True) + advapi = ctypes.WinDLL("advapi32", use_last_error=True) + kernel.GetCurrentProcess.restype = wintypes.HANDLE + kernel.CloseHandle.argtypes = [wintypes.HANDLE] + kernel.LocalFree.argtypes = [ctypes.c_void_p] + advapi.OpenProcessToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)] + advapi.GetTokenInformation.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)] + advapi.ConvertSidToStringSidW.argtypes = [ctypes.c_void_p, ctypes.POINTER(wintypes.LPWSTR)] + advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(ctypes.c_void_p), ctypes.c_void_p] + advapi.GetSecurityDescriptorDacl.argtypes = [ctypes.c_void_p, ctypes.POINTER(wintypes.BOOL), ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(wintypes.BOOL)] + advapi.SetNamedSecurityInfoW.argtypes = [wintypes.LPWSTR, ctypes.c_int, wintypes.DWORD, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] + + def checked(ok): + if not ok: + raise ctypes.WinError(ctypes.get_last_error()) + + token = wintypes.HANDLE() + sid_string = wintypes.LPWSTR() + descriptor = ctypes.c_void_p() + checked(advapi.OpenProcessToken(kernel.GetCurrentProcess(), 0x0008, ctypes.byref(token))) + try: + size = wintypes.DWORD() + advapi.GetTokenInformation(token, 1, None, 0, ctypes.byref(size)) + data = ctypes.create_string_buffer(size.value) + checked(advapi.GetTokenInformation(token, 1, data, size, ctypes.byref(size))) + sid = ctypes.cast(data, ctypes.POINTER(ctypes.c_void_p))[0] + checked(advapi.ConvertSidToStringSidW(sid, ctypes.byref(sid_string))) + checked(advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW( + f"D:P(A;OICI;FA;;;{sid_string.value})", 1, ctypes.byref(descriptor), None)) + present, defaulted, dacl = wintypes.BOOL(), wintypes.BOOL(), ctypes.c_void_p() + checked(advapi.GetSecurityDescriptorDacl(descriptor, ctypes.byref(present), ctypes.byref(dacl), ctypes.byref(defaulted))) + result = advapi.SetNamedSecurityInfoW(str(path), 1, 0x80000004, None, None, dacl, None) + if result: + raise ctypes.WinError(result) + finally: + kernel.CloseHandle(token) + if sid_string: + kernel.LocalFree(sid_string) + if descriptor: + kernel.LocalFree(descriptor) + + +def publish_credentials(endpoint: str) -> tuple[Path, str]: + path = credential_path(endpoint) + path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + _protect_directory(path.parent) + token = secrets.token_urlsafe(32) + staging = path.with_name(f".{path.name}.{os.getpid()}") + try: + with open(staging, "w", encoding="utf-8") as handle: + if os.name != "nt": + os.fchmod(handle.fileno(), 0o600) + json.dump({"endpoint": endpoint, "pid": os.getpid(), "token": token}, handle) + os.replace(staging, path) + finally: + staging.unlink(missing_ok=True) + return path, token + + +def load_token(endpoint: str) -> str: + document = json.loads(credential_path(endpoint).read_text(encoding="utf-8")) + if urlsplit(document["endpoint"]).port != urlsplit(endpoint).port: + raise ValueError("MCP credential endpoint does not match") + token = document["token"] + if not isinstance(token, str) or not token: + raise ValueError("MCP credential token is missing") + return token + + +def remove_credentials(endpoint: str, token: str) -> None: + path = credential_path(endpoint) + try: + current = json.loads(path.read_text(encoding="utf-8")) + except FileNotFoundError: + return + if current.get("token") == token: + path.unlink() diff --git a/package/editor/infernux_mcp/server.py b/package/editor/infernux_mcp/server.py index 94d242b..ba3c86a 100644 --- a/package/editor/infernux_mcp/server.py +++ b/package/editor/infernux_mcp/server.py @@ -6,6 +6,9 @@ import os import threading import time +import sys +import socket +from contextvars import copy_context from dataclasses import dataclass, field from typing import Optional @@ -23,6 +26,7 @@ HEALTH_PATH = "/health" SERVER_NAME = "Infernux Editor" _RUNTIME_SERVICE_NAME = "infernux.editor.mcp.http" +_TRANSPORT_CONTRACT = 1 @dataclass @@ -33,6 +37,8 @@ class _ServerState: mcp: object transport: object adapter_shutdown: object + credential_token: str = field(default="", repr=False) + transport_contract: int = _TRANSPORT_CONTRACT adapter_begin_shutdown: object = None thread: Optional[threading.Thread] = None error: BaseException | None = None @@ -82,8 +88,20 @@ def _active_state() -> _ServerState | None: def start_server(project_path: str, *, host: str = HOST, port: int = PORT) -> bool: """Start the embedded HTTP MCP server if it is not already running.""" + from infernux_mcp.supervisor_utils import _require_loopback_host, _require_port + + host = _require_loopback_host(host) + port = _require_port(port) with _lifecycle_lock: existing = _active_state() + contract = getattr(existing, "transport_contract", 0) if existing is not None else _TRANSPORT_CONTRACT + if contract not in {0, _TRANSPORT_CONTRACT}: + raise RuntimeError("Infernux MCP transport owner has an unsupported version contract") + if existing is not None and contract == 0: + # Pre-authentication owners can survive module reload. Retire that + # concrete legacy transport before publishing an authenticated one. + _stop_state(existing) + existing = _active_state() if existing is not None: if existing.stop_requested.is_set(): if not existing.stopped.wait(timeout=10.0): @@ -110,7 +128,7 @@ def start_server(project_path: str, *, host: str = HOST, port: int = PORT) -> bo try: FastMCP = _import_fastmcp() - except Exception as exc: + except ImportError as exc: Debug.log_warning( "Infernux MCP disabled: install PyPI packages 'mcp' and 'fastmcp' to enable " f"the embedded HTTP server ({exc})." @@ -141,7 +159,15 @@ def start_server(project_path: str, *, host: str = HOST, port: int = PORT) -> bo ) except Exception as exc: Debug.log_suppressed("infernux_mcp.start_session_log", exc) - mcp = FastMCP(SERVER_NAME) + from mcp.server.transport_security import TransportSecuritySettings + mcp = FastMCP( + SERVER_NAME, stateless_http=True, json_response=True, log_level="WARNING", + transport_security=TransportSecuritySettings( + enable_dns_rebinding_protection=True, + allowed_hosts=[f"127.0.0.1:{port}", f"localhost:{port}"], + allowed_origins=[], + ), + ) # Keep health probing outside the streamable HTTP mount. A bare GET on # /mcp is transport negotiation, not a stable readiness endpoint. @@ -153,13 +179,7 @@ async def _mcp_health_probe(request: Request) -> JSONResponse: return JSONResponse( { "name": SERVER_NAME, - "message": ( - "MCP endpoint is alive. Use streamable HTTP at /mcp " - "for tool calls." - ), - "transport": "streamable-http", - "path": HEALTH_PATH, - "url": endpoint_url(host=host, port=int(port)), + "ready": True, } ) @@ -168,22 +188,23 @@ async def _mcp_health_probe(request: Request) -> JSONResponse: import uvicorn - app = mcp.streamable_http_app() - endpoint = next(route.endpoint for route in app.routes if route.path == PATH) - - class SessionAwareServer(uvicorn.Server): - async def _wait_tasks_to_complete(self) -> None: - # Uvicorn has stopped accepting requests at this point, but - # an MCP GET stream remains open until its session terminates. - # Waiting for it before app lifespan shutdown is circular: - # FastMCP normally terminates these sessions in that lifespan. - # Use the same SDK transport termination as FastMCP's lifespan, - # while the session manager and its task group are still alive. - for session in tuple(endpoint.session_manager._server_instances.values()): - await session.terminate() - await super()._wait_tasks_to_complete() - - transport = SessionAwareServer( + from infernux_mcp.credentials import publish_credentials + from infernux_mcp.transport_security import EditorTransportSecurity + listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + listener.setsockopt(socket.SOL_SOCKET, + socket.SO_EXCLUSIVEADDRUSE if os.name == "nt" else socket.SO_REUSEADDR, 1) + listener.bind((host, port)) + listener.listen(2048) + listener.setblocking(False) + _, credential_token = publish_credentials(endpoint_url(host=host, port=port)) + except OSError as exc: + listener.close() + shutdown_adapter() + raise RuntimeError("Infernux MCP transport failed before becoming ready") from exc + app = EditorTransportSecurity(mcp.streamable_http_app(), port=port, token=credential_token) + + transport = uvicorn.Server( uvicorn.Config( app, host=str(host), @@ -204,21 +225,22 @@ async def _wait_tasks_to_complete(self) -> None: transport=transport, adapter_shutdown=shutdown_adapter, adapter_begin_shutdown=begin_shutdown_adapter, + credential_token=credential_token, ) def _run() -> None: try: # Capture this generation's transport. Reading a module global # here lets hot reload redirect an old thread to a new server. - transport.run() + transport.run(sockets=[listener]) except BaseException as exc: state.error = exc if not state.stop_requested.is_set(): Debug.log_error(f"Infernux MCP HTTP server stopped: {exc}") + context = copy_context() state.thread = threading.Thread( - target=_run, name="InfernuxMCPHTTP", daemon=True - ) + target=lambda: context.run(_run), name="InfernuxMCPHTTP", daemon=True) install_runtime_service(_RUNTIME_SERVICE_NAME, state) state.thread.start() deadline = time.monotonic() + 5.0 @@ -286,6 +308,9 @@ def _reap_state(state: _ServerState) -> None: if thread is not None and thread is not threading.current_thread(): thread.join() try: + if getattr(state, "transport_contract", 0) == _TRANSPORT_CONTRACT: + from infernux_mcp.credentials import remove_credentials + remove_credentials(endpoint_url(host=state.host, port=state.port), state.credential_token) state.adapter_shutdown() if state.project_path: _remove_discovery_files( @@ -335,6 +360,7 @@ def connection_info(*, host: str | None = None, port: int | None = None) -> dict (state.port if state is not None else PORT) if port is None else int(port) ) url = endpoint_url(host=resolved_host, port=resolved_port) + from infernux_mcp.credentials import credential_path return { "name": SERVER_NAME, "transport": "streamable-http", @@ -343,86 +369,29 @@ def connection_info(*, host: str | None = None, port: int | None = None) -> dict "path": PATH, "url": url, "health_url": health_url(host=resolved_host, port=resolved_port), + "authentication": {"type": "bearer", "token_file": str(credential_path(url))}, "clients": _client_connection_configs(url), } def _client_connection_configs(url: str) -> dict: - return { - "generic": { - "file": "mcp.json", - "format": "mcpServers", - "config": { - "mcpServers": { - "infernux-editor": { - "url": url, - "transport": "streamable-http", - } - } - }, - }, - "cursor": { - "file": ".cursor/mcp.json", - "format": "mcpServers", - "config": { - "mcpServers": { - "infernux-editor": { - "url": url, - "transport": "streamable-http", - } - } - }, - }, - "claude_code": { - "file": ".mcp.json", - "format": "mcpServers", - "config": { - "mcpServers": { - "infernux-editor": { - "type": "http", - "url": url, - } - } - }, - }, - "vscode_copilot": { - "file": ".vscode/mcp.json", - "format": "servers", - "config": { - "servers": { - "infernux-editor": { - "type": "http", - "url": url, - } - } - }, - }, - "trae": { - "file": ".trae/mcp.json", - "format": "mcpServers", - "config": { - "mcpServers": { - "infernux-editor": { - "type": "http", - "url": url, - } - } - }, - }, - "gemini": { - "file": ".gemini/settings.json", - "format": "mcpServers", - "config": { - "mcpServers": { - "infernux-editor": { - "httpUrl": url, - "timeout": 600000, - "trust": False, - } - } - }, - }, - } + bridge = os.path.join(os.path.dirname(__file__), "bridge.py") + command = {"command": sys.executable, "args": [bridge, "--endpoint", url]} + clients = {} + for name, file, root_key, typed in ( + ("generic", "mcp.json", "mcpServers", False), + ("cursor", ".cursor/mcp.json", "mcpServers", False), + ("claude_code", ".mcp.json", "mcpServers", True), + ("vscode_copilot", ".vscode/mcp.json", "servers", True), + ("trae", ".trae/mcp.json", "mcpServers", True), + ("gemini", ".gemini/settings.json", "mcpServers", False), + ): + entry = dict(command) + if typed: + entry["type"] = "stdio" + clients[name] = {"file": file, "format": root_key, + "config": {root_key: {"infernux-editor": entry}}} + return clients def _write_discovery_files(project_path: str, *, host: str, port: int) -> None: @@ -436,16 +405,11 @@ def _write_discovery_files(project_path: str, *, host: str, port: int) -> None: if not root: return info = connection_info(host=host, port=port) - try: - os.makedirs(root, exist_ok=True) - _write_generic_manifest(root, info) - for client_name, client in info["clients"].items(): - if client_name == "generic": - continue + _update_discovery_file(os.path.join(root, "mcp.json"), _write_generic_manifest_file, info) + for client_name, client in info["clients"].items(): + if client_name != "generic": target = os.path.join(root, client["file"]) - _merge_client_json_config(target, client["config"]) - except Exception as exc: - Debug.log_suppressed("infernux_mcp.write_discovery_files", exc) + _update_discovery_file(target, _merge_client_json_config, client["config"]) def _remove_discovery_files( @@ -461,18 +425,20 @@ def _remove_discovery_files( root = resolved_path(project_path or "") if not root: return - try: - _remove_generic_manifest(os.path.join(root, "mcp.json")) - info = connection_info(host=host, port=port) - for client_name, client in info["clients"].items(): - if client_name == "generic": - continue + _update_discovery_file(os.path.join(root, "mcp.json"), _remove_generic_manifest) + info = connection_info(host=host, port=port) + for client_name, client in info["clients"].items(): + if client_name != "generic": target = os.path.join(root, client["file"]) - root_key = next(iter(client["config"]), "") - if root_key: - _remove_json_server(target, root_key, "infernux-editor") - except Exception as exc: - Debug.log_suppressed("infernux_mcp.remove_discovery_files", exc) + root_key = next(iter(client["config"])) + _update_discovery_file(target, _remove_json_server, root_key, "infernux-editor") + + +def _update_discovery_file(path: str, update, *args) -> None: + try: + update(path, *args) + except (OSError, ValueError) as exc: + Debug.log_suppressed(f"infernux_mcp.discovery_file: {path}", exc) def _remove_generic_manifest(path: str) -> None: @@ -520,9 +486,8 @@ def _remove_generated_file(path: str) -> None: pass -def _write_generic_manifest(root: str, info: dict) -> None: +def _write_generic_manifest_file(path: str, info: dict) -> None: generic = info["clients"]["generic"]["config"] - path = os.path.join(root, "mcp.json") data = _read_json_object(path) data["infernux"] = { "name": info["name"], @@ -531,6 +496,7 @@ def _write_generic_manifest(root: str, info: dict) -> None: "port": info["port"], "path": info["path"], "url": info["url"], + "authentication": info["authentication"], } data["clients"] = { name: {"file": client["file"], "format": client["format"]} @@ -563,14 +529,14 @@ def _merge_client_json_config(path: str, config: dict) -> None: def _read_json_object(path: str) -> dict: - if not os.path.isfile(path): - return {} try: with open(path, "r", encoding="utf-8") as f: value = json.load(f) - return value if isinstance(value, dict) else {} - except Exception: + except FileNotFoundError: return {} + if not isinstance(value, dict): + raise ValueError(f"MCP client configuration must be a JSON object: {path}") + return value def _write_json_if_changed(path: str, value: dict) -> None: diff --git a/package/editor/infernux_mcp/session.py b/package/editor/infernux_mcp/session.py index 1f9fa28..8ae3990 100644 --- a/package/editor/infernux_mcp/session.py +++ b/package/editor/infernux_mcp/session.py @@ -101,7 +101,7 @@ def configure(project_path: str, config: dict[str, Any] | None = None) -> McpSes build_profile = str(policy.get("build_profile", "debug_feedback") or "debug_feedback") if build_profile not in VALID_BUILD_PROFILES: build_profile = "debug_feedback" - session_id = str(policy.get("session_id", "") or _new_session_id()) + session_id = checkpoint_store.normalize_checkpoint_id(policy.get("session_id") or _new_session_id()) roots = _normalized_roots(policy.get("allowed_project_roots"), root) if not _is_within_any_root(root, roots): roots.insert(0, root) diff --git a/package/editor/infernux_mcp/supervisor_utils.py b/package/editor/infernux_mcp/supervisor_utils.py index f2c515b..4636854 100644 --- a/package/editor/infernux_mcp/supervisor_utils.py +++ b/package/editor/infernux_mcp/supervisor_utils.py @@ -164,7 +164,8 @@ def _available_port(host: str, preferred: int) -> int: def _port_available(host: str, port: int) -> bool: try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + if os.name == "nt": + sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) sock.bind((host, int(port))) return True except OSError: diff --git a/package/editor/infernux_mcp/transport_security.py b/package/editor/infernux_mcp/transport_security.py new file mode 100644 index 0000000..a384602 --- /dev/null +++ b/package/editor/infernux_mcp/transport_security.py @@ -0,0 +1,32 @@ +"""Authentication and browser boundaries shared by every HTTP route.""" + +import hmac + +from starlette.responses import JSONResponse + + +class EditorTransportSecurity: + def __init__(self, app, *, port: int, token: str): + self.app = app + self.hosts = {f"127.0.0.1:{port}", f"localhost:{port}"} + self.authorization = f"Bearer {token}".encode("ascii") + + async def __call__(self, scope, receive, send): + if scope["type"] == "http": + headers = scope["headers"] + hosts = [value.decode("ascii", errors="replace").lower() for name, value in headers if name.lower() == b"host"] + origins = [value for name, value in headers if name.lower() == b"origin"] + error = None + if len(hosts) != 1 or hosts[0] not in self.hosts: + error = JSONResponse({"error": "Invalid Host"}, status_code=421) + elif origins: + error = JSONResponse({"error": "Browser origins are not allowed"}, status_code=403) + elif scope["path"] != "/health": + authorization = [value for name, value in headers if name.lower() == b"authorization"] + if len(authorization) != 1 or not hmac.compare_digest(authorization[0], self.authorization): + error = JSONResponse({"error": "Authentication required"}, status_code=401, + headers={"WWW-Authenticate": "Bearer"}) + if error is not None: + await error(scope, receive, send) + return + await self.app(scope, receive, send) diff --git a/package/plugin_pages/operations.md b/package/plugin_pages/operations.md index 9911574..52a681e 100644 --- a/package/plugin_pages/operations.md +++ b/package/plugin_pages/operations.md @@ -19,6 +19,21 @@ Player builds and other slow work should go through `operation_job_submit`. Poll ## Python client +The Editor regenerates its `infernux-editor` entries as standard stdio proxy +configurations. Valid JSON configurations retain unrelated servers and settings; +old HTTP entries owned by this plugin are replaced. JSONC, malformed JSON and +non-object documents are left untouched and reported in the Console; other +client files still update. Merge the corresponding `connection_info()["clients"]` +configuration into such a file yourself. Restart the client if it was using an old HTTP +configuration. An existing stdio proxy reads the current credential on every +request and remains usable after an Editor restart on the same port. + +The server binds only to loopback and requires bearer authorization. The Python +client reads its credential from the current user's private state directory, +outside the project. Do not copy credentials into client JSON, Git, process +arguments or environment variables. Browser Origin requests are rejected; +`/health` reports readiness only and is not an MCP client endpoint. + Use the same Python environment as the Editor. From this plugin checkout, add `package/editor` to `PYTHONPATH` (preserving existing entries). For example in Bash: `export PYTHONPATH="$PWD/package/editor${PYTHONPATH:+:$PYTHONPATH}"`. @@ -59,6 +74,9 @@ The connection is local and uses the existing schemas, capability grants, undo paths and session identity. Reusing a connection does not authorize additional actions or suppress client/host confirmation requirements. The CLI never replays a failed call or opens a replacement client to retry it. A timeout or disconnect does not prove a command was cancelled or rolled back; inspect the scene/job before deciding whether to retry. +Completed request results are written before disconnecting. A disconnect error +is reported separately on stderr and causes a nonzero exit status, preserving +the request result on stdout. Long work still belongs in `operation_job_submit` followed by status queries. `--timeout` bounds MCP initialization and each request, not the entire session or idle time waiting for your next input. Network transport cleanup may add time. diff --git a/package/plugin_pages/operations.zh-CN.md b/package/plugin_pages/operations.zh-CN.md index 2f1d3ee..b037d93 100644 --- a/package/plugin_pages/operations.zh-CN.md +++ b/package/plugin_pages/operations.zh-CN.md @@ -19,6 +19,10 @@ ## Python 客户端 +编辑器会把它拥有的 `infernux-editor` 配置重新生成为标准 stdio 代理配置。有效 JSON 中的其他服务器和设置会保留,旧的本插件 HTTP 配置会被替换。JSONC、损坏 JSON 或非对象文档不会被覆盖,Console 会报告问题,其他客户端文件仍会更新;这类文件可按 `connection_info()["clients"]` 中的对应配置手动合入。已使用旧 HTTP 配置的客户端需要重启;现有 stdio 代理每次读取当前凭据,编辑器在同端口重启后仍可继续使用。 + +服务只监听本机,并要求 bearer 认证。Python 客户端会从当前用户的私有状态目录读取凭据,不需要项目文件保存凭据。不要把凭据放进客户端 JSON、Git、进程参数或环境变量。带浏览器 Origin 的请求会被拒绝;`/health` 只报告就绪状态,不能用于 MCP 调用。 + 使用编辑器的同一个 Python 环境。在插件源码目录中,把 `package/editor` 加到 `PYTHONPATH`,保留原有条目;Bash 示例:`export PYTHONPATH="$PWD/package/editor${PYTHONPATH:+:$PYTHONPATH}"`。项目中已安装的插件对应路径为 `Packages/infernux/mcp/editor`。 ```bash @@ -40,6 +44,8 @@ python -m infernux_mcp.client --timeout 30 --timings session 复用连接仍遵守原有 schema、能力白名单、撤销路径、会话身份和确认要求,不代表获得额外授权。CLI 不会重新发出失败命令,也不会新建客户端来重试它。超时或断连不能证明命令已取消或回滚,重试前先查看项目或任务状态。长任务仍应通过 `operation_job_submit` 提交再查询。`--timeout` 限制 MCP 初始化和每次请求,不限制整个会话或等候下一行输入的空闲时间;传输清理可能增加总耗时。 +已完成的请求结果会在断开连接前写入 stdout。断连错误单独写入 stderr,并使退出码为非零;它不会抹掉 stdout 中的请求结果。 + ## 耗时诊断 `--timings` 把 JSON 计时写入 stderr,不包含参数和结果内容。`client_create` 包含传输模块的延迟导入;`connect_initialize` 合并连接与 MCP 初始化;`request` 合并通信、编辑器主线程排队和执行;`serialize` 是本地 JSON 编码,`disconnect` 和 `total` 分别表示清理和 CLI 生命周期。`total` 不包含 Python 解释器/模块启动;比较独立进程时需要进程墙钟时间。客户端计时无法单独区分编辑器排队与执行,应结合错误码、控制台和引擎日志判断。输入、连接初始化和请求阶段的错误会分别标注。 diff --git a/package/plugin_pages/trust.md b/package/plugin_pages/trust.md index 4dc7a46..56a4e1f 100644 --- a/package/plugin_pages/trust.md +++ b/package/plugin_pages/trust.md @@ -4,8 +4,11 @@ This is a local development hook, not a public server. It only binds to localhos ![Local-only access](media/trust_gates.png) -Every call is checked against the operation schema and `ProjectSettings/mcp_capabilities.json`. Scene edits go through the Editor's normal undo stack. +Every call is checked against the operation schema and `ProjectSettings/mcp_capabilities.json`. Read the schema's `reversible` and `side_effects` fields before editing. Commands that declare undo support use the Editor's normal undo stack; saving or reloading files, checkpoint restoration and Player builds are not general undo transactions. Screenshots come from the engine's Scene, Game, or composed Editor render targets, never from the desktop. A few short-lived tokens exist for shutting down the Editor, locking the current project, and talking to a Debug Player. Status calls never return the secret itself. +HTTP requests require a per-user bearer credential. The credential lives under the user state directory, never the project. Standard IDE configurations use a stdio proxy which reads the current credential automatically; direct HTTP clients need authorization. Host checks apply to every route and browser Origin headers are rejected. `/health` is a credential-free readiness probe and exposes no project or owner state. + +Authenticated development access is trusted access, not a sandbox. Writing project Python or building a Player can execute code with the Editor user's privileges. Capability profiles select the intended workflow; they do not isolate code from that user. diff --git a/package/plugin_pages/trust.zh-CN.md b/package/plugin_pages/trust.zh-CN.md index b6f3e9a..3e38f5b 100644 --- a/package/plugin_pages/trust.zh-CN.md +++ b/package/plugin_pages/trust.zh-CN.md @@ -4,8 +4,12 @@ ![仅本机访问](media/trust_gates.png) -每次调用都会核对:有没有这个 operation、参数对不对、项目有没有开这个权限(`ProjectSettings/mcp_capabilities.json`)。改场景走编辑器自己的撤销,不会偷偷改磁盘。 +每次调用都会核对 operation、参数和项目权限(`ProjectSettings/mcp_capabilities.json`)。编辑前阅读 schema 的 `reversible` 与 `side_effects`:声明支持撤销的命令走编辑器自己的撤销栈;保存或重载文件、恢复检查点、构建 Player 不能统一通过撤销回滚。 截图来自引擎的 Scene / Game 画面,不会去抓桌面。 关编辑器、认准当前项目、跟 Debug Player 说话,各有一个短期口令。状态接口不会把口令原文吐出来。 + +HTTP 请求必须携带当前用户的 bearer 凭据。凭据保存在用户状态目录中,不进入项目;IDE 的标准 stdio 代理会自动读取当前凭据,直接连接 HTTP 的客户端需要认证。所有路由都检查 Host,并拒绝带浏览器 Origin 的请求。`/health` 无需凭据,只报告服务是否就绪,不提供项目或所有者信息。 + +认证后的开发权限属于可信访问,不是沙箱。编写项目 Python 或构建 Player 可以使用编辑器用户的权限执行代码。能力配置用于选择工作流,不隔离代码和该用户。 diff --git a/package/requirements.txt b/package/requirements.txt index b60aec6..4f57248 100644 --- a/package/requirements.txt +++ b/package/requirements.txt @@ -1,2 +1,2 @@ -mcp>=1.24,<2 -fastmcp>=3,<4 +mcp>=1.29,<1.30 +fastmcp>=3.4,<3.5 diff --git a/test/test_client_transport.py b/test/test_client_transport.py index df9c3be..34db984 100644 --- a/test/test_client_transport.py +++ b/test/test_client_transport.py @@ -15,6 +15,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "package" / "editor")) from infernux_mcp.client import create_loopback_client +from infernux_mcp.credentials import publish_credentials, remove_credentials +from infernux_mcp.transport_security import EditorTransportSecurity try: from mcp.server.fastmcp import FastMCP @@ -27,25 +29,30 @@ class ClientTransportTests(unittest.TestCase): @classmethod def setUpClass(cls): - cls.cancelled = threading.Event() - mcp = FastMCP("Client Transport Test") + cls.finished = threading.Event() + cls.slow_calls = 0 + mcp = FastMCP("Client Transport Test", stateless_http=True, json_response=True) @mcp.tool() def mcp_ping() -> dict[str, object]: return {"ok": True, "data": "pong"} @mcp.tool() - async def wait_until_cancelled() -> dict[str, object]: + async def slow_query() -> dict[str, object]: + cls.slow_calls += 1 try: - await asyncio.sleep(30) + await asyncio.sleep(1) return {"ok": True} finally: - cls.cancelled.set() + cls.finished.set() cls.sock = socket.socket() cls.sock.bind(("127.0.0.1", 0)) - cls.endpoint = f"http://127.0.0.1:{cls.sock.getsockname()[1]}/mcp" - cls.server = uvicorn.Server(uvicorn.Config(mcp.streamable_http_app(), log_level="error")) + port = cls.sock.getsockname()[1] + cls.endpoint = f"http://127.0.0.1:{port}/mcp" + _, cls.token = publish_credentials(cls.endpoint) + app = EditorTransportSecurity(mcp.streamable_http_app(), port=port, token=cls.token) + cls.server = uvicorn.Server(uvicorn.Config(app, log_level="error")) cls.thread = threading.Thread(target=cls.server.run, kwargs={"sockets": [cls.sock]}, daemon=True) cls.thread.start() deadline = time.monotonic() + 5 @@ -61,6 +68,7 @@ def tearDownClass(cls): cls.sock.close() if cls.thread.is_alive(): raise RuntimeError("Test MCP server did not shut down") + remove_credentials(cls.endpoint, cls.token) def cli(self, *args): env = dict(os.environ) @@ -77,15 +85,18 @@ async def run(): self.assertEqual((await connection.call_tool("mcp_ping", {})).data, {"ok": True, "data": "pong"}) asyncio.run(run()) - def test_request_timeout_does_not_wait_indefinitely_and_server_receives_cancel(self): - self.cancelled.clear() + def test_request_timeout_keeps_failure_reply_without_replaying(self): + self.finished.clear() started = time.monotonic() - with self.cli("--timeout", "0.2", "call", "wait_until_cancelled") as process: - out, _ = process.communicate(timeout=5) + with self.cli("--timeout", "0.2", "call", "slow_query") as process: + out, err = process.communicate(timeout=5) self.assertEqual(process.returncode, 1) + self.assertTrue(out.strip(), err) self.assertEqual(json.loads(out)["error"]["phase"], "request") + self.assertIn("does not replay", json.loads(out)["error"]["hint"]) self.assertLess(time.monotonic() - started, 5) - self.assertTrue(self.cancelled.wait(2), "Server did not receive cancellation") + self.assertTrue(self.finished.wait(2), "Test query did not finish") + self.assertEqual(self.slow_calls, 1) @unittest.skipIf(os.name == "nt", "SIGINT subprocess test is POSIX-specific") def test_interrupt_while_stdin_idle_exits_without_waiting_for_eof(self):