Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(agents): LLM tool-calling — tool registry + ReAct loop (Wave 4a) (#538)
Beenu Arora799ae1b888fb
diff --git a/services/agents/app/agents/tool_loop.py b/services/agents/app/agents/tool_loop.pynew file mode 100644index 000000000..736a9aa1a--- /dev/null+++ b/services/agents/app/agents/tool_loop.py@@ -0,0 +1,72 @@+"""LLM tool-calling loop (Wave 4a).++A minimal, provider-agnostic ReAct loop: bind the registry's tools to the model,+let the model choose which to call, execute the calls, feed results back, and+repeat until the model answers without a tool call (or a cap is hit). This is+the primitive that lets specialist agents *use tools* instead of reasoning over+a single pre-serialised blob.++Bounded + fail-soft: at most ``max_iters`` round-trips; tool errors come back to+the model as structured results (via ToolRegistry.execute) rather than aborting.+"""++from __future__ import annotations++import json+from typing import Any++import structlog+from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage++from app.tools.registry import ToolRegistry++logger = structlog.get_logger()+++async def run_with_tools(+ llm: Any,+ *,+ system: str,+ user: str,+ registry: ToolRegistry,+ max_iters: int = 4,+) -> dict[str, Any]:+ """Run a tool-calling conversation and return the final content + tool trace.++ Returns ``{"content": str, "tool_trace": [...], "iterations": int,+ "truncated": bool}``.+ """+ bound = llm.bind_tools(registry.openai_schemas())+ messages: list[Any] = [SystemMessage(content=system), HumanMessage(content=user)]+ trace: list[dict[str, Any]] = []++ for iteration in range(1, max_iters + 1):+ response = await bound.ainvoke(messages)+ messages.append(response)+ tool_calls = getattr(response, "tool_calls", None) or []+ if not tool_calls:+ return {+ "content": _content(response),+ "tool_trace": trace,+ "iterations": iteration,+ "truncated": False,+ }+ for call in tool_calls:+ name = call.get("name", "")+ args = call.get("args", {}) or {}+ call_id = call.get("id", "") or ""+ result = await registry.execute(name, args)+ trace.append({"tool": name, "args": args, "result_preview": str(result)[:200]})+ messages.append(ToolMessage(content=json.dumps(result, default=str)[:4000], tool_call_id=call_id))++ logger.info("tool_loop.truncated", iterations=max_iters, tools_called=len(trace))+ return {"content": _content(messages[-1]), "tool_trace": trace, "iterations": max_iters, "truncated": True}+++def _content(message: Any) -> str:+ content = getattr(message, "content", "")+ if isinstance(content, str):+ return content+ if isinstance(content, AIMessage): # pragma: no cover - defensive+ return str(content.content)+ return str(content)diff --git a/services/agents/app/tools/registry.py b/services/agents/app/tools/registry.pynew file mode 100644index 000000000..a3987b1fc--- /dev/null+++ b/services/agents/app/tools/registry.py@@ -0,0 +1,110 @@+"""Tool registry for LLM tool-calling (Wave 4a).++Until now no agent used LLM tool-calling: tools were hardcoded Python calls the+code decided to make, and the model only returned a JSON verdict. This registry+exposes AiSOC's real tools (IOC enrichment, MITRE lookup, IOC/technique+extraction, graph blast-radius) as OpenAI-style function schemas so an LLM can+*choose* which to call, and executes the model's selected calls safely.++Design:+* Each ``Tool`` carries a JSON-schema ``parameters`` block (what ``bind_tools``+ ships to the provider) and a callable (sync or async).+* ``execute`` is fail-soft: an unknown tool or a raising tool returns a+ structured ``{"error": ...}`` the model can react to, never an exception that+ aborts the loop.+"""++from __future__ import annotations++import inspect+from collections.abc import Awaitable, Callable+from dataclasses import dataclass+from typing import Any+++@dataclass(frozen=True)+class Tool:+ name: str+ description: str+ parameters: dict[str, Any] # JSON schema for the arguments+ fn: Callable[..., Any] | Callable[..., Awaitable[Any]]++ def openai_schema(self) -> dict[str, Any]:+ return {+ "type": "function",+ "function": {"name": self.name, "description": self.description, "parameters": self.parameters},+ }+++class ToolRegistry:+ def __init__(self, tools: list[Tool] | None = None) -> None:+ self._tools: dict[str, Tool] = {}+ for tool in tools or []:+ self.register(tool)++ def register(self, tool: Tool) -> None:+ self._tools[tool.name] = tool++ def names(self) -> list[str]:+ return sorted(self._tools)++ def openai_schemas(self) -> list[dict[str, Any]]:+ return [t.openai_schema() for t in self._tools.values()]++ async def execute(self, name: str, args: dict[str, Any]) -> Any:+ tool = self._tools.get(name)+ if tool is None:+ return {"error": f"unknown tool: {name}"}+ try:+ result = tool.fn(**(args or {}))+ if inspect.isawaitable(result):+ result = await result+ return result+ except Exception as exc: # noqa: BLE001 — surface tool failure to the model, don't abort+ return {"error": f"{type(exc).__name__}: {exc}"}+++def _str_param(name: str, desc: str) -> dict[str, Any]:+ return {"type": "object", "properties": {name: {"type": "string", "description": desc}}, "required": [name]}+++def default_registry() -> ToolRegistry:+ """Registry of AiSOC's real analyst tools, wrapped for LLM tool-calling."""+ from app.investigator.tools import enrich_ioc, extract_iocs, map_to_mitre+ from app.tools.mitre import lookup_technique++ return ToolRegistry(+ [+ Tool(+ name="extract_iocs",+ description="Extract IOCs (IPs, domains, hashes, URLs) from free text.",+ parameters=_str_param("text", "The text to scan for indicators of compromise."),+ fn=lambda text: extract_iocs(text),+ ),+ Tool(+ name="map_to_mitre",+ description="Map free text describing behaviour to MITRE ATT&CK technique IDs.",+ parameters=_str_param("text", "The behaviour description to map to ATT&CK techniques."),+ fn=lambda text: map_to_mitre(text),+ ),+ Tool(+ name="lookup_technique",+ description="Look up a MITRE ATT&CK technique by ID (e.g. T1110).",+ parameters=_str_param("technique_id", "The ATT&CK technique ID, e.g. T1059.001."),+ fn=lambda technique_id: lookup_technique(technique_id),+ ),+ Tool(+ name="enrich_ioc",+ description="Enrich a single IOC (ip|domain|hash|url) with threat intelligence.",+ parameters={+ "type": "object",+ "properties": {+ "ioc_value": {"type": "string", "description": "The IOC value."},+ "ioc_type": {"type": "string", "enum": ["ip", "domain", "hash", "url"]},+ },+ "required": ["ioc_value", "ioc_type"],+ },+ fn=lambda ioc_value, ioc_type: enrich_ioc(ioc_value, ioc_type),+ ),+ ]+ )diff --git a/services/agents/tests/test_tool_calling.py b/services/agents/tests/test_tool_calling.pynew file mode 100644index 000000000..835a1b5a7--- /dev/null+++ b/services/agents/tests/test_tool_calling.py@@ -0,0 +1,77 @@+"""Wave 4a — LLM tool-calling: the registry exposes real tools and the loop+executes the model's selected calls, feeds results back, and terminates."""++from __future__ import annotations++from types import SimpleNamespace++import pytest+from app.agents.tool_loop import run_with_tools+from app.tools.registry import Tool, ToolRegistry, default_registry+++class _FakeLLM:+ """Scripted chat model exposing bind_tools + ainvoke."""++ def __init__(self, script: list) -> None:+ self._script = script+ self.calls = 0+ self.bound_tools = None++ def bind_tools(self, tools):+ self.bound_tools = tools+ return self++ async def ainvoke(self, _messages):+ resp = self._script[min(self.calls, len(self._script) - 1)]+ self.calls += 1+ return resp+++def _tool_call(name, args, cid="c1"):+ return SimpleNamespace(content="", tool_calls=[{"name": name, "args": args, "id": cid}])+++def _final(text):+ return SimpleNamespace(content=text, tool_calls=[])+++def test_registry_exposes_openai_schemas():+ reg = default_registry()+ schemas = reg.openai_schemas()+ names = {s["function"]["name"] for s in schemas}+ assert {"extract_iocs", "map_to_mitre", "lookup_technique", "enrich_ioc"} <= names+ assert all(s["type"] == "function" for s in schemas)+++async def test_registry_execute_runs_real_tool_and_handles_unknown():+ reg = default_registry()+ iocs = await reg.execute("extract_iocs", {"text": "beacon to evil.example and 45.9.148.99"})+ assert isinstance(iocs, list)+ # Unknown tool fails soft.+ err = await reg.execute("nope", {})+ assert "error" in err+++async def test_tool_loop_executes_selected_tool_then_answers():+ reg = default_registry()+ llm = _FakeLLM([_tool_call("extract_iocs", {"text": "45.9.148.99 and evil.example"}), _final("Two IOCs found.")])+ out = await run_with_tools(llm, system="You are an analyst.", user="Find IOCs.", registry=reg)+ assert out["truncated"] is False+ assert out["content"] == "Two IOCs found."+ assert out["iterations"] == 2+ assert any(t["tool"] == "extract_iocs" for t in out["tool_trace"])+ assert llm.bound_tools is not None # tools were bound to the model+++async def test_tool_loop_is_bounded_by_max_iters():+ # A model that always asks for a tool must not loop forever.+ reg = ToolRegistry([Tool(name="noop", description="noop", parameters={"type": "object", "properties": {}}, fn=lambda: {"ok": True})])+ llm = _FakeLLM([_tool_call("noop", {})]) # always returns a tool call+ out = await run_with_tools(llm, system="s", user="u", registry=reg, max_iters=3)+ assert out["truncated"] is True+ assert out["iterations"] == 3+ assert len(out["tool_trace"]) == 3