Download code/src/agents/tools.py from DuyTa/cve-kgrag-db: direct link, hf CLI and curl.
- Browser
- Download file 15.9 kB
-
https://huggingface.co/datasets/DuyTa/cve-kgrag-db/resolve/main/code/src/agents/tools.py
- Command line
-
hf download hf://datasets/DuyTa/cve-kgrag-db/code/src/agents/tools.py
-
curl -L -o tools.py https://huggingface.co/datasets/DuyTa/cve-kgrag-db/resolve/main/code/src/agents/tools.py
15.9 kB
| """ | |
| Agent tools for CVE-KGRAG. | |
| Five tools exposed to the agent: | |
| 1. search(query, collections, k, severity, year, is_in_kev) — unified Qdrant hybrid search (parallel) | |
| 2. explore_kg(node_id, node_label, hops) — Neo4j graph traversal from any node label | |
| 3. find_similar_cves(cve_id, k) — Neo4j CVE similarity scoring | |
| 4. translate_symptom(symptom_text) — LLM + cheat-sheet: symptom → {techniques, cwes, keywords} | |
| 5. search_web(query) — optional web search (Tavily) | |
| Tools are created via factories because they need runtime dependencies | |
| (rag_system, graph_service, llm_client, cheat_sheet) injected at startup. | |
| """ | |
| from __future__ import annotations | |
| import asyncio | |
| import concurrent.futures | |
| import logging | |
| from typing import Any | |
| from src.agents.agent_config import AGENT_DEFAULT_K, AGENT_SEARCH_TIMEOUT | |
| logger = logging.getLogger(__name__) | |
| def _format_search_results(results: list[dict], max_per_result: int = 300) -> str: | |
| if not results: | |
| return "No results found." | |
| lines = [] | |
| for i, r in enumerate(results, 1): | |
| meta = r.get("metadata", {}) | |
| cve_id = meta.get("cve_id", "") | |
| tech_id = meta.get("technique_id", "") | |
| capec_id = meta.get("capec_id", "") | |
| cwe_id = meta.get("cwe_id", "") | |
| ids = [x for x in [cve_id, tech_id, capec_id, cwe_id] if x] | |
| id_str = ids[0] if ids else r.get("id", "?") | |
| severity = meta.get("severity", "") | |
| cvss = meta.get("cvss_score", "") | |
| text = (r.get("text", "") or "")[:max_per_result] | |
| score = r.get("score", 0.0) | |
| meta_parts = [] | |
| if severity: | |
| meta_parts.append(f"severity={severity}") | |
| if cvss: | |
| meta_parts.append(f"CVSS={cvss}") | |
| meta_str = f" ({', '.join(meta_parts)})" if meta_parts else "" | |
| lines.append(f"[{i}] {id_str}{meta_str} score={score:.3f}\n{text}") | |
| return "\n\n".join(lines) | |
| def _search_single_collection( | |
| rag_system: Any, query: str, collection: str, k: int, | |
| filters: dict | None = None, | |
| ) -> list[dict]: | |
| """Search a single Qdrant collection (runs in thread pool for parallelism).""" | |
| try: | |
| return rag_system.search(query, n_results=k, collection=collection, filters=filters) | |
| except Exception as e: | |
| logger.warning("Search failed for %s: %s", collection, e) | |
| return [] | |
| def create_search_tool(rag_system: Any): | |
| """ | |
| Create the unified search tool. | |
| Searches ALL requested collections in parallel via ThreadPoolExecutor. | |
| Merges and deduplicates results from all collections. | |
| """ | |
| from langchain_core.tools import tool as lc_tool | |
| valid_collections = {"cve", "mitre", "capec", "cwe"} | |
| def search( | |
| query: str, | |
| collections: list[str] = ["cve"], | |
| k: int = AGENT_DEFAULT_K, | |
| severity: str | None = None, | |
| year: str | None = None, | |
| is_in_kev: bool | None = None, | |
| ) -> str: | |
| """Search CVE vulnerability knowledge bases across multiple collections in parallel. | |
| Available collections: | |
| 'cve' - CVE vulnerability entries (descriptions, CVSS scores, affected products) | |
| 'mitre' - MITRE ATT&CK techniques (T-codes like T1059, procedures) | |
| 'capec' - CAPEC attack patterns (CAPEC-IDs, attack vector descriptions) | |
| 'cwe' - CWE weakness types (CWE-IDs, weakness taxonomy) | |
| Use 'cve' alone for most queries. Add others when the user mentions | |
| techniques, attack patterns, or weakness types. | |
| Optional filters (apply to 'cve' collection only): | |
| severity - CRITICAL / HIGH / MEDIUM / LOW | |
| year - e.g. "2024" | |
| is_in_kev - True to restrict to Known Exploited Vulnerabilities | |
| """ | |
| collections = [c for c in collections if c in valid_collections] | |
| if not collections: | |
| collections = ["cve"] | |
| filters: dict | None = None | |
| raw_filters = { | |
| "severity": severity, | |
| "year": year, | |
| "is_in_kev": is_in_kev, | |
| } | |
| active = {fk: fv for fk, fv in raw_filters.items() if fv is not None} | |
| if active: | |
| filters = active | |
| all_results: list[dict] = [] | |
| if len(collections) == 1: | |
| all_results = list(_search_single_collection(rag_system, query, collections[0], k * 2, filters)) | |
| else: | |
| with concurrent.futures.ThreadPoolExecutor(max_workers=len(collections)) as executor: | |
| futures = { | |
| executor.submit( | |
| _search_single_collection, rag_system, query, col, k * 2, | |
| filters if col == "cve" else None, | |
| ): col | |
| for col in collections | |
| } | |
| try: | |
| for future in concurrent.futures.as_completed(futures, timeout=AGENT_SEARCH_TIMEOUT): | |
| col = futures[future] | |
| try: | |
| results = future.result() | |
| all_results.extend(results) | |
| except Exception as e: | |
| logger.warning("Search failed for %s: %s", col, e) | |
| except concurrent.futures.TimeoutError: | |
| logger.warning("Parallel search timed out after %.0fs — using partial results (%d)", AGENT_SEARCH_TIMEOUT, len(all_results)) | |
| all_results.sort(key=lambda x: x.get("score", 0), reverse=True) | |
| unique = [] | |
| seen = set() | |
| for r in all_results: | |
| rid = r.get("id", "") | |
| if rid not in seen: | |
| seen.add(rid) | |
| unique.append(r) | |
| return _format_search_results(unique[:k]) | |
| return search | |
| def create_explore_kg_tool(graph_service: Any): | |
| """ | |
| Create the Neo4j knowledge graph explorer tool. | |
| Supports any node label as the traversal seed (CVE, CWE, Product, Technique, | |
| Tactic, CAPEC, Vendor), not just CVE. Falls back to empty string gracefully. | |
| """ | |
| from langchain_core.tools import tool as lc_tool | |
| def explore_kg(node_id: str, node_label: str = "CVE", hops: int = 1) -> str: | |
| """Explore the Neo4j knowledge graph starting from any node. | |
| node_label must be one of: CVE, CWE, CAPEC, Technique, Tactic, Product, Vendor. | |
| Use when: | |
| - User asks "what CVEs relate to CVE-X" → node_label="CVE" | |
| - User asks "CVEs affecting Apache Struts" → node_label="Product" | |
| - User asks "CVEs mapped to T1190" → node_label="Technique" | |
| - User asks "CVEs in tactic TA0001" → node_label="Tactic" | |
| - User asks "CVEs with CWE-79 weakness" → node_label="CWE" | |
| - User asks "CVEs using CAPEC-66 pattern" → node_label="CAPEC" | |
| Returns empty string if no graph data is found. | |
| """ | |
| if graph_service is None: | |
| return "" | |
| valid_labels = {"CVE", "CWE", "CAPEC", "Technique", "Tactic", "Product", "Vendor"} | |
| if node_label not in valid_labels: | |
| return f"Unknown node_label {node_label!r}. Must be one of: {', '.join(sorted(valid_labels))}" | |
| try: | |
| subgraph = graph_service.subgraph_from_nodes( | |
| [{"label": node_label, "id": node_id}], hops=hops | |
| ) | |
| nodes = subgraph.get("nodes", []) | |
| edges = subgraph.get("edges", []) | |
| if not nodes and not edges: | |
| # Try cves_for_node as fallback (non-CVE seeds often need direct query) | |
| if node_label != "CVE": | |
| cves = graph_service.cves_for_node(node_label, node_id, k=10) | |
| if cves: | |
| lines = [f"CVEs connected to {node_label} {node_id!r}:"] | |
| for c in cves: | |
| cvss = f" CVSS={c['cvss']}" if c.get("cvss") else "" | |
| lines.append(f" {c['id']}{cvss}") | |
| return "\n".join(lines) | |
| return "" | |
| by_label: dict[str, list[str]] = {} | |
| for n in nodes: | |
| lbl = n.get("label", "Unknown") | |
| nid = n.get("id") or n.get("name") or "?" | |
| by_label.setdefault(lbl, []).append(str(nid)) | |
| parts = [f"Knowledge Graph — {node_label} {node_id!r}:"] | |
| for lbl, ids in by_label.items(): | |
| parts.append(f" {lbl}: {', '.join(ids[:12])}") | |
| if edges: | |
| edge_summ: dict[str, int] = {} | |
| for e in edges: | |
| rtype = e.get("type", "RELATED_TO") | |
| edge_summ[rtype] = edge_summ.get(rtype, 0) + 1 | |
| parts.append("Relationships: " + ", ".join( | |
| f"{count}× {rtype}" for rtype, count in edge_summ.items() | |
| )) | |
| return "\n".join(parts) | |
| except Exception as e: | |
| logger.warning("KG explore failed for %s %s: %s", node_label, node_id, e) | |
| return "" | |
| return explore_kg | |
| # Keep old name as alias for any external callers | |
| create_traverse_kg_tool = create_explore_kg_tool | |
| def create_web_search_tool(): | |
| """ | |
| Create the web search tool (optional, requires Tavily API key). | |
| Gracefully returns a message if not configured. | |
| """ | |
| from langchain_core.tools import tool as lc_tool | |
| from src.agents.agent_config import WEB_SEARCH_ENABLED | |
| _tavily_available = False | |
| try: | |
| from langchain_community.tools.tavily_search import TavilySearchResults | |
| _tavily_available = True | |
| except ImportError: | |
| pass | |
| if not _tavily_available or not WEB_SEARCH_ENABLED: | |
| def search_web(query: str) -> str: | |
| """Search the web for recent exploit/POC information. Currently disabled.""" | |
| return "Web search is not configured. Set WEB_SEARCH_ENABLED=true and install langchain-community with Tavily API key." | |
| return search_web | |
| def search_web(query: str) -> str: | |
| """Search the web for recent exploits, POC code, or latest vulnerability news. | |
| Use when the user asks about exploits, proof-of-concept code, zero-day | |
| vulnerabilities, or very recent CVEs not yet in the local database. | |
| """ | |
| try: | |
| tool = TavilySearchResults(max_results=3, search_depth="advanced") | |
| results = tool.invoke(query) | |
| lines = ["[Web search results:]"] | |
| for i, r in enumerate(results, 1): | |
| lines.append(f"[{i}] {r.get('title', '?')}\n{r.get('content', '')[:300]}\n{r.get('url', '')}") | |
| return "\n\n".join(lines) | |
| except Exception as e: | |
| logger.warning("Web search failed: %s", e) | |
| return f"Web search failed: {e}" | |
| return search_web | |
| def create_find_similar_cves_tool(graph_service: Any): | |
| """ | |
| Create the similar-CVE lookup tool. | |
| Queries Neo4j for CVEs sharing CWE / product / tactic with the given CVE. | |
| Returns empty string when graph_service is unavailable or no results found. | |
| """ | |
| from langchain_core.tools import tool as lc_tool | |
| def find_similar_cves(cve_id: str, k: int = 5) -> str: | |
| """Find CVEs similar to the given one based on shared weaknesses, affected products, or tactics. | |
| Use when the user asks: | |
| - "what CVEs are similar to CVE-X?" | |
| - "CVEs related to CVE-X" | |
| - "find vulnerabilities like CVE-X" | |
| Returns empty string if no graph data is available. | |
| """ | |
| if graph_service is None: | |
| return "" | |
| try: | |
| results = graph_service.similar_cves(cve_id, k=k) | |
| if not results: | |
| return f"No similar CVEs found for {cve_id} in the knowledge graph." | |
| lines = [f"CVEs similar to {cve_id}:"] | |
| for r in results: | |
| lines.append( | |
| f" - {r['cve_id']} (via shared {r['shared_type']}, score={r['score']})" | |
| ) | |
| return "\n".join(lines) | |
| except Exception as e: | |
| logger.warning("similar_cves failed for %s: %s", cve_id, e) | |
| return "" | |
| return find_similar_cves | |
| def create_translate_symptom_tool(llm_client: Any, cheat_sheet: Any = None): | |
| """ | |
| Create the symptom-to-CTI-entity translation tool. | |
| Uses cheat-sheet hints for grounding + LLM to map free-text observations | |
| (log lines, behavioral symptoms) to MITRE techniques, CWE IDs, and keywords. | |
| Returns JSON string: {"techniques": [...], "cwes": [...], "keywords": [...]}. | |
| """ | |
| import json as _json | |
| from langchain_core.tools import tool as lc_tool | |
| from src.agents.prompts import TRANSLATE_SYMPTOM_PROMPT | |
| from src.agents.tracing import traced_llm_call | |
| def _parse_json_safely(text: str, default: dict) -> dict: | |
| import re | |
| text = (text or "").strip() | |
| for prefix in ("```json", "```"): | |
| if text.startswith(prefix): | |
| text = text[len(prefix):] | |
| if text.endswith("```"): | |
| text = text[:-3] | |
| text = text.strip() | |
| try: | |
| return _json.loads(text) | |
| except _json.JSONDecodeError: | |
| try: | |
| m = re.search(r'\{.*\}', text, re.DOTALL) | |
| if m: | |
| return _json.loads(m.group()) | |
| except (_json.JSONDecodeError, AttributeError): | |
| pass | |
| return default | |
| def translate_symptom(symptom_text: str) -> str: | |
| """Translate a free-text security symptom or log observation into MITRE techniques, | |
| CWE IDs, and search keywords. | |
| Use FIRST when the user describes observed behavior without mentioning a CVE-ID, | |
| product name, or CWE-ID. Examples: | |
| - "process spawning powershell.exe with base64-encoded args from outlook" | |
| - "server files are encrypted with ransom note left behind" | |
| - "unauthenticated read of /etc/passwd via crafted URL parameter" | |
| Returns JSON: {"techniques": ["T1059", ...], "cwes": ["CWE-78", ...], "keywords": [...]} | |
| Use the returned techniques/CWEs as inputs to explore_kg; use keywords for search(). | |
| """ | |
| if llm_client is None: | |
| return '{"techniques": [], "cwes": [], "keywords": []}' | |
| hint_block = "" | |
| if cheat_sheet is not None: | |
| try: | |
| hints = cheat_sheet.entity_to_hints(symptom_text) | |
| hint_block = cheat_sheet.render_hint_block(hints) or "" | |
| except Exception: | |
| pass | |
| prompt = TRANSLATE_SYMPTOM_PROMPT.format( | |
| symptom=symptom_text, | |
| hints=hint_block or "(no taxonomy hints available)", | |
| ) | |
| try: | |
| with traced_llm_call( | |
| llm_client, prompt, "translate_symptom", | |
| system_prompt="Answer in JSON only.", max_tokens=300, | |
| ) as gen: | |
| raw = gen() | |
| parsed = _parse_json_safely(raw, {"techniques": [], "cwes": [], "keywords": []}) | |
| return _json.dumps(parsed) | |
| except Exception as e: | |
| logger.warning("translate_symptom failed: %s", e) | |
| return '{"techniques": [], "cwes": [], "keywords": []}' | |
| return translate_symptom | |
| def create_agent_tools( | |
| rag_system: Any, | |
| graph_service: Any, | |
| llm_client: Any = None, | |
| cheat_sheet: Any = None, | |
| ) -> list: | |
| """Create all agent tools with runtime dependencies injected.""" | |
| tools = [ | |
| create_search_tool(rag_system), | |
| create_explore_kg_tool(graph_service), | |
| create_find_similar_cves_tool(graph_service), | |
| ] | |
| if llm_client is not None: | |
| tools.append(create_translate_symptom_tool(llm_client, cheat_sheet)) | |
| tools.append(create_web_search_tool()) | |
| return tools | |