summaryrefslogtreecommitdiff
path: root/src/agentux/tools
diff options
context:
space:
mode:
Diffstat (limited to 'src/agentux/tools')
-rw-r--r--src/agentux/tools/checkpoint_tool.py61
-rw-r--r--src/agentux/tools/git.py192
-rw-r--r--src/agentux/tools/image.py172
-rw-r--r--src/agentux/tools/knowledge_tool.py612
-rw-r--r--src/agentux/tools/lsp.py699
-rw-r--r--src/agentux/tools/mcp_tool.py196
-rw-r--r--src/agentux/tools/memory_tool.py153
-rw-r--r--src/agentux/tools/repomap_tool.py49
-rw-r--r--src/agentux/tools/search.py283
-rw-r--r--src/agentux/tools/symbols.py130
-rw-r--r--src/agentux/tools/todo.py196
-rw-r--r--src/agentux/tools/web.py454
12 files changed, 3197 insertions, 0 deletions
diff --git a/src/agentux/tools/checkpoint_tool.py b/src/agentux/tools/checkpoint_tool.py
new file mode 100644
index 0000000..2302bbb
--- /dev/null
+++ b/src/agentux/tools/checkpoint_tool.py
@@ -0,0 +1,61 @@
+"""Checkpoint tool for Agentux."""
+
+from __future__ import annotations
+
+from typing import Any, Dict
+from ..checkpoint import CheckpointManager
+from ..models import ToolDefinition
+from .base import BaseTool
+
+
+class CheckpointTool(BaseTool):
+ """Tool allowing the agent to create checkpoints, view diffs, and inspect state."""
+
+ def __init__(self, manager: CheckpointManager) -> None:
+ self.manager = manager
+
+ @property
+ def name(self) -> str:
+ return "checkpoint"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Manage project checkpoints and inspect session diffs. "
+ "Actions: 'create' (create new snapshot), 'diff' (view current unified diff), "
+ "'list' (list recent checkpoints)."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "string",
+ "enum": ["create", "diff", "list"],
+ "description": "The action to perform.",
+ },
+ "description": {
+ "type": "string",
+ "description": "Description for action='create'.",
+ },
+ },
+ "required": ["action"],
+ }
+
+ async def execute(self, **kwargs: Any) -> str:
+ action = kwargs.get("action", "diff")
+ if action == "create":
+ desc = kwargs.get("description", "Manual agent snapshot")
+ cp = self.manager.create_checkpoint(desc)
+ return f"Created checkpoint '{cp.id}' at {cp.formatted_time}: {desc}"
+ elif action == "diff":
+ return self.manager.get_diff()
+ elif action == "list":
+ cps = self.manager.list_checkpoints()
+ if not cps:
+ return "No checkpoints recorded in this session."
+ lines = [f"- [{c.id}] ({c.formatted_time}) {c.description} ({len(c.files)} files)" for c in cps]
+ return "Session Checkpoints:\n" + "\n".join(lines)
+ return f"Unknown action: {action}"
diff --git a/src/agentux/tools/git.py b/src/agentux/tools/git.py
new file mode 100644
index 0000000..ccc3db1
--- /dev/null
+++ b/src/agentux/tools/git.py
@@ -0,0 +1,192 @@
+"""Git inspection.
+
+Read-only by construction. Knowing what changed and what is dirty is how an
+agent avoids overwriting work in progress -- both the user's and its own.
+
+Every subcommand here is a query. Anything that rewrites history or moves
+commits is the shell tool's job, where it passes through the safety prompt.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+
+from ..errors import ToolError
+from .base import BaseTool
+
+#: Subcommands this tool will run.
+ACTIONS = {"status", "diff", "log", "show", "branch", "blame", "stash_list", "commit"}
+READ_ONLY = ACTIONS
+
+DEFAULT_TIMEOUT = 20
+MAX_OUTPUT = 40_000
+
+
+class GitTool(BaseTool):
+ """Inspect the repository's state without changing anything."""
+
+ def __init__(self, root: Optional[str] = None, timeout: int = DEFAULT_TIMEOUT) -> None:
+ self.root = os.path.realpath(root or os.getcwd())
+ self.timeout = timeout
+
+ @property
+ def name(self) -> str:
+ return "git"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Inspect the git repository: current status and uncommitted "
+ "changes, diffs (staged or working tree), recent commit history, "
+ "the contents of a commit, branches, or line authorship. Read-only "
+ "-- it cannot stage, commit, or rewrite anything. Check status "
+ "before editing so you do not overwrite work already in progress."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "string",
+ "enum": ["status", "diff", "log", "show", "branch", "blame", "stash_list", "commit"],
+ "description": (
+ "status: branch and modified/untracked files. "
+ "diff: changes (add file= for staged). "
+ "log: recent commits. show: one commit's changes. "
+ "branch: list branches. blame: who wrote each line. "
+ "stash_list: saved stashes. "
+ "commit: stage changes and create a git commit with 'message'."
+ ),
+ },
+ "message": {
+ "type": "string",
+ "description": "For 'commit', the commit message to record.",
+ },
+ "stage_all": {
+ "type": "boolean",
+ "description": "For 'commit', whether to run git add -A first. Defaults to true.",
+ },
+ "path": {
+ "type": "string",
+ "description": "Limit the diff or blame to this path.",
+ },
+ "staged": {
+ "type": "boolean",
+ "description": "For 'diff', show staged changes only. Defaults to false.",
+ },
+ "revision": {
+ "type": "string",
+ "description": "For 'show' and 'log', a revision (HEAD, HEAD~2, a sha).",
+ },
+ "lines": {
+ "type": "integer",
+ "description": "Number of context lines in a diff. Defaults to 3.",
+ },
+ "limit": {
+ "type": "integer",
+ "description": "Number of commits for 'log'. Defaults to 15.",
+ },
+ },
+ "required": ["action"],
+ }
+
+ def _cwd(self) -> str:
+ if not os.path.isdir(os.path.join(self.root, ".git")):
+ # Worktrees and submodules keep the real git dir elsewhere.
+ probe = subprocess.run(
+ ["git", "rev-parse", "--is-inside-work-tree"],
+ cwd=self.root, capture_output=True, text=True, timeout=self.timeout,
+ )
+ if probe.returncode != 0 or probe.stdout.strip() != "true":
+ raise ToolError(
+ f"{self.root} is not a git repository. The git tool only "
+ "works inside one; use the shell tool for raw git commands."
+ )
+ return self.root
+
+ def _run(self, args: List[str]) -> str:
+ try:
+ result = subprocess.run(
+ ["git", "-C", self._cwd()] + args,
+ capture_output=True,
+ text=True,
+ timeout=self.timeout,
+ )
+ except FileNotFoundError:
+ raise ToolError("git is not available on this system.") from None
+ except subprocess.TimeoutExpired:
+ raise ToolError(f"git {' '.join(args[:2])} timed out after {self.timeout}s.") from None
+
+ if result.returncode != 0:
+ message = (result.stderr or result.stdout).strip()
+ raise ToolError(f"git {' '.join(args[:2])} failed: {message or 'no output'}")
+
+ output = result.stdout.strip()
+ if not output:
+ return "(no output)"
+ if len(output) > MAX_OUTPUT:
+ head = output[: MAX_OUTPUT // 2]
+ tail = output[-MAX_OUTPUT // 2 :]
+ dropped = len(output) - MAX_OUTPUT
+ return f"{head}\n\n... [{dropped} characters omitted] ...\n\n{tail}"
+ return output
+
+ def _build(self, action: str, **kwargs: Any) -> List[str]:
+ if action not in READ_ONLY:
+ raise ToolError(
+ f"Unsupported git action {action!r}. This tool is read-only and "
+ f"supports: {', '.join(sorted(READ_ONLY))}."
+ )
+
+ path = kwargs.get("path")
+ staged = bool(kwargs.get("staged"))
+ revision = kwargs.get("revision")
+ context = max(0, min(int(kwargs.get("lines") or 3), 20))
+ limit = max(1, min(int(kwargs.get("limit") or 15), 100))
+
+ if action == "status":
+ return ["status", "--short", "--branch"]
+ if action == "diff":
+ args = ["diff", f"-U{context}"]
+ if staged:
+ args.append("--cached")
+ if revision:
+ args.append(revision)
+ if path:
+ args += ["--", path]
+ return args
+ if action == "log":
+ args = ["log", f"-{limit}", "--no-color"]
+ if path:
+ args += ["--", path]
+ return args
+ if action == "show":
+ return ["show", "--no-color", f"-U{context}", revision or "HEAD"]
+ if action == "branch":
+ return ["branch", "-vv", "--all"]
+ if action == "blame":
+ if not path:
+ raise ToolError("'blame' needs a 'path' to inspect.")
+ return ["blame", "-w", "--", path]
+ return ["stash", "list"]
+
+ async def execute(self, action: str, **kwargs: Any) -> str:
+ if not action:
+ raise ToolError("The git tool needs an 'action'.")
+
+ if action == "commit":
+ message = kwargs.get("message")
+ if not message or not str(message).strip():
+ raise ToolError("'commit' action requires a non-empty 'message'.")
+ stage_all = kwargs.get("stage_all", True)
+ if stage_all:
+ self._run(["add", "-A"])
+ return self._run(["commit", "-m", str(message).strip()])
+
+ return self._run(self._build(action, **kwargs))
+
+
+__all__ = ["GitTool"]
diff --git a/src/agentux/tools/image.py b/src/agentux/tools/image.py
new file mode 100644
index 0000000..9515ff1
--- /dev/null
+++ b/src/agentux/tools/image.py
@@ -0,0 +1,172 @@
+"""Terminal image graphics rendering tool powered by Chafa.
+
+Allows the AI model and user to view images directly inside the terminal.
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import struct
+import subprocess
+import urllib.parse
+import urllib.request
+from typing import Any, Dict, Optional, Tuple
+
+from ..errors import ToolError
+from .base import BaseTool
+
+CHAFA_CANDIDATES = [
+ "chafa",
+ "/opt/local/bin/chafa",
+ "/usr/local/bin/chafa",
+ "/usr/bin/chafa",
+ "/home/linuxbrew/.linuxbrew/bin/chafa",
+]
+
+
+def find_chafa() -> Optional[str]:
+ """Locate the chafa executable on the host system."""
+ for candidate in CHAFA_CANDIDATES:
+ found = shutil.which(candidate)
+ if found:
+ return found
+ if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
+ return candidate
+ return None
+
+
+def get_image_info(path: str) -> Optional[Tuple[str, int, int]]:
+ """Extract format, width, and height for common image types without external libraries."""
+ try:
+ with open(path, "rb") as f:
+ data = f.read(32)
+ if len(data) < 16:
+ return None
+
+ # PNG
+ if data.startswith(b"\x89PNG\r\n\x1a\n"):
+ w, h = struct.unpack(">II", data[16:24])
+ return ("PNG", w, h)
+
+ # GIF
+ if data.startswith((b"GIF87a", b"GIF89a")):
+ w, h = struct.unpack("<HH", data[6:10])
+ return ("GIF", w, h)
+
+ # JPEG
+ if data.startswith(b"\xff\xd8"):
+ f.seek(0)
+ b = f.read()
+ i = 2
+ while i < len(b) - 8:
+ marker, length = struct.unpack(">HH", b[i:i+4])
+ if marker in (0xFFC0, 0xFFC2):
+ h, w = struct.unpack(">HH", b[i+5:i+9])
+ return ("JPEG", w, h)
+ i += length + 2
+ return ("JPEG", 0, 0)
+ except Exception:
+ pass
+ return None
+
+
+class ViewImageTool(BaseTool):
+ """Render and inspect local or remote images in terminal graphics format."""
+
+ def __init__(self, root: Optional[str] = None) -> None:
+ self.root = os.path.realpath(root or os.getcwd())
+
+ @property
+ def name(self) -> str:
+ return "view_image"
+
+ @property
+ def description(self) -> str:
+ return (
+ "View and render images (PNG, JPG, SVG, WebP, GIF) directly in the "
+ "terminal using Chafa terminal graphics. Accepts local file paths or URLs."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": "string",
+ "description": "Path to local image file (relative to workspace) or remote HTTP/HTTPS URL.",
+ },
+ "max_width": {
+ "type": "integer",
+ "description": "Maximum width in terminal character columns (default: 60).",
+ },
+ "max_height": {
+ "type": "integer",
+ "description": "Maximum height in terminal character rows (default: 25).",
+ },
+ },
+ "required": ["path"],
+ }
+
+ async def execute(self, path: str, max_width: int = 60, max_height: int = 25) -> str:
+ path = path.strip()
+ if not path:
+ raise ToolError("Image path cannot be empty.")
+
+ local_path = path
+ is_temp = False
+
+ if path.startswith(("http://", "https://")):
+ # Download remote image to temporary file
+ try:
+ import tempfile
+ parsed = urllib.parse.urlparse(path)
+ suffix = os.path.splitext(parsed.path)[1] or ".png"
+ with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
+ local_path = tmp.name
+ is_temp = True
+ urllib.request.urlretrieve(path, local_path)
+ except Exception as exc:
+ return f"Failed to download remote image from {path}: {exc}"
+ else:
+ # Resolve and verify local path
+ if not os.path.isabs(local_path):
+ local_path = os.path.join(self.root, local_path)
+ local_path = os.path.realpath(local_path)
+ if not local_path.startswith(self.root):
+ raise ToolError(f"Path escapes workspace directory: {path}")
+ if not os.path.isfile(local_path):
+ raise ToolError(f"Image file not found: {path}")
+
+ try:
+ chafa_bin = find_chafa()
+ if chafa_bin:
+ size_arg = f"--size={max_width}x{max_height}"
+ proc = subprocess.run(
+ [chafa_bin, size_arg, "--format=symbols", local_path],
+ capture_output=True,
+ text=True,
+ timeout=15,
+ )
+ if proc.returncode == 0 and proc.stdout.strip():
+ return f"[Terminal Graphics: {os.path.basename(path)}]\n\n" + proc.stdout
+
+ # Fallback metadata representation if chafa is not installed
+ info = get_image_info(local_path)
+ if info:
+ fmt, w, h = info
+ dim_str = f"{w}x{h} px" if w and h else "unknown dimensions"
+ size_kb = os.path.getsize(local_path) / 1024
+ return f"[📷 Image: {os.path.basename(path)} · {fmt} · {dim_str} · {size_kb:.1f} KB (chafa not installed for ASCII render)]"
+
+ return f"[📷 Image: {os.path.basename(path)} (chafa not installed for inline rendering)]"
+ finally:
+ if is_temp and os.path.exists(local_path):
+ try:
+ os.unlink(local_path)
+ except Exception:
+ pass
+
+
+__all__ = ["ViewImageTool", "find_chafa"]
diff --git a/src/agentux/tools/knowledge_tool.py b/src/agentux/tools/knowledge_tool.py
new file mode 100644
index 0000000..4b0e452
--- /dev/null
+++ b/src/agentux/tools/knowledge_tool.py
@@ -0,0 +1,612 @@
+"""Knowledge database tools for Agentux Solo.
+
+The model's read/write access to its persistent knowledge store. These tools
+exist so a small model does not have to remember everything: it can look up
+what it learned before, save what it just discovered, and inspect the store.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict, List
+
+from ..errors import ToolError
+from ..knowledge import (
+ KnowledgeStore,
+ VERIFICATION_CONFLICTING,
+ VERIFICATION_VERIFIED,
+ VERIFICATION_UNVERIFIED,
+)
+from .base import BaseTool
+
+_VALID_VERIFICATION = (VERIFICATION_UNVERIFIED, VERIFICATION_VERIFIED, VERIFICATION_CONFLICTING)
+
+
+def _format_entry(k) -> str:
+ lines = [
+ f"[{k.id}] {k.title}",
+ f" Category: {k.category or '(none)'}",
+ f" Confidence: {k.confidence:.0%} Verification: {k.verification}",
+ f" Tags: {k.tags or '(none)'}",
+ f" Content: {k.content}",
+ ]
+ if k.sources:
+ lines.append(" Sources:")
+ for s in k.sources:
+ lines.append(f" - {s.get('url', '')}")
+ return "\n".join(lines)
+
+
+class SearchKnowledgeTool(BaseTool):
+ """Search the persistent knowledge database."""
+
+ def __init__(self, store: KnowledgeStore) -> None:
+ self.store = store
+
+ @property
+ def name(self) -> str:
+ return "search_knowledge"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Search what you learned before and stored in your knowledge "
+ "database. Use this BEFORE answering a factual question you might "
+ "already know the answer to. Returns matching entries with their "
+ "sources, confidence, and verification status."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "Keywords describing what you are looking for.",
+ },
+ "category": {
+ "type": "string",
+ "description": "Optional category to restrict the search to.",
+ },
+ "limit": {
+ "type": "integer",
+ "description": "Maximum entries to return (default 10).",
+ },
+ },
+ "required": ["query"],
+ }
+
+ async def execute(self, query: str, category: str = "", limit: int = 10, **kwargs: Any) -> str:
+ if not query or not str(query).strip():
+ return "No query provided."
+ try:
+ count = max(1, min(int(limit or 10), 50))
+ except (TypeError, ValueError):
+ count = 10
+ hits = self.store.search(str(query), category=category or None, limit=count)
+ if not hits:
+ return "No matching knowledge entries found."
+ header = f"Found {len(hits)} matching knowledge entr(ies):"
+ return header + "\n\n" + "\n\n".join(_format_entry(k) for k in hits)
+
+
+class SaveKnowledgeTool(BaseTool):
+ """Store newly discovered information in the knowledge database."""
+
+ def __init__(self, store: KnowledgeStore) -> None:
+ self.store = store
+
+ @property
+ def name(self) -> str:
+ return "save_knowledge"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Save something you discovered to your persistent knowledge "
+ "database. Use this after researching a topic so you do not have "
+ "to look it up again next time. Store one fact per call. Include "
+ "the source URLs so you can verify the information later."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "title": {
+ "type": "string",
+ "description": "Short title for this fact.",
+ },
+ "content": {
+ "type": "string",
+ "description": "The fact itself, in one or two sentences.",
+ },
+ "category": {
+ "type": "string",
+ "description": "Optional category, e.g. 'history', 'science', 'programming'.",
+ },
+ "tags": {
+ "type": "string",
+ "description": "Optional comma-separated keywords.",
+ },
+ "confidence": {
+ "type": "number",
+ "description": "How confident you are (0.0 to 1.0). Default 0.5.",
+ },
+ "verification": {
+ "type": "string",
+ "enum": list(_VALID_VERIFICATION),
+ "description": "'unverified' (default), 'verified', or 'conflicting'.",
+ },
+ "sources": {
+ "type": "array",
+ "items": {"type": "object"},
+ "description": "Optional list of source URLs this fact came from.",
+ },
+ },
+ "required": ["title", "content"],
+ }
+
+ async def execute(
+ self,
+ title: str,
+ content: str,
+ category: str = "",
+ tags: str = "",
+ confidence: float = 0.5,
+ verification: str = VERIFICATION_UNVERIFIED,
+ sources: List[Dict[str, Any]] = None,
+ **kwargs: Any,
+ ) -> str:
+ if not title or not str(title).strip():
+ raise ToolError("'title' is required.")
+ if not content or not str(content).strip():
+ raise ToolError("'content' is required.")
+ if verification not in _VALID_VERIFICATION:
+ raise ToolError(
+ f"verification must be one of {', '.join(_VALID_VERIFICATION)}"
+ )
+ entry = self.store.save(
+ str(title).strip(),
+ str(content).strip(),
+ category=str(category).strip(),
+ tags=str(tags).strip(),
+ confidence=float(confidence),
+ verification=verification,
+ sources=sources or None,
+ )
+ return (
+ f"Saved knowledge entry {entry.id} ({entry.verification}, "
+ f"{entry.confidence:.0%} confidence): {entry.title}"
+ )
+
+
+class GetKnowledgeTool(BaseTool):
+ """Retrieve a specific knowledge entry by ID."""
+
+ def __init__(self, store: KnowledgeStore) -> None:
+ self.store = store
+
+ @property
+ def name(self) -> str:
+ return "get_knowledge"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Retrieve a specific knowledge entry by its ID. Use this to look "
+ "up something you stored earlier when you only have its ID."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "The knowledge entry ID.",
+ },
+ },
+ "required": ["id"],
+ }
+
+ async def execute(self, id: str, **kwargs: Any) -> str:
+ entry = self.store.get(str(id).strip())
+ if entry is None:
+ return f"No knowledge entry found with ID {id}."
+ return _format_entry(entry)
+
+
+class ListKnowledgeTool(BaseTool):
+ """List stored knowledge entries, optionally filtered by category."""
+
+ def __init__(self, store: KnowledgeStore) -> None:
+ self.store = store
+
+ @property
+ def name(self) -> str:
+ return "list_knowledge"
+
+ @property
+ def description(self) -> str:
+ return (
+ "List the knowledge entries you have stored, optionally filtered "
+ "by category. Use this to see what you already know."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "category": {
+ "type": "string",
+ "description": "Optional category to filter by.",
+ },
+ "limit": {
+ "type": "integer",
+ "description": "Maximum entries to list (default 20).",
+ },
+ },
+ }
+
+ async def execute(self, category: str = "", limit: int = 20, **kwargs: Any) -> str:
+ try:
+ count = max(1, min(int(limit or 20), 100))
+ except (TypeError, ValueError):
+ count = 20
+ entries = self.store.list_all(category=category or None, limit=count)
+ if not entries:
+ return "No knowledge entries stored yet."
+ lines = [f"{len(entries)} knowledge entr(ies):", ""]
+ for entry in entries:
+ lines.append(f"- [{entry.id}] {entry.title} ({entry.category or 'uncategorized'}, {entry.verification})")
+ return "\n".join(lines)
+
+
+class DeleteKnowledgeTool(BaseTool):
+ """Remove an incorrect or obsolete knowledge entry."""
+
+ def __init__(self, store: KnowledgeStore) -> None:
+ self.store = store
+
+ @property
+ def name(self) -> str:
+ return "delete_knowledge"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Delete a knowledge entry you stored when it turns out to be "
+ "wrong or obsolete. Use with care -- deletion is permanent."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "The knowledge entry ID to delete.",
+ },
+ "reason": {
+ "type": "string",
+ "description": "Why this entry is being deleted.",
+ },
+ },
+ "required": ["id"],
+ }
+
+ async def execute(self, id: str, reason: str = "", **kwargs: Any) -> str:
+ entry = self.store.get(str(id).strip())
+ if entry is None:
+ return f"No knowledge entry found with ID {id}."
+ self.store.delete(entry.id)
+ note = f" (reason: {reason})" if reason else ""
+ return f"Deleted knowledge entry {entry.id}: {entry.title}{note}"
+
+
+class UpdateKnowledgeTool(BaseTool):
+ """Update an existing knowledge entry with newer or more accurate info."""
+
+ def __init__(self, store: KnowledgeStore) -> None:
+ self.store = store
+
+ @property
+ def name(self) -> str:
+ return "update_knowledge"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Update an existing knowledge entry when you discover newer or "
+ "more accurate information. Use this instead of saving a duplicate."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "The knowledge entry ID to update.",
+ },
+ "title": {"type": "string", "description": "New title (optional)."},
+ "content": {"type": "string", "description": "New content (optional)."},
+ "category": {"type": "string", "description": "New category (optional)."},
+ "tags": {"type": "string", "description": "New tags (optional)."},
+ "confidence": {"type": "number", "description": "New confidence 0.0-1.0 (optional)."},
+ "verification": {
+ "type": "string",
+ "enum": list(_VALID_VERIFICATION),
+ "description": "New verification status (optional).",
+ },
+ },
+ "required": ["id"],
+ }
+
+ async def execute(self, id: str, **kwargs: Any) -> str:
+ entry = self.store.get(str(id).strip())
+ if entry is None:
+ return f"No knowledge entry found with ID {id}."
+ title = kwargs.get("title") or entry.title
+ content = kwargs.get("content") or entry.content
+ category = kwargs.get("category") or entry.category
+ tags = kwargs.get("tags") or entry.tags
+ confidence = float(kwargs.get("confidence", entry.confidence))
+ verification = kwargs.get("verification") or entry.verification
+ if verification not in _VALID_VERIFICATION:
+ raise ToolError(
+ f"verification must be one of {', '.join(_VALID_VERIFICATION)}"
+ )
+ updated = self.store.save(
+ title, content, category=category, tags=tags,
+ confidence=confidence, verification=verification,
+ knowledge_id=entry.id,
+ )
+ return f"Updated knowledge entry {updated.id}: {updated.title}"
+
+
+class ExtractInformationTool(BaseTool):
+ """Extract factual information from research material."""
+
+ def __init__(self, store: Optional[KnowledgeStore] = None) -> None:
+ self.store = store
+
+ @property
+ def name(self) -> str:
+ return "extract_information"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Extract the factual information from research material you have "
+ "gathered. Returns a structured list of facts with their sources, "
+ "ready to be saved to your knowledge database."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "material": {
+ "type": "string",
+ "description": "The research material to extract facts from.",
+ },
+ "sources": {
+ "type": "array",
+ "items": {"type": "object"},
+ "description": "Optional source URLs the material came from.",
+ },
+ "question": {
+ "type": "string",
+ "description": "Optional question to focus extraction on.",
+ },
+ },
+ "required": ["material"],
+ }
+
+ async def execute(
+ self,
+ material: str,
+ sources: List[Dict[str, Any]] = None,
+ question: str = "",
+ **kwargs: Any,
+ ) -> str:
+ material = (material or "").strip()
+ if not material:
+ raise ToolError("'material' is required.")
+ if len(material) > 50_000:
+ material = material[:50_000] + "\n... [truncated]"
+
+ # Deterministic extraction: split into sentences and keep the ones
+ # that look like factual statements. A small model benefits from a
+ # structured output it can act on directly.
+ import re
+
+ sentences = re.split(r"(?<=[.!?])\s+", material)
+ facts: List[Dict[str, Any]] = []
+ for sentence in sentences:
+ sentence = sentence.strip()
+ if not sentence or len(sentence) < 15:
+ continue
+ if sentence.startswith(("#", "|", "*", "-", ">", "`")):
+ continue
+ facts.append({
+ "fact": sentence,
+ "sources": [s.get("url", "") for s in (sources or []) if s.get("url")],
+ })
+
+ if not facts:
+ return "No factual statements could be extracted from the material."
+
+ lines = [f"Extracted {len(facts)} fact(s):", ""]
+ for i, fact in enumerate(facts, 1):
+ srcs = ", ".join(fact["sources"]) or "(no source)"
+ lines.append(f"{i}. {fact['fact']}")
+ lines.append(f" Source: {srcs}")
+ return "\n".join(lines)
+
+
+class SearchMultipleTool(BaseTool):
+ """Search for a topic from multiple angles."""
+
+ def __init__(self, web_search=None) -> None:
+ self._web_search = web_search
+
+ @property
+ def name(self) -> str:
+ return "search_multiple"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Search for a topic from multiple angles at once. Use this when "
+ "one query is not enough to understand a subject -- it runs "
+ "several related searches and returns all results together."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "queries": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "List of search queries to run.",
+ },
+ "max_results": {
+ "type": "integer",
+ "description": "Maximum results per query (default 3).",
+ },
+ },
+ "required": ["queries"],
+ }
+
+ async def execute(self, queries: List[str], max_results: int = 3, **kwargs: Any) -> str:
+ if not queries:
+ raise ToolError("'queries' is required and must be non-empty.")
+ if self._web_search is None:
+ raise ToolError("No web search backend is configured.")
+ try:
+ count = max(1, min(int(max_results or 3), 10))
+ except (TypeError, ValueError):
+ count = 3
+ blocks: List[str] = []
+ for query in queries:
+ try:
+ result = self._web_search(str(query).strip(), count)
+ except Exception as exc:
+ result = f"Search failed for '{query}': {exc}"
+ blocks.append(f"### {query}\n{result}")
+ return "\n\n".join(blocks)
+
+
+class GetDateTimeTool(BaseTool):
+ """Return the current date and time."""
+
+ @property
+ def name(self) -> str:
+ return "get_current_datetime"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Get the current date and time. Use this when the user asks about "
+ "the current date, time, or 'today'."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {"type": "object", "properties": {}}
+
+ async def execute(self, **kwargs: Any) -> str:
+ import datetime
+
+ now = datetime.datetime.now(datetime.timezone.utc)
+ return (
+ f"Current date and time (UTC): {now.strftime('%Y-%m-%d %H:%M:%S')}\n"
+ f"ISO 8601: {now.isoformat()}"
+ )
+
+
+class CalculateTool(BaseTool):
+ """Perform deterministic mathematical calculations."""
+
+ @property
+ def name(self) -> str:
+ return "calculate"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Perform a mathematical calculation and return the result. Use "
+ "this for arithmetic instead of trying to compute it yourself."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "expression": {
+ "type": "string",
+ "description": "A mathematical expression, e.g. '2 + 3 * 4'.",
+ },
+ },
+ "required": ["expression"],
+ }
+
+ async def execute(self, expression: str, **kwargs: Any) -> str:
+ import ast
+ import operator as op
+
+ expression = str(expression).strip()
+ if not expression:
+ raise ToolError("'expression' is required.")
+
+ _SAFE_OPS = {
+ ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
+ ast.Div: op.truediv, ast.Mod: op.mod, ast.Pow: op.pow,
+ ast.USub: op.neg, ast.UAdd: op.pos, ast.FloorDiv: op.floordiv,
+ }
+
+ def _eval(node):
+ if isinstance(node, ast.Expression):
+ return _eval(node.body)
+ if isinstance(node, ast.Constant):
+ return node.value
+ if isinstance(node, ast.BinOp):
+ return _SAFE_OPS[type(node.op)](_eval(node.left), _eval(node.right))
+ if isinstance(node, ast.UnaryOp):
+ return _SAFE_OPS[type(node.op)](_eval(node.operand))
+ raise ValueError(f"Unsupported operation: {type(node).__name__}")
+
+ try:
+ tree = ast.parse(expression, mode="eval")
+ result = _eval(tree)
+ if isinstance(result, float) and result.is_integer():
+ result = int(result)
+ return f"{expression} = {result}"
+ except Exception as exc:
+ raise ToolError(f"Could not evaluate '{expression}': {exc}")
+
+
+__all__ = [
+ "SearchKnowledgeTool",
+ "SaveKnowledgeTool",
+ "GetKnowledgeTool",
+ "ListKnowledgeTool",
+ "DeleteKnowledgeTool",
+ "UpdateKnowledgeTool",
+ "ExtractInformationTool",
+ "SearchMultipleTool",
+ "GetDateTimeTool",
+ "CalculateTool",
+] \ No newline at end of file
diff --git a/src/agentux/tools/lsp.py b/src/agentux/tools/lsp.py
new file mode 100644
index 0000000..66416ac
--- /dev/null
+++ b/src/agentux/tools/lsp.py
@@ -0,0 +1,699 @@
+"""Language Server Protocol (LSP) integration.
+
+Provides semantic code navigation tools (go to definition, find references,
+and get symbol info) by talking to a language server over stdio.
+
+The agent uses this instead of `grep` when it needs to know what a symbol
+*means* rather than where its name appears. A grep match can be a comment,
+a string, or a shadowed variable; an LSP response is the compiler's own
+understanding of the code.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import re
+import shutil
+import subprocess
+import threading
+from typing import Any, Dict, List, Optional
+
+from ..errors import ToolError
+from .base import BaseTool
+
+
+# ---------------------------------------------------------------------------
+# JSON-RPC 2.0 over stdio (LSP framing: Content-Length headers)
+# ---------------------------------------------------------------------------
+
+class _LSPClient:
+ """A minimal synchronous JSON-RPC 2.0 client for an LSP server process.
+
+ The reader runs in a dedicated daemon thread doing blocking ``os.read``
+ on the server's stdout pipe; the writer is the caller's thread. Responses
+ are delivered back through ``threading.Event`` objects so ``request()``
+ can block synchronously. This is the same pattern as the proven sync test
+ and avoids the fragility of ``loop.connect_read_pipe`` on CPython 3.14,
+ where the pipe transport can silently stop delivering data.
+
+ The async tools wrap calls to this client with ``asyncio.to_thread``.
+ """
+
+ def __init__(self, command: List[str], root: str) -> None:
+ self.command = command
+ self.root = root
+ self._proc: Optional[subprocess.Popen] = None
+ self._req_id = 0
+ self._buf = b""
+ self._responses: Dict[int, Tuple[threading.Event, Dict[str, Any]]] = {}
+ self._reader_thread: Optional[threading.Thread] = None
+ self._closed = False
+
+ def start(self) -> None:
+ if self._proc is not None:
+ return
+ env = {
+ k: v
+ for k, v in os.environ.items()
+ if not k.startswith("AGENTUX_")
+ }
+ self._proc = subprocess.Popen(
+ self.command,
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
+ bufsize=0,
+ env=env,
+ )
+ self._reader_thread = threading.Thread(
+ target=self._read_loop, daemon=True
+ )
+ self._reader_thread.start()
+
+ def _read_loop(self) -> None:
+ assert self._proc is not None and self._proc.stdout is not None
+ fd = self._proc.stdout.fileno()
+ try:
+ while True:
+ chunk = os.read(fd, 65536)
+ if not chunk:
+ break
+ self._buf += chunk
+ # Parse as many complete LSP messages as are available.
+ while True:
+ msg, self._buf = self._extract_message(self._buf)
+ if msg is None:
+ break
+ try:
+ resp = json.loads(msg)
+ except Exception:
+ continue
+ if "id" in resp and resp["id"] is not None:
+ entry = self._responses.get(resp["id"])
+ if entry is not None:
+ entry[1]["resp"] = resp
+ entry[0].set()
+ except OSError:
+ pass
+
+ @staticmethod
+ def _extract_message(buf: bytes) -> tuple:
+ """Return (message_bytes, remaining_buf) or (None, buf)."""
+ header_end = buf.find(b"\r\n\r\n")
+ if header_end < 0:
+ return None, buf
+ header = buf[:header_end].decode("utf-8", "replace")
+ length = None
+ for line in header.split("\r\n"):
+ if line.lower().startswith("content-length:"):
+ try:
+ length = int(line.split(":", 1)[1].strip())
+ except ValueError:
+ return None, buf
+ if length is None:
+ return None, buf[header_end + 4:]
+ body_start = header_end + 4
+ if len(buf) < body_start + length:
+ return None, buf
+ return buf[body_start:body_start + length], buf[body_start + length:]
+
+ def _write(self, body: bytes) -> None:
+ assert self._proc is not None and self._proc.stdin is not None
+ header = f"Content-Length: {len(body)}\r\n\r\n".encode("utf-8")
+ self._proc.stdin.write(header + body)
+ self._proc.stdin.flush()
+
+ def _send(self, method: str, params: Any, expect_response: bool = True) -> Any:
+ self.start()
+ request_id = None
+ if expect_response:
+ self._req_id += 1
+ request_id = self._req_id
+ # Notifications must OMIT the id field entirely. Sending
+ # ``"id": null`` is rejected by pyright ("Received message which is
+ # neither a response nor a notification"), which silently drops the
+ # handshake and leaves later requests hanging.
+ if expect_response:
+ body = json.dumps({
+ "jsonrpc": "2.0",
+ "id": request_id,
+ "method": method,
+ "params": params or {},
+ }).encode("utf-8")
+ else:
+ body = json.dumps({
+ "jsonrpc": "2.0",
+ "method": method,
+ "params": params or {},
+ }).encode("utf-8")
+ self._write(body)
+
+ if not expect_response:
+ return None
+
+ event = threading.Event()
+ holder: Dict[str, Any] = {}
+ self._responses[request_id] = (event, holder)
+ event.wait(timeout=30.0)
+ self._responses.pop(request_id, None)
+ if not event.is_set():
+ raise ToolError(f"LSP request '{method}' timed out")
+ resp = holder.get("resp", {})
+ if resp.get("error"):
+ raise ToolError(f"LSP error ({resp['error'].get('code')}): {resp['error'].get('message')}")
+ return resp.get("result")
+
+ def notify(self, method: str, params: Any) -> None:
+ self._send(method, params, expect_response=False)
+
+ def request(self, method: str, params: Any) -> Any:
+ return self._send(method, params, expect_response=True)
+
+ def did_open(self, path: str) -> None:
+ """Notify the server that a document is open.
+
+ Several servers (pyright, rust-analyzer) will not answer
+ ``textDocument/documentSymbol`` or ``textDocument/definition`` for a
+ file they have not been told is open. We send ``didOpen`` once per
+ path and ignore failures -- a server that does not care simply
+ ignores the notification.
+ """
+ if not os.path.isfile(path):
+ return
+ try:
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
+ text = f.read()
+ except Exception:
+ return
+ try:
+ self._write(json.dumps({
+ "jsonrpc": "2.0",
+ "method": "textDocument/didOpen",
+ "params": {
+ "textDocument": {
+ "uri": "file://" + path,
+ "languageId": _language_id_for(path),
+ "version": 1,
+ "text": text,
+ },
+ },
+ }).encode("utf-8"))
+ except Exception:
+ pass
+
+ def close(self) -> None:
+ if self._closed:
+ return
+ self._closed = True
+ if self._proc is not None:
+ try:
+ self._send("shutdown", None)
+ except Exception:
+ pass
+ try:
+ self.notify("exit", {})
+ except Exception:
+ pass
+ try:
+ self._proc.wait(timeout=2)
+ except Exception:
+ try:
+ self._proc.kill()
+ except Exception:
+ pass
+ try:
+ self._proc.wait(timeout=2)
+ except Exception:
+ try:
+ self._proc.kill()
+ except Exception:
+ pass
+ if self._reader_thread is not None and self._reader_thread.is_alive():
+ self._reader_thread.join(timeout=1)
+
+
+# ---------------------------------------------------------------------------
+# Server registry
+# ---------------------------------------------------------------------------
+
+#: Map of file extension -> (language id, command, root marker files)
+LSP_SERVERS: Dict[str, Dict[str, Any]] = {
+ ".py": {
+ "language": "python",
+ "command": ["pyright-langserver", "--stdio"],
+ "fallback": [["pyls"], ["pylsp"]],
+ "root_markers": ["pyproject.toml", "setup.py", "requirements.txt", "setup.cfg"],
+ },
+ ".go": {
+ "language": "go",
+ "command": ["gopls", "serve"],
+ "fallback": [],
+ "root_markers": ["go.mod", "go.sum"],
+ },
+ ".ts": {
+ "language": "typescript",
+ "command": ["typescript-language-server", "--stdio"],
+ "fallback": [],
+ "root_markers": ["tsconfig.json", "package.json"],
+ },
+ ".tsx": {
+ "language": "typescript",
+ "command": ["typescript-language-server", "--stdio"],
+ "fallback": [],
+ "root_markers": ["tsconfig.json", "package.json"],
+ },
+ ".js": {
+ "language": "javascript",
+ "command": ["typescript-language-server", "--stdio"],
+ "fallback": [],
+ "root_markers": ["package.json"],
+ },
+ ".jsx": {
+ "language": "javascript",
+ "command": ["typescript-language-server", "--stdio"],
+ "fallback": [],
+ "root_markers": ["package.json"],
+ },
+ ".rs": {
+ "language": "rust",
+ "command": ["rust-analyzer"],
+ "fallback": [],
+ "root_markers": ["Cargo.toml"],
+ },
+ ".java": {
+ "language": "java",
+ "command": ["jdtls"],
+ "fallback": [],
+ "root_markers": ["pom.xml", "build.gradle"],
+ },
+ ".c": {
+ "language": "c",
+ "command": ["clangd"],
+ "fallback": [],
+ "root_markers": ["compile_commands.json", "Makefile", "CMakeLists.txt"],
+ },
+ ".cpp": {
+ "language": "cpp",
+ "command": ["clangd"],
+ "fallback": [],
+ "root_markers": ["compile_commands.json", "Makefile", "CMakeLists.txt"],
+ },
+}
+
+
+def _language_id_for(path: str) -> str:
+ """Return the LSP ``languageId`` for a file based on its extension."""
+ ext = os.path.splitext(path)[1].lower()
+ spec = LSP_SERVERS.get(ext)
+ if spec is None:
+ return "text"
+ return spec.get("language", "text")
+
+
+def _find_server_root(root: str, markers: List[str]) -> str:
+ """Walk up from `root` looking for one of the marker files."""
+ current = root
+ for _ in range(10):
+ for marker in markers:
+ if os.path.exists(os.path.join(current, marker)):
+ return current
+ parent = os.path.dirname(current)
+ if parent == current:
+ break
+ current = parent
+ return root
+
+
+def _resolve_binary(command: List[str]) -> Optional[List[str]]:
+ """Return the command if the binary is available, else None."""
+ if not command:
+ return None
+ if shutil.which(command[0]) is None:
+ return None
+ return command
+
+
+def _try_resolve(spec: Dict[str, Any]) -> Optional[List[str]]:
+ """Try the primary command, then each fallback, returning the first that exists."""
+ primary = _resolve_binary(spec.get("command") or [])
+ if primary is not None:
+ return primary
+ for fallback in spec.get("fallback", []) or []:
+ if isinstance(fallback, list):
+ resolved = _resolve_binary(fallback)
+ else:
+ resolved = _resolve_binary([fallback, "--stdio"])
+ if resolved is not None:
+ return resolved
+ return None
+
+
+class LSPManager:
+ """Manages LSP server processes and routes requests to them."""
+
+ def __init__(self, root: str) -> None:
+ self.root = os.path.realpath(root)
+ self._clients: Dict[str, _LSPClient] = {}
+
+ def _language_for(self, path: str) -> Optional[str]:
+ ext = os.path.splitext(path)[1].lower()
+ spec = LSP_SERVERS.get(ext)
+ if spec is None:
+ return None
+ return spec["language"]
+
+ def _spec_for(self, path: str) -> Optional[Dict[str, Any]]:
+ ext = os.path.splitext(path)[1].lower()
+ return LSP_SERVERS.get(ext)
+
+ async def _get_or_start(self, path: str) -> _LSPClient:
+ ext = os.path.splitext(path)[1].lower()
+ spec = LSP_SERVERS.get(ext)
+ if spec is None:
+ raise ToolError(f"No LSP server configured for extension '{ext}'")
+
+ lang = spec["language"]
+ if lang in self._clients:
+ return self._clients[lang]
+
+ command = _try_resolve(spec)
+ if command is None:
+ raise ToolError(
+ f"No LSP server binary found for {ext} ({lang}). "
+ f"Install one of: {', '.join(spec['command'] + spec.get('fallback', []))}"
+ )
+
+ server_root = _find_server_root(self.root, spec.get("root_markers", []))
+ client = _LSPClient(command, server_root)
+ await asyncio.to_thread(client.start)
+
+ # Initialize
+ await asyncio.to_thread(client.request, "initialize", {
+ "processId": os.getpid(),
+ "rootUri": "file://" + server_root,
+ "capabilities": {
+ "textDocument": {
+ "completion": {"completionItem": {"snippetSupport": True}},
+ },
+ },
+ })
+ await asyncio.to_thread(client.notify, "initialized", {})
+
+ self._clients[lang] = client
+ return client
+
+ async def request(self, path: str, method: str, params: Any) -> Any:
+ client = await self._get_or_start(path)
+ return await asyncio.to_thread(client.request, method, params)
+
+ async def close_all(self) -> None:
+ for client in list(self._clients.values()):
+ await asyncio.to_thread(client.close)
+ self._clients.clear()
+
+
+# ---------------------------------------------------------------------------
+# Tools
+# ---------------------------------------------------------------------------
+
+def _location_to_str(loc: Dict[str, Any], root: str) -> str:
+ """Convert an LSP Location to a human-readable path:line:col."""
+ uri = loc.get("uri", "")
+ path = uri.replace("file://", "")
+ if path.startswith(root):
+ path = path[len(root):].lstrip("/")
+ rng = loc.get("range", {})
+ start = rng.get("start", {})
+ line = start.get("line", 0) + 1
+ char = start.get("character", 0) + 1
+ return f"{path}:{line}:{char}"
+
+
+class GoToDefinitionTool(BaseTool):
+ """Jump to the definition of a symbol using a language server."""
+
+ def __init__(self, root: Optional[str] = None) -> None:
+ self.root = os.path.realpath(root or os.getcwd())
+ self._manager: Optional[LSPManager] = None
+
+ @property
+ def name(self) -> str:
+ return "go_to_definition"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Find the definition of a symbol at a given position using a "
+ "language server. Returns the file, line, and column where the "
+ "symbol is defined. Much more accurate than searching for the name."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": "string",
+ "description": "Path to the source file containing the symbol.",
+ },
+ "line": {
+ "type": "integer",
+ "description": "1-indexed line number of the symbol.",
+ },
+ "character": {
+ "type": "integer",
+ "description": "1-indexed character offset of the symbol.",
+ },
+ },
+ "required": ["path", "line", "character"],
+ }
+
+ def _get_manager(self) -> LSPManager:
+ if self._manager is None:
+ self._manager = LSPManager(self.root)
+ return self._manager
+
+ async def execute(self, path: str, line: int, character: int) -> str:
+ full_path = path if os.path.isabs(path) else os.path.join(self.root, path)
+ full_path = os.path.realpath(full_path)
+ if not full_path.startswith(self.root):
+ raise ToolError(f"Path escapes workspace directory: {path}")
+ if not os.path.isfile(full_path):
+ raise ToolError(f"File not found: {path}")
+
+ manager = self._get_manager()
+ client = await manager._get_or_start(full_path)
+ await asyncio.to_thread(client.did_open, full_path)
+ try:
+ result = await asyncio.to_thread(
+ client.request,
+ "textDocument/definition",
+ {
+ "textDocument": {"uri": "file://" + full_path},
+ "position": {"line": line - 1, "character": character - 1},
+ },
+ )
+ except ToolError:
+ raise
+ except Exception as exc:
+ raise ToolError(f"LSP definition failed: {exc}")
+
+ if not result:
+ return f"No definition found for symbol at {path}:{line}:{character}."
+
+ if isinstance(result, list):
+ if not result:
+ return f"No definition found for symbol at {path}:{line}:{character}."
+ locations = [_location_to_str(loc, self.root) for loc in result]
+ return "Definitions:\n" + "\n".join(locations)
+
+ if isinstance(result, dict) and "uri" in result:
+ return "Definition: " + _location_to_str(result, self.root)
+
+ return f"Definition (raw): {json.dumps(result)}"
+
+
+class FindReferencesTool(BaseTool):
+ """Find all references to a symbol using a language server."""
+
+ def __init__(self, root: Optional[str] = None) -> None:
+ self.root = os.path.realpath(root or os.getcwd())
+ self._manager: Optional[LSPManager] = None
+
+ @property
+ def name(self) -> str:
+ return "find_references"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Find all references to a symbol at a given position using a "
+ "language server. Returns a list of locations where the symbol "
+ "is used. Useful before renaming or refactoring."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": "string",
+ "description": "Path to the source file containing the symbol.",
+ },
+ "line": {
+ "type": "integer",
+ "description": "1-indexed line number of the symbol.",
+ },
+ "character": {
+ "type": "integer",
+ "description": "1-indexed character offset of the symbol.",
+ },
+ },
+ "required": ["path", "line", "character"],
+ }
+
+ def _get_manager(self) -> LSPManager:
+ if self._manager is None:
+ self._manager = LSPManager(self.root)
+ return self._manager
+
+ async def execute(self, path: str, line: int, character: int) -> str:
+ full_path = path if os.path.isabs(path) else os.path.join(self.root, path)
+ full_path = os.path.realpath(full_path)
+ if not full_path.startswith(self.root):
+ raise ToolError(f"Path escapes workspace directory: {path}")
+ if not os.path.isfile(full_path):
+ raise ToolError(f"File not found: {path}")
+
+ manager = self._get_manager()
+ client = await manager._get_or_start(full_path)
+ await asyncio.to_thread(client.did_open, full_path)
+ try:
+ result = await asyncio.to_thread(
+ client.request,
+ "textDocument/references",
+ {
+ "textDocument": {"uri": "file://" + full_path},
+ "position": {"line": line - 1, "character": character - 1},
+ "context": {"includeDeclaration": True},
+ },
+ )
+ except ToolError:
+ raise
+ except Exception as exc:
+ raise ToolError(f"LSP references failed: {exc}")
+
+ if not result:
+ return f"No references found for symbol at {path}:{line}:{character}."
+
+ locations = [_location_to_str(loc, self.root) for loc in result]
+ header = f"Found {len(locations)} reference(s) for symbol at {path}:{line}:{character}:"
+ return header + "\n" + "\n".join(locations)
+
+
+class GetSymbolInfoTool(BaseTool):
+ """Get the document symbols (outline) of a file using a language server."""
+
+ def __init__(self, root: Optional[str] = None) -> None:
+ self.root = os.path.realpath(root or os.getcwd())
+ self._manager: Optional[LSPManager] = None
+
+ @property
+ def name(self) -> str:
+ return "get_symbol_info"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Get the list of symbols (functions, classes, variables, etc.) "
+ "in a file using a language server. Returns a structured outline "
+ "with names, kinds, and line numbers."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": "string",
+ "description": "Path to the source file to inspect.",
+ },
+ },
+ "required": ["path"],
+ }
+
+ def _get_manager(self) -> LSPManager:
+ if self._manager is None:
+ self._manager = LSPManager(self.root)
+ return self._manager
+
+ async def execute(self, path: str) -> str:
+ full_path = path if os.path.isabs(path) else os.path.join(self.root, path)
+ full_path = os.path.realpath(full_path)
+ if not full_path.startswith(self.root):
+ raise ToolError(f"Path escapes workspace directory: {path}")
+ if not os.path.isfile(full_path):
+ raise ToolError(f"File not found: {path}")
+
+ manager = self._get_manager()
+ client = await manager._get_or_start(full_path)
+ await asyncio.to_thread(client.did_open, full_path)
+ try:
+ result = await asyncio.to_thread(
+ client.request,
+ "textDocument/documentSymbol",
+ {"textDocument": {"uri": "file://" + full_path}},
+ )
+ except ToolError:
+ raise
+ except Exception as exc:
+ raise ToolError(f"LSP documentSymbol failed: {exc}")
+
+ if not result:
+ return f"No symbols found in {path}."
+
+ # Handle both flat DocumentSymbol[] and flat SymbolInformation[]
+ kind_names = {
+ 1: "File", 2: "Module", 3: "Namespace", 4: "Package", 5: "Class",
+ 6: "Method", 7: "Property", 8: "Field", 9: "Constructor", 10: "Enum",
+ 11: "Interface", 12: "Function", 13: "Variable", 14: "Constant",
+ 15: "String", 16: "Number", 17: "Boolean", 18: "Array", 19: "Object",
+ 20: "Key", 21: "Null", 22: "EnumMember", 23: "Struct", 24: "Event",
+ 25: "Operator", 26: "TypeParameter",
+ }
+
+ lines = [f"Symbols in {path}:"]
+ if isinstance(result, list):
+ for sym in result:
+ if "location" in sym:
+ # DocumentSymbol (has children)
+ name = sym.get("name", "?")
+ kind = kind_names.get(sym.get("kind", 0), "Unknown")
+ loc = sym["location"]["range"]["start"]
+ lines.append(f" L{loc['line'] + 1:<5} [{kind:<12}] {name}")
+ for child in sym.get("children", []) or []:
+ cname = child.get("name", "?")
+ ckind = kind_names.get(child.get("kind", 0), "Unknown")
+ cloc = child["location"]["range"]["start"]
+ lines.append(f" L{cloc['line'] + 1:<5} [{ckind:<12}] {cname}")
+ else:
+ # SymbolInformation (flat)
+ name = sym.get("name", "?")
+ kind = kind_names.get(sym.get("kind", 0), "Unknown")
+ loc = sym.get("location", {}).get("range", {}).get("start", {})
+ lines.append(f" L{loc.get('line', 0) + 1:<5} [{kind:<12}] {name}")
+
+ return "\n".join(lines)
+
+
+__all__ = [
+ "GoToDefinitionTool",
+ "FindReferencesTool",
+ "GetSymbolInfoTool",
+ "LSPManager",
+] \ No newline at end of file
diff --git a/src/agentux/tools/mcp_tool.py b/src/agentux/tools/mcp_tool.py
new file mode 100644
index 0000000..03f8951
--- /dev/null
+++ b/src/agentux/tools/mcp_tool.py
@@ -0,0 +1,196 @@
+"""Exposing MCP server tools to the agent.
+
+Each remote tool becomes an ordinary :class:`~agentux.tools.base.BaseTool`, so
+the agent loop cannot tell the difference between a tool Agentux implements and
+one that lives in another process. That is the point: adding MCP changes what
+the model can call without changing how the loop calls it.
+
+Remote tools are namespaced ``mcp__<server>__<tool>``. Namespacing is not
+cosmetic -- a server is free to publish a tool called ``shell`` or ``write``,
+and without a prefix it would silently shadow a built-in one.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any, Dict, List, Optional, Tuple
+
+from ..errors import MCPError
+from ..mcp import DEFAULT_TIMEOUT, MCPServer, render_tool_result
+from ..mcp_config import MCPServerConfig, load_server_configs
+from ..models import ToolDefinition
+from .base import BaseTool
+
+#: Separator between the server name and the tool name.
+SEPARATOR = "__"
+
+
+def qualify(server: str, tool: str) -> str:
+ """The name the model uses to call a remote tool."""
+ return f"mcp{SEPARATOR}{server}{SEPARATOR}{tool}"
+
+
+def split(name: str) -> Optional[Tuple[str, str]]:
+ """Inverse of :func:`qualify`, or ``None`` if the name is not a remote tool."""
+ if not name.startswith(f"mcp{SEPARATOR}"):
+ return None
+ remainder = name[len(f"mcp{SEPARATOR}"):]
+ server, separator, tool = remainder.partition(SEPARATOR)
+ if not separator or not server or not tool:
+ return None
+ return server, tool
+
+
+class MCPTool(BaseTool):
+ """One tool provided by an MCP server."""
+
+ def __init__(
+ self,
+ server: MCPServer,
+ remote_name: str,
+ description: str,
+ schema: Dict[str, Any],
+ ) -> None:
+ self.server = server
+ self.remote_name = remote_name
+ self._description = description or "No description provided by the server."
+ self._schema = schema or {"type": "object", "properties": {}}
+
+ @property
+ def name(self) -> str:
+ return qualify(self.server.name, self.remote_name)
+
+ @property
+ def description(self) -> str:
+ return f"[MCP server {self.server.name!r}] {self._description}"
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ # Servers send JSON Schema; providers want the same shape. Only the
+ # fields that vary are rewritten.
+ schema = dict(self._schema)
+ schema.setdefault("type", "object")
+ schema.setdefault("properties", {})
+ return schema
+
+ def to_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name=self.name, description=self.description, parameters=self.parameters
+ )
+
+ async def execute(self, **kwargs: Any) -> str:
+ result = await self.server.call_tool(self.remote_name, kwargs)
+
+ text = render_tool_result(result)
+ if result.get("isError"):
+ # Surfaced as text, not raised: the spec is explicit that these are
+ # the errors a model can act on, and aborting the run would deny it
+ # the chance to retry with better arguments.
+ return f"ERROR (from MCP server {self.server.name!r}): {text}"
+ return text
+
+
+class MCPToolManager:
+ """Owns the running MCP servers and the tools they provide."""
+
+ def __init__(
+ self,
+ working_dir: str,
+ timeout: float = DEFAULT_TIMEOUT,
+ on_log: Optional[Any] = None,
+ ) -> None:
+ self.working_dir = working_dir
+ self.timeout = timeout
+ self.on_log = on_log
+ self.servers: Dict[str, MCPServer] = {}
+ self.tools: List[MCPTool] = []
+ self.warnings: List[str] = []
+ self.configs: List[MCPServerConfig] = []
+ #: (server name, tool name, reason) for each server that failed to load.
+ self.failed: List[Tuple[str, str]] = []
+
+ def _log(self, message: str) -> None:
+ if self.on_log:
+ try:
+ self.on_log(message)
+ except Exception:
+ pass
+
+ async def load(self, start: bool = True) -> List[MCPTool]:
+ """Load configured servers and their tools.
+
+ A server that fails to start is recorded and skipped. One broken server
+ must not take down the session -- Agentux's own tools still work.
+
+ Returns a snapshot, not the live list: :meth:`close` clears the
+ internal one, and a caller that kept the result should not find it
+ emptied out from under it.
+ """
+ self.configs, self.warnings = load_server_configs(self.working_dir)
+
+ for config in self.configs:
+ server = MCPServer(config, timeout=self.timeout, on_log=self._log)
+ self.servers[config.name] = server
+
+ if not start:
+ continue
+
+ try:
+ await server.start()
+ remote_tools = await server.list_tools()
+ except (MCPError, asyncio.TimeoutError, OSError) as exc:
+ self.failed.append((config.name, str(exc)))
+ self._log(f"skipping MCP server {config.name!r}: {exc}")
+ await server.close()
+ continue
+
+ for entry in remote_tools:
+ remote_name = entry.get("name")
+ if not remote_name:
+ continue
+ self.tools.append(
+ MCPTool(
+ server=server,
+ remote_name=str(remote_name),
+ description=str(entry.get("description") or ""),
+ schema=entry.get("inputSchema") or {},
+ )
+ )
+
+ self._log(
+ f"MCP server {config.name!r} ready: {len(remote_tools)} tool(s)"
+ )
+
+ return list(self.tools)
+
+ def describe(self) -> List[str]:
+ """One line per configured server, for ``--list-tools`` and ``/mcp``."""
+ lines: List[str] = []
+ for name, server in self.servers.items():
+ info = server.server_info or {}
+ label = info.get("name") or config_name(server.config)
+ version = info.get("version")
+ detail = f"{label}" + (f" {version}" if version else "")
+ if name in {f for f, _ in self.failed}:
+ reason = next(r for f, r in self.failed if f == name)
+ lines.append(f"{name}: unavailable — {reason}")
+ else:
+ count = sum(1 for t in self.tools if t.server.name == name)
+ lines.append(f"{name}: {detail} — {count} tool(s)")
+ return lines
+
+ async def close(self) -> None:
+ for server in self.servers.values():
+ try:
+ await server.close()
+ except Exception:
+ pass
+ self.servers.clear()
+ self.tools.clear()
+
+
+def config_name(config: MCPServerConfig) -> str:
+ return f"{config.command} {' '.join(config.args)}".strip()
+
+
+__all__ = ["MCPTool", "MCPToolManager", "qualify", "split", "SEPARATOR"]
diff --git a/src/agentux/tools/memory_tool.py b/src/agentux/tools/memory_tool.py
new file mode 100644
index 0000000..68baf96
--- /dev/null
+++ b/src/agentux/tools/memory_tool.py
@@ -0,0 +1,153 @@
+"""Memory tools: the model's own read and write access to the store.
+
+``memory_save`` is how the model records something it learned. ``memory_search``
+is how it looks for something it might already know. Both are deliberately
+plain: the model hands over text, the store does the ranking, and the result
+comes back as text the model can read and act on.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict
+
+from ..errors import ToolError
+from ..memory import (
+ SCOPE_GLOBAL,
+ SCOPE_PROJECT,
+ VALID_SCOPES,
+ MemoryStore,
+)
+from .base import BaseTool
+
+
+class MemorySaveTool(BaseTool):
+ """Write one thing the model learned into the store."""
+
+ def __init__(self, store: MemoryStore, project: str = "") -> None:
+ self.store = store
+ self.project = project
+
+ @property
+ def name(self) -> str:
+ return "memory_save"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Save something you learned so you can recall it later. Use it for "
+ "anything non-obvious: a gotcha, a fact about this project, a "
+ "convention, a command that works, a URL, a correction the user "
+ "gave you. One fact per call. Be specific enough that the fact is "
+ "useful months from now."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "body": {
+ "type": "string",
+ "description": "The fact to remember, in one or two sentences.",
+ },
+ "scope": {
+ "type": "string",
+ "enum": list(VALID_SCOPES),
+ "description": (
+ "'project' (default) keeps it visible only in this "
+ "workspace. 'global' makes it visible everywhere — use "
+ "that only for lessons that are genuinely general."
+ ),
+ },
+ "tags": {
+ "type": "string",
+ "description": "Optional comma-separated keywords, e.g. 'go,channels'.",
+ },
+ },
+ "required": ["body"],
+ }
+
+ async def execute(
+ self,
+ body: str,
+ scope: str = SCOPE_PROJECT,
+ tags: str = "",
+ **kwargs: Any,
+ ) -> str:
+ if body is None or not str(body).strip():
+ raise ToolError("'body' is required and must be non-empty.")
+ if scope not in VALID_SCOPES:
+ raise ToolError(
+ f"Scope must be one of {', '.join(VALID_SCOPES)}, got {scope!r}."
+ )
+ if scope == SCOPE_GLOBAL:
+ project = None
+ else:
+ project = self.project or None
+
+ memory = self.store.save(
+ str(body), scope=scope, project=project, source="model", tags=str(tags)
+ )
+ preview = memory.body if len(memory.body) <= 80 else memory.body[:80] + "..."
+ return f"Saved memory {memory.id} ({memory.scope}): {preview}"
+
+
+class MemorySearchTool(BaseTool):
+ """Look for something the model might already know."""
+
+ def __init__(self, store: MemoryStore, project: str = "") -> None:
+ self.store = store
+ self.project = project
+
+ @property
+ def name(self) -> str:
+ return "memory_search"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Search what you have learned before. Use this before answering "
+ "something you might already know, and whenever a question mentions "
+ "a project, a command, or a technology you have seen before."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": (
+ "Keywords describing what you are looking for. A few "
+ "specific words work better than a whole sentence."
+ ),
+ },
+ "limit": {
+ "type": "integer",
+ "description": "Maximum memories to return. Defaults to 5.",
+ },
+ },
+ "required": ["query"],
+ }
+
+ async def execute(self, query: str, limit: int = 5, **kwargs: Any) -> str:
+ if not query or not str(query).strip():
+ return "No memories matched."
+ try:
+ count = max(1, min(int(limit or 5), 20))
+ except (TypeError, ValueError):
+ count = 5
+
+ hits = self.store.search(str(query), project=self.project or None, limit=count)
+ if not hits:
+ return "No memories matched."
+
+ lines = [f"{len(hits)} remembered:"]
+ for index, (memory, _score) in enumerate(hits, 1):
+ scope = memory.scope if memory.scope == SCOPE_GLOBAL else "project"
+ lines.append(f"{index}. [{scope}] {memory.body}")
+ return "\n".join(lines)
+
+
+__all__ = ["MemorySaveTool", "MemorySearchTool"]
diff --git a/src/agentux/tools/repomap_tool.py b/src/agentux/tools/repomap_tool.py
new file mode 100644
index 0000000..c265c51
--- /dev/null
+++ b/src/agentux/tools/repomap_tool.py
@@ -0,0 +1,49 @@
+"""Repomap tool for Agentux."""
+
+from __future__ import annotations
+
+from typing import Any, Dict
+from ..models import ToolDefinition
+from ..repomap import RepoMap
+from .base import BaseTool
+
+
+class RepomapTool(BaseTool):
+ """Tool allowing the agent to inspect the codebase symbol outline."""
+
+ def __init__(self, root: str) -> None:
+ self.repomap = RepoMap(root)
+
+ @property
+ def name(self) -> str:
+ return "repomap"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Generate a compact, token-efficient repository symbol map. "
+ "Shows all classes, structs, functions, methods, and line numbers "
+ "across the codebase without reading entire files. "
+ "Optionally filter by symbol query or path keyword."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "Optional symbol name, keyword, or path to filter the map.",
+ },
+ "max_tokens": {
+ "type": "integer",
+ "description": "Maximum token budget for the map (default 600).",
+ },
+ },
+ }
+
+ async def execute(self, **kwargs: Any) -> str:
+ query = kwargs.get("query")
+ max_tokens = int(kwargs.get("max_tokens", 600))
+ return self.repomap.generate_map(max_tokens=max_tokens, query=query)
diff --git a/src/agentux/tools/search.py b/src/agentux/tools/search.py
new file mode 100644
index 0000000..9344ac3
--- /dev/null
+++ b/src/agentux/tools/search.py
@@ -0,0 +1,283 @@
+"""Content search across the workspace.
+
+Regex-based, the way an agent actually needs to find things: a symbol's
+definition and its call sites, a string literal, an error message. Every result
+carries enough context to act on without a second read.
+
+Results are capped and files are skipped by extension and directory, because an
+unbounded search is how an agent fills its own context window with noise.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+
+from ..errors import ToolError
+from .base import BaseTool
+
+#: Directories that are never worth grepping.
+SKIP_DIRS = {
+ ".git", ".hg", ".svn", "node_modules", "__pycache__", ".venv", "venv",
+ ".mypy_cache", ".pytest_cache", ".ruff_cache", ".tox", "dist", "build",
+ ".idea", ".vscode", "target", ".next", ".gradle", ".cache", "site-packages",
+ ".eggs", "*.egg-info",
+}
+
+#: Binary and generated formats with nothing useful in them as text.
+SKIP_SUFFIXES = {
+ ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico", ".webp", ".svgz",
+ ".pdf", ".zip", ".gz", ".bz2", ".xz", ".tar", ".7z", ".rar",
+ ".so", ".dylib", ".dll", ".exe", ".bin", ".o", ".a", ".class", ".jar",
+ ".pyc", ".pyo", ".wasm", ".woff", ".woff2", ".ttf", ".eot", ".otf",
+ ".mp3", ".mp4", ".mov", ".avi", ".wav", ".flac", ".ogg",
+ ".db", ".sqlite", ".sqlite3", ".lock",
+}
+
+#: Files larger than this are reported but not searched: a 4 MB minified bundle
+#: matches everything and tells the model nothing.
+MAX_FILE_BYTES = 1_000_000
+
+#: Caps that keep a search result readable and the context window survivable.
+MAX_MATCHES = 200
+MAX_FILES = 2_000
+MAX_LINE_CHARS = 400
+MAX_FILE_LIST = 100
+
+
+class SearchTool(BaseTool):
+ """Find text in files across the workspace."""
+
+ def __init__(self, root: Optional[str] = None) -> None:
+ self.root = os.path.realpath(root or os.getcwd())
+
+ @property
+ def name(self) -> str:
+ return "search"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Search file contents with a regular expression. Returns matching "
+ "lines with file:line references and surrounding context. Use this "
+ "to find where something is defined or used before reading whole "
+ "files. Also supports listing file paths by glob pattern when "
+ "'content_pattern' is omitted."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "content_pattern": {
+ "type": "string",
+ "description": (
+ "Regular expression to search for. Omit to list files "
+ "whose paths match 'file_pattern' instead."
+ ),
+ },
+ "path": {
+ "type": "string",
+ "description": "File or directory to search under. Defaults to the project root.",
+ },
+ "file_pattern": {
+ "type": "string",
+ "description": (
+ "Glob restricting which files are searched, e.g. '*.py' "
+ "or 'src/**/*.ts'. Omit to search all text files."
+ ),
+ },
+ "context_lines": {
+ "type": "integer",
+ "description": "Lines of context to show around each match. Defaults to 1.",
+ },
+ "ignore_case": {
+ "type": "boolean",
+ "description": "Case-insensitive match. Defaults to false.",
+ },
+ "max_matches": {
+ "type": "integer",
+ "description": "Maximum matches to return. Defaults to 200.",
+ },
+ },
+ "required": [],
+ }
+
+ # ------------------------------------------------------------------
+ # Path handling
+ # ------------------------------------------------------------------
+ def _base(self, path: Optional[str]) -> str:
+ if not path:
+ return self.root
+ candidate = path if os.path.isabs(path) else os.path.join(self.root, path)
+ resolved = os.path.realpath(os.path.expanduser(candidate))
+ if not resolved.startswith(self.root + os.sep) and resolved != self.root:
+ raise ToolError(f"Path {path!r} is outside the workspace root {self.root}.")
+ return resolved
+
+ def _walk(self, base: str) -> Iterator[str]:
+ """Yield searchable files under ``base``, pruning noise directories."""
+ if os.path.isfile(base):
+ yield base
+ return
+
+ checked = 0
+ for dirpath, dirnames, filenames in os.walk(base):
+ dirnames[:] = sorted(
+ d for d in dirnames
+ if d not in SKIP_DIRS and not d.endswith(".egg-info")
+ )
+ for filename in sorted(filenames):
+ if os.path.splitext(filename)[1].lower() in SKIP_SUFFIXES:
+ continue
+ full = os.path.join(dirpath, filename)
+ try:
+ if os.path.getsize(full) > MAX_FILE_BYTES:
+ continue
+ except OSError:
+ continue
+ yield full
+ checked += 1
+ if checked >= MAX_FILES:
+ return
+
+ def _matches_glob(self, path: str, pattern: Optional[str]) -> bool:
+ if not pattern:
+ return True
+ try:
+ from fnmatch import fnmatch
+
+ if fnmatch(path, pattern):
+ return True
+ # A bare '*.py' should also match nested paths.
+ return fnmatch(os.path.basename(path), pattern)
+ except Exception:
+ return True
+
+ # ------------------------------------------------------------------
+ # Actions
+ # ------------------------------------------------------------------
+ def _list_files(self, base: str, file_pattern: Optional[str]) -> str:
+ matches = [
+ os.path.relpath(p, self.root)
+ for p in self._walk(base)
+ if self._matches_glob(p, file_pattern)
+ ]
+ if not matches:
+ scope = os.path.relpath(base, self.root) or "."
+ return f"No files matching {file_pattern!r} under {scope}."
+
+ shown = matches[:MAX_FILE_LIST]
+ lines = "\n".join(shown)
+ footer = ""
+ if len(matches) > MAX_FILE_LIST:
+ footer = f"\n... {len(matches) - MAX_FILE_LIST} more (narrow 'file_pattern')"
+ return f"{len(matches)} file(s):\n{lines}{footer}"
+
+ def _grep(
+ self,
+ base: str,
+ pattern: str,
+ file_pattern: Optional[str],
+ context_lines: int,
+ ignore_case: bool,
+ max_matches: int,
+ ) -> str:
+ flags = re.IGNORECASE if ignore_case else 0
+ try:
+ regex = re.compile(pattern, flags)
+ except re.error as exc:
+ raise ToolError(
+ f"Invalid regular expression {pattern!r}: {exc}"
+ ) from exc
+
+ span = max(0, min(int(context_lines or 0), 5))
+ results: List[str] = []
+ matched_files: List[str] = []
+ truncated_at: Optional[str] = None
+ total = 0
+
+ for full in self._walk(base):
+ if not self._matches_glob(full, file_pattern):
+ continue
+ try:
+ with open(full, encoding="utf-8", errors="replace") as handle:
+ lines = handle.readlines()
+ except (OSError, PermissionError):
+ continue
+
+ rel = os.path.relpath(full, self.root)
+ hits = [i for i, line in enumerate(lines) if regex.search(line)]
+ if not hits:
+ continue
+ matched_files.append(rel)
+ total += len(hits)
+
+ # Collapse a run of nearby hits into one block instead of repeating
+ # the same context lines for every match.
+ shown_lines: set = set()
+ for index in hits:
+ if len(results) >= max_matches:
+ truncated_at = rel
+ break
+ start, end = max(0, index - span), min(len(lines), index + span + 1)
+ if any(j in shown_lines for j in range(start, end)):
+ continue
+ shown_lines.update(range(start, end))
+ if start > 0:
+ results.append(" ...")
+ for j in range(start, end):
+ marker = ">" if j == index else " "
+ text = lines[j].rstrip("\n")
+ if len(text) > MAX_LINE_CHARS:
+ text = text[:MAX_LINE_CHARS] + "..."
+ results.append(f"{marker} {rel}:{j + 1}: {text}")
+ if end < len(lines):
+ results.append(" ...")
+ if truncated_at:
+ break
+
+ if not results:
+ scope = os.path.relpath(base, self.root) or "."
+ where = f" under {scope}" if scope != "." else ""
+ suffix = f" matching {file_pattern!r}" if file_pattern else ""
+ return f"No matches for {pattern!r}{where}{suffix}."
+
+ header = f"{total} match(es) for {pattern!r} in {len(matched_files)} file(s)"
+ footer = ""
+ if truncated_at:
+ footer = (
+ f"\n\n... stopped at {max_matches} matches (in {truncated_at}). "
+ "Narrow the pattern or the file_pattern to see the rest."
+ )
+ elif total > max_matches:
+ footer = "\n\n... output capped."
+ return f"{header}\n\n" + "\n".join(results) + footer
+
+ async def execute(
+ self,
+ content_pattern: Optional[str] = None,
+ path: Optional[str] = None,
+ file_pattern: Optional[str] = None,
+ context_lines: int = 1,
+ ignore_case: bool = False,
+ max_matches: int = MAX_MATCHES,
+ **kwargs: Any,
+ ) -> str:
+ base = self._base(path)
+
+ if not content_pattern:
+ return self._list_files(base, file_pattern)
+
+ return self._grep(
+ base=base,
+ pattern=content_pattern,
+ file_pattern=file_pattern,
+ context_lines=context_lines,
+ ignore_case=bool(ignore_case),
+ max_matches=max(1, min(int(max_matches or MAX_MATCHES), 500)),
+ )
+
+
+__all__ = ["SearchTool"]
diff --git a/src/agentux/tools/symbols.py b/src/agentux/tools/symbols.py
new file mode 100644
index 0000000..19c269a
--- /dev/null
+++ b/src/agentux/tools/symbols.py
@@ -0,0 +1,130 @@
+"""High-speed symbol outline and code skeleton extraction tool.
+
+Allows the AI model to locate classes, functions, and types in large files
+with precise line numbers, minimizing token consumption.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+from typing import Any, Dict, List, Optional, Tuple
+
+from ..errors import ToolError
+from .base import BaseTool
+
+
+class OutlineSymbolsTool(BaseTool):
+ """Extract symbol outlines (classes, functions, types) from workspace source code."""
+
+ def __init__(self, root: Optional[str] = None) -> None:
+ self.root = os.path.realpath(root or os.getcwd())
+
+ @property
+ def name(self) -> str:
+ return "outline_symbols"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Extracts a high-level symbol outline (classes, functions, methods, types, "
+ "interfaces) with line numbers from source files (Python, Go, JS/TS, Rust). "
+ "Far faster and more token-efficient than reading full files."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": "string",
+ "description": "Path to the source code file (relative to workspace).",
+ },
+ },
+ "required": ["path"],
+ }
+
+ async def execute(self, path: str) -> str:
+ path = path.strip()
+ if not path:
+ raise ToolError("File path cannot be empty.")
+
+ full_path = path if os.path.isabs(path) else os.path.join(self.root, path)
+ full_path = os.path.realpath(full_path)
+
+ if not full_path.startswith(self.root):
+ raise ToolError(f"Path escapes workspace directory: {path}")
+ if not os.path.isfile(full_path):
+ raise ToolError(f"File not found: {path}")
+
+ ext = os.path.splitext(full_path)[1].lower()
+ patterns = self._get_patterns_for_ext(ext)
+
+ symbols: List[Tuple[int, str, str]] = []
+ total_lines = 0
+
+ try:
+ with open(full_path, "r", encoding="utf-8", errors="replace") as f:
+ for idx, line in enumerate(f, 1):
+ total_lines = idx
+ stripped = line.strip()
+ if not stripped or stripped.startswith(("//", "#", "/*", "*")):
+ continue
+
+ for kind, regex in patterns:
+ if regex.search(stripped):
+ symbols.append((idx, kind, stripped))
+ break
+ except Exception as exc:
+ raise ToolError(f"Failed to read file {path}: {exc}")
+
+ rel_path = os.path.relpath(full_path, self.root)
+ header = f"Outline of {rel_path} ({total_lines} lines, {len(symbols)} symbols found):\n"
+
+ if not symbols:
+ return header + "\n(no top-level classes or functions detected)"
+
+ out_lines = [header]
+ for line_num, kind, raw in symbols:
+ out_lines.append(f"L{line_num:<4} [{kind:<7}] {raw}")
+
+ return "\n".join(out_lines)
+
+ def _get_patterns_for_ext(self, ext: str) -> List[Tuple[str, re.Pattern]]:
+ if ext == ".py":
+ return [
+ ("class", re.compile(r"^class\s+[A-Za-z0-9_]+")),
+ ("async", re.compile(r"^async\s+def\s+[A-Za-z0-9_]+\s*\(")),
+ ("def", re.compile(r"^def\s+[A-Za-z0-9_]+\s*\(")),
+ ]
+ elif ext == ".go":
+ return [
+ ("method", re.compile(r"^func\s+\([^)]+\)\s+[A-Za-z0-9_]+\s*\(")),
+ ("func", re.compile(r"^func\s+[A-Za-z0-9_]+\s*\(")),
+ ("struct", re.compile(r"^type\s+[A-Za-z0-9_]+\s+struct\b")),
+ ("interface", re.compile(r"^type\s+[A-Za-z0-9_]+\s+interface\b")),
+ ("type", re.compile(r"^type\s+[A-Za-z0-9_]+\s+")),
+ ]
+ elif ext in (".ts", ".tsx", ".js", ".jsx"):
+ return [
+ ("class", re.compile(r"^(?:export\s+)?(?:default\s+)?class\s+[A-Za-z0-9_]+")),
+ ("func", re.compile(r"^(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+[A-Za-z0-9_]+")),
+ ("type", re.compile(r"^(?:export\s+)?(?:interface|type)\s+[A-Za-z0-9_]+")),
+ ("const", re.compile(r"^(?:export\s+)?(?:const|let|var)\s+[A-Za-z0-9_]+\s*=\s*(?:async\s*)?\(")),
+ ]
+ elif ext == ".rs":
+ return [
+ ("fn", re.compile(r"^(?:pub\s+)?(?:async\s+)?fn\s+[A-Za-z0-9_]+")),
+ ("struct", re.compile(r"^(?:pub\s+)?struct\s+[A-Za-z0-9_]+")),
+ ("enum", re.compile(r"^(?:pub\s+)?enum\s+[A-Za-z0-9_]+")),
+ ("impl", re.compile(r"^impl(?:\s*<[^>]+>)?\s+[A-Za-z0-9_]+")),
+ ("trait", re.compile(r"^(?:pub\s+)?trait\s+[A-Za-z0-9_]+")),
+ ]
+ else:
+ return [
+ ("symbol", re.compile(r"^(?:class|struct|function|def|func)\s+[A-Za-z0-9_]+")),
+ ]
+
+
+__all__ = ["OutlineSymbolsTool"]
diff --git a/src/agentux/tools/todo.py b/src/agentux/tools/todo.py
new file mode 100644
index 0000000..43d5d02
--- /dev/null
+++ b/src/agentux/tools/todo.py
@@ -0,0 +1,196 @@
+"""Task tracking for multi-step work.
+
+An agent given a five-part task will quietly do three of them and report
+success. Writing the plan down first, and updating it as it goes, is the
+cheapest thing that keeps the whole task in view.
+
+The list lives in memory and is rendered back to the model on every update, so
+the current state is always in the conversation rather than something the model
+has to remember.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict, List, Optional
+
+from ..errors import ToolError
+from .base import BaseTool
+
+#: The states a task moves through. Kept small on purpose.
+STATUSES = ("pending", "in_progress", "completed", "cancelled")
+
+#: The columns a rendered board uses, in order.
+ORDER = ("in_progress", "pending", "completed", "cancelled")
+
+MAX_TASKS = 50
+
+
+class TodoTool(BaseTool):
+ """Maintain a checklist of what the current task requires."""
+
+ def __init__(self) -> None:
+ self._items: List[Dict[str, str]] = []
+ self._next_id = 1
+
+ @property
+ def name(self) -> str:
+ return "todo"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Track a checklist of steps for the current task. Create the full "
+ "list before starting a multi-step job, keep exactly one item "
+ "'in_progress' at a time, and mark items completed as you finish "
+ "them. The rendered list comes back on every update, so you do not "
+ "need to track it yourself. Use it for anything with more than "
+ "about three steps; skip it for single actions."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "string",
+ "enum": ["add", "update", "list", "clear"],
+ "description": (
+ "add: append tasks. update: change one task's status. "
+ "list: render the current checklist. clear: remove all."
+ ),
+ },
+ "tasks": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "Task descriptions. Required for 'add'.",
+ },
+ "id": {
+ "type": "integer",
+ "description": "Task id to update. Required for 'update'.",
+ },
+ "status": {
+ "type": "string",
+ "enum": list(STATUSES),
+ "description": "New status for a task. Required for 'update'.",
+ },
+ },
+ "required": ["action"],
+ }
+
+ # ------------------------------------------------------------------
+ def _find(self, task_id: Any) -> Dict[str, str]:
+ try:
+ wanted = int(task_id)
+ except (TypeError, ValueError):
+ raise ToolError(f"Task id must be an integer, got {task_id!r}.") from None
+
+ for item in self._items:
+ if int(item["id"]) == wanted:
+ return item
+ valid = ", ".join(str(i["id"]) for i in self._items) or "(none)"
+ raise ToolError(f"No task with id {wanted}. Existing ids: {valid}")
+
+ def _render(self) -> str:
+ if not self._items:
+ return "The checklist is empty."
+
+ done = sum(1 for i in self._items if i["status"] == "completed")
+ cancelled = sum(1 for i in self._items if i["status"] == "cancelled")
+ total = len(self._items)
+
+ summary = f"{done}/{total} complete"
+ if cancelled:
+ summary += f", {cancelled} cancelled"
+ lines = [f"Checklist ({summary}):"]
+
+ for status in ORDER:
+ group = [i for i in self._items if i["status"] == status]
+ if not group:
+ continue
+ label = {"in_progress": "IN PROGRESS", "pending": "TODO",
+ "completed": "DONE", "cancelled": "SKIPPED"}[status]
+ lines.append(f"\n{label}")
+ for item in group:
+ text = item["task"]
+ if len(text) > 120:
+ text = text[:120] + "..."
+ lines.append(f" [{str(item['id']):>2}] {text}")
+
+ remaining = total - done - cancelled
+ if remaining:
+ lines.append(f"\n{remaining} item(s) still open.")
+ else:
+ lines.append("\nEverything on the list is finished.")
+ return "\n".join(lines)
+
+ def _add(self, tasks: Optional[List[str]]) -> str:
+ if not tasks:
+ raise ToolError("'add' needs a 'tasks' list of descriptions.")
+ room = MAX_TASKS - len(self._items)
+ if room <= 0:
+ raise ToolError(
+ f"The checklist is full ({MAX_TASKS} items). Update or clear "
+ "existing tasks before adding more."
+ )
+ for text in tasks[:room]:
+ self._items.append({
+ "id": str(self._next_id),
+ "task": str(text),
+ "status": "pending",
+ })
+ self._next_id += 1
+ if len(tasks) > room:
+ return self._render() + f"\n\n... {len(tasks) - room} task(s) dropped: the list is full."
+ return self._render()
+
+ def _update(self, task_id: Any, status: Optional[str]) -> str:
+ if task_id is None:
+ raise ToolError("'update' needs a task 'id'.")
+ if status not in STATUSES:
+ raise ToolError(
+ f"Invalid status {status!r}. Use one of: {', '.join(STATUSES)}."
+ )
+
+ item = self._find(task_id)
+ previous = item["status"]
+ item["status"] = status
+
+ # Keep at most one task in progress so "what am I doing now" stays
+ # unambiguous as the list gets long.
+ cleared = ""
+ if status == "in_progress":
+ for other in self._items:
+ if other is not item and other["status"] == "in_progress":
+ other["status"] = "pending"
+ cleared = f"\nMoved task [{other['id']}] back to pending."
+
+ return (
+ f"Task [{item['id']}]: {previous} -> {status}.{cleared}\n\n" + self._render()
+ )
+
+ async def execute(
+ self,
+ action: str,
+ tasks: Optional[List[str]] = None,
+ id: Optional[int] = None, # noqa: A002 - matches the JSON Schema name
+ status: Optional[str] = None,
+ **kwargs: Any,
+ ) -> str:
+ if action == "list":
+ return self._render()
+ if action == "add":
+ return self._add(tasks)
+ if action == "update":
+ return self._update(id, status)
+ if action == "clear":
+ count = len(self._items)
+ self._items.clear()
+ return f"Cleared {count} task(s)."
+
+ raise ToolError(
+ f"Unsupported action {action!r}. Use 'add', 'update', 'list', or 'clear'."
+ )
+
+
+__all__ = ["TodoTool"]
diff --git a/src/agentux/tools/web.py b/src/agentux/tools/web.py
new file mode 100644
index 0000000..eae5eab
--- /dev/null
+++ b/src/agentux/tools/web.py
@@ -0,0 +1,454 @@
+"""Live technical web search and page content extraction tools.
+
+Enables the agent to search online documentation, code references,
+and error solutions without third-party python dependencies.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import html
+import json
+import os
+import re
+import urllib.parse
+import urllib.request
+from typing import Any, Dict, List, Optional
+
+from ..errors import ToolError
+from .base import BaseTool
+
+USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Agentux/0.2.0"
+
+#: Words that carry no subject, so they must not drive a Wikipedia lookup.
+_WIKI_STOPWORDS = frozenset(
+ {
+ "what", "who", "whom", "whose", "when", "where", "why", "how", "which",
+ "is", "are", "was", "were", "do", "does", "did", "can", "could",
+ "should", "would", "will", "the", "and", "for", "with", "that",
+ "this", "from", "tell", "explain", "please", "about", "your", "you",
+ }
+)
+
+
+class WebSearchTool(BaseTool):
+ """Search technical documentation and code solutions on the live web."""
+
+ def __init__(self) -> None:
+ pass
+
+ @property
+ def name(self) -> str:
+ return "web_search"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Search technical documentation, error messages, and API references "
+ "on the live web. Uses DuckDuckGo HTML search by default, or Tavily/Brave "
+ "if API keys are configured."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "Technical search query (e.g. 'pydantic v2 field_validator example').",
+ },
+ "max_results": {
+ "type": "integer",
+ "description": "Maximum number of search results to return (default: 5).",
+ },
+ },
+ "required": ["query"],
+ }
+
+ def search(self, query: str, max_results: int = 5) -> str:
+ """Run a search synchronously.
+
+ Exists so callers outside the async tool path -- Agentux Solo grounds a
+ question before the model answers it -- can use it without an event
+ loop. ``execute`` is the tool-facing wrapper.
+ """
+ query = query.strip()
+ if not query:
+ raise ToolError("Query cannot be empty.")
+
+ # Check for Tavily API key
+ tavily_key = os.environ.get("TAVILY_API_KEY")
+ if tavily_key:
+ return self._search_tavily(query, tavily_key, max_results)
+
+ # Check for Brave API key
+ brave_key = os.environ.get("BRAVE_API_KEY")
+ if brave_key:
+ return self._search_brave(query, brave_key, max_results)
+
+ # Default: Zero-dependency DuckDuckGo HTML scraper
+ return self._search_duckduckgo(query, max_results)
+
+ async def execute(self, query: str, max_results: int = 5, **kwargs: Any) -> str:
+ if "num_results" in kwargs:
+ max_results = int(kwargs["num_results"])
+ return await asyncio.to_thread(self.search, query, max_results)
+
+ def _fetch(self, url: str) -> str:
+ """GET a URL and return the decoded body."""
+ req = urllib.request.Request(
+ url,
+ headers={"User-Agent": USER_AGENT, "Accept": "application/json, text/html"},
+ )
+ with urllib.request.urlopen(req, timeout=20) as resp:
+ return resp.read().decode("utf-8", errors="replace")
+
+ def search_wikipedia(self, query: str, max_chars: int = 1200) -> str:
+ """Look a topic up on Wikipedia and return its lead sentence.
+
+ Keyless and reliable, which makes it the best grounding source for a
+ small model: it returns a sentence containing the fact rather than a
+ headline the model can misread.
+
+ Each candidate phrase is searched on its own and the best-matching
+ article wins. Opensearch matches whole phrases, so a question finds
+ nothing while its content words find the article; a single word often
+ lands on a disambiguation page ("Mojo" is one), so the phrase is tried
+ first. A title that merely contains the word is not enough either --
+ the extract has to mention it, and a short title beats a long one when
+ the mentions tie.
+ """
+ words = self._subject_words(query)
+ if not words:
+ return ""
+ terms = set(words)
+
+ candidates: List[str] = []
+ phrase = " ".join(words)
+ if phrase:
+ candidates.append(phrase)
+ candidates.extend(word for word in words if word != phrase)
+
+ best_score = None
+ best_title = ""
+ best_extract = ""
+ try:
+ for candidate in candidates[:4]:
+ for title in self._wikipedia_titles(candidate)[:2]:
+ extract = self._wikipedia_summary(title)
+ if not extract:
+ continue
+ haystack = (title + " " + extract).lower()
+ hits = sum(1 for term in terms if term in haystack)
+ score = (hits, -len(title.split()))
+ if best_score is None or score > best_score:
+ best_score = score
+ best_title = title
+ best_extract = extract
+ if not best_extract:
+ return ""
+ # The lead paragraph may not answer the question -- "who invented
+ # the transistor" is not answered by a definition. Pick the
+ # paragraph that mentions the subject words most.
+ paragraph = self._wikipedia_best_paragraph(best_title, list(terms))
+ return (paragraph or best_extract)[:max_chars]
+ except Exception:
+ return ""
+
+ def _wikipedia_best_paragraph(self, title: str, terms: List[str]) -> str:
+ """The paragraph of an article that mentions the subject words most."""
+ text = self._wikipedia_full_extract(title)
+ if not text:
+ return ""
+ best = ""
+ best_hits = 0
+ for paragraph in text.split("\n"):
+ clean = " ".join(paragraph.split())
+ if len(clean) < 40:
+ continue
+ lowered = clean.lower()
+ hits = sum(1 for term in terms if term in lowered)
+ if hits > best_hits:
+ best, best_hits = clean, hits
+ return best
+
+ def _wikipedia_full_extract(self, title: str) -> str:
+ url = "https://en.wikipedia.org/w/api.php?" + urllib.parse.urlencode(
+ {
+ "action": "query",
+ "prop": "extracts",
+ "explaintext": 1,
+ "format": "json",
+ "redirects": 1,
+ "titles": title,
+ }
+ )
+ data = json.loads(self._fetch(url))
+ for page in data.get("query", {}).get("pages", {}).values():
+ extract = page.get("extract")
+ if extract:
+ return str(extract)
+ return ""
+
+ @staticmethod
+ def _subject_words(query: str) -> List[str]:
+ """The words in a question that could name its subject, in order."""
+ return [
+ word
+ for word in re.findall(r"[a-z0-9]+", str(query).lower())
+ if len(word) >= 4 and word not in _WIKI_STOPWORDS
+ ]
+
+ def _wikipedia_titles(self, query: str) -> List[str]:
+ url = "https://en.wikipedia.org/w/api.php?" + urllib.parse.urlencode(
+ {
+ "action": "opensearch",
+ "search": query,
+ "limit": 5,
+ "format": "json",
+ "profile": "fuzzy",
+ }
+ )
+ data = json.loads(self._fetch(url))
+ if len(data) > 1 and isinstance(data[1], list):
+ return [str(title) for title in data[1]]
+ return []
+
+ def _wikipedia_summary(self, title: str) -> str:
+ path = urllib.parse.quote(title.replace(" ", "_"), safe="()_")
+ data = json.loads(
+ self._fetch(f"https://en.wikipedia.org/api/rest_v1/page/summary/{path}")
+ )
+ extract = data.get("extract")
+ if not extract or data.get("type") == "disambiguation":
+ return ""
+ return f"{data.get('title', title)}: {extract}"
+
+ def _search_duckduckgo(self, query: str, max_results: int) -> str:
+ encoded_query = urllib.parse.urlencode({"q": query, "b": ""})
+ url = f"https://html.duckduckgo.com/html/?{encoded_query}"
+
+ req = urllib.request.Request(
+ url,
+ headers={
+ "User-Agent": USER_AGENT,
+ "Accept": "text/html,application/xhtml+xml",
+ "Accept-Language": "en-US,en;q=0.9",
+ },
+ )
+
+ try:
+ with urllib.request.urlopen(req, timeout=15) as resp:
+ content = resp.read().decode("utf-8", errors="replace")
+ except Exception as exc:
+ return f"Web search failed: {exc}"
+
+ # Parse results with regex
+ results: List[Dict[str, str]] = []
+ pattern = re.compile(
+ r'<a[^>]+class="result__snippet"[^>]*href="(?P<link>[^"]+)"[^>]*>(?P<snippet>.*?)</a>',
+ re.DOTALL | re.IGNORECASE,
+ )
+ title_pattern = re.compile(
+ r'<a[^>]+class="result__url"[^>]*>(?P<title>.*?)</a>',
+ re.DOTALL | re.IGNORECASE,
+ )
+
+ # Alternative generic extraction for DuckDuckGo HTML layout
+ block_pattern = re.compile(
+ r'<div[^>]+class="[^"]*result__body[^"]*"[^>]*>(.*?)</div>\s*</div>',
+ re.DOTALL | re.IGNORECASE,
+ )
+
+ for block in block_pattern.findall(content):
+ if len(results) >= max_results:
+ break
+
+ title_m = re.search(r'<a[^>]+class="result__a"[^>]*href="([^"]+)"[^>]*>(.*?)</a>', block, re.DOTALL)
+ snippet_m = re.search(r'<a[^>]+class="result__snippet"[^>]*>(.*?)</a>', block, re.DOTALL)
+
+ if title_m:
+ raw_url = title_m.group(1)
+ # Unpack DuckDuckGo redirect uddg= if present
+ if "uddg=" in raw_url:
+ parsed = urllib.parse.parse_qs(urllib.parse.urlparse(raw_url).query)
+ raw_url = parsed.get("uddg", [raw_url])[0]
+
+ title = re.sub(r"<[^>]+>", "", title_m.group(2)).strip()
+ title = html.unescape(title)
+
+ snippet = ""
+ if snippet_m:
+ snippet = re.sub(r"<[^>]+>", "", snippet_m.group(1)).strip()
+ snippet = html.unescape(snippet)
+
+ results.append({
+ "title": title or "Untitled",
+ "url": raw_url,
+ "snippet": snippet,
+ })
+
+ if not results:
+ return f"No results found for query: {query!r}"
+
+ lines = [f"Web Search Results for '{query}' ({len(results)} matches):\n"]
+ for idx, item in enumerate(results, 1):
+ lines.append(f"{idx}. **{item['title']}**")
+ lines.append(f" URL: {item['url']}")
+ if item["snippet"]:
+ lines.append(f" {item['snippet']}")
+ lines.append("")
+
+ return "\n".join(lines).strip()
+
+ def _search_tavily(self, query: str, api_key: str, max_results: int) -> str:
+ req_data = json.dumps({"api_key": api_key, "query": query, "max_results": max_results}).encode("utf-8")
+ req = urllib.request.Request(
+ "https://api.tavily.com/search",
+ data=req_data,
+ headers={"Content-Type": "application/json", "User-Agent": USER_AGENT},
+ )
+ try:
+ with urllib.request.urlopen(req, timeout=15) as resp:
+ data = json.loads(resp.read().decode("utf-8"))
+ except Exception as exc:
+ return f"Tavily search error: {exc}"
+
+ results = data.get("results", [])
+ if not results:
+ return f"No results found for query: {query!r}"
+
+ lines = [f"Tavily Search Results for '{query}':\n"]
+ for idx, r in enumerate(results[:max_results], 1):
+ lines.append(f"{idx}. **{r.get('title', 'Untitled')}**")
+ lines.append(f" URL: {r.get('url', '')}")
+ lines.append(f" {r.get('content', '')}\n")
+ return "\n".join(lines).strip()
+
+ def _search_brave(self, query: str, api_key: str, max_results: int) -> str:
+ encoded = urllib.parse.urlencode({"q": query, "count": max_results})
+ url = f"https://api.search.brave.com/res/v1/web/search?{encoded}"
+ req = urllib.request.Request(
+ url,
+ headers={"X-Subscription-Token": api_key, "Accept": "application/json", "User-Agent": USER_AGENT},
+ )
+ try:
+ with urllib.request.urlopen(req, timeout=15) as resp:
+ data = json.loads(resp.read().decode("utf-8"))
+ except Exception as exc:
+ return f"Brave search error: {exc}"
+
+ results = data.get("web", {}).get("results", [])
+ if not results:
+ return f"No results found for query: {query!r}"
+
+ lines = [f"Brave Search Results for '{query}':\n"]
+ for idx, r in enumerate(results[:max_results], 1):
+ lines.append(f"{idx}. **{r.get('title', 'Untitled')}**")
+ lines.append(f" URL: {r.get('url', '')}")
+ lines.append(f" {r.get('description', '')}\n")
+ return "\n".join(lines).strip()
+
+
+class FetchWebPageTool(BaseTool):
+ """Scrape and convert online web pages and documentation to clean readable text."""
+
+ @property
+ def name(self) -> str:
+ return "fetch_web_page"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Fetch an online URL and extract its text content, converting HTML "
+ "into clean readable plain text / markdown. Useful for reading documentation."
+ )
+
+ @property
+ def parameters(self) -> Dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "url": {
+ "type": "string",
+ "description": "Full HTTP or HTTPS URL to fetch.",
+ },
+ "max_chars": {
+ "type": "integer",
+ "description": "Maximum characters to return (default: 8000).",
+ },
+ },
+ "required": ["url"],
+ }
+
+ async def execute(self, url: str, max_chars: int = 8000) -> str:
+ url = url.strip()
+ if not url.startswith(("http://", "https://")):
+ raise ToolError(f"URL must start with http:// or https://: {url!r}")
+
+ req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
+ try:
+ with urllib.request.urlopen(req, timeout=20) as resp:
+ headers = getattr(resp, "headers", None)
+ charset = (headers.get_content_charset() if headers and hasattr(headers, "get_content_charset") else None) or "utf-8"
+ raw_html = resp.read().decode(charset, errors="replace")
+ except Exception as exc:
+ return f"Failed to fetch {url}: {exc}"
+
+ text = self._html_to_markdown(raw_html)
+ if len(text) > max_chars:
+ text = text[:max_chars] + f"\n\n[... truncated at {max_chars} characters ...]"
+
+ return f"Content of {url}:\n\n{text}"
+
+ def _html_to_markdown(self, raw_html: str) -> str:
+ # Strip script, style, head, nav, footer
+ content = re.sub(r"<(script|style|head|nav|footer)[^>]*>.*?</\1>", " ", raw_html, flags=re.DOTALL | re.IGNORECASE)
+ content = re.sub(r"<!--.*?-->", " ", content, flags=re.DOTALL)
+
+ # Convert links <a href="url">text</a> -> [text](url)
+ content = re.sub(
+ r'<a[^>]+href="([^"]+)"[^>]*>(.*?)</a>',
+ lambda m: f"[{re.sub(r'<[^>]+>', '', m.group(2)).strip()}]({m.group(1)})",
+ content,
+ flags=re.DOTALL | re.IGNORECASE,
+ )
+
+ # Convert headings
+ for h in range(6, 0, -1):
+ content = re.sub(
+ rf"<h{h}[^>]*>(.*?)</h{h}>",
+ rf"\n\n{'#' * h} \1\n\n",
+ content,
+ flags=re.DOTALL | re.IGNORECASE,
+ )
+
+ # Convert paragraphs, list items, breaks
+ content = re.sub(r"<li[^>]*>(.*?)</li>", r"\n• \1", content, flags=re.DOTALL | re.IGNORECASE)
+ content = re.sub(r"<p[^>]*>(.*?)</p>", r"\n\n\1\n\n", content, flags=re.DOTALL | re.IGNORECASE)
+ content = re.sub(r"<br\s*/?>", "\n", content, flags=re.IGNORECASE)
+
+ # Strip remaining tags
+ content = re.sub(r"<[^>]+>", " ", content)
+
+ # Decode HTML entities
+ content = html.unescape(content)
+
+ # Collapse whitespace
+ lines = [re.sub(r"[ \t]+", " ", line).strip() for line in content.split("\n")]
+ collapsed = []
+ prev_blank = False
+ for line in lines:
+ if not line:
+ if not prev_blank:
+ collapsed.append("")
+ prev_blank = True
+ else:
+ collapsed.append(line)
+ prev_blank = False
+
+ return "\n".join(collapsed).strip()
+
+
+__all__ = ["WebSearchTool", "FetchWebPageTool"]