Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand All @@ -49,15 +49,15 @@ 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;
`reset_statistics` starts a new measurement interval. Enable `profiling` explicitly
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

Expand Down
8 changes: 4 additions & 4 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`,减少通信往返。

Expand All @@ -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` 获取。这些操作需要配套的引擎宿主。

## 仓库说明

Expand Down
18 changes: 12 additions & 6 deletions package/editor/infernux_mcp/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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))
Expand All @@ -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()
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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(
Expand Down
19 changes: 19 additions & 0 deletions package/editor/infernux_mcp/bridge.py
Original file line number Diff line number Diff line change
@@ -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()
5 changes: 5 additions & 0 deletions package/editor/infernux_mcp/capabilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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:
Expand Down
35 changes: 26 additions & 9 deletions package/editor/infernux_mcp/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down Expand Up @@ -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():
Expand Down Expand Up @@ -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
Expand Down
108 changes: 108 additions & 0 deletions package/editor/infernux_mcp/credentials.py
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading