Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

code search and less opinionated tool calling interface (#733)

r33drichards6d9cbc1a9043
diff --git a/.prettierignore b/.prettierignore
index 81d0f08963..c9aaff70f2 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -32,4 +32,7 @@ pnpm-lock.yaml
uv.lock
# Docs with complex JSX formatting
-docs/content/docs/get-started/quickstart.mdx
\ No newline at end of file
+docs/content/docs/get-started/quickstart.mdx
+
+# Git worktrees (separate branches)
+.worktrees/
\ No newline at end of file
diff --git a/docs/scripts/README.md b/docs/scripts/README.md
index 317350a420..07c32cc02f 100644
--- a/docs/scripts/README.md
+++ b/docs/scripts/README.md
@@ -113,3 +113,121 @@ modal app show cua-docs-mcp
```
The crawler runs daily at 6 AM UTC and automatically updates the databases.
+
+## Code Indexing
+
+The Modal app also indexes the CUA source code across all git tags, enabling semantic and full-text search over versioned code.
+
+### Architecture
+
+Code indexing uses **parallel sharded processing** for performance:
+
+```
+┌─────────────────────────────────────────────────────────────────┐
+│ generate_code_index_parallel() │
+│ │
+│ 1. Clone/fetch git repository │
+│ 2. Get all tags (e.g., agent-v0.7.3, computer-v0.5.0) │
+│ 3. Group tags by component │
+│ 4. Dispatch parallel workers via Modal starmap │
+└─────────────────────────────────────────────────────────────────┘
+ │
+ ┌──────────────────┼──────────────────┐
+ ▼ ▼ ▼
+ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
+ │ index_ │ │ index_ │ │ index_ │
+ │ component │ │ component │ │ component │
+ │ (agent) │ │ (computer) │ │ (lume) │
+ │ │ │ │ │ │
+ │ 112 tags │ │ 58 tags │ │ 49 tags │
+ └─────────────┘ └─────────────┘ └─────────────┘
+ │ │ │
+ ▼ ▼ ▼
+ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
+ │ SQLite + │ │ SQLite + │ │ SQLite + │
+ │ LanceDB │ │ LanceDB │ │ LanceDB │
+ │ (agent) │ │ (computer) │ │ (lume) │
+ └─────────────┘ └─────────────┘ └─────────────┘
+```
+
+Each component gets its own databases:
+- `code_index_{component}.sqlite` - FTS5 full-text search
+- `code_index_{component}.lancedb/` - Vector embeddings for semantic search
+
+### Running Code Indexing
+
+```bash
+# Run parallel code indexing (default)
+modal run docs/scripts/modal_app.py --code-only
+
+# Run in detached mode to monitor via dashboard
+modal run --detach docs/scripts/modal_app.py --code-only
+
+# Run sequential (legacy) mode
+modal run docs/scripts/modal_app.py --code-only --no-parallel
+
+# Skip code indexing, only crawl docs
+modal run docs/scripts/modal_app.py --skip-code
+```
+
+### MCP Server: Querying Sharded Databases
+
+The MCP server automatically discovers and queries across all component databases:
+
+**SQLite Queries** - Uses `ATTACH DATABASE` to create a unified view:
+```sql
+-- This queries across ALL component databases
+SELECT component, version, file_path
+FROM code_files
+WHERE component = 'agent' AND version = '0.7.3'
+
+-- Full-text search across all components
+SELECT * FROM code_files_fts
+WHERE code_files_fts MATCH 'ComputerAgent'
+```
+
+**Vector Search** - Queries all LanceDBs and merges results by similarity:
+```python
+# Searches all component databases, returns top results
+query_code_vectors("screenshot capture implementation", limit=10)
+
+# Search specific component only
+query_code_vectors("agent loop", component="agent", limit=10)
+```
+
+### Database Schema
+
+**SQLite Table: code_files**
+| Column | Type | Description |
+|--------|------|-------------|
+| id | INTEGER | Primary key |
+| component | TEXT | Component name (agent, computer, etc.) |
+| version | TEXT | Version string (0.7.3) |
+| file_path | TEXT | Path within repository |
+| content | TEXT | Full source code |
+| language | TEXT | python, typescript, javascript |
+
+**LanceDB Schema: code**
+| Column | Type | Description |
+|--------|------|-------------|
+| text | TEXT | Source code (embedded) |
+| vector | VECTOR(384) | all-MiniLM-L6-v2 embedding |
+| component | TEXT | Component name |
+| version | TEXT | Version string |
+| file_path | TEXT | Path within repository |
+| language | TEXT | Programming language |
+
+### Size Limits
+
+- **SQLite**: Files up to 1MB are indexed
+- **LanceDB**: Files up to 100KB are embedded (larger files skip embedding)
+- **File types**: `.py`, `.ts`, `.tsx`, `.js`
+
+### Scheduled Indexing
+
+Code indexing runs daily at 5 AM UTC (before docs crawl at 6 AM):
+
+```bash
+# View scheduled runs
+modal app show cua-docs-mcp
+```
diff --git a/docs/scripts/mcp_server.py b/docs/scripts/mcp_server.py
index 01864425b5..6df6b9c646 100644
--- a/docs/scripts/mcp_server.py
+++ b/docs/scripts/mcp_server.py
@@ -1,73 +1,221 @@
"""
-FastMCP SSE HTTP Server for CUA Documentation
-Provides semantic search (LanceDB) and full-text search (SQLite FTS5) over the documentation
+FastMCP SSE HTTP Server for CUA Documentation and Code
+Provides direct read-only query access to documentation and versioned source code databases.
+
+Available databases:
+- Documentation SQLite (docs.sqlite): Full-text search over documentation pages
+- Documentation LanceDB (docs.lance): Semantic vector search over documentation
+- Code SQLite (code_index.sqlite): Full-text search over versioned source code
+- Code LanceDB (code_index.lancedb): Semantic vector search over versioned source code
"""
import sqlite3
from pathlib import Path
-from typing import Optional
+from typing import Any, Optional
import lancedb
from fastmcp import FastMCP
from lancedb.embeddings import get_registry
-# Configuration
+# Configuration - Documentation
DB_PATH = Path(__file__).parent.parent / "docs_db"
SQLITE_PATH = DB_PATH / "docs.sqlite"
+# Configuration - Code Index
+CODE_DB_PATH = Path(__file__).parent.parent / "code_db"
+# Legacy paths (for backward compatibility)
+CODE_SQLITE_PATH = CODE_DB_PATH / "code_index.sqlite"
+CODE_LANCEDB_PATH = CODE_DB_PATH / "code_index.lancedb"
+
# Initialize the embedding model (same as used for indexing)
model = get_registry().get("sentence-transformers").create(name="all-MiniLM-L6-v2")
# Create FastMCP server
mcp = FastMCP(
name="CUA Docs",
- instructions="""CUA Documentation Server - provides search and retrieval for Computer Use Agent (CUA) documentation.
+ instructions="""CUA Documentation and Code Server - provides direct read-only query access to Computer Use Agent (CUA) documentation and versioned source code.
+
+=== AVAILABLE TOOLS ===
+
+Documentation:
+- query_docs_db: Execute SQL queries against the documentation SQLite database
+- query_docs_vectors: Execute vector similarity searches against the documentation LanceDB
+
+Code:
+- query_code_db: Execute SQL queries against the code search SQLite database
+- query_code_vectors: Execute vector similarity searches against the code LanceDB
-Documentation covers:
-- CUA SDK: Python library for building computer-use agents with screen capture, mouse/keyboard control
+All tools are READ-ONLY. Only SELECT queries are allowed for SQL databases.
+
+=== DOCUMENTATION DATABASE ===
+
+The documentation database contains crawled pages from cua.ai/docs covering:
+- CUA SDK: Python library for building computer-use agents
- CUA Bench: Benchmarking framework for evaluating computer-use agents
- Agent Loop: Core execution loop for autonomous agent operation
- Sandboxes: Docker and cloud VM environments for safe agent execution
- Computer interfaces: Screen, mouse, keyboard, and bash interaction APIs
-Available tools:
-- search_docs: Semantic/vector search - best for conceptual queries like "how does X work?"
-- search_docs_fts: Full-text search - best for exact terms, code snippets, or specific keywords
-- get_page_content: Get full content of a specific page by URL
-- get_page_raw_markdown: Get raw markdown with original formatting
-- list_pages: Browse available documentation pages
-- get_doc_categories: See all documentation categories
+=== CODE DATABASE ===
+
+The code database contains versioned source code indexed across all git tags.
+Components include: agent, computer, mcp-server, som, etc.
+
+=== WORKFLOW EXAMPLES ===
-IMPORTANT: After performing search_docs or search_docs_fts queries, ALWAYS use get_page_content
-to retrieve the full page context before answering. Search results return snippets/chunks that
-may lack important context. The full page often contains setup instructions, prerequisites,
-code examples, and related information essential for complete answers.
+1. Find documentation about a topic:
+ - Use query_docs_vectors with a natural language query for semantic search
+ - Use query_docs_db with FTS5 MATCH for keyword search
-Always cite the source URL when providing information.""",
+2. Explore code across versions:
+ - List components: SELECT component, COUNT(DISTINCT version) FROM code_files GROUP BY component
+ - Search code: Use query_code_db with FTS5 on code_files_fts
+ - Get file content: SELECT content FROM code_files WHERE component='agent' AND version='0.7.3' AND file_path='...'
+
+3. Semantic code search:
+ - Use query_code_vectors with natural language queries like "screenshot capture implementation"
+
+IMPORTANT: Always cite sources - URLs for docs, component@version:path for code.""",
)
# Global database connections
_lance_db: Optional[lancedb.DBConnection] = None
_lance_table = None
_sqlite_conn: Optional[sqlite3.Connection] = None
+_code_lance_tables: dict = {} # component -> (db, table)
+_code_sqlite_conn = None
+_code_components: list[str] = []
def get_lance_table():
- """Get or create LanceDB connection"""
+ """Get or create documentation LanceDB connection"""
global _lance_db, _lance_table
if _lance_table is None:
if not DB_PATH.exists():
raise RuntimeError(
- f"Database not found at {DB_PATH}. "
- "Run generate_db.py first to create the database."
+ f"Database not found at {DB_PATH}. Run generate_db.py first to create the database."
)
_lance_db = lancedb.connect(DB_PATH)
_lance_table = _lance_db.open_table("docs")
return _lance_table
+def discover_code_components() -> list[str]:
+ """Discover available component databases."""
+ global _code_components
+ if not _code_components:
+ if CODE_DB_PATH.exists():
+ # Find all component SQLite databases
+ for db_file in CODE_DB_PATH.glob("code_index_*.sqlite"):
+ component = db_file.stem.replace("code_index_", "")
+ _code_components.append(component)
+ # Fallback to legacy single database
+ if not _code_components and CODE_SQLITE_PATH.exists():
+ _code_components.append("_legacy")
+ return _code_components
+
+
+def get_code_lance_tables() -> list[tuple[str, Any]]:
+ """Get LanceDB connections for all code components."""
+ global _code_lance_tables
+ components = discover_code_components()
+
+ for component in components:
+ if component not in _code_lance_tables:
+ if component == "_legacy":
+ db_path = CODE_LANCEDB_PATH
+ else:
+ db_path = CODE_DB_PATH / f"code_index_{component}.lancedb"
+
+ if db_path.exists():
+ db = lancedb.connect(db_path)
+ table = db.open_table("code")
+ _code_lance_tables[component] = (db, table)
+
+ return [(comp, tbl) for comp, (_, tbl) in _code_lance_tables.items()]
+
+
+def get_code_sqlite_conn():
+ """Get SQLite connection with all component databases attached."""
+ global _code_sqlite_conn
+ if _code_sqlite_conn is None:
+ components = discover_code_components()
+ if not components:
+ raise RuntimeError(
+ f"No code databases found at {CODE_DB_PATH}. "
+ "Run 'modal run docs/scripts/modal_app.py' to create the databases."
+ )
+
+ # Create in-memory database and attach all component databases
+ _code_sqlite_conn = sqlite3.connect(":memory:")
+ _code_sqlite_conn.row_factory = sqlite3.Row
+
+ # Check for legacy single database first
+ has_legacy = False
+ if CODE_SQLITE_PATH.exists() and "_legacy" in components:
+ _code_sqlite_conn.execute(
+ f"ATTACH DATABASE 'file:{CODE_SQLITE_PATH}?mode=ro' AS code_legacy"
+ )
+ has_legacy = True
+
+ # Attach each component database
+ attached = []
+ for component in components:
+ if component == "_legacy":
+ continue
+ db_path = CODE_DB_PATH / f"code_index_{component}.sqlite"
+ if db_path.exists():
+ # SQLite schema names can't have hyphens
+ safe_name = component.replace("-", "_")
+ _code_sqlite_conn.execute(
+ f"ATTACH DATABASE 'file:{db_path}?mode=ro' AS code_{safe_name}"
+ )
+ attached.append(safe_name)
+
+ # Create unified view across all component databases
+ if attached or has_legacy:
+ union_parts = []
+
+ # Include legacy database if it exists
+ if has_legacy:
+ union_parts.append(
+ "SELECT id, component, version, file_path, content, language FROM code_legacy.code_files"
+ )
+
+ # Include component databases
+ for safe_name in attached:
+ union_parts.append(
+ f"SELECT id, component, version, file_path, content, language FROM code_{safe_name}.code_files"
+ )
+
+ union_sql = " UNION ALL ".join(union_parts)
+ _code_sqlite_conn.execute(f"CREATE VIEW code_files AS {union_sql}")
+
+ # Create unified FTS view (queries individual FTS tables)
+ # Note: This is a regular view, not an FTS table, so MATCH won't work on it
+ # Users must query component-specific FTS tables like: code_agent.code_files_fts
+ fts_union_parts = []
+
+ # Include legacy FTS if it exists
+ if has_legacy:
+ fts_union_parts.append(
+ "SELECT rowid, content, component, version, file_path FROM code_legacy.code_files_fts"
+ )
+
+ # Include component FTS tables
+ for safe_name in attached:
+ fts_union_parts.append(
+ f"SELECT rowid, content, component, version, file_path FROM code_{safe_name}.code_files_fts"
+ )
+
+ fts_union_sql = " UNION ALL ".join(fts_union_parts)
+ _code_sqlite_conn.execute(f"CREATE VIEW code_files_fts_union AS {fts_union_sql}")
+
+ return _code_sqlite_conn
+
+
def get_sqlite_conn() -> sqlite3.Connection:
- """Get or create SQLite connection"""
+ """Get or create documentation SQLite connection (read-only)"""
global _sqlite_conn
if _sqlite_conn is None:
if not SQLITE_PATH.exists():
@@ -75,337 +223,325 @@ def get_sqlite_conn() -> sqlite3.Connection:
f"SQLite database not found at {SQLITE_PATH}. "
"Run generate_sqlite.py first to create the database."
)
- _sqlite_conn = sqlite3.connect(SQLITE_PATH)
+ _sqlite_conn = sqlite3.connect(f"file:{SQLITE_PATH}?mode=ro", uri=True)
_sqlite_conn.row_factory = sqlite3.Row
return _sqlite_conn
# =============================================================================
-# Semantic Search Tools (LanceDB)
+# Documentation Query Tools (Read-Only)
# =============================================================================
@mcp.tool
-def search_docs(query: str, limit: int = 5, category: Optional[str] = None) -> list[dict]:
+def query_docs_db(sql: str) -> list[dict]:
"""
- Semantic search over CUA documentation using vector embeddings.
- Best for conceptual queries like "how does the agent loop work?" or "what is a sandbox?"
+ Execute a SQL query against the documentation database.
+ The database is READ-ONLY.
+
+ Database Schema:
+
+ Table: pages
+ - id INTEGER PRIMARY KEY AUTOINCREMENT
+ - url TEXT NOT NULL UNIQUE -- Full URL of the documentation page
+ - title TEXT NOT NULL -- Page title
+ - description TEXT -- Page description/summary
+ - category TEXT NOT NULL -- Category (e.g., 'cua', 'cuabench', 'llms.txt')
+ - subcategory TEXT -- Subcategory within the main category
+ - page_name TEXT -- Short page name
+ - content TEXT NOT NULL -- Plain text content (markdown stripped)
+ - raw_markdown TEXT -- Original markdown content
+
+ Virtual Table: pages_fts (FTS5 full-text search)
+ - title TEXT -- Full-text indexed title
+ - content TEXT -- Full-text indexed content
+
+ Example queries:
+
+ 1. List all pages with categories:
+ SELECT url, title, category FROM pages ORDER BY category, title
+
+ 2. Get page count by category:
+ SELECT category, COUNT(*) as count FROM pages GROUP BY category
+
+ 3. Full-text search with snippets:
+ SELECT p.url, p.title, snippet(pages_fts, 1, '>>>', '<<<', '...', 64) as snippet
+ FROM pages_fts
+ JOIN pages p ON pages_fts.rowid = p.id
+ WHERE pages_fts MATCH 'agent loop'
+ ORDER BY rank
+ LIMIT 10
+
+ 4. Get full page content:
+ SELECT url, title, content, raw_markdown FROM pages WHERE url LIKE '%quickstart%'
+
+ 5. Search in specific category:
+ SELECT p.url, p.title
+ FROM pages_fts
+ JOIN pages p ON pages_fts.rowid = p.id
+ WHERE pages_fts MATCH 'sandbox'
+ AND p.category = 'cua'
+
+ 6. FTS5 query syntax examples:
+ - Simple words: 'install' finds pages containing 'install'
+ - Phrases: '"computer use agent"' finds exact phrase
+ - AND/OR: 'install AND docker' or 'install OR setup'
+ - Prefix: 'config*' matches configure, configuration, etc.
+ - NOT: 'install NOT windows'
Args:
- query: Natural language search query - describe what you're looking for
- limit: Maximum number of results to return (default: 5, max: 20)
- category: Optional category filter (e.g., 'cua', 'cuabench', 'llms.txt')
+ sql: SQL query to execute
Returns:
- List of relevant documentation chunks with URLs, content, and relevance scores
+ List of dictionaries, one per row, with column names as keys
"""
- limit = min(max(1, limit), 20)
-
- table = get_lance_table()
-
- # Build search query
- search = table.search(query).limit(limit)
-
- # Apply category filter if specified
- if category:
- # Escape single quotes to prevent injection via the category parameter
- safe_category = category.replace("'", "''")
- search = search.where(f"category = '{safe_category}'")
-
- results = search.to_list()
-
- # Format results
- formatted = []
- for r in results:
- formatted.append(
- {
- "title": r.get("title", ""),
- "url": r.get("url", ""),
- "category": r.get("category", ""),
- "content": r.get("text", ""),
- "relevance_score": round(1 - r.get("_distance", 0), 4),
- }
- )
-
- return formatted
-
-
-# =============================================================================
-# Full-Text Search Tools (SQLite FTS5)
-# =============================================================================
+ conn = get_sqlite_conn()
+ cursor = conn.cursor()
+ cursor.execute(sql)
+ return [dict(row) for row in cursor.fetchall()]
@mcp.tool
-def search_docs_fts(
- query: str, limit: int = 5, category: Optional[str] = None, highlight: bool = True
+def query_docs_vectors(
+ query: str,
+ limit: int = 10,
+ where: Optional[str] = None,
+ select: Optional[list[str]] = None,
) -> list[dict]:
"""
- Full-text search over CUA documentation using SQLite FTS5.
- Best for exact keyword matches, code snippets, function names, or specific terms.
-
- Supports FTS5 query syntax:
- - Simple words: "install" finds pages containing "install"
- - Phrases: '"computer use agent"' finds exact phrase
- - AND/OR: "install AND docker" or "install OR setup"
- - Prefix: "config*" matches configure, configuration, etc.
- - NOT: "install NOT windows"
-
- Args:
- query: FTS5 search query
- limit: Maximum number of results (default: 5, max: 50)
- category: Optional category filter
- highlight: Include highlighted snippets (default: True)
-
- Returns:
- List of matching pages with URLs, titles, and optional snippets
- """
- limit = min(max(1, limit), 50)
-
- conn = get_sqlite_conn()
- cursor = conn.cursor()
-
- try:
- if highlight:
- sql = """
- SELECT
- p.url,
- p.title,
- p.category,
- snippet(pages_fts, 1, '**', '**', '...', 64) as snippet
- FROM pages_fts
- JOIN pages p ON pages_fts.rowid = p.id
- WHERE pages_fts MATCH ?
- """
- else:
- sql = """
- SELECT p.url, p.title, p.category
- FROM pages_fts
- JOIN pages p ON pages_fts.rowid = p.id
- WHERE pages_fts MATCH ?
- """
-
- params = [query]
- if category:
- sql += " AND p.category = ?"
- params.append(category)
-
- sql += " ORDER BY rank LIMIT ?"
- params.append(limit)
+ Execute a vector similarity search against the documentation LanceDB (read-only).
- cursor.execute(sql, params)
- rows = cursor.fetchall()
+ This provides direct access to the vector database for semantic search.
+ The query is embedded using all-MiniLM-L6-v2 and compared against document embeddings.
- results = []
- for row in rows:
- result = {
- "url": row["url"],
- "title": row["title"],
- "category": row["category"],
- }
- if highlight and "snippet" in row.keys():
- result["snippet"] = row["snippet"]
- results.append(result)
-
- return results
-
- except sqlite3.OperationalError as e:
- raise ValueError(f"FTS query error: {str(e)}. Try simplifying your query.")
-
-
-def get_page_content(url: str) -> dict:
- """
- Get the full content of a specific documentation page.
+ Schema:
+ - text TEXT -- The document chunk text
+ - vector VECTOR -- Embedding vector (all-MiniLM-L6-v2, 384 dimensions)
+ - url TEXT -- Source URL
+ - title TEXT -- Document title
+ - category TEXT -- Category (e.g., 'cua', 'cuabench')
+ - chunk_index INT -- Index of chunk within document
Args:
- url: The URL of the documentation page (exact or partial match)
+ query: Natural language query to embed and search for
+ limit: Maximum number of results (default: 10, max: 100)
+ where: Optional SQL-like filter (e.g., "category = 'cua'", "title LIKE '%agent%'")
+ select: Optional list of columns to return (default: all columns except vector)
Returns:
- Full page content with title, category, and raw markdown
- """
- conn = get_sqlite_conn()
- cursor = conn.cursor()
-
- # Try exact match first
- cursor.execute(
- "SELECT url, title, category, content, raw_markdown FROM pages WHERE url = ?", (url,)
- )
- row = cursor.fetchone()
+ List of matching documents with similarity scores (_distance field,
+ lower is more similar)
- # If no exact match, try partial match
- if not row:
- cursor.execute(
- "SELECT url, title, category, content, raw_markdown FROM pages WHERE url LIKE ?",
- (f"%{url}%",),
- )
- row = cursor.fetchone()
-
- if not row:
- raise ValueError(f"No page found matching URL: {url}")
+ Example usage:
+ - query="how to capture screenshots", limit=5
+ - query="agent loop architecture", where="category = 'cua'"
+ - query="benchmarking evaluation", select=["url", "title", "text"]
+ """
+ limit = min(max(1, limit), 100)
- return {
- "url": row["url"],
- "title": row["title"],
- "category": row["category"],
- "content": row["content"],
- "has_raw_markdown": bool(row["raw_markdown"]),
- }
+ table = get_lance_table()
+ # Build search query
+ search = table.search(query).limit(limit)
-def get_page_raw_markdown(url: str) -> dict:
- """
- Get the raw markdown content of a documentation page.
- Useful when you need the original formatting, code blocks, etc.
+ # Apply where filter if specified
+ if where:
+ search = search.where(where)
- Args:
- url: The URL of the documentation page
+ # Apply column selection if specified
+ if select:
+ search = search.select(select)
- Returns:
- Raw markdown content of the page
- """
- conn = get_sqlite_conn()
- cursor = conn.cursor()
-
- cursor.execute("SELECT url, title, raw_markdown FROM pages WHERE url LIKE ?", (f"%{url}%",))
- row = cursor.fetchone()
+ results = search.to_list()
- if not row:
- raise ValueError(f"No page found matching URL: {url}")
+ # Format results - include all fields except vector
+ formatted = []
+ for r in results:
+ result = {}
+ for key, value in r.items():
+ # Skip the vector field as it's large and not useful to return
+ if key == "vector":
+ continue
+ result[key] = value
+ formatted.append(result)
- return {
- "url": row["url"],
- "title": row["title"],
- "raw_markdown": row["raw_markdown"],
- }
+ return formatted
# =============================================================================
-# Discovery Tools
+# Code Query Tools (Read-Only)
# =============================================================================
@mcp.tool
-def get_doc_categories() -> list[dict]:
- """
- Get all available documentation categories with page counts.
-
- Returns:
- List of categories with their page counts
- """
- conn = get_sqlite_conn()
- cursor = conn.cursor()
-
- cursor.execute(
- """
- SELECT category, COUNT(*) as page_count
- FROM pages
- GROUP BY category
- ORDER BY page_count DESC
- """
- )
- rows = cursor.fetchall()
-
- return [{"category": row["category"], "page_count": row["page_count"]} for row in rows]
-
-
-def list_pages(category: Optional[str] = None, limit: int = 50) -> list[dict]:
+def query_code_db(sql: str) -> list[dict]:
"""
- List documentation pages, optionally filtered by category.
+ Execute a SQL query against the code search database.
+ The database is READ-ONLY.
+
+ Database Schema:
+
+ Table: code_files
+ - id INTEGER PRIMARY KEY AUTOINCREMENT
+ - component TEXT NOT NULL -- Component name (e.g., "agent", "computer", "mcp-server")
+ - version TEXT NOT NULL -- Version string (e.g., "0.7.3", "0.7.2")
+ - file_path TEXT NOT NULL -- Path to file (e.g., "agent/computer_agent.py")
+ - content TEXT NOT NULL -- Full source code content
+ - language TEXT NOT NULL -- Programming language (e.g., "python", "typescript")
+ - UNIQUE(component, version, file_path)
+
+ Indexes:
+ - idx_component ON code_files(component)
+ - idx_version ON code_files(component, version)
+
+ Virtual Table: code_files_fts (component-sharded FTS5 full-text search)
+ - Available in each component schema: code_agent.code_files_fts, code_computer.code_files_fts, etc.
+ - content TEXT -- Full-text indexed content
+ - component TEXT UNINDEXED -- Component name for filtering
+ - version TEXT UNINDEXED -- Version for filtering
+ - file_path TEXT UNINDEXED -- File path for reference
+
+ Note: FTS5 MATCH queries must target component-specific tables (e.g., code_agent.code_files_fts).
+ For non-FTS queries, use the unified code_files view which aggregates all components.
+
+ Example queries:
+
+ 1. List all components with version counts:
+ SELECT component, COUNT(DISTINCT version) as version_count
+ FROM code_files
+ GROUP BY component
+ ORDER BY component
+
+ 2. List versions for a component:
+ SELECT DISTINCT version
+ FROM code_files
+ WHERE component = 'agent'
+ ORDER BY version DESC
+
+ 3. List files in a component@version:
+ SELECT file_path, language
+ FROM code_files
+ WHERE component = 'agent' AND version = '0.7.3'
+
+ 4. Get file content:
+ SELECT content, language
+ FROM code_files
+ WHERE component = 'agent' AND version = '0.7.3' AND file_path = 'agent/core.py'
+
+ 5. Full-text search in a specific component (FTS5):
+ SELECT f.component, f.version, f.file_path, f.language,
+ snippet(fts, 0, '>>>', '<<<', '...', 64) as snippet
+ FROM code_agent.code_files_fts fts
+ JOIN code_files f ON fts.rowid = f.id AND f.component = 'agent'
+ WHERE fts MATCH 'ComputerAgent'
+ ORDER BY rank
+ LIMIT 10
+
+ 6. Search across all components using LIKE (slower but simpler):
+ SELECT component, version, file_path,
+ substr(content, 1, 200) as preview
+ FROM code_files
+ WHERE content LIKE '%ComputerAgent%'
+ LIMIT 10
+
+ 7. Search for function definitions in a component:
+ SELECT f.component, f.version, f.file_path,
+ snippet(fts, 0, '>>>', '<<<', '...', 100) as snippet
+ FROM code_agent.code_files_fts fts
+ JOIN code_files f ON fts.rowid = f.id AND f.component = 'agent'
+ WHERE fts MATCH '"def screenshot" OR "async def screenshot"'
+ ORDER BY rank
+ LIMIT 10
Args:
- category: Optional category to filter by
- limit: Maximum number of pages to return (default: 50)
+ sql: SQL query to execute
Returns:
- List of pages with URLs and titles
+ List of dictionaries, one per row, with column names as keys
"""
- limit = min(max(1, limit), 200)
-
- conn = get_sqlite_conn()
+ conn = get_code_sqlite_conn()
cursor = conn.cursor()
-
- if category:
- cursor.execute(
- "SELECT url, title, category FROM pages WHERE category = ? LIMIT ?", (category, limit)
- )
- else:
- cursor.execute("SELECT url, title, category FROM pages LIMIT ?", (limit,))
-
- rows = cursor.fetchall()
- return [{"url": row["url"], "title": row["title"], "category": row["category"]} for row in rows]
+ cursor.execute(sql)
+ results = [dict(row) for row in cursor.fetchall()]
+ return results
@mcp.tool
-def search_by_url(url_pattern: str, limit: int = 10) -> list[dict]:
+def query_code_vectors(
+ query: str,
+ limit: int = 10,
+ where: Optional[str] = None,
+ select: Optional[list[str]] = None,
+ component: Optional[str] = None,
+) -> list[dict]:
"""
- Search for documentation pages by URL pattern.
+ Execute a vector similarity search against code LanceDBs (read-only).
+
+ Searches across all component databases and returns merged results sorted by similarity.
+
+ Schema:
+ - text TEXT -- The source code content
+ - vector VECTOR -- Embedding vector (all-MiniLM-L6-v2, 384 dimensions)
+ - component TEXT -- Component name (e.g., "agent", "computer")
+ - version TEXT -- Version string (e.g., "0.7.3")
+ - file_path TEXT -- Path to file within the component
+ - language TEXT -- Programming language (e.g., "python", "typescript")
Args:
- url_pattern: Partial URL to search for (e.g., 'get-started', 'reference/agent-sdk')
- limit: Maximum number of results to return
+ query: Natural language query to embed and search for
+ (e.g., "screenshot capture implementation", "error handling in agent loop")
+ limit: Maximum number of results (default: 10, max: 100)
+ where: Optional SQL-like filter (e.g., "component = 'agent'", "version = '0.7.3'",
+ "component = 'agent' AND version = '0.7.3'")
+ select: Optional list of columns to return (default: all columns except vector)
+ component: Optional component to search (if not specified, searches all)
Returns:
- List of matching documentation pages
+ List of matching code files with similarity scores (_distance field,
+ lower is more similar)
+
+ Example usage:
+ - query="mouse click implementation", limit=5
+ - query="screenshot capture", component="computer"
+ - query="agent loop error handling", where="component = 'agent' AND version = '0.7.3'"
+ - query="async task execution", select=["component", "version", "file_path", "text"]
"""
- limit = min(max(1, limit), 50)
-
- conn = get_sqlite_conn()
- cursor = conn.cursor()
-
- cursor.execute(
- "SELECT url, title, category FROM pages WHERE url LIKE ? LIMIT ?",
- (f"%{url_pattern}%", limit),
- )
- rows = cursor.fetchall()
-
- return [{"url": row["url"], "title": row["title"], "category": row["category"]} for row in rows]
-
-
-# =============================================================================
-# Resources
-# =============================================================================
+ limit = min(max(1, limit), 100)
+ tables = get_code_lance_tables()
+ all_results = []
[email protected]("docs://categories")
-def list_categories_resource() -> str:
- """List all documentation categories"""
- categories = get_doc_categories()
- lines = ["Documentation Categories:", ""]
- for cat in categories:
- lines.append(f"- {cat['category']}: {cat['page_count']} pages")
- return "\n".join(lines)
+ for comp_name, table in tables:
+ # Skip if component filter specified and doesn't match
+ if component and comp_name != component:
+ continue
+ search = table.search(query).limit(limit)
[email protected]("docs://stats")
-def get_stats_resource() -> str:
- """Get documentation database statistics"""
- conn = get_sqlite_conn()
- cursor = conn.cursor()
-
- cursor.execute("SELECT COUNT(*) FROM pages")
- total_pages = cursor.fetchone()[0]
+ if where:
+ search = search.where(where)
+ if select:
+ search = search.select(select)
- cursor.execute("SELECT category, COUNT(*) FROM pages GROUP BY category")
- categories = cursor.fetchall()
+ results = search.to_list()
+ all_results.extend(results)
- # Get LanceDB stats
- table = get_lance_table()
- total_chunks = table.count_rows()
+ # Sort by distance and take top results
+ all_results.sort(key=lambda x: x.get("_distance", float("inf")))
+ all_results = all_results[:limit]
- stats = [
- "CUA Documentation Database Statistics",
- "=" * 40,
- f"Total pages: {total_pages}",
- f"Total chunks (for semantic search): {total_chunks}",
- "",
- "Pages by category:",
- ]
- for cat, count in categories:
- stats.append(f" - {cat}: {count}")
+ # Format results - include all fields except vector
+ formatted = []
+ for r in all_results:
+ result = {}
+ for key, value in r.items():
+ # Skip the vector field as it's large and not useful to return
+ if key == "vector":
+ continue
+ result[key] = value
+ formatted.append(result)
- return "\n".join(stats)
+ return formatted
# =============================================================================
@@ -430,16 +566,38 @@ def main():
if args.transport in ["sse", "http"]:
print(f"URL: http://{args.host}:{args.port}")
- # Verify databases exist
+ # Verify documentation databases exist
try:
get_lance_table()
- print(f"LanceDB loaded from: {DB_PATH}")
+ print(f"Docs LanceDB loaded from: {DB_PATH}")
except RuntimeError as e:
print(f"Warning: {e}")
try:
get_sqlite_conn()
- print(f"SQLite loaded from: {SQLITE_PATH}")
+ print(f"Docs SQLite loaded from: {SQLITE_PATH}")
+ except RuntimeError as e:
+ print(f"Warning: {e}")
+
+ # Verify code index databases exist
+ try:
+ if CODE_SQLITE_PATH.exists():
+ conn = sqlite3.connect(CODE_SQLITE_PATH)
+ cursor = conn.cursor()
+ cursor.execute("SELECT COUNT(*) FROM code_files")
+ total_files = cursor.fetchone()[0]
+ cursor.execute("SELECT COUNT(DISTINCT component) FROM code_files")
+ total_components = cursor.fetchone()[0]
+ conn.close()
+ print(f"Code SQLite loaded: {total_files} files across {total_components} components")
+ else:
+ print(f"Warning: Code SQLite not found at {CODE_SQLITE_PATH}")
+ except Exception as e:
+ print(f"Warning: Code SQLite not available: {e}")
+
+ try:
+ get_code_lance_table()
+ print(f"Code LanceDB loaded from: {CODE_LANCEDB_PATH}")
except RuntimeError as e:
print(f"Warning: {e}")
diff --git a/docs/scripts/modal_app.py b/docs/scripts/modal_app.py
index 67e9a6dd73..1bb7ab96c9 100644
--- a/docs/scripts/modal_app.py
+++ b/docs/scripts/modal_app.py
@@ -22,12 +22,17 @@ from markdown_it import MarkdownIt
# Define the Modal app
app = modal.App("cua-docs-mcp")
-# Create a persistent volume for storing crawled data and databases
+# Create persistent volumes for storing data
docs_volume = modal.Volume.from_name("cua-docs-data", create_if_missing=True)
+code_volume = modal.Volume.from_name("cua-code-index", create_if_missing=True)
+
+# GitHub token secret for cloning
+github_secret = modal.Secret.from_name("github-secret", required_keys=["GITHUB_TOKEN"])
# Define the container image with all dependencies
image = (
modal.Image.debian_slim(python_version="3.12")
+ .apt_install("git")
.pip_install(
"crawl4ai>=0.4.0",
"playwright>=1.40.0",
@@ -44,11 +49,16 @@ image = (
.run_commands("playwright install --with-deps chromium")
)
-# Volume mount path
+# Volume mount paths
VOLUME_PATH = "/data"
CRAWLED_DATA_PATH = f"{VOLUME_PATH}/crawled_data"
DB_PATH = f"{VOLUME_PATH}/docs_db"
+# Code index volume mount path
+CODE_VOLUME_PATH = "/code_data"
+CODE_REPO_PATH = f"{CODE_VOLUME_PATH}/repo"
+CODE_DB_PATH = f"{CODE_VOLUME_PATH}/code_db"
+
# =============================================================================
# Helper Functions
@@ -396,10 +406,7 @@ async def generate_vector_db():
continue
# Convert markdown to plain text
- try:
- text = clean_markdown(markdown)
- except Exception:
- text = markdown
+ text = clean_markdown(markdown)
# Simple chunking by paragraphs
paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()]
@@ -536,19 +543,13 @@ async def generate_sqlite_db():
continue
# Convert markdown to plain text
- try:
- text = clean_markdown(markdown)
- except Exception:
- text = markdown
+ text = clean_markdown(markdown)
- try:
- cursor.execute(
- "INSERT OR REPLACE INTO pages (url, title, category, content) VALUES (?, ?, ?, ?)",
- (url, title, category, text),
- )
- inserted += 1
- except Exception as e:
- print(f"Error inserting {url}: {e}")
+ cursor.execute(
+ "INSERT OR REPLACE INTO pages (url, title, category, content) VALUES (?, ?, ?, ?)",
+ (url, title, category, text),
+ )
+ inserted += 1
# Create FTS triggers
cursor.execute(
@@ -588,6 +589,578 @@ async def generate_sqlite_db():
return {"pages": inserted}
+# =============================================================================
+# Code Index Generation Functions
+# =============================================================================
+
+# Source file extensions to index
+SOURCE_EXTENSIONS = {".py", ".ts", ".js", ".tsx"}
+MAX_FILE_SIZE_SQLITE = 1_000_000 # 1MB for SQLite
+MAX_FILE_SIZE_EMBEDDINGS = 100_000 # 100KB for embeddings
+
+
+def parse_tag(tag: str) -> tuple[str, str]:
+ """Parse a git tag into component and version."""
+ if tag.startswith("v") and len(tag) > 1 and tag[1].isdigit():
+ return ("cua", tag[1:])
+ match = re.match(r"^(.+)-v(\d+\.\d+\.\d+.*)$", tag)
+ if match:
+ return (match.group(1), match.group(2))
+ raise ValueError(f"Cannot parse tag: {tag}")
+
+
+def detect_language(file_path: str) -> str:
+ """Detect programming language from file extension."""
+ ext = Path(file_path).suffix.lower()
+ return {".py": "python", ".ts": "typescript", ".tsx": "typescript", ".js": "javascript"}.get(
+ ext, "unknown"
+ )
+
+
+def group_tags_by_component(tags: list[str]) -> dict[str, list[str]]:
+ """Group git tags by their component."""
+ grouped: dict[str, list[str]] = {}
+ for tag in tags:
+ try:
+ component, _ = parse_tag(tag)
+ if component not in grouped:
+ grouped[component] = []
+ grouped[component].append(tag)
+ except ValueError:
+ continue
+ return grouped
+
+
+ image=image,
+ volumes={CODE_VOLUME_PATH: code_volume},
+ secrets=[github_secret],
+ timeout=1800, # 30 minutes per component
+ cpu=2.0,
+ memory=8192,
+)
+def index_component(component: str, tags: list[str], repo_path: str) -> dict:
+ """Index a single component's tags into its own SQLite and LanceDB.
+
+ Each component gets its own databases to enable parallel processing.
+
+ Args:
+ component: The component name (e.g., "agent", "computer")
+ tags: List of git tags for this component
+ repo_path: Path to the bare git repository
+
+ Returns:
+ Dict with indexing statistics
+ """
+ import shutil
+ import subprocess
+ import tempfile
+
+ import lancedb
+ from lancedb.embeddings import get_registry
+ from lancedb.pydantic import LanceModel, Vector
+
+ print(f"[{component}] Starting indexing of {len(tags)} tags...")
+
+ DB_DIR = Path(CODE_DB_PATH)
+ DB_DIR.mkdir(parents=True, exist_ok=True)
+
+ # Component-specific database paths
+ SQLITE_PATH = DB_DIR / f"code_index_{component}.sqlite"
+ TMP_LANCE_DIR = Path(tempfile.mkdtemp(prefix=f"code_lancedb_{component}_"))
+
+ # Initialize SQLite for this component
+ if SQLITE_PATH.exists():
+ SQLITE_PATH.unlink()
+
+ conn = sqlite3.connect(SQLITE_PATH)
+ cursor = conn.cursor()
+
+ cursor.execute(
+ """
+ CREATE TABLE code_files (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ component TEXT NOT NULL,
+ version TEXT NOT NULL,
+ file_path TEXT NOT NULL,
+ content TEXT NOT NULL,
+ language TEXT NOT NULL,
+ UNIQUE(component, version, file_path)
+ )
+ """
+ )
+ cursor.execute("CREATE INDEX idx_component ON code_files(component)")
+ cursor.execute("CREATE INDEX idx_version ON code_files(component, version)")
+
+ cursor.execute(
+ """
+ CREATE VIRTUAL TABLE code_files_fts USING fts5(
+ content,
+ component UNINDEXED,
+ version UNINDEXED,
+ file_path UNINDEXED,
+ content='code_files',
+ content_rowid='id'
+ )
+ """
+ )
+
+ cursor.execute(
+ """
+ CREATE TRIGGER code_files_ai AFTER INSERT ON code_files BEGIN
+ INSERT INTO code_files_fts(rowid, content, component, version, file_path)
+ VALUES (new.id, new.content, new.component, new.version, new.file_path);
+ END;
+ """
+ )
+ conn.commit()
+
+ # Initialize LanceDB
+ model = get_registry().get("sentence-transformers").create(name="all-MiniLM-L6-v2")
+
+ class CodeFile(LanceModel):
+ text: str = model.SourceField()
+ vector: Vector(model.ndims()) = model.VectorField()
+ component: str
+ version: str
+ file_path: str
+ language: str
+
+ lance_db = lancedb.connect(TMP_LANCE_DIR)
+ lance_table = lance_db.create_table("code", schema=CodeFile, mode="overwrite")
+
+ # Process tags for this component
+ total_files = 0
+ total_embedded = 0
+ failed_tags = []
+ COMMIT_BATCH_SIZE = 10
+
+ for i, tag in enumerate(tags):
+ print(f"[{component}] [{i + 1}/{len(tags)}] Processing {tag}")
+
+ try:
+ _, version = parse_tag(tag)
+ except ValueError as e:
+ print(f"[{component}] Skipping: {e}")
+ failed_tags.append(tag)
+ continue
+
+ # Get files at this tag
+ try:
+ result = subprocess.run(
+ ["git", "ls-tree", "-r", "--name-only", tag],
+ cwd=repo_path,
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ files = [
+ f.strip()
+ for f in result.stdout.strip().split("\n")
+ if f.strip() and Path(f.strip()).suffix.lower() in SOURCE_EXTENSIONS
+ ]
+ except subprocess.CalledProcessError:
+ failed_tags.append(tag)
+ continue
+
+ lance_batch = []
+
+ for file_path in files:
+ try:
+ result = subprocess.run(
+ ["git", "show", f"{tag}:{file_path}"],
+ cwd=repo_path,
+ check=True,
+ capture_output=True,
+ )
+ content = result.stdout.decode("utf-8", errors="replace")
+ if "\x00" in content[:1024]:
+ continue # Skip binary
+ except (subprocess.CalledProcessError, UnicodeDecodeError):
+ continue
+
+ language = detect_language(file_path)
+ content_size = len(content)
+
+ # Add to SQLite
+ if content_size <= MAX_FILE_SIZE_SQLITE:
+ cursor.execute(
+ "INSERT OR REPLACE INTO code_files (component, version, file_path, content, language) VALUES (?, ?, ?, ?, ?)",
+ (component, version, file_path, content, language),
+ )
+ total_files += 1
+
+ # Queue for LanceDB
+ if content_size <= MAX_FILE_SIZE_EMBEDDINGS:
+ lance_batch.append(
+ {
+ "text": content,
+ "component": component,
+ "version": version,
+ "file_path": file_path,
+ "language": language,
+ }
+ )
+
+ # Batch commits
+ if (i + 1) % COMMIT_BATCH_SIZE == 0:
+ conn.commit()
+ print(f"[{component}] Committed batch at tag {i + 1}/{len(tags)}")
+
+ # Add to LanceDB
+ if lance_batch:
+ lance_table.add(lance_batch)
+ total_embedded += len(lance_batch)
+
+ # Final commit
+ conn.commit()
+ conn.close()
+
+ # Copy LanceDB to volume
+ lance_dest = DB_DIR / f"code_index_{component}.lancedb"
+ if lance_dest.exists():
+ shutil.rmtree(lance_dest)
+ shutil.copytree(TMP_LANCE_DIR, lance_dest)
+ shutil.rmtree(TMP_LANCE_DIR)
+
+ # Clean up LanceDB resources
+ del lance_table
+ del lance_db
+
+ print(f"[{component}] Complete: {total_files} files, {total_embedded} embedded")
+ return {
+ "component": component,
+ "files": total_files,
+ "embedded": total_embedded,
+ "failed_tags": len(failed_tags),
+ "tags_processed": len(tags),
+ }
+
+
+ image=image,
+ volumes={CODE_VOLUME_PATH: code_volume},
+ secrets=[github_secret],
+ timeout=3600, # 1 hour
+ cpu=1.0,
+ memory=4096,
+)
+def generate_code_index_parallel(max_concurrent: int = 4) -> dict:
+ """Generate code search index with parallel component processing.
+
+ This function:
+ 1. Clones/updates the git repository
+ 2. Groups tags by component
+ 3. Dispatches parallel workers to index each component
+ 4. Each component gets its own SQLite and LanceDB
+
+ Args:
+ max_concurrent: Maximum number of concurrent component indexing jobs
+
+ Returns:
+ Aggregated statistics from all component workers
+ """
+ import os
+ import subprocess
+
+ print(f"Starting parallel code indexing (max {max_concurrent} concurrent)...")
+
+ # Build authenticated URL
+ github_token = os.environ.get("GITHUB_TOKEN", "")
+ if github_token:
+ REPO_URL = f"https://{github_token}@github.com/trycua/cua.git"
+ print("Using authenticated GitHub URL")
+ else:
+ REPO_URL = "https://github.com/trycua/cua.git"
+ print("Warning: No GITHUB_TOKEN found")
+
+ REPO_PATH = Path(CODE_REPO_PATH)
+
+ # Clone or update repo
+ if REPO_PATH.exists():
+ print("Fetching latest tags...")
+ subprocess.run(["git", "fetch", "--all", "--tags"], cwd=REPO_PATH, check=True)
+ else:
+ print("Cloning repository...")
+ REPO_PATH.parent.mkdir(parents=True, exist_ok=True)
+ subprocess.run(["git", "clone", "--bare", REPO_URL, str(REPO_PATH)], check=True)
+
+ # Get all tags
+ result = subprocess.run(
+ ["git", "tag"], cwd=REPO_PATH, check=True, capture_output=True, text=True
+ )
+ all_tags = [t.strip() for t in result.stdout.strip().split("\n") if t.strip()]
+ print(f"Found {len(all_tags)} tags")
+
+ # Group tags by component
+ component_tags = group_tags_by_component(all_tags)
+ print(f"Components found: {list(component_tags.keys())}")
+ for comp, tags in component_tags.items():
+ print(f" {comp}: {len(tags)} tags")
+
+ # Dispatch parallel workers using Modal's map
+ repo_path_str = str(REPO_PATH)
+ args = [(comp, tags, repo_path_str) for comp, tags in component_tags.items()]
+
+ print(f"Dispatching {len(args)} parallel indexing jobs...")
+ results = list(index_component.starmap(args, order_outputs=False))
+
+ # Commit all changes to volume
+ code_volume.commit()
+
+ # Aggregate results
+ total_files = sum(r["files"] for r in results)
+ total_embedded = sum(r["embedded"] for r in results)
+ total_failed = sum(r["failed_tags"] for r in results)
+
+ summary = {
+ "total_files": total_files,
+ "total_embedded": total_embedded,
+ "total_failed_tags": total_failed,
+ "components": results,
+ }
+
+ print("\nParallel indexing complete:")
+ print(f" Total files: {total_files}")
+ print(f" Total embedded: {total_embedded}")
+ print(f" Components indexed: {len(results)}")
+
+ return summary
+
+
+ image=image,
+ volumes={CODE_VOLUME_PATH: code_volume},
+ secrets=[github_secret],
+ timeout=3600, # 1 hour
+ cpu=2.0,
+ memory=8192,
+)
+async def generate_code_index():
+ """Generate code search index from all git tags"""
+ import os
+ import shutil
+ import subprocess
+ import tempfile
+
+ import lancedb
+ from lancedb.embeddings import get_registry
+ from lancedb.pydantic import LanceModel, Vector
+
+ print("Generating code search index...")
+
+ # Build authenticated URL using GitHub token
+ github_token = os.environ.get("GITHUB_TOKEN", "")
+ if github_token:
+ REPO_URL = f"https://{github_token}@github.com/trycua/cua.git"
+ print("Using authenticated GitHub URL")
+ else:
+ REPO_URL = "https://github.com/trycua/cua.git"
+ print("Warning: No GITHUB_TOKEN found, using unauthenticated URL")
+
+ REPO_PATH = Path(CODE_REPO_PATH)
+ DB_DIR = Path(CODE_DB_PATH)
+ SQLITE_PATH = DB_DIR / "code_index.sqlite"
+
+ DB_DIR.mkdir(parents=True, exist_ok=True)
+
+ # Clone or update repo (bare clone for efficiency)
+ if REPO_PATH.exists():
+ print("Fetching latest tags...")
+ subprocess.run(["git", "fetch", "--all", "--tags"], cwd=REPO_PATH, check=True)
+ else:
+ print("Cloning repository...")
+ REPO_PATH.parent.mkdir(parents=True, exist_ok=True)
+ subprocess.run(["git", "clone", "--bare", REPO_URL, str(REPO_PATH)], check=True)
+
+ # Get all tags
+ result = subprocess.run(
+ ["git", "tag"], cwd=REPO_PATH, check=True, capture_output=True, text=True
+ )
+ all_tags = [t.strip() for t in result.stdout.strip().split("\n") if t.strip()]
+ print(f"Found {len(all_tags)} tags")
+
+ # Initialize SQLite
+ if SQLITE_PATH.exists():
+ SQLITE_PATH.unlink()
+
+ conn = sqlite3.connect(SQLITE_PATH)
+ cursor = conn.cursor()
+
+ cursor.execute(
+ """
+ CREATE TABLE code_files (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ component TEXT NOT NULL,
+ version TEXT NOT NULL,
+ file_path TEXT NOT NULL,
+ content TEXT NOT NULL,
+ language TEXT NOT NULL,
+ UNIQUE(component, version, file_path)
+ )
+ """
+ )
+ cursor.execute("CREATE INDEX idx_component ON code_files(component)")
+ cursor.execute("CREATE INDEX idx_version ON code_files(component, version)")
+
+ cursor.execute(
+ """
+ CREATE VIRTUAL TABLE code_files_fts USING fts5(
+ content,
+ component UNINDEXED,
+ version UNINDEXED,
+ file_path UNINDEXED,
+ content='code_files',
+ content_rowid='id'
+ )
+ """
+ )
+
+ # FTS triggers
+ cursor.execute(
+ """
+ CREATE TRIGGER code_files_ai AFTER INSERT ON code_files BEGIN
+ INSERT INTO code_files_fts(rowid, content, component, version, file_path)
+ VALUES (new.id, new.content, new.component, new.version, new.file_path);
+ END;
+ """
+ )
+ conn.commit()
+
+ # Initialize LanceDB in temp directory
+ TMP_LANCE_DIR = Path(tempfile.mkdtemp(prefix="code_lancedb_"))
+ model = get_registry().get("sentence-transformers").create(name="all-MiniLM-L6-v2")
+
+ class CodeFile(LanceModel):
+ text: str = model.SourceField()
+ vector: Vector(model.ndims()) = model.VectorField()
+ component: str
+ version: str
+ file_path: str
+ language: str
+
+ lance_db = lancedb.connect(TMP_LANCE_DIR)
+ lance_table = lance_db.create_table("code", schema=CodeFile, mode="overwrite")
+
+ # Process each tag
+ total_files = 0
+ total_embedded = 0
+ failed_tags = []
+ COMMIT_BATCH_SIZE = 10 # Commit every 10 tags for better performance
+
+ for i, tag in enumerate(all_tags):
+ print(f"[{i + 1}/{len(all_tags)}] Processing {tag}")
+
+ try:
+ component, version = parse_tag(tag)
+ except ValueError as e:
+ print(f" Skipping: {e}")
+ failed_tags.append(tag)
+ continue
+
+ # Get files at this tag
+ try:
+ result = subprocess.run(
+ ["git", "ls-tree", "-r", "--name-only", tag],
+ cwd=REPO_PATH,
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ files = [
+ f.strip()
+ for f in result.stdout.strip().split("\n")
+ if f.strip() and Path(f.strip()).suffix.lower() in SOURCE_EXTENSIONS
+ ]
+ except subprocess.CalledProcessError:
+ failed_tags.append(tag)
+ continue
+
+ lance_batch = []
+
+ for file_path in files:
+ try:
+ result = subprocess.run(
+ ["git", "show", f"{tag}:{file_path}"],
+ cwd=REPO_PATH,
+ check=True,
+ capture_output=True,
+ )
+ content = result.stdout.decode("utf-8", errors="replace")
+ if "\x00" in content[:1024]:
+ continue # Skip binary
+ except (subprocess.CalledProcessError, UnicodeDecodeError):
+ continue
+
+ language = detect_language(file_path)
+ content_size = len(content)
+
+ # Add to SQLite
+ if content_size <= MAX_FILE_SIZE_SQLITE:
+ cursor.execute(
+ "INSERT OR REPLACE INTO code_files (component, version, file_path, content, language) VALUES (?, ?, ?, ?, ?)",
+ (component, version, file_path, content, language),
+ )
+ total_files += 1
+
+ # Queue for LanceDB
+ if content_size <= MAX_FILE_SIZE_EMBEDDINGS:
+ lance_batch.append(
+ {
+ "text": content,
+ "component": component,
+ "version": version,
+ "file_path": file_path,
+ "language": language,
+ }
+ )
+
+ # Batch commits: commit every COMMIT_BATCH_SIZE tags
+ if (i + 1) % COMMIT_BATCH_SIZE == 0:
+ conn.commit()
+ print(f" Committed batch at tag {i + 1}/{len(all_tags)}")
+
+ # Add to LanceDB
+ if lance_batch:
+ lance_table.add(lance_batch)
+ total_embedded += len(lance_batch)
+
+ # Final commit for any remaining tags
+ conn.commit()
+ conn.close()
+
+ # Copy LanceDB to volume
+ try:
+ lance_dest = DB_DIR / "code_index.lancedb"
+ if lance_dest.exists():
+ shutil.rmtree(lance_dest)
+ shutil.copytree(TMP_LANCE_DIR, lance_dest)
+ shutil.rmtree(TMP_LANCE_DIR)
+ finally:
+ # Ensure LanceDB resources are released even if an exception occurs
+ del lance_table
+ del lance_db
+ code_volume.commit()
+
+ print(f"Code index complete: {total_files} files in SQLite, {total_embedded} embedded")
+ return {"files": total_files, "embedded": total_embedded, "failed_tags": len(failed_tags)}
+
+
+ image=image,
+ volumes={CODE_VOLUME_PATH: code_volume},
+ secrets=[github_secret],
+ schedule=modal.Cron("0 5 * * *"), # Daily at 5 AM UTC (before docs crawl)
+ timeout=3600,
+)
+async def scheduled_code_index():
+ """Scheduled daily code index generation (uses parallel processing)"""
+ print("Running scheduled code indexing (parallel)...")
+ result = await generate_code_index_parallel.remote.aio()
+ print(f"Code indexing complete: {result}")
+ return result
+
+
# =============================================================================
# MCP Server
# =============================================================================
@@ -595,7 +1168,7 @@ async def generate_sqlite_db():
@app.function(
image=image,
- volumes={VOLUME_PATH: docs_volume},
+ volumes={VOLUME_PATH: docs_volume, CODE_VOLUME_PATH: code_volume},
cpu=1.0,
memory=2048,
)
@@ -610,27 +1183,50 @@ def web():
# Initialize the MCP server
mcp = FastMCP(
- name="CUA Docs",
- instructions="""CUA Documentation Server - provides search and retrieval for Computer Use Agent (CUA) documentation.
+ name="CUA Docs & Code",
+ instructions="""CUA Documentation and Code Server - provides direct read-only query access to Computer Use Agent (CUA) documentation and versioned source code.
-Documentation covers:
-- CUA SDK: Python library for building computer-use agents with screen capture, mouse/keyboard control
+=== AVAILABLE TOOLS ===
+
+Documentation:
+- query_docs_db: Execute SQL queries against the documentation SQLite database
+- query_docs_vectors: Execute vector similarity searches against the documentation LanceDB
+
+Code:
+- query_code_db: Execute SQL queries against the code search SQLite database
+- query_code_vectors: Execute vector similarity searches against the code LanceDB
+
+All tools are READ-ONLY. Only SELECT queries are allowed for SQL databases.
+
+=== DOCUMENTATION DATABASE ===
+
+The documentation database contains crawled pages from cua.ai/docs covering:
+- CUA SDK: Python library for building computer-use agents
- CUA Bench: Benchmarking framework for evaluating computer-use agents
- Agent Loop: Core execution loop for autonomous agent operation
- Sandboxes: Docker and cloud VM environments for safe agent execution
- Computer interfaces: Screen, mouse, keyboard, and bash interaction APIs
-Available tools:
-- search_docs: Semantic/vector search - best for conceptual queries like "how does X work?"
-- sql_query: Direct SQL/FTS5 queries for exact keyword matches and advanced filtering
+=== CODE DATABASE ===
+
+The code database contains versioned source code indexed across all git tags.
+Components include: agent, computer, mcp-server, som, etc.
+
+=== WORKFLOW EXAMPLES ===
+
+1. Find documentation about a topic:
+ - Use query_docs_vectors with a natural language query for semantic search
+ - Use query_docs_db with FTS5 MATCH for keyword search
-IMPORTANT: After performing search_docs queries, ALWAYS use sql_query to retrieve the full page content
-before answering. Search results return snippets/chunks that may lack important context. Example:
- sql_query("SELECT url, title, content FROM pages WHERE url LIKE '%installation%'")
-The full page often contains setup instructions, prerequisites, code examples, and related information
-essential for complete answers.
+2. Explore code across versions:
+ - List components: SELECT component, COUNT(DISTINCT version) FROM code_files GROUP BY component
+ - Search code: Use query_code_db with FTS5 on code_files_fts
+ - Get file content: SELECT content FROM code_files WHERE component='agent' AND version='0.7.3' AND file_path='...'
-Always cite the source URL when providing information.""",
+3. Semantic code search:
+ - Use query_code_vectors with natural language queries like "screenshot capture implementation"
+
+IMPORTANT: Always cite sources - URLs for docs, component@version:path for code.""",
)
# Initialize embedding model
@@ -640,9 +1236,27 @@ Always cite the source URL when providing information.""",
_lance_db = None
_lance_table = None
_sqlite_conn = None
+ _code_lance_tables: dict = {} # component -> (db, table)
+ _code_sqlite_conn = None
+ _code_components: list[str] = []
+
+ def discover_code_components() -> list[str]:
+ """Discover available component databases."""
+ nonlocal _code_components
+ if not _code_components:
+ db_dir = Path(CODE_DB_PATH)
+ if db_dir.exists():
+ # Find all component SQLite databases
+ for db_file in db_dir.glob("code_index_*.sqlite"):
+ component = db_file.stem.replace("code_index_", "")
+ _code_components.append(component)
+ # Fallback to legacy single database
+ if not _code_components and (db_dir / "code_index.sqlite").exists():
+ _code_components.append("_legacy")
+ return _code_components
def get_lance_table():
- """Get or create LanceDB connection"""
+ """Get or create LanceDB connection for docs"""
nonlocal _lance_db, _lance_table
if _lance_table is None:
db_path = Path(DB_PATH)
@@ -653,83 +1267,306 @@ Always cite the source URL when providing information.""",
return _lance_table
def get_sqlite_conn():
- """Get or create read-only SQLite connection"""
+ """Get or create read-only SQLite connection for docs"""
nonlocal _sqlite_conn
if _sqlite_conn is None:
sqlite_path = Path(DB_PATH) / "docs.sqlite"
if not sqlite_path.exists():
raise RuntimeError("SQLite database not found.")
- # Open in read-only mode
_sqlite_conn = sqlite3.connect(f"file:{sqlite_path}?mode=ro", uri=True)
_sqlite_conn.row_factory = sqlite3.Row
return _sqlite_conn
+ def get_code_lance_tables() -> list[tuple[str, any]]:
+ """Get LanceDB connections for all code components."""
+ nonlocal _code_lance_tables
+ components = discover_code_components()
+
+ for component in components:
+ if component not in _code_lance_tables:
+ if component == "_legacy":
+ db_path = Path(CODE_DB_PATH) / "code_index.lancedb"
+ else:
+ db_path = Path(CODE_DB_PATH) / f"code_index_{component}.lancedb"
+
+ if db_path.exists():
+ db = lancedb.connect(db_path)
+ table = db.open_table("code")
+ _code_lance_tables[component] = (db, table)
+
+ return [(comp, tbl) for comp, (_, tbl) in _code_lance_tables.items()]
+
+ def get_code_sqlite_conn():
+ """Get SQLite connection with all component databases attached."""
+ nonlocal _code_sqlite_conn
+ if _code_sqlite_conn is None:
+ components = discover_code_components()
+ if not components:
+ raise RuntimeError(
+ "No code databases found. Run generate_code_index_parallel first."
+ )
+
+ # Create in-memory database and attach all component databases
+ _code_sqlite_conn = sqlite3.connect(":memory:")
+ _code_sqlite_conn.row_factory = sqlite3.Row
+
+ db_dir = Path(CODE_DB_PATH)
+
+ # Check for legacy single database first
+ legacy_path = db_dir / "code_index.sqlite"
+ if legacy_path.exists() and "_legacy" in components:
+ _code_sqlite_conn.execute(
+ f"ATTACH DATABASE 'file:{legacy_path}?mode=ro' AS code_legacy"
+ )
+
+ # Attach each component database
+ attached = []
+ for component in components:
+ if component == "_legacy":
+ continue
+ db_path = db_dir / f"code_index_{component}.sqlite"
+ if db_path.exists():
+ # SQLite schema names can't have hyphens
+ safe_name = component.replace("-", "_")
+ _code_sqlite_conn.execute(
+ f"ATTACH DATABASE 'file:{db_path}?mode=ro' AS code_{safe_name}"
+ )
+ attached.append(safe_name)
+
+ # Create unified view across all component databases
+ if attached:
+ union_parts = []
+ for safe_name in attached:
+ union_parts.append(
+ f"SELECT id, component, version, file_path, content, language FROM code_{safe_name}.code_files"
+ )
+ union_sql = " UNION ALL ".join(union_parts)
+ _code_sqlite_conn.execute(f"CREATE VIEW code_files AS {union_sql}")
+
+ # Create unified FTS view (queries individual FTS tables)
+ fts_union_parts = []
+ for safe_name in attached:
+ fts_union_parts.append(
+ f"SELECT rowid, content, component, version, file_path FROM code_{safe_name}.code_files_fts"
+ )
+ fts_union_sql = " UNION ALL ".join(fts_union_parts)
+ _code_sqlite_conn.execute(f"CREATE VIEW code_files_fts_union AS {fts_union_sql}")
+
+ return _code_sqlite_conn
+
+ # =================== DOCUMENTATION QUERY TOOLS (READ-ONLY) ===================
+
@mcp.tool()
- def search_docs(query: str, limit: int = 5, category: Optional[str] = None) -> list[dict]:
+ def query_docs_db(sql: str) -> list[dict]:
"""
- Semantic search over CUA documentation using vector embeddings.
- Best for conceptual queries like "how does the agent loop work?"
+ Execute a SQL query against the documentation database.
+ The database is READ-ONLY.
+
+ Database Schema:
+
+ Table: pages
+ - id INTEGER PRIMARY KEY AUTOINCREMENT
+ - url TEXT NOT NULL UNIQUE -- Full URL of the documentation page
+ - title TEXT NOT NULL -- Page title
+ - category TEXT NOT NULL -- Category (e.g., 'cua', 'cuabench', 'llms.txt')
+ - content TEXT NOT NULL -- Plain text content (markdown stripped)
+
+ Virtual Table: pages_fts (FTS5 full-text search)
+ - content TEXT -- Full-text indexed content
+ - url TEXT UNINDEXED
+ - title TEXT UNINDEXED
+ - category TEXT UNINDEXED
+
+ Example queries:
+
+ 1. List all pages: SELECT url, title, category FROM pages ORDER BY category, title
+
+ 2. Full-text search with snippets:
+ SELECT p.url, p.title, snippet(pages_fts, 0, '>>>', '<<<', '...', 64) as snippet
+ FROM pages_fts JOIN pages p ON pages_fts.rowid = p.id
+ WHERE pages_fts MATCH 'agent loop' ORDER BY rank LIMIT 10
+
+ 3. Get page content: SELECT url, title, content FROM pages WHERE url LIKE '%quickstart%'
Args:
- query: Natural language search query
- limit: Maximum number of results (default: 5, max: 20)
- category: Optional category filter (e.g., 'cua', 'cuabench')
+ sql: SQL query to execute
Returns:
- List of relevant documentation chunks with URLs and content
+ List of dictionaries, one per row, with column names as keys
+ """
+ conn = get_sqlite_conn()
+ cursor = conn.cursor()
+ cursor.execute(sql)
+ return [dict(row) for row in cursor.fetchall()]
+
+ @mcp.tool()
+ def query_docs_vectors(
+ query: str,
+ limit: int = 10,
+ where: Optional[str] = None,
+ select: Optional[list[str]] = None,
+ ) -> list[dict]:
"""
- limit = min(max(1, limit), 20)
+ Execute a vector similarity search against the documentation LanceDB (read-only).
+
+ Schema:
+ - text TEXT -- The document chunk text
+ - vector VECTOR -- Embedding vector (all-MiniLM-L6-v2, 384 dimensions)
+ - url TEXT -- Source URL
+ - title TEXT -- Document title
+ - category TEXT -- Category (e.g., 'cua', 'cuabench')
+ - chunk_index INT -- Index of chunk within document
+ Args:
+ query: Natural language query to embed and search for
+ limit: Maximum number of results (default: 10, max: 100)
+ where: Optional SQL-like filter (e.g., "category = 'cua'")
+ select: Optional list of columns to return (default: all except vector)
+
+ Returns:
+ List of matching documents with similarity scores (_distance field)
+ """
+ limit = min(max(1, limit), 100)
table = get_lance_table()
+
search = table.search(query).limit(limit)
- if category:
- safe_category = category.replace("'", "''")
- search = search.where(f"category = '{safe_category}'")
+ if where:
+ search = search.where(where)
+ if select:
+ search = search.select(select)
results = search.to_list()
- return [
- {
- "text": r.get("text", ""),
- "url": r.get("url", ""),
- "title": r.get("title", ""),
- "category": r.get("category", ""),
- "score": float(r.get("_distance", 0.0)),
- }
- for r in results
- ]
+ formatted = []
+ for r in results:
+ result = {}
+ for key, value in r.items():
+ if key == "vector":
+ continue
+ result[key] = value
+ formatted.append(result)
+
+ return formatted
+
+ # =================== CODE QUERY TOOLS (READ-ONLY) ===================
@mcp.tool()
- def sql_query(query: str) -> list[dict]:
+ def query_code_db(sql: str) -> list[dict]:
"""
- Execute a read-only SQL query on the documentation database.
+ Execute a SQL query against the code search database.
+ The database is READ-ONLY.
+
+ Database Schema:
+
+ Table: code_files
+ - id INTEGER PRIMARY KEY AUTOINCREMENT
+ - component TEXT NOT NULL -- Component name (e.g., "agent", "computer")
+ - version TEXT NOT NULL -- Version string (e.g., "0.7.3")
+ - file_path TEXT NOT NULL -- Path to file
+ - content TEXT NOT NULL -- Full source code content
+ - language TEXT NOT NULL -- Programming language
+ - UNIQUE(component, version, file_path)
+
+ Virtual Table: code_files_fts (FTS5 full-text search)
+ - content TEXT -- Full-text indexed content
+ - component TEXT UNINDEXED
+ - version TEXT UNINDEXED
+ - file_path TEXT UNINDEXED
- Tables:
- - pages: id, url, title, category, content
- - pages_fts: FTS5 virtual table for full-text search (content, url, title, category)
+ Example queries:
- FTS5 examples:
- - SELECT * FROM pages_fts WHERE pages_fts MATCH 'agent' LIMIT 10
- - SELECT p.*, snippet(pages_fts, 0, '**', '**', '...', 32) as snippet
- FROM pages_fts JOIN pages p ON pages_fts.rowid = p.id
- WHERE pages_fts MATCH 'computer use' ORDER BY rank LIMIT 5
+ 1. List components: SELECT component, COUNT(DISTINCT version) as version_count
+ FROM code_files GROUP BY component ORDER BY component
+
+ 2. List versions: SELECT DISTINCT version FROM code_files
+ WHERE component = 'agent' ORDER BY version DESC
+
+ 3. Full-text search:
+ SELECT f.component, f.version, f.file_path,
+ snippet(code_files_fts, 0, '>>>', '<<<', '...', 64) as snippet
+ FROM code_files_fts JOIN code_files f ON code_files_fts.rowid = f.id
+ WHERE code_files_fts MATCH 'ComputerAgent' ORDER BY rank LIMIT 10
+
+ 4. Get file content: SELECT content, language FROM code_files
+ WHERE component = 'agent' AND version = '0.7.3' AND file_path = 'agent/core.py'
Args:
- query: SQL query (SELECT only, connection is read-only)
+ sql: SQL query to execute
Returns:
- List of result rows as dictionaries
+ List of dictionaries, one per row, with column names as keys
"""
- conn = get_sqlite_conn()
+ conn = get_code_sqlite_conn()
cursor = conn.cursor()
+ cursor.execute(sql)
+ return [dict(row) for row in cursor.fetchall()]
- try:
- cursor.execute(query)
- results = cursor.fetchall()
- return [dict(row) for row in results]
- except sqlite3.Error as e:
- return [{"error": str(e)}]
+ @mcp.tool()
+ def query_code_vectors(
+ query: str,
+ limit: int = 10,
+ where: Optional[str] = None,
+ select: Optional[list[str]] = None,
+ component: Optional[str] = None,
+ ) -> list[dict]:
+ """
+ Execute a vector similarity search against code LanceDBs (read-only).
+
+ Searches across all component databases and returns merged results sorted by similarity.
+
+ Schema:
+ - text TEXT -- The source code content
+ - vector VECTOR -- Embedding vector (all-MiniLM-L6-v2, 384 dimensions)
+ - component TEXT -- Component name (e.g., "agent", "computer")
+ - version TEXT -- Version string (e.g., "0.7.3")
+ - file_path TEXT -- Path to file within the component
+ - language TEXT -- Programming language
+
+ Args:
+ query: Natural language query to embed and search for
+ limit: Maximum number of results (default: 10, max: 100)
+ where: Optional SQL-like filter (e.g., "version = '0.7.3'")
+ select: Optional list of columns to return (default: all except vector)
+ component: Optional component to search (if not specified, searches all)
+
+ Returns:
+ List of matching code files with similarity scores (_distance field)
+ """
+ limit = min(max(1, limit), 100)
+ tables = get_code_lance_tables()
+
+ all_results = []
+
+ for comp_name, table in tables:
+ # Skip if component filter specified and doesn't match
+ if component and comp_name != component and comp_name != "_legacy":
+ continue
+
+ search = table.search(query).limit(limit)
+
+ if where:
+ search = search.where(where)
+ if select:
+ search = search.select(select)
+
+ results = search.to_list()
+ all_results.extend(results)
+
+ # Sort by distance and take top results
+ all_results.sort(key=lambda x: x.get("_distance", float("inf")))
+ all_results = all_results[:limit]
+
+ formatted = []
+ for r in all_results:
+ result = {}
+ for key, value in r.items():
+ if key == "vector":
+ continue
+ result[key] = value
+ formatted.append(result)
+
+ return formatted
# Create SSE app directly - endpoints at /sse (GET) and /messages (POST)
from starlette.middleware import Middleware
@@ -756,18 +1593,43 @@ Always cite the source URL when providing information.""",
@app.local_entrypoint()
-def main():
- """Run initial crawl and database generation"""
- print("Running initial crawl...")
- summary = crawl_docs.remote()
- print(f"Crawl summary: {summary}")
-
- print("Generating vector database...")
- vector_result = generate_vector_db.remote()
- print(f"Vector DB: {vector_result}")
-
- print("Generating SQLite database...")
- sqlite_result = generate_sqlite_db.remote()
- print(f"SQLite DB: {sqlite_result}")
+def main(
+ skip_docs: bool = False,
+ skip_code: bool = False,
+ parallel: bool = True,
+ code_only: bool = False,
+):
+ """Run initial crawl and database generation
+
+ Args:
+ skip_docs: Skip documentation crawl and indexing
+ skip_code: Skip code indexing
+ parallel: Use parallel code indexing (default: True)
+ code_only: Only run code indexing (shortcut for --skip-docs)
+ """
+ if code_only:
+ skip_docs = True
+
+ if not skip_docs:
+ print("Running initial crawl...")
+ summary = crawl_docs.remote()
+ print(f"Crawl summary: {summary}")
+
+ print("Generating vector database...")
+ vector_result = generate_vector_db.remote()
+ print(f"Vector DB: {vector_result}")
+
+ print("Generating SQLite database...")
+ sqlite_result = generate_sqlite_db.remote()
+ print(f"SQLite DB: {sqlite_result}")
+
+ if not skip_code:
+ if parallel:
+ print("Generating code index (parallel)...")
+ code_result = generate_code_index_parallel.remote()
+ else:
+ print("Generating code index (sequential)...")
+ code_result = generate_code_index.remote()
+ print(f"Code index: {code_result}")
print("Done! Deploy with: modal deploy docs/scripts/modal_app.py")
diff --git a/docs/src/app/api/copilotkit/route.ts b/docs/src/app/api/copilotkit/route.ts
index e6c89c5daa..3b95f5e491 100644
--- a/docs/src/app/api/copilotkit/route.ts
+++ b/docs/src/app/api/copilotkit/route.ts
@@ -4,8 +4,8 @@ import {
copilotRuntimeNextJSAppRouterEndpoint,
} from '@copilotkit/runtime';
import { BuiltInAgent, InMemoryAgentRunner } from '@copilotkit/runtime/v2';
-import { NextRequest } from 'next/server';
import { randomUUID } from 'crypto';
+import { NextRequest } from 'next/server';
import { PostHog } from 'posthog-node';
const posthog = process.env.NEXT_PUBLIC_POSTHOG_API_KEY
@@ -286,6 +286,14 @@ class AnthropicSafeBuiltInAgent extends BuiltInAgent {
parentObservable.subscribe = (observer: any) => {
const wrappedObserver = {
next: (event: any) => {
+ // Debug logging
+ if (process.env.NODE_ENV === 'development') {
+ const deltaPreview = event.delta
+ ? `delta: ${String(event.delta).substring(0, 50)}...`
+ : '';
+ console.log('[CopilotKit] Event:', event.type, deltaPreview);
+ }
+
if (event.type === 'TEXT_MESSAGE_CHUNK') {
if (event.delta) {
responseChunks.push(event.delta);
@@ -306,6 +314,7 @@ class AnthropicSafeBuiltInAgent extends BuiltInAgent {
}
},
error: (err: any) => {
+ console.error('[CopilotKit] Error:', err?.message || String(err), err?.stack);
if (posthog) {
posthog.capture({
distinctId: conversationId,
@@ -383,21 +392,25 @@ class AnthropicSafeBuiltInAgent extends BuiltInAgent {
const docsAgent = new AnthropicSafeBuiltInAgent({
maxSteps: 100,
- model: 'anthropic/claude-sonnet-4-20250514',
+ model: 'anthropic/claude-haiku-4-5-20251001',
prompt: `You are a helpful assistant for Cua (Computer Use Agent) and Cua-Bench documentation.
Be concise and helpful. Answer questions about the documentation accurately.
Use Cua as the name of the product and CUA for Computer Use Agent.
-You have access to tools for searching the Cua documentation:
-- search_docs: Semantic search for documentation content
-- sql_query: Direct SQL queries on the documentation database
+You have access to tools for searching the Cua documentation and code:
+- query_docs_db: SQL queries on the documentation database (full-text search via FTS5)
+- query_docs_vectors: Semantic vector search over documentation
+- query_code_db: SQL queries on the code database (full-text search, file content, versions)
+- query_code_vectors: Semantic vector search over source code
-When using search_docs, follow up by checking the source document for accuracy.
+When using query_docs_vectors, follow up by checking the source document for accuracy.
Include links to documentation pages in your responses.
+When providing code examples, use query_code_db or query_code_vectors to ensure accuracy.
If users seem stuck, invite them to join the Discord: https://discord.com/invite/cua-ai`,
temperature: 0.7,
+ maxTokens: 8192 * 4,
mcpServers: [
{
type: 'sse',
diff --git a/docs/src/providers/copilotkit-provider.tsx b/docs/src/providers/copilotkit-provider.tsx
index 9587917a39..f574252bbd 100644
--- a/docs/src/providers/copilotkit-provider.tsx
+++ b/docs/src/providers/copilotkit-provider.tsx
@@ -6,7 +6,12 @@ if (typeof window !== 'undefined') {
applyCopilotKitFetchPatch();
}
-import { CopilotKit, useRenderToolCall, useCopilotChat } from '@copilotkit/react-core';
+import {
+ CopilotKit,
+ useRenderToolCall,
+ useCopilotChat,
+ CatchAllActionRenderProps,
+} from '@copilotkit/react-core';
import {
CopilotPopup,
AssistantMessage as DefaultAssistantMessage,
@@ -78,84 +83,59 @@ function CustomAssistantMessage(props: React.ComponentProps<typeof DefaultAssist
return <DefaultAssistantMessage {...rest} message={processedMessage as typeof message} />;
}
-function ToolCallIndicators() {
- useRenderToolCall({
- name: 'search_docs',
- description: 'Searches the Cua documentation',
- parameters: [{ name: 'query', type: 'string', description: 'Search query', required: true }],
- render: ({ status, args }) => {
- if (status === 'inProgress') {
- return (
- <div className="copilotkit-tool-indicator">
- <div className="copilotkit-tool-indicator-icon">
- <svg
- className="copilotkit-spinner"
- viewBox="0 0 24 24"
- fill="none"
- xmlns="http://www.w3.org/2000/svg"
- >
- <circle
- className="opacity-25"
- cx="12"
- cy="12"
- r="10"
- stroke="currentColor"
- strokeWidth="4"
- ></circle>
- <path
- className="opacity-75"
- fill="currentColor"
- d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
- ></path>
- </svg>
- </div>
- <span className="copilotkit-tool-indicator-text">
- Searching documentation{args?.query ? `: "${args.query}"` : '...'}
- </span>
- </div>
- );
- }
- return <></>;
- },
- });
+// Tool display name mapping - add new tools here
+const TOOL_DISPLAY_NAMES: Record<string, string> = {
+ query_docs_db: 'Querying documentation database',
+ query_docs_vectors: 'Searching documentation',
+ query_code_db: 'Querying code database',
+ query_code_vectors: 'Searching code',
+};
+function ToolIndicator({ name, status }: { name: string; status: string }) {
+ if (status !== 'inProgress') {
+ return null;
+ }
+
+ const displayName = TOOL_DISPLAY_NAMES[name] || `Running ${name}`;
+
+ return (
+ <div className="copilotkit-tool-indicator">
+ <div className="copilotkit-tool-indicator-icon">
+ <svg
+ className="copilotkit-spinner"
+ viewBox="0 0 24 24"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <circle
+ className="opacity-25"
+ cx="12"
+ cy="12"
+ r="10"
+ stroke="currentColor"
+ strokeWidth="4"
+ ></circle>
+ <path
+ className="opacity-75"
+ fill="currentColor"
+ d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
+ ></path>
+ </svg>
+ </div>
+ <span className="copilotkit-tool-indicator-text">{displayName}...</span>
+ </div>
+ );
+}
+
+function ToolCallIndicators() {
+ // Generic catch-all for any tool call using wildcard pattern
+ // Type assertion needed because useRenderToolCall's types don't properly handle name: '*'
+ // but CatchAllActionRenderProps includes the name property at runtime
useRenderToolCall({
- name: 'sql_query',
- description: 'Queries the documentation database',
- parameters: [{ name: 'query', type: 'string', description: 'SQL query', required: true }],
- render: ({ status }) => {
- if (status === 'inProgress') {
- return (
- <div className="copilotkit-tool-indicator">
- <div className="copilotkit-tool-indicator-icon">
- <svg
- className="copilotkit-spinner"
- viewBox="0 0 24 24"
- fill="none"
- xmlns="http://www.w3.org/2000/svg"
- >
- <circle
- className="opacity-25"
- cx="12"
- cy="12"
- r="10"
- stroke="currentColor"
- strokeWidth="4"
- ></circle>
- <path
- className="opacity-75"
- fill="currentColor"
- d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
- ></path>
- </svg>
- </div>
- <span className="copilotkit-tool-indicator-text">
- Fetching detailed documentation...
- </span>
- </div>
- );
- }
- return <></>;
+ name: '*',
+ render: (props) => {
+ const { name, status } = props as CatchAllActionRenderProps;
+ return <ToolIndicator name={name} status={status} />;
},
});
@@ -307,6 +287,7 @@ function CopilotPopupWithFeedback() {
const findPrecedingUserPrompt = useCallback(
(assistantMessageId: string) => {
+ if (!visibleMessages) return null;
const messageIndex = visibleMessages.findIndex(
(m: CopilotMessage) => m.id === assistantMessageId
);
@@ -360,8 +341,12 @@ function CopilotPopupWithFeedback() {
<CopilotPopup
instructions={DOCS_INSTRUCTIONS}
labels={{
- title: 'Cua Docs Assistant',
- initial: `Ask me anything about Cua!
+ title: 'CUA Docs Assistant',
+ initial: `Hello!
+
+I'm an agent that can search cua's docs and code to help answer questions
+
+Ask me anything about CUA!
This is currently an **experimental** feature.
diff --git a/pyproject.toml b/pyproject.toml
index 5b78a8562e..387ee0419a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -49,6 +49,7 @@ docs-scripts = [
"markdown-it-py>=3.0.0",
"markitdown>=0.0.1",
"modal>=0.63.0",
+ "gitpython>=3.1.43",
]
test = [
"aioresponses>=0.7.4",