语义代码搜索服务

CodeBrain MCP Server 是一个基于AI嵌入和向量相似性的语义代码搜索工具,支持多项目代码库的智能索引和搜索。

  • by candrle20
  • TypeScript
  • 本地部署
  • 更新于
在 GitHub 查看 candrle20/codebrain

使用说明

🧠 CodeBrain MCP服务器

由AI嵌入和向量相似性提供支持的语义代码搜索。

通过模型上下文协议(MCP)将智能代码搜索直接集成到Claude Desktop和Cursor中。

🎯 它做什么

CodeBrain使用基于AST的拆分和AI嵌入对代码库进行索引,从而实现:

  • 语义搜索 -按含义查找代码,而不仅仅是关键字
  • 智能分块 -AST感知代码拆分(尊重函数、类等)
  • 快速检索 -基于pgvector的向量相似度搜索
  • 多项目 -跨多个代码库进行索引和搜索

🚀 快速开始

1.先决条件

# 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.设置数据库

# 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.配置环境

编辑 .env:

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

4.测试服务器

# 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

🔌 连接到Cursor/Claude

对于光标

  1. 打开光标设置 → MCP服务器
  2. 添加服务器 命名 codebrain
  3. 复制此配置:
{
  "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. 重新启动游标
  2. 验证 -检查MCP面板是否显示“代码库”已连接

📖 详细指南: 看 CURSOR_SETUP.md

适用于克劳德桌面

编辑 ~/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"
      }
    }
  }
}

重新启动克劳德桌面。

🛠️ 可用的MCP工具

1. index_codebase

为语义搜索的代码库建立索引。

参数:

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

例子:

“将我的React项目索引到/Users/me/projects/my app,并命名为‘my app’”

2. semantic_search

在索引项目中语义搜索代码。

参数:

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

例子:

“在我的应用程序中查找身份验证逻辑”

3. list_projects

列出所有索引项目。

参数: 无

例子:

“显示所有索引项目”

4. get_project_stats

获取项目的统计数据。

参数:

{
  projectName: string;   // Project to query
}

例子:

“显示我的应用程序项目的统计数据”

📊 建筑

┌─────────────────────────────────────────────┐
│         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        │  │
│  └──────────────────────────────────────┘  │
└─────────────────────────────────────────────┘

🧪 测试

# 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

🌐 图形查看器(React)

使用React/Vite查看器在浏览器中可视化代码图。

# 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

使用覆盖API目标 VITE_GRAPH_API_URL (里面 apps/graph-viewer/.env)如果服务器在其他地方运行。

📁 项目结构

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

🗃️ 数据库模式

Project (1) ─┐
             ├─> File (N) ─┐
                           ├─> Chunk (N) ─┐
                                          ├─> Embedding (N)
  • 项目:根容器(名称,rootPath)
  • 文件:单个源文件(路径、语言、哈希)
  • 块:代码段(文本、行、AST元数据)
  • 嵌入:矢量表示(768 dim、模型、相似性搜索)

🔧 发展

脚本

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

环境变量

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

# Optional
NODE_ENV=development

🐛 故障排除

MCP连接问题

问题: 服务器无法在Cursor中连接

解决:

  1. 手动测试: npx tsx src/index.ts (应输出启动消息)
  2. 检查配置中的绝对路径是否与您的目录匹配
  3. 验证MCP配置中的环境变量
  4. 完全重新启动游标(Cmd+Q,然后重新打开)
  5. 检查MCP输出面板是否有错误日志

数据库问题

问题: type "vector" does not exist

解决方案:

pnpm db:setup  # This installs pgvector in cbmcp schema

问题: 连接被拒绝

解决方案:

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

嵌入问题

问题: GEMINI_API_KEY is required

解决方案: 将API密钥添加到 .env 和MCP配置

性能问题

问题: 索引速度慢

解决:

  • 嵌入被缓存-后续运行更快
  • 调整批次大小 indexing.ts 如有需要
  • 考虑排除大型目录(node_modules等)

📈 演出

  • 索引: 每个文件约2-5秒(第一次,包括嵌入生成)
  • 重新索引: 每个文件约100ms(如果不变,则使用哈希比较)
  • 搜索: 每次查询约500ms(包括嵌入+向量搜索)
  • 储存: 每个代码块约10KB(文本+嵌入+元数据)

🔐 安全

  • 存储在环境变量中的API键(不在代码中)
  • 数据库凭据可配置
  • MCP在本地运行(除Gemini外,没有外部API调用)
  • 向量嵌入不会离开你的机器

📝 许可证

麻省理工学院

🤝 贡献

这是一个个人项目,但请随时根据您的需求进行修改和调整!

🎓 了解更多

✅ 状态

  • ✅ 数据库设置和迁移
  • ✅ 基于AST的代码拆分
  • ✅ Gemini嵌入集成
  • ✅ 向量相似性搜索
  • ✅ MCP服务器实现
  • ✅ 综合测试套件(28项测试)
  • ✅ 多项目支持
  • ✅ Cursor/Claude集成就绪

准备投入生产使用! 🚀