CodeBrain MCP Server

CodeBrain MCP Server

Enables semantic code search across codebases using AI embeddings and vector similarity, integrated with Claude Desktop and Cursor.

Category
访问服务器

README

🧠 CodeBrain MCP Server

Semantic code search powered by AI embeddings and vector similarity.

Integrate intelligent code search directly into Claude Desktop and Cursor through the Model Context Protocol (MCP).

🎯 What It Does

CodeBrain indexes your codebase using AST-based splitting and AI embeddings, enabling:

  • Semantic search - Find code by meaning, not just keywords
  • Smart chunking - AST-aware code splitting (respects functions, classes, etc.)
  • Fast retrieval - Vector similarity search with pgvector
  • Multi-project - Index and search across multiple codebases

🚀 Quick Start

1. Prerequisites

# Docker running (for PostgreSQL + pgvector)
docker ps | grep codebrain

# Node.js 20+
node --version

# Dependencies installed
cd /Users/conorandrle/Documents/Coding/CodeBrainMCP/CodeBrain
pnpm install

2. Setup Database

# Start PostgreSQL with pgvector (if not running)
docker run -d \
  --name codebrain \
  -p 5484:5432 \
  -e POSTGRES_PASSWORD=postgres \
  -e POSTGRES_DB=codebrain \
  pgvector/pgvector:pg15

# Setup database schema
pnpm db:setup
pnpm db:migrate

3. Configure Environment

Edit .env:

GEMINI_API_KEY=your_api_key_here
DATABASE_URL=postgresql://postgres:postgres@localhost:5484/codebrain?schema=cbmcp

4. Test the Server

# Run tests
pnpm test

# Should show: ✅ 28 tests passed

# Test MCP server starts
npx tsx src/index.ts
# Should output: 🚀 CodeBrain MCP Server started (stdio mode)
# Press Ctrl+C to stop

🔌 Connect to Cursor/Claude

For Cursor

  1. Open Cursor Settings → MCP Servers
  2. Add server named codebrain
  3. Copy this config:
{
  "command": "npx",
  "args": [
    "-y",
    "tsx",
    "/Users/conorandrle/Documents/Coding/CodeBrainMCP/CodeBrain/src/index.ts"
  ],
  "env": {
    "GEMINI_API_KEY": "your_key_here",
    "DATABASE_URL": "postgresql://postgres:postgres@localhost:5484/codebrain?schema=cbmcp"
  }
}
  1. Restart Cursor
  2. Verify - Check MCP panel shows "codebrain" connected

📖 Detailed guide: See CURSOR_SETUP.md

For Claude Desktop

Edit ~/Library/Application Support/Claude/claude_desktop_config.json:

{
  "mcpServers": {
    "codebrain": {
      "command": "npx",
      "args": [
        "-y",
        "tsx",
        "/Users/conorandrle/Documents/Coding/CodeBrainMCP/CodeBrain/src/index.ts"
      ],
      "env": {
        "GEMINI_API_KEY": "your_key_here",
        "DATABASE_URL": "postgresql://postgres:postgres@localhost:5484/codebrain?schema=cbmcp"
      }
    }
  }
}

Restart Claude Desktop.

🛠️ Available MCP Tools

1. index_codebase

Index a codebase for semantic search.

Parameters:

{
  projectName: string;   // Unique project identifier
  rootPath: string;      // Absolute path to code
  force?: boolean;       // Re-index existing files
}

Example:

"Index my React project at /Users/me/projects/my-app with name 'my-app'"

2. semantic_search

Search code semantically across indexed projects.

Parameters:

{
  query: string;         // What to search for
  projectName?: string;  // Filter by project
  topK?: number;        // Number of results (default: 5)
  threshold?: number;   // Similarity threshold (default: 0.5)
}

Example:

"Find authentication logic in my-app"

3. list_projects

List all indexed projects.

Parameters: None

Example:

"Show me all indexed projects"

4. get_project_stats

Get statistics for a project.

Parameters:

{
  projectName: string;   // Project to query
}

Example:

"Show me stats for the my-app project"

📊 Architecture

┌─────────────────────────────────────────────┐
│         Cursor / Claude Desktop             │
│              (MCP Client)                   │
└─────────────────┬───────────────────────────┘
                  │ MCP Protocol (stdio)
                  │
┌─────────────────▼───────────────────────────┐
│         CodeBrain MCP Server                │
│  ┌─────────────────────────────────────┐   │
│  │  AST Code Splitter                  │   │
│  │  - JavaScript/TypeScript            │   │
│  │  - Python, Go, Rust, Java, C++      │   │
│  └──────────────┬──────────────────────┘   │
│                 │                           │
│  ┌──────────────▼──────────────────────┐   │
│  │  Gemini Embeddings                  │   │
│  │  - 768-dimensional vectors          │   │
│  │  - Semantic descriptions            │   │
│  └──────────────┬──────────────────────┘   │
│                 │                           │
│  ┌──────────────▼──────────────────────┐   │
│  │  Vector Search                      │   │
│  │  - Cosine similarity                │   │
│  │  - Threshold filtering              │   │
│  └──────────────┬──────────────────────┘   │
└─────────────────┼───────────────────────────┘
                  │
┌─────────────────▼───────────────────────────┐
│      PostgreSQL + pgvector                  │
│  ┌──────────────────────────────────────┐  │
│  │  Projects → Files → Chunks → Embeds │  │
│  │  Normalized relational schema        │  │
│  └──────────────────────────────────────┘  │
└─────────────────────────────────────────────┘

🧪 Testing

# Run all tests
pnpm test

# Watch mode
pnpm test:watch

# Individual test suites
pnpm test:splitter     # AST code splitter
pnpm test:indexing     # Indexing workflow
pnpm test:search       # Semantic search
pnpm test:embedding    # Embedding generation

# Integration test (end-to-end)
pnpm test:integration

🌐 Graph Viewer (React)

Visualise the code graph in the browser with the React/Vite viewer.

# Start the Graph API server (serves graph JSON on http://localhost:4000)
pnpm graph:server

# In a separate terminal, install and run the viewer UI
cd apps/graph-viewer
pnpm install
pnpm dev

# Open the browser UI → http://localhost:5173

Override the API target with VITE_GRAPH_API_URL (inside apps/graph-viewer/.env) if the server runs elsewhere.

📁 Project Structure

CodeBrain/
├── src/
│   ├── index.ts              # MCP server entry point
│   ├── core/
│   │   ├── indexing.ts       # Indexing orchestration
│   │   ├── search.ts         # Semantic search
│   │   ├── splitter.ts       # AST-based code splitting
│   │   └── embedding/
│   │       ├── base-embedding.ts      # Embedding interface
│   │       └── gemini-embedding.ts    # Gemini implementation
│   └── test/
│       ├── *.test.ts         # Unit tests
│       └── utils.ts          # Test utilities
├── db/
│   ├── index.ts              # Prisma client
│   ├── setup.ts              # Database setup script
│   └── vector-indexes.ts     # Vector index management
├── prisma/
│   └── schema.prisma         # Database schema
├── .env                      # Environment variables
├── mcp-config.json          # MCP configuration template
├── CURSOR_SETUP.md          # Cursor integration guide
└── README.md                # This file

🗃️ Database Schema

Project (1) ─┐
             ├─> File (N) ─┐
                           ├─> Chunk (N) ─┐
                                          ├─> Embedding (N)
  • Project: Root container (name, rootPath)
  • File: Individual source files (path, language, hash)
  • Chunk: Code segments (text, lines, AST metadata)
  • Embedding: Vector representations (768-dim, model, similarity search)

🔧 Development

Scripts

pnpm dev              # Start with auto-reload
pnpm start            # Start server
pnpm build            # Compile TypeScript

pnpm db:setup         # Setup database + pgvector
pnpm db:migrate       # Run migrations
pnpm db:generate      # Generate Prisma client
pnpm db:studio        # Open Prisma Studio

Environment Variables

# Required
GEMINI_API_KEY=your_gemini_api_key
DATABASE_URL=postgresql://user:pass@host:port/db?schema=cbmcp

# Optional
NODE_ENV=development

🐛 Troubleshooting

MCP Connection Issues

Problem: Server won't connect in Cursor

Solutions:

  1. Test manually: npx tsx src/index.ts (should output startup message)
  2. Check absolute path in config matches your directory
  3. Verify environment variables in MCP config
  4. Restart Cursor completely (Cmd+Q, then reopen)
  5. Check MCP output panel for error logs

Database Issues

Problem: type "vector" does not exist

Solution:

pnpm db:setup  # This installs pgvector in cbmcp schema

Problem: Connection refused

Solution:

docker ps | grep codebrain  # Verify container running
docker start codebrain      # Start if stopped

Embedding Issues

Problem: GEMINI_API_KEY is required

Solution: Add API key to .env and MCP config

Performance Issues

Problem: Indexing is slow

Solutions:

  • Embeddings are cached - subsequent runs are faster
  • Adjust batch size in indexing.ts if needed
  • Consider excluding large directories (node_modules, etc.)

📈 Performance

  • Indexing: ~2-5 seconds per file (first time, includes embedding generation)
  • Re-indexing: ~100ms per file (if unchanged, uses hash comparison)
  • Search: ~500ms per query (includes embedding + vector search)
  • Storage: ~10KB per code chunk (text + embedding + metadata)

🔐 Security

  • API keys stored in environment variables (not in code)
  • Database credentials configurable
  • MCP runs locally (no external API calls except Gemini)
  • Vector embeddings don't leave your machine

📝 License

MIT

🤝 Contributing

This is a personal project, but feel free to fork and adapt for your needs!

🎓 Learn More

✅ Status

  • ✅ Database setup and migrations
  • ✅ AST-based code splitting
  • ✅ Gemini embedding integration
  • ✅ Vector similarity search
  • ✅ MCP server implementation
  • ✅ Comprehensive test suite (28 tests)
  • ✅ Multi-project support
  • ✅ Cursor/Claude integration ready

Ready for production use! 🚀

推荐服务器

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 模型以安全和受控的方式获取实时的网络信息。

官方
精选