# ARIA-X

> Запустите ARIA-X на NotHoly через OpenAI-совместимый провайдер, затем добавьте CKE 2.0 и инструменты небольшим мостом.


[ARIA-X](https://github.com/01NGVI-QINGYI/ARIA-X) — это local-first движок для исследований по безопасности, написанный только на стандартной библиотеке. Он берёт модель из OpenAI-совместимого провайдера, поэтому работает на NotHoly с base URL и вашим ключом. Для инференса ничего специфичного для NotHoly не нужно.

ARIA-X работает в Linux и macOS с CPython 3.11 или новее. В его документации Windows отмечен как непроверенный, а локальная песочница запускает команды через bash, поэтому в Windows установите WSL 2 и выполняйте шаги для Linux внутри него.

Скачайте код и создайте начальную конфигурацию. Лаунчер `./aria-x` сам находит подходящий Python и задаёт путь импорта, так что `pip install` не нужен.

```bash
git clone https://github.com/01NGVI-QINGYI/ARIA-X.git
cd ARIA-X
./aria-x init
```

`init` создаёт `configs/aria-x.toml`. Заполните в нём блок `[scope]` целями вашей лаборатории, как описано в README ARIA-X, затем задайте блок `[llm]`:

```toml
[llm]
provider = "openai"
base_url = "https://api.notholy.com/v1"
model = "notholy-specter"
```

Положите ключ в окружение и проверьте соединение. `export` действует до конца сессии; чтобы ключ сохранился, добавьте строку в `~/.bashrc` (bash, в том числе в WSL) или `~/.zshrc` (zsh, оболочка по умолчанию в macOS).

```bash
export ARIA_X_API_KEY="nh_live_..."
./aria-x doctor --llm
```

В `model` подходит любой ID модели из каталога. Список выдаёт `GET /v1/models`; контекстное окно указано там как `context_length` (1048576 для `notholy-specter`).

Те же OpenAI-совместимые значения, `provider = "openai"`, base URL `https://api.notholy.com/v1` и ваш ключ, направляют ARIA-X на NotHoly, хоть из файла конфигурации, хоть через переменные окружения `ARIA_X_PROVIDER` / `ARIA_X_BASE_URL` / `ARIA_X_MODEL`.

## 5% дополнительного кредита

Пополните баланс в [консоли](https://notholy.com/ru/console/billing), откройте поле купона в диалоге пополнения и введите `ARIAX`. Бонус 5% зачисляется на баланс после подтверждения платежа. Код действует до 30 ноября 2026 года; уже зачисленные кредиты не сгорают.

## Добавьте CKE 2.0 и инструменты

Настройка выше даёт только инференс. ARIA-X работает с фиксированным набором встроенных инструментов и не имеет MCP-клиента, поэтому блок JSON `mcpServers`, который используют другие клиенты, здесь не применяется. Чтобы дать его агентам поиск CVE, поиск по CKE 2.0, бюллетени, веб-поиск и чтение URL, запускайте ARIA-X через небольшой мост ниже. Он читает список инструментов с MCP-эндпоинта NotHoly, оборачивает каждый как нативный инструмент ARIA-X, передаёт их исследовательским ролям и затем запускает ARIA-X как обычно.

Сохраните его в корне клона ARIA-X как `notholy_mcp_tools.py`:

```python
#!/usr/bin/env python3
"""Give ARIA-X the NotHoly MCP tools (CVE lookup, CKE 2.0 search, web, advisories).

ARIA-X ships a fixed, in-process tool set and has no MCP client of its own. This
launcher adds NotHoly's hosted tools to a run without forking ARIA-X: it reads the
tool list from the NotHoly MCP endpoint, wraps each one as a native ARIA-X tool, and
hands the agents those tools alongside the built-ins. Then it starts ARIA-X normally.

Usage (same arguments as `aria-x`):
    export ARIA_X_API_KEY="<your NotHoly key>"   # the model key doubles as the MCP key
    PYTHONPATH="$PWD/src" python3 notholy_mcp_tools.py run --goal "..." --config configs/aria-x.toml

Standard library only. Tested against ARIA-X v0.1.x; the modules it patches are
unchanged in v0.2.1.
"""
from __future__ import annotations

import json
import os
import sys
import urllib.request
from typing import Any

MCP_URL = os.environ.get("NOTHOLY_MCP_URL", "https://api.notholy.com/mcp")
API_KEY = os.environ.get("NOTHOLY_API_KEY") or os.environ.get("ARIA_X_API_KEY") or ""

# Read-only knowledge and research tools (no traffic to the engagement target), so
# they do not need Scope approval. Raise the risk here if you expose active tools.
_RISK = "low"


class MCPClient:
    """A minimal MCP client over Streamable HTTP (JSON-RPC 2.0 + Bearer)."""

    def __init__(self, url: str, api_key: str, timeout: float = 60.0) -> None:
        self.url = url
        self.api_key = api_key
        self.timeout = timeout
        self.session_id = ""
        self._id = 0

    def _call(self, method: str, params: dict[str, Any] | None = None, notify: bool = False) -> Any:
        body: dict[str, Any] = {"jsonrpc": "2.0", "method": method}
        if params is not None:
            body["params"] = params
        if not notify:
            self._id += 1
            body["id"] = self._id
        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json, text/event-stream",
            "Authorization": f"Bearer {self.api_key}",
        }
        if self.session_id:
            headers["Mcp-Session-Id"] = self.session_id
        req = urllib.request.Request(self.url, data=json.dumps(body).encode(), headers=headers)
        with urllib.request.urlopen(req, timeout=self.timeout) as resp:
            sid = resp.headers.get("Mcp-Session-Id")
            if sid:
                self.session_id = sid
            raw = resp.read().decode("utf-8", "replace")
        if notify:
            return None
        payload = _parse_jsonrpc(raw)
        if "error" in payload:
            raise RuntimeError(f"MCP {method} failed: {payload['error']}")
        return payload.get("result")

    def handshake(self) -> None:
        self._call("initialize", {
            "protocolVersion": "2025-06-18",
            "capabilities": {},
            "clientInfo": {"name": "aria-x-notholy", "version": "1"},
        })
        self._call("notifications/initialized", notify=True)

    def list_tools(self) -> list[dict[str, Any]]:
        return list((self._call("tools/list") or {}).get("tools", []))

    def call_tool(self, name: str, arguments: dict[str, Any]) -> str:
        result = self._call("tools/call", {"name": name, "arguments": arguments}) or {}
        parts = [c.get("text", "") for c in result.get("content", []) if c.get("type") == "text"]
        text = "\n".join(p for p in parts if p) or json.dumps(result, ensure_ascii=False)
        if result.get("isError"):
            raise RuntimeError(text)
        return text


def _parse_jsonrpc(raw: str) -> dict[str, Any]:
    """Accept a plain JSON body or an SSE stream and return the JSON-RPC object."""
    raw = raw.strip()
    if raw.startswith("{"):
        return json.loads(raw)
    data_lines = [ln[5:].strip() for ln in raw.splitlines() if ln.startswith("data:")]
    for chunk in reversed(data_lines):  # the last data frame carries the result
        try:
            obj = json.loads(chunk)
        except json.JSONDecodeError:
            continue
        if isinstance(obj, dict) and ("result" in obj or "error" in obj):
            return obj
    raise RuntimeError(f"no JSON-RPC payload in MCP response: {raw[:200]}")


def _make_tool(client: MCPClient, tool: dict[str, Any]):
    """Wrap one MCP tool as an ARIA-X FunctionTool (spec + handler)."""
    from aria_x.tools.base import ToolResult, ToolSpec

    name = f"notholy_{tool['name']}"
    schema = tool.get("inputSchema") or {"type": "object", "properties": {}}
    spec = ToolSpec(
        name=name,
        description=(tool.get("description") or f"NotHoly {tool['name']}").strip(),
        parameters=schema,
        risk=_RISK,
        requires_scope=False,
        read_only=True,
        tags=("notholy", "knowledge"),
    )

    def run(ctx: Any, args: dict[str, Any]) -> "ToolResult":
        try:
            return ToolResult.success(text=client.call_tool(tool["name"], dict(args or {})))
        except Exception as exc:  # keep the run alive; surface the error to the model
            return ToolResult.failure(f"notholy tool '{tool['name']}' failed: {exc}")

    return spec, run


def install(client: MCPClient) -> list[str]:
    """Register the MCP tools in ARIA-X's registry and offer them to the agents."""
    import aria_x.agents.roles as roles
    import aria_x.tools.builtin as builtin

    wrapped = [_make_tool(client, t) for t in client.list_tools()]
    names = [spec.name for spec, _ in wrapped]
    if not names:
        return []

    base_build = builtin.build_registry

    def build_registry(ctx=None):
        registry = base_build(ctx)
        for spec, fn in wrapped:
            registry.add(spec, fn)
        return registry

    builtin.build_registry = build_registry

    # Role specs read these module tuples at build time; a tool not listed for a
    # role is never offered to it. Hand the knowledge tools to the researchers,
    # the worker and the planner.
    extra = tuple(names)
    roles.WORKER_TOOLS = tuple(dict.fromkeys(roles.WORKER_TOOLS + extra))
    roles.PLANNER_TOOLS = tuple(dict.fromkeys(roles.PLANNER_TOOLS + extra))
    roles.SPECIALIST_TOOLS = dict(roles.SPECIALIST_TOOLS)
    roles.SPECIALIST_TOOLS["researcher"] = tuple(
        dict.fromkeys(roles.SPECIALIST_TOOLS["researcher"] + extra)
    )
    return names


def main() -> int:
    if not API_KEY:
        sys.exit("set NOTHOLY_API_KEY (or ARIA_X_API_KEY) before running")
    client = MCPClient(MCP_URL, API_KEY)
    client.handshake()
    added = install(client)
    print(f"[notholy] added {len(added)} tool(s): {', '.join(added) or '(none)'}", file=sys.stderr)

    from aria_x.cli import main as aria_main
    return aria_main(sys.argv[1:])


if __name__ == "__main__":
    raise SystemExit(main())
```

Запускайте из корня клона с теми же аргументами, что и `aria-x`. `PYTHONPATH` позволяет мосту импортировать ARIA-X без установки, а `python3` должен быть версии 3.11 или новее (проверьте через `python3 --version`):

```bash
export ARIA_X_API_KEY="nh_live_..."
PYTHONPATH="$PWD/src" python3 notholy_mcp_tools.py run --goal "..." --config configs/aria-x.toml
```

API = инференс; мост = CKE 2.0 + инструменты. Один ключ покрывает оба. В [руководстве по MCP](/ru/mcp/connect) описан каждый инструмент и подключение клиентов, которые уже говорят на MCP.

## Что дальше

- [Модели](/ru/getting-started/models)
