Anki MCP Data Bridge

Anki MCP Data Bridge

Provides comprehensive CRUD access to Anki flashcard data via MCP, enabling Claude to analyze decks, manage cards, create and update flashcards, organize tags, and perform advanced spaced repetition analysis through 18 data management tools.

Category
访问服务器

README

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

# 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:

# 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):

{
  "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

# 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:

{
  "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)

{
  "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)

{
  "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:

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:

    cp config.template.json config.json
    
  2. Customize config.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:

    cp env.template .env
    
  2. Customize .env:

    # 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:

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

# 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:
Tool(
    name="my_new_tool",
    description="Description of what it does",
    inputSchema={
        "type": "object",
        "properties": {"param": {"type": "string"}},
        "required": ["param"]
    }
)
  1. Implement the handler in @server.call_tool():
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))]
  1. Test the changes:
./venv/bin/python test_server.py
  1. Restart Claude Desktop to pick up changes

🎯 Quick Setup for GitHub Users

  1. Clone and setup:

    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):

    # 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:

    {
      "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.

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选