# Anki MCP Data Bridge Setup & Integration Guide
## Overview
This is a **comprehensive MCP (Model Context Protocol) data bridge** that provides full CRUD (Create, Read, Update, Delete) access to your Anki flashcard data via JSON-RPC over stdin/stdout. The server acts as a complete Anki management interface - **Claude handles all analysis and decision-making**.
## š Quick Start
1. **Install dependencies**: `pip install -r requirements.txt` (minimal - no AI libraries!)
2. **Install AnkiConnect add-on** in Anki (code: `2055492159`)
3. **Test the server**: `./venv/bin/python test_server.py`
4. **Configure Claude Desktop** with the provided JSON config (no API keys needed!)
5. **Ask Claude**: *"Analyze my Anki decks!"* (Claude gets rich data and provides analysis)
## Architecture
```
Claude Desktop āā Anki MCP Data Bridge āā AnkiConnect āā Anki Application
(AI Analysis) (JSON-RPC/stdio) (Structured Data)
```
**Key Principle**: Server = Data Bridge, Claude = AI Analysis
## ā ļø Important: This is a data-only server
- **No external AI dependencies** - Claude handles all analysis
- **No API keys required** - Just provides structured Anki data
- **Faster & more reliable** - No external service calls
- Communicates via **stdin/stdout** using MCP protocol
## š What's New in This Version
### ā
**Architectural Improvements**
- **Eliminated external AI dependencies** - No more Gemini API calls or failures
- **Simplified configuration** - No API keys or external service setup required
- **Enhanced reliability** - No more "404 model not found" or quota errors
- **Improved performance** - Direct data access without API round trips
### ā
**Enhanced Functionality**
- **6 comprehensive data tools** (upgraded from 4 analysis tools)
- **Richer data structures** with detailed card statistics and metadata
- **Advanced search capabilities** using full Anki search syntax
- **Better error handling** with actionable troubleshooting information
### ā
**User Experience**
- **Faster responses** - No waiting for external AI processing
- **More detailed data** - Access to all Anki card and deck information
- **Flexible analysis** - Claude can perform any analysis you request
- **Zero maintenance** - No API keys to manage or renew
## Project Structure
```
anki-mcp/
āāā mcp_server.py # Main MCP data bridge server
āāā test_server.py # Test script for verification
āāā config.template.json # Server configuration template
āāā env.template # Environment variables template
āāā claude_desktop_config.json # Example Claude Desktop config
āāā requirements.txt # Minimal Python dependencies (no AI libs)
āāā .gitignore # Git ignore patterns
āāā README.md # This comprehensive guide
āāā venv/ # Virtual environment (not in git)
```
## Setup Instructions
### 1. Prerequisites
- **Python 3.8+** installed on your system
- **Anki application** installed and running
- **Claude Desktop** installed
- **AnkiConnect add-on** installed in Anki
### 2. Clone and Install Dependencies
```bash
# Clone or download this project
cd "/path/to/your/anki-mcp-project"
# Create virtual environment
python3 -m venv venv
# Activate virtual environment
source venv/bin/activate
# Install required packages
pip install -r requirements.txt
```
### 3. Install AnkiConnect Add-on
1. Open Anki
2. Go to Tools ā Add-ons ā Get Add-ons
3. Enter code: `2055492159`
4. Restart Anki
5. Verify it's working by keeping Anki running
### 4. Configure Environment (Optional)
**Environment Variables:**
```bash
# AnkiConnect URL (change if needed, default works for most setups)
export ANKI_CONNECT_URL="http://localhost:8765"
```
**Claude Desktop Configuration:**
Environment variables are set in the Claude Desktop config (shown in step 7 below):
```json
{
"env": {
"ANKI_CONNECT_URL": "http://localhost:8765"
}
}
```
**Note:** No API keys needed! The server only provides structured data - Claude handles all AI analysis.
### 5. Test the Server
```bash
# Make sure Anki is running, then test the server
./venv/bin/python test_server.py
```
Expected output:
```
š All tests passed! MCP server is ready for Claude Desktop.
```
**Note: This is an MCP server - it doesn't run as a standalone HTTP server. It's launched by Claude Desktop when needed.**
### 6. Configure Claude Desktop
**Step 1: Find Your Claude Desktop Config File**
- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
**Step 2: Add the MCP Server Configuration**
Create or edit the file with this content:
```json
{
"mcpServers": {
"anki": {
"command": "/path/to/your/anki-mcp-project/venv/bin/python",
"args": ["/path/to/your/anki-mcp-project/mcp_server.py"],
"cwd": "/path/to/your/anki-mcp-project",
"env": {
"ANKI_CONNECT_URL": "http://localhost:8765"
}
}
}
}
```
**ā ļø Important Customizations:**
- **Use absolute paths for everything**: Use full paths for both `"command"` and `"args"`, not relative paths
- Update all paths to match your actual project directory
- **No API keys needed**: Server only provides data, Claude handles analysis
**Step 3: Restart Claude Desktop**
Close Claude Desktop completely and reopen it.
**Step 4: Verify Integration**
Ask Claude: *"Can you help me analyze my Anki decks?"*
Claude should now have access to 18 MCP tools for comprehensive Anki management (6 read + 12 write operations).
## Available MCP Tools
Once configured, Claude Desktop will have access to these **18 comprehensive Anki management tools**:
### š **Read Operations (6 tools)**
| Tool | Description | Example Usage |
|------|-------------|---------------|
| `get_card_data` | Retrieve detailed information about a specific card | *"Get data for card ID 1234567890"* |
| `get_deck_overview` | Get comprehensive deck statistics and metrics | *"Give me an overview of my Spanish deck"* |
| `get_deck_cards` | Retrieve all cards from a specified deck | *"Get all cards from my Medical Terminology deck"* |
| `get_lapsed_cards` | Get recently failed cards for review | *"Show me cards I failed in the last week"* |
| `search_cards` | Search cards using Anki's search syntax | *"Find all cards tagged 'difficult'"* |
| `list_decks` | List all available decks with basic information | *"What decks do I have?"* |
### āļø **Write Operations (12 tools)**
#### **Card Creation**
| Tool | Description | Example Usage |
|------|-------------|---------------|
| `create_card` | Create a single flashcard in a specified deck | *"Create a card with 'bonjour' on front and 'hello' on back"* |
| `create_cards_batch` | Create multiple cards efficiently in one operation | *"Create 20 vocabulary cards from this list"* |
#### **Card Updates**
| Tool | Description | Example Usage |
|------|-------------|---------------|
| `update_card` | Update fields and tags of an existing card | *"Update card 123 to fix the pronunciation"* |
| `update_cards_batch` | Update multiple cards efficiently | *"Add audio pronunciations to all Spanish cards"* |
#### **Card Management**
| Tool | Description | Example Usage |
|------|-------------|---------------|
| `suspend_cards` | Suspend cards to remove them from review temporarily | *"Suspend all cards I keep getting wrong"* |
| `unsuspend_cards` | Unsuspend previously suspended cards | *"Unsuspend my anatomy cards for next week's exam"* |
| `delete_cards` | Permanently delete cards (requires confirmation) | *"Delete all duplicate cards in my German deck"* |
#### **Deck Management**
| Tool | Description | Example Usage |
|------|-------------|---------------|
| `create_deck` | Create a new deck or subdeck | *"Create a new deck called 'MCAT Biology'"* |
| `move_cards_to_deck` | Move cards between decks | *"Move difficult chemistry cards to a separate deck"* |
| `delete_deck` | Delete a deck and optionally its cards | *"Delete my old French deck and move cards to archive"* |
#### **Tag Management**
| Tool | Description | Example Usage |
|------|-------------|---------------|
| `add_tags_to_cards` | Add tags to multiple cards without replacing existing ones | *"Tag all anatomy cards with 'medical' and 'memorize'"* |
| `remove_tags_from_cards` | Remove specific tags from multiple cards | *"Remove 'easy' tag from cards I now find difficult"* |
### š Rich Data Structures
Each tool provides comprehensive, structured data that Claude can analyze. Here's what Claude receives:
#### **Card Data Example** (`get_card_data`)
```json
{
"card_id": 1234567890,
"note_id": 1598765432,
"deck_name": "Spanish Vocabulary",
"model_name": "Basic",
"ease_factor": 2.5,
"interval": 45,
"reviews": 12,
"lapses": 2,
"fields": {
"Front": "perro",
"Back": "dog"
},
"tags": ["animals", "basic"],
"due": "2024-03-15",
"queue": 2
}
```
#### **Deck Overview Example** (`get_deck_overview`)
```json
{
"deck_name": "Spanish Vocabulary",
"total_cards": 247,
"card_distribution": {
"new": 23,
"learning": 45,
"review": 179
},
"difficulty_metrics": {
"avg_ease_factor": 2.3,
"avg_interval": 28.5,
"total_lapses": 156,
"cards_with_lapses": 89
},
"sample_cards": [/* 10 representative cards */]
}
```
This detailed data allows Claude to perform sophisticated analysis that was impossible with the old AI-dependent approach.
### Example Conversations with Claude
#### **Advanced Analysis & Action**
```
You: "Can you analyze my Spanish vocabulary deck and help me reorganize it?"
Claude: *Uses get_deck_overview and get_deck_cards tools to retrieve data*
"I analyzed your 247 Spanish cards and found several improvement opportunities:
š Analysis:
- 15% of cards have ease factors below 2.0 (indicating difficulty)
- 23 cards have been lapsed more than 3 times
- 45 cards are missing pronunciation tags
š§ Recommended Actions:
1. Move 23 difficult cards to a separate 'Spanish - Review' deck
2. Add 'pronunciation' tags to cards missing audio
3. Update 12 cards with better mnemonics
Should I execute these changes?"
You: "Yes, please do that"
Claude: *Uses create_deck, move_cards_to_deck, add_tags_to_cards, and update_cards_batch*
"ā
Created 'Spanish - Review' deck
ā
Moved 23 difficult cards
ā
Tagged 45 cards with 'pronunciation'
ā
Updated 12 cards with better content
Your Spanish deck is now better organized for effective learning!"
```
#### **Bulk Content Creation**
```
You: "Create flashcards for these 50 biology terms I need to memorize"
Claude: *Uses create_cards_batch tool*
"I'll create 50 biology flashcards in your Biology deck. Each card will have:
- Front: Term name
- Back: Definition + context
- Tags: 'biology', 'exam', 'memorize'
Creating cards now..."
*Creates all 50 cards efficiently*
"ā
Created 50 biology flashcards! They're ready for review."
```
#### **Smart Deck Management**
```
You: "I want to reorganize my medical school cards - separate by subject and difficulty"
Claude: *Uses get_deck_cards, search_cards, then create_deck and move_cards_to_deck*
"I'll reorganize your 500+ medical cards into a structured system:
š Created deck structure:
- Medical::Anatomy::Easy (120 cards)
- Medical::Anatomy::Difficult (45 cards)
- Medical::Physiology::Easy (95 cards)
- Medical::Physiology::Difficult (38 cards)
- Medical::Pharmacology (85 cards)
ā
Moved all cards to appropriate decks based on subject and performance
Your medical cards are now organized for optimal study efficiency!"
```
```
You: "What's in my difficult cards tagged collection?"
Claude: *Uses search_cards tool with query 'tag:difficult'*
"I found 45 cards tagged as 'difficult'. Analysis shows:
- Average ease factor: 1.7 (below optimal 2.5)
- Most are from your Medical Terminology deck
- Common pattern: complex multi-part definitions
Let me suggest some improvements..."
```
### Alternative: Custom MCP Client Integration
**For developers building custom MCP clients:**
```python
import asyncio
import json
from mcp.client import Client
from mcp.client.stdio import stdio_client
async def use_anki_tools():
# Connect to the MCP server
async with stdio_client() as (read, write):
async with Client(read, write) as client:
# Initialize the connection
await client.initialize()
# List available tools
tools = await client.list_tools()
print("Available tools:", [tool.name for tool in tools])
# Call a tool
result = await client.call_tool("analyze_card", {"card_id": 1234567890})
print("Analysis:", result)
# Run the client
asyncio.run(use_anki_tools())
```
**Note:** This requires implementing your own MCP client. Claude Desktop handles this automatically.
## Configuration Options
### š§ **Method 1: Configuration File (Recommended)**
1. **Copy the template**:
```bash
cp config.template.json config.json
```
2. **Customize `config.json`**:
```json
{
"anki_connect": {
"url": "http://localhost:8765",
"timeout": 30
},
"server": {
"name": "anki-mcp",
"log_level": "INFO"
},
"limits": {
"max_cards_per_query": 50,
"max_search_results": 100
},
"write_operations": {
"enabled": true,
"require_confirmation": ["delete_cards", "delete_deck"],
"batch_size_limit": 100,
"backup_before_delete": false
}
}
```
### š§ **Method 2: Environment Variables**
1. **Copy the template**:
```bash
cp env.template .env
```
2. **Customize `.env`**:
```bash
# AnkiConnect URL (default: http://localhost:8765)
ANKI_CONNECT_URL=http://localhost:8765
# Optional: Log level (DEBUG, INFO, WARNING, ERROR)
LOG_LEVEL=INFO
```
### š§ **Method 3: Direct Environment (No Files)**
Set environment variables directly:
```bash
export ANKI_CONNECT_URL="http://localhost:8765"
export LOG_LEVEL="INFO"
```
### āļø **Configuration Priority**
The server loads configuration in this order (later overrides earlier):
1. **Built-in defaults**
2. **config.json** file (if exists)
3. **Environment variables** (if set)
### š ļø **Available Options**
| Setting | Default | Description |
|---------|---------|-------------|
| `anki_connect.url` | `http://localhost:8765` | AnkiConnect endpoint URL |
| `anki_connect.timeout` | `30` | Request timeout in seconds |
| `server.name` | `anki-mcp` | MCP server name |
| `server.log_level` | `INFO` | Logging level (DEBUG/INFO/WARNING/ERROR) |
| `limits.max_cards_per_query` | `50` | Maximum cards returned per query |
| `limits.max_search_results` | `100` | Maximum search results |
| `write_operations.enabled` | `true` | Enable/disable write operations |
| `write_operations.require_confirmation` | `["delete_cards", "delete_deck"]` | Operations requiring explicit confirmation |
| `write_operations.batch_size_limit` | `100` | Maximum items per batch operation |
| `write_operations.backup_before_delete` | `false` | Create backup before destructive operations |
## Troubleshooting
### Test MCP Server Connection
```bash
# Test if server starts and connects to AnkiConnect
./venv/bin/python test_server.py
```
Expected output:
```
š Anki MCP Data Bridge Test Suite
ā
AnkiConnect connected: version 6
ā
Server configured as data bridge - Claude handles all analysis
ā
MCP tools registered successfully
š All tests passed! MCP Data Bridge server is ready for Claude Desktop.
```
### Common Issues
1. **Claude Desktop can't find the server or script**
- **`spawn ./venv/bin/python ENOENT`**: Use absolute path for `"command"`: `"/path/to/your/anki-mcp-project/venv/bin/python"`
- **`can't open file '//mcp_server.py'`**: Use absolute path for `"args"`: `["/path/to/your/anki-mcp-project/mcp_server.py"]`
- **Use absolute paths for everything** - Claude Desktop sometimes has issues with relative paths
- Check the `cwd` path in your Claude config matches your project directory
- Verify files exist: `ls -la venv/bin/python` and `ls -la mcp_server.py`
2. **AnkiConnect not found**
- Make sure Anki is running
- Verify AnkiConnect add-on is installed and enabled
- Check AnkiConnect is listening on port 8765
3. **Module not found errors**
- Ensure virtual environment is properly set up
- Reinstall dependencies: `pip install -r requirements.txt`
- Check the Python path in Claude config
4. **Data retrieval errors**
- **Card not found**: Verify the card ID exists in your Anki collection
- **Deck not found**: Check deck name spelling and ensure deck exists
- **Permission errors**: Verify AnkiConnect is properly configured and Anki is running
- **Large dataset timeouts**: Use limit parameters for large deck queries
- Server provides detailed error messages for troubleshooting
5. **MCP Protocol errors**
- Restart Claude Desktop after config changes
- Check Claude Desktop logs for specific error messages
- Ensure no other processes are interfering
## Usage Examples
### With Claude Desktop
Once configured, you can ask Claude things like:
```
"Analyze my Spanish deck and tell me which cards need improvement"
"Show me all the cards I failed in the last week"
"Get an overview of my Medical Terminology deck"
"Find all cards with ease factors below 2.0"
"What patterns do you see in my difficult cards?"
```
Claude will automatically use the MCP tools to:
1. Connect to your Anki via AnkiConnect
2. Retrieve structured data about your cards and decks
3. Analyze the data using its AI capabilities
4. Present you with actionable insights and recommendations
## Features
### š **Comprehensive Card Data**
- **Detailed card information** including content, statistics, and scheduling data
- **Rich metadata** with ease factors, intervals, lapses, and review counts
- **Field-by-field content** with tags and model information
### š **Advanced Deck Analytics**
- **Complete deck statistics** with card distribution analysis
- **Performance metrics** including average ease factors and intervals
- **Difficulty patterns** and learning progress indicators
- **Sample card analysis** for representative overview
### šÆ **Powerful Search & Filtering**
- **Flexible card search** using Anki's full search syntax
- **Lapsed card identification** with detailed failure history
- **Deck-specific queries** and cross-deck analysis
- **Customizable result limits** for large datasets
### ā” **Fast & Reliable Data Bridge**
- **No external dependencies** - pure Anki data access
- **High-performance queries** with structured JSON responses
- **Robust error handling** with detailed error messages
- **Real-time data** directly from your Anki collection
## Security Notes
- ā
**No network exposure** - MCP server runs only when invoked by Claude Desktop
- ā
**Secure communication** - All data exchange via stdin/stdout
- ā
**API key protection** - Gemini API key stored in Claude Desktop config
- ā
**Local operation** - AnkiConnect only accepts localhost connections
- ā
**No data persistence** - Server doesn't store your Anki data
## Development & Customization
### Adding New Tools
1. **Define the tool** in `@server.list_tools()` decorator:
```python
Tool(
name="my_new_tool",
description="Description of what it does",
inputSchema={
"type": "object",
"properties": {"param": {"type": "string"}},
"required": ["param"]
}
)
```
2. **Implement the handler** in `@server.call_tool()`:
```python
elif name == "my_new_tool":
param = arguments.get("param")
result = await my_new_function(param)
return [TextContent(type="text", text=json.dumps(result, indent=2))]
```
3. **Test the changes**:
```bash
./venv/bin/python test_server.py
```
4. **Restart Claude Desktop** to pick up changes
### šÆ **Quick Setup for GitHub Users**
1. **Clone and setup**:
```bash
git clone <your-repo-url> anki-mcp
cd anki-mcp
python3 -m venv venv
source venv/bin/activate # Linux/macOS
# or: venv\Scripts\activate # Windows
pip install -r requirements.txt
```
2. **Configure (choose one)**:
```bash
# Option A: Use config file
cp config.template.json config.json
# Edit config.json with your settings
# Option B: Use environment file
cp env.template .env
# Edit .env with your settings
```
3. **Update Claude Desktop config** with YOUR absolute paths:
```json
{
"mcpServers": {
"anki": {
"command": "/YOUR/PATH/TO/anki-mcp/venv/bin/python",
"args": ["/YOUR/PATH/TO/anki-mcp/mcp_server.py"],
"cwd": "/YOUR/PATH/TO/anki-mcp"
}
}
}
```
### š§ **Customizing the Server**
The server is designed to be configurable without code changes:
- **Performance tuning**: Adjust `max_cards_per_query` in config.json
- **Logging control**: Set `log_level` to DEBUG for troubleshooting
- **Network settings**: Change AnkiConnect URL/timeout for custom setups
- **Custom limits**: Modify search result limits for your needs
For advanced customization, edit `mcp_server.py` to:
- Add new MCP tools for additional Anki data access
- Enhance data structures with additional fields
- Implement custom error handling or logging
## š Summary: Complete Anki Management Solution
### šÆ **What You Can Do Now**
#### **š Smart Analysis**
- Analyze deck performance and identify problem cards
- Get detailed statistics and learning insights
- Find patterns in your study habits
#### **ā” Intelligent Automation**
- Bulk create cards from lists or notes
- Automatically reorganize decks by difficulty/subject
- Batch update tags and content across multiple cards
#### **š§ Powerful Management**
- Create and manage decks with subdecks
- Move cards between decks intelligently
- Suspend/unsuspend cards based on criteria
- Clean up duplicate or outdated content
#### **š”ļø Safe Operations**
- Confirmation required for destructive operations
- Batch size limits prevent overwhelming Anki
- Detailed error messages for troubleshooting
- Atomic operations where possible
### šļø **Architecture Advantages**
```
Claude āā MCP Server āā AnkiConnect āā Anki
š§ š š” š¾
AI Data Protocol Database
Analysis Bridge Layer Storage
```
- **š§ Claude**: Handles all analysis, decision-making, and user interaction
- **š MCP Server**: Provides complete CRUD operations as a data bridge
- **š” AnkiConnect**: Reliable protocol for Anki communication
- **š¾ Anki**: Your flashcard database remains local and secure
### š **Key Benefits**
- **š Complete Control**: Full read/write access to your Anki data
- **š¤ AI-Powered**: Claude can analyze and act on your behalf
- **ā” Efficient**: Batch operations for large-scale changes
- **š”ļø Safe**: Validation and confirmation for destructive operations
- **š Local**: All data stays on your machine
- **š§ Configurable**: Customize limits and safety features
- **š Rich Data**: Access to all card metadata and statistics
**This is the most comprehensive Anki automation solution available - combining the power of Claude's intelligence with complete control over your flashcard data.**