agent-library
CLAUDE.md32 starsChanged 6 months agoApache-2.0View on GitHub
Agent Library (package name: agent-library, Python module: librarian) is a multi-modal knowledge library for AI agents built on Arcade for the Model Context Protocol (MCP). It provides persistent storage with semantic and keyword search for text, code, images, and PDFs. Naming note for contributors: The product is "Agent Library." The Python module path is librarian (don't rename — it's the import surface). The MCP server identifies itself as Librarian (MCPApp(name="Librarian") in server.py), which is why exposed tools carry the Librarian_…
- Installs packages
The file
Show its rules and text
We split this CLAUDE.md into the rules it gives an agent
27 rules. About 0 are common, 14 are distinctive, and 13 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈14
Distinctive · estimate
This author's own choices. Worth a look.
13
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 22
Search Integration: All search tools return asset_type to AI agents
- Distinctive: line 54
No additional dependencies required
- Distinctive: line 58
After installing optional dependencies, verify they work:
- Distinctive: line 118
All components use strongly-typed enums:
- Distinctive: line 165
All search operations (vector, FTS, hybrid) preserve and return asset_type
- Distinctive: line 166
Search results include asset_type for filtering and display
- Very specific: line 183
All settings in librarian/config.py can be overridden via environment variables:
- Distinctive: line 239
Enum-First Design: All parameters use typed enums for safety
- Distinctive: line 306
All search tools return asset_type in results:
- Very specific: line 362
All new code should use enums from librarian/types.py
- Very specific: line 366
Use pytest -m slow to run them explicitly
- Very specific: line 367
Test fixtures in conftest.py provide mock database and embedder
- Distinctive: line 368
All tests must pass before merging features
- Distinctive: line 378
All search queries JOIN documents table to preserve asset_type
- Very specific: line 401
Add tests in tests/test_myparser.py
- Distinctive: line 427
Use Context for logging and progress reporting
- Very specific: line 430
Add to librarian/types.py in appropriate section
- Very specific: line 431
Use str, Enum base for string enums
- Distinctive: line 432
Document in this file under Type System section
- Very specific: line 437
Check IMPLEMENTATION_STATUS.md for what's needed
- Distinctive: line 439
Write tests first (TDD)
- Very specific: line 441
Run make check and make test
- Distinctive: line 449
No emojis in code
- Very specific: line 454
Use fixtures from conftest.py
- Very specific: line 515
Use await context.log.debug() in tools for detailed logging
- Very specific: line 516
Check ~/.librarian/index.db with SQLite browser for database inspection
- Very specific: line 517
Use -v -s flags with pytest for verbose output
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Project Overview
Agent Library (package name: agent-library, Python module: librarian) is a multi-modal knowledge library for AI agents built on Arcade for the Model Context Protocol (MCP). It provides persistent storage with semantic and keyword search for text, code, images, and PDFs.
Naming note for contributors: The product is "Agent Library." The Python module path is librarian (don't rename — it's the import surface). The MCP server identifies itself as Librarian (MCPApp(name="Librarian") in server.py), which is why exposed tools carry the Librarian_ prefix. Keep that distinction in mind: prose says "Agent Library"; code-level identifiers say "librarian"/"Librarian".
Key Technologies
- SQLite with
sqlite-vecfor vector search - FTS5 with BM25 ranking for full-text search
- Hybrid search combining both approaches with Max Marginal Relevance (MMR)
- Configurable embedding models (local sentence-transformers or OpenAI-compatible API)
- Support for multi-modal assets (text, code, images, PDFs)
Current Status
- Multi-Modal Support Complete: Code, PDF, and image parsing with asset type preservation
- Parser Registry: Automatic parser selection based on file extension
- Database Schema: Multi-modal columns (asset_type, modality_data) fully implemented
- Search Integration: All search tools return asset_type to AI agents
- See
IMPLEMENTATION_STATUS.mdfor detailed progress tracking - See
MULTI_MODAL_LIBRARIAN_DESIGN.mdfor complete design specification
Development Commands
Setup & Installation
./setup.sh # Initial setup
make install # Install base dependencies
make sync # Sync dependencies from pyproject.toml
# Install optional multi-modal dependencies
uv pip install -e ".[pdf]" # PDF processing (pypdf)
uv pip install -e ".[vision]" # Image processing (Pillow)
uv pip install -e ".[all]" # All multi-modal featuresOptional Dependencies:
- PDF Support: Install
pypdfto enable PDF parsing
Without this, PDF files will be skipped during indexing.uv pip install -e ".[pdf]" - Image Support: Install
Pillowto enable image metadata extraction
Without this, image files will be skipped during indexing.uv pip install -e ".[vision]" - Code Parsing: Works out-of-the-box with regex-based symbol extraction
- No additional dependencies required
- Supports 18+ programming languages
Testing Multi-Modal Features: After installing optional dependencies, verify they work:
# Test PDF parsing
uv run pytest tests/test_multimodal.py::TestPDFParser -v
# Test image parsing
uv run pytest tests/test_multimodal.py::TestImageParser -v
# Test all multi-modal features
uv run pytest tests/test_multimodal.py -vTesting
make test # Run all tests with coverage
make test-fast # Run tests without coverage
uv run pytest tests/test_file.py # Run specific test file
uv run pytest tests/test_file.py::TestClass::test_method # Run specific test
uv run pytest -m slow # Run slow tests (loads real embedding models)Code Quality
make check # Run all checks (lint + format-check + typecheck)
make lint # Run ruff linting
make lint-fix # Auto-fix linting issues
make format # Format code with ruff
make typecheck # Run mypy type checkingBuilding & Evaluation
make build # Build wheel distribution
make evals # Run Arcade tool evaluationsCLI Usage
# Multi-modal indexing (auto-detects file types)
libr add ~/notes # Index markdown files (AssetType.TEXT)
libr add ~/code # Index source code (AssetType.CODE)
libr add ~/docs # Index PDFs, images, code, markdown - all types
libr search "query" # Search across all asset types
# Search results include asset_type
# Example: {"asset_type": "code", "document_path": "main.py", ...}
# Library management
libr list # List all sources
libr index # Show library statistics
libr serve stdio # Start MCP server (stdio)
libr serve http --port 8000 # Start MCP server (HTTP)Architecture Overview
Core Pipeline
File → Parser → Chunker → Embedder → Database → Search
Type System
All components use strongly-typed enums:
AssetType: TEXT, CODE, IMAGE, PDF, MULTIMODALSourceType: DOCUMENTS, CODEBASE, KNOWLEDGE_BASE, ASSETS, MIXEDChunkingStrategy: HEADERS, PARAGRAPHS, SENTENCES, FIXED, CODE_BLOCKS, PAGESEmbeddingModality: TEXT, CODE, VISION, HYBRIDProgrammingLanguage: 18 supported languages (PYTHON, JAVASCRIPT, etc.)CodeSymbolType: FUNCTION, CLASS, METHOD, VARIABLE, etc.SearchMode: HYBRID, SEMANTIC, KEYWORD
Document Processing (librarian/processing/)
- Parsers (
parsers/):base.py: Base parser interface with parse_file() and parse_content()md.py: Markdown parser with frontmatter (AssetType.TEXT)obsidian.py: Obsidian-flavored markdown with wikilinkscode.py: Source code parser with symbol extraction (AssetType.CODE)- Supports: Python, JavaScript, TypeScript, Go, Rust, Java, C++, etc.
- Extracts: Classes, functions, methods, variables
pdf.py: PDF text extraction with page-based chunking (AssetType.PDF)- Requires:
pypdf(install withuv pip install -e ".[pdf]")
- Requires:
image.py: Image metadata and EXIF extraction (AssetType.IMAGE)- Requires:
Pillow(install withuv pip install -e ".[vision]")
- Requires:
registry.py: Automatic parser selection by file extension
- Chunking (
transform/):chunker.py: Text chunking with multiple strategiescode.py: Code-aware chunking by symbols (functions, classes)pdf.py: Page-based chunking for PDF documents
- Embeddings (
embed/):base.py: Embedding provider interfacelocal.py: Sentence-transformers (local models)openai.py: OpenAI-compatible API- Note: Currently all assets use TEXT embeddings (all-MiniLM-L6-v2)
- Future: CodeBERT for code, CLIP for images
Storage Layer (librarian/storage/)
database.py: Core SQLite operations with thread-safe connection managementvector_store.py: Vector similarity search using sqlite-vec (preserves asset_type)fts_store.py: Full-text search using FTS5 with BM25 ranking (preserves asset_type)
Multi-Modal Schema (Complete):
documentstable: Stores file metadata withasset_typeandmodality_datacolumnschunkstable: Stores chunks withasset_typecolumn for filteringchunk_embeddingsvirtual table: sqlite-vec index for vector searchchunks_ftsvirtual table: FTS5 index for full-text search
Asset Type Preservation:
- All search operations (vector, FTS, hybrid) preserve and return asset_type
- Search results include asset_type for filtering and display
- Database queries JOIN documents table to retrieve asset_type
Retrieval (librarian/retrieval/)
search.py: Hybrid search combining vector + FTS with configurable weighting- MMR algorithm for diverse result selection
Indexing (librarian/indexing.py)
Coordinates the full pipeline: parsing → chunking → embedding → storage Handles modification time tracking for incremental updates
Interfaces
server.py: MCP server with tools for agentscli.py: Command-line interface wrapping server functions
Configuration
All settings in librarian/config.py can be overridden via environment variables:
Core Settings
DATABASE_PATH: SQLite database location (default:~/.librarian/index.db)SOURCES_CONFIG_PATH: Sources configuration (default:~/.librarian/sources.json)DOCUMENTS_PATH: Default document directory (default:./documents)
Text Embedding
EMBEDDING_PROVIDER: "local" or "openai"EMBEDDING_MODEL: Local model name (default:all-MiniLM-L6-v2)OPENAI_API_BASE: OpenAI-compatible API endpointOPENAI_EMBEDDING_MODEL: API model name
Code Processing (Optional)
ENABLE_CODE_EMBEDDINGS: Enable code-specific embeddingsCODE_EMBEDDING_MODEL: CodeBERT modelCODE_CHUNK_STRATEGY: "code_blocks" or "fixed"CODE_CONTEXT_LINES: Lines of context around code
Vision Processing (Optional)
ENABLE_VISION_EMBEDDINGS: Enable image embeddingsVISION_EMBEDDING_MODEL: CLIP modelIMAGE_GENERATE_CAPTIONS: Auto-generate image captions
PDF Processing (Optional)
ENABLE_PDF_PROCESSING: Enable PDF parsingPDF_OCR_ENABLED: Enable OCR for image-based PDFsPDF_CHUNK_STRATEGY: "pages" or "sections"
Search
CHUNK_SIZE,CHUNK_OVERLAP: Text chunking parametersHYBRID_ALPHA: Vector vs keyword weight (0=keyword only, 1=vector only)MMR_LAMBDA: Diversity parameter (0=max diversity, 1=max relevance)SEARCH_LIMIT: Default results limit
Codebase Management
CODEBASE_AUTO_DETECT: Auto-detect languages and frameworkCODEBASE_INDEX_TESTS: Include test files when indexingCODEBASE_MAX_FILE_SIZE_KB: Max file size to index
Key Design Patterns
- Singleton Pattern: Global instances for database, embedder, indexing service
get_database(),get_embedder(),get_indexing_service()
- Provider Pattern: Swappable embedding backends
EmbeddingProviderbase classLocalEmbeddingProviderandOpenAIEmbeddingProviderimplementations
- Registry Pattern: Automatic parser selection (planned)
ParserRegistryroutes files to appropriate parser by extension
- Thread Safety: Database connections use thread-local storage
- Each thread gets its own connection via
_localattribute - Operations protected with
threading.RLock()
- Each thread gets its own connection via
- Enum-First Design: All parameters use typed enums for safety
- Prevents invalid values at runtime
- Better IDE autocomplete and type checking
Multi-Modal Architecture
Parser Registry
The parser registry automatically selects the appropriate parser based on file extension:
from librarian.processing.parsers.registry import get_parser_for_file
from pathlib import Path
# Automatic parser selection
parser, asset_type = get_parser_for_file(Path("example.py"))
# Returns: (CodeParser(language=ProgrammingLanguage.PYTHON), AssetType.CODE)
parser, asset_type = get_parser_for_file(Path("document.pdf"))
# Returns: (PDFParser(), AssetType.PDF)
parser, asset_type = get_parser_for_file(Path("diagram.png"))
# Returns: (ImageParser(), AssetType.IMAGE)Supported file types:
- Code: .py, .js, .ts, .jsx, .tsx, .go, .rs, .java, .cpp, .c, .h, .cs, .rb, .php, .swift, .kt, .scala
- PDF: .pdf (requires
pypdf) - Images: .png, .jpg, .jpeg, .gif, .webp (requires
Pillow) - Text: .md, .txt
Using Parsers Directly
from librarian.processing.parsers.code import CodeParser
from librarian.types import ProgrammingLanguage
# Parse Python code
parser = CodeParser(language=ProgrammingLanguage.PYTHON)
parsed = parser.parse_file(Path("script.py"))
print(f"Asset Type: {parsed.asset_type}") # AssetType.CODE
print(f"Symbols: {len(parsed.metadata['symbols'])}") # Classes, functions, methods
# Symbols include:
for symbol in parsed.metadata['symbols']:
print(f" {symbol['type']}: {symbol['name']} (line {symbol['line_start']})")Multi-Modal Indexing
The indexing service automatically detects file types and routes to the correct parser:
from librarian.indexing import get_indexing_service
service = get_indexing_service()
# Index any file type - parser auto-detected
result = service.index_file(Path("example.py"))
# Returns: {"status": "created", "chunks": 6, "asset_type": "code"}
result = service.index_file(Path("document.pdf"))
# Returns: {"status": "created", "chunks": 10, "asset_type": "pdf"}
result = service.index_file(Path("diagram.png"))
# Returns: {"status": "created", "chunks": 1, "asset_type": "image"}Multi-Modal Search
All search tools return asset_type in results:
from librarian.retrieval.search import HybridSearcher
from librarian.processing.embed import get_embedder
searcher = HybridSearcher(embedder=get_embedder())
# Hybrid search (vector + keyword)
results = searcher.search("calculator", limit=10)
for r in results:
print(f"[{r.asset_type.value}] {Path(r.document_path).name}")
# [code] example.py
# [pdf] math_tutorial.pdf
# [text] calculator_notes.md
# Vector-only search (semantic similarity)
results = searcher.vector_search("authentication code", limit=5)
# Keyword-only search (exact matching)
results = searcher.keyword_search("Calculator", limit=5)MCP Tool Integration
AI agents receive asset_type in all search results via the unified search_library tool:
# search_library MCP tool response (all modes: hybrid, semantic, keyword)
{
"chunk_id": 42,
"document_path": "/path/to/example.py",
"content": "class Calculator...",
"asset_type": "code", # ← AI agents see this
"score": 0.87
}
# search_library with mode="semantic" and asset_type="pdf"
{
"asset_type": "pdf",
"document_path": "/path/to/document.pdf",
...
}
# search_library with mode="keyword"
{
"asset_type": "image",
"document_path": "/path/to/diagram.png",
...
}Important Notes
Type Checking
- mypy is configured to exclude
cli.py(wraps Arcade-decorated functions) - Type ignores used for optional provider dependencies
- All new code should use enums from
librarian/types.py
Testing
- Tests marked
@pytest.mark.slowload real embedding models (skip by default) - Use
pytest -m slowto run them explicitly - Test fixtures in
conftest.pyprovide mock database and embedder - All tests must pass before merging features
Linting
- UP007/UP045 ignored for typer CLI compatibility (use
Optional[]not| None) - Security warnings S603/S607 ignored in
cli.pyfor controlled subprocess calls
Database Schema
Multi-modal schema is fully implemented:
documents.asset_type: Stores file type (text, code, pdf, image)documents.modality_data: JSON field for type-specific metadata (language, dimensions, etc.)- All search queries JOIN documents table to preserve asset_type
- Vector and FTS search results include asset_type from documents table
Schema ensures asset type is preserved throughout the entire search pipeline.
Extending the System
Adding a New Parser
- Create
librarian/processing/parsers/myparser.py:
from librarian.processing.parsers.base import BaseParser
from librarian.types import AssetType, ParsedDocument
class MyParser(BaseParser):
asset_type = AssetType.MY_TYPE
supported_extensions = {".ext"}
def parse_file(self, file_path: Path) -> ParsedDocument:
# Parse file and return ParsedDocument with asset_type set
pass- Register in
ParserRegistry(when implemented) - Add tests in
tests/test_myparser.py
Adding a New MCP Tool
- Add to
librarian/server.py:
from arcade_mcp_server import Context, MCPApp
@app.tool
async def my_tool(
context: Context,
param: Annotated[AssetType, "Description"],
) -> dict[str, Any]:
"""Tool description for AI."""
await context.log.info(f"Starting my_tool with {param}")
try:
await context.progress(0.0, "Initializing...")
# Do work
await context.progress(1.0, "Complete")
return {"result": "success"}
except Exception as e:
await context.log.error(f"Error: {e}")
return {"error": str(e)}- Add tests in
tests/test_tools.py - Use Context for logging and progress reporting
Adding a New Enum
- Add to
librarian/types.pyin appropriate section - Use
str, Enumbase for string enums - Document in this file under Type System section
Development Workflow
- Feature Development:
- Check
IMPLEMENTATION_STATUS.mdfor what's needed - Review
MULTI_MODAL_LIBRARIAN_DESIGN.mdfor design - Write tests first (TDD)
- Implement feature
- Run
make checkandmake test
- Check
- Code Review Checklist:
- All tests passing
- Type hints on all functions
- Enums used instead of strings
- Logging via Context in tools
- Documentation updated
- No emojis in code
- Testing Strategy:
- Unit tests for parsers, chunkers, embedders
- Integration tests for tools
- Use fixtures from
conftest.py - Mock expensive operations (embedding models)
Project Structure
librarian/
├── types.py # All enums and data classes
├── config.py # Configuration management
├── indexing.py # Document indexing service
├── storage/
│ ├── database.py # SQLite operations
│ ├── vector_store.py # Vector search
│ └── fts_store.py # Full-text search
├── processing/
│ ├── embed/ # Embedding providers
│ ├── parsers/ # Document parsers
│ └── transform/ # Text chunking
├── retrieval/
│ └── search.py # Hybrid search + MMR
├── sources/ # Source management (planned)
│ ├── codebase.py # Codebase management
│ └── ignore.py # .librarianignore support
├── server.py # MCP server and tool definitions
├── cli.py # Command-line interface
└── utils/
└── timeframe.py # Time filter utilitiesResources
- Arcade.dev - MCP server framework
- Arcade Documentation - Integration guides
- MULTI_MODAL_LIBRARIAN_DESIGN.md - Complete design
- IMPLEMENTATION_STATUS.md - Current progress
Quick Reference
Common Tasks
# Run tests for specific component
uv run pytest tests/test_parser.py -v
# Type check specific file
uv run mypy librarian/processing/parsers/md.py
# Format and lint
make format && make lint
# Run single test with output
uv run pytest tests/test_tools.py::TestSearchTools::test_search_library -v -sEnvironment Variables for Testing
export DATABASE_PATH=":memory:" # Use in-memory DB for tests
export EMBEDDING_PROVIDER="local"
export CHUNK_SIZE="256"Debugging
- Use
await context.log.debug()in tools for detailed logging - Check
~/.librarian/index.dbwith SQLite browser for database inspection - Use
-v -sflags with pytest for verbose output
License
Apache License 2.0 - see LICENSE for details.
Contact
- Email: contact@arcade.dev
- Website: arcade.dev
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

