#!/usr/bin/env python3
import json
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).parent.parent))
from database.db import init_db, get_cve, search_cves, get_stats
_conn = None
def get_connection():
global _conn
if _conn is None:
_conn = init_db()
return _conn
def tool_get_cve_details(cve_id: str) -> str:
conn = get_connection()
cve_id = cve_id.strip().upper()
if not cve_id.startswith("CVE-"):
cve_id = "CVE-{}".format(cve_id)
result = get_cve(conn, cve_id)
if result:
if result.get('references_json'):
try:
result['references'] = json.loads(result['references_json'])
except:
result['references'] = []
del result['references_json']
return json.dumps(result, indent=2)
return json.dumps({"error": "not found", "cve_id": cve_id})
def tool_search_cves(keyword: str, limit: int = 10) -> str:
# TODO: switch to FTS5 for better search performance
conn = get_connection()
limit = min(max(1, limit), 50)
results = search_cves(conn, keyword.strip(), limit)
# tried to sort by CVSS score but too slow on large datasets
# results.sort(key=lambda x: x.get('cvss_score') or 0, reverse=True)
formatted = []
for cve in results:
desc = cve['description']
if len(desc) > 300:
desc = desc[:300] + "..."
formatted.append({
"cve_id": cve['cve_id'],
"severity": cve['severity'],
"cvss_score": cve['cvss_score'],
"description": desc,
"published_date": cve['published_date']
})
return json.dumps({"query": keyword, "count": len(formatted), "results": formatted}, indent=2)
def tool_get_statistics() -> str:
conn = get_connection()
stats = get_stats(conn)
return json.dumps(stats, indent=2)