# ARIA-X

> Corre ARIA-X en NotHoly con el proveedor OpenAI-compatible y luego agrega CKE 2.0 y las herramientas con un puente pequeño.


[ARIA-X](https://github.com/01NGVI-QINGYI/ARIA-X) es un motor de investigación de seguridad local-first, hecho solo con la biblioteca estándar. Lee su modelo desde un proveedor compatible con OpenAI, así que corre en NotHoly con una URL base y tu clave. No hace falta nada específico de NotHoly para la inferencia.

ARIA-X corre en Linux y macOS con CPython 3.11 o posterior. Su documentación marca Windows como no verificado, y el sandbox local ejecuta comandos con bash, así que en Windows instala WSL 2 y sigue los pasos de Linux dentro de él.

Descarga el código y genera una config inicial. El launcher `./aria-x` encuentra un Python adecuado y ajusta la ruta de import, así que no hace falta `pip install`.

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

`init` escribe `configs/aria-x.toml`. Completa su bloque `[scope]` con los objetivos de tu lab, como describe el README de ARIA-X, y luego ajusta el bloque `[llm]`:

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

Pon tu clave en el entorno y prueba la conexión. `export` dura lo que la sesión; para conservarla, agrega la línea a `~/.bashrc` (bash, también en WSL) o a `~/.zshrc` (zsh, el shell por defecto de macOS).

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

Cualquier ID de modelo del catálogo sirve en `model`. Lístalos con `GET /v1/models`; la ventana de contexto aparece ahí como `context_length` (1048576 para `notholy-specter`).

Los mismos valores compatibles con OpenAI, `provider = "openai"`, URL base `https://api.notholy.com/v1` y tu clave, apuntan ARIA-X a NotHoly, ya sea desde el archivo de config o desde las variables de entorno `ARIA_X_PROVIDER` / `ARIA_X_BASE_URL` / `ARIA_X_MODEL`.

## 5% de crédito extra

Agrega crédito en la [consola](https://notholy.com/es/console/billing), abre el campo de cupón en el diálogo de depósito e ingresa `ARIAX`. El bono del 5% entra al saldo una vez confirmado el pago. El código es válido hasta el 30 de noviembre de 2026; los créditos ya acreditados no vencen.

## Agrega CKE 2.0 y las herramientas

La configuración anterior es solo inferencia. ARIA-X corre un conjunto fijo de herramientas internas y no tiene cliente MCP, así que el bloque JSON `mcpServers` que usan otros clientes no aplica aquí. Para darle a sus agentes consulta de CVEs, búsqueda en CKE 2.0, advisories, búsqueda web y lectura de URL, corre ARIA-X con el puente pequeño de abajo. Lee la lista de herramientas desde el endpoint MCP de NotHoly, envuelve cada una como herramienta nativa de ARIA-X, se las entrega a los roles de investigación y luego inicia ARIA-X de forma normal.

Guárdalo en la raíz del checkout de ARIA-X como `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())
```

Córrelo desde la raíz del checkout con los mismos argumentos que le pasarías a `aria-x`. `PYTHONPATH` permite que el puente importe ARIA-X sin instalarlo, y `python3` debe ser 3.11 o posterior (compruébalo con `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 = inferencia; el puente = CKE 2.0 + herramientas. Una clave cubre ambos. La [guía de MCP](/es/mcp/connect) explica cada herramienta y conecta los clientes que ya hablan MCP.

## Siguientes pasos

- [Modelos](/es/getting-started/models)
