代码索引服务

一个基于内存的源代码索引服务器,提供快速的代码搜索和文件管理功能,适用于大型代码库和AI代码分析工具。

  • by lexandro
  • Go
  • 本地部署
  • 3 星标
  • 更新于
在 GitHub 查看 lexandro/codeindex-mcp

使用说明

代码索引mcp

内存中 主控程序 用于源代码索引的服务器。一个快速、索引化的替代品 grep 和 find,专为 克劳德代码 以及任何MCP兼容客户端。

为什么?

  • 数量级更快 比 grep/find 在大型代码库上——所有文件内容都由内存索引提供
  • 精确的grep语义 --具有完全召回的文字子字符串、精确短语和RE2正则表达式查询(mutex 发现 sync.RWMutex);没有标记器假阴性
  • 令牌高效输出 --合并的上下文块、每个文件的匹配上限,以及 files/count 为AI代理设计的输出模式
  • 基于Glob的文件搜索 和 ** 双星支持
  • 自动更新 --后台文件监视器加上定期同步验证,使索引与磁盘保持一致
  • 可配置的过滤 --尊重 .gitignore 和 .claudeignore 在每个目录级别,加上自定义排除模式
  • 单个二进制 --无运行时依赖关系;轻量级构建没有CGo,完整的AST构建包括树视图语法

快速开始

# Register for a project (creates .mcp.json)
./codeindex-mcp register project /path/to/your/project

# Or register globally for all projects (updates ~/.claude.json)
./codeindex-mcp register user

就是这样——Claude Code将自动发现并使用索引搜索工具。

安装

先决条件

  • 转到1.25+
  • GCC C编译器 --仅适用于完整的AST构建(make build-ast);轻量级构建不依赖于CGo

安装脚本会自动处理一切。

从源代码构建

git clone https://github.com/lexandro/codeindex-mcp.git
cd codeindex-mcp

首次设置 (安装Go、GCC、make(如果缺少)):

# Windows
powershell -ExecutionPolicy Bypass -File scripts/setup_build.ps1

# Linux / macOS
bash scripts/setup_build.sh

该脚本检测您的包管理器(apt、dnf、pacman、brew、winget),安装任何缺失的依赖项,并在最后打印确切的构建命令。

两种构建变体:

轻量级 全AST
二进制大小 ~18 MB ~31 MB
CGo/GCC 不需要 需要
转到AST索引 是 是
TypeScript/Python/JS AST 否 是
构建命令 make build make build-ast
# Lightweight — no GCC needed, works everywhere
make build
make test

# Full AST — requires GCC (run setup_build first)
make build-ast
make test-ast

没有 make:

go build -o codeindex-mcp .                               # lightweight
CGO_ENABLED=1 go build -tags ast -o codeindex-mcp .      # full AST

在克劳德代码中注册

构建后,注册服务器,以便Claude Code可以找到它:

# Project-specific (writes .mcp.json in the target directory)
./codeindex-mcp register project /path/to/your/project

# Global (writes ~/.claude.json — available in all projects)
./codeindex-mcp register user

# With extra server flags
./codeindex-mcp register project . -- --max-file-size 5242880 --exclude "vendor/"

这 register 命令自动检测二进制路径并创建正确的配置条目,包括 cmd /C Windows上的包装器。

运行测试

make test        # lightweight (no CGo)
make test-ast    # full AST build (requires GCC)

# manually:
go test ./...                              # lightweight
CGO_ENABLED=1 go test -tags ast ./...     # full AST

用法

独立式(用于测试)

./codeindex-mcp --root /path/to/project

服务器使用MCP协议通过stdio(stdin/stdout)进行通信,因此它本身不是交互式的——从MCP客户端使用它。

Claude代码集成

注册服务器最简单的方法是内置 register 子命令:

# Register for a specific project (writes .mcp.json in the project directory)
./codeindex-mcp register project /path/to/project

# Register globally for all projects (writes ~/.claude.json)
./codeindex-mcp register user

# Forward extra flags to the server
./codeindex-mcp register project . -- --max-file-size 5242880 --exclude "vendor/"

或者,手动添加到您的Claude Code MCP设置中。对于特定于项目的配置,请创建 .mcp.json 在项目根目录中:

{
  "mcpServers": {
    "codeindex": {
      "command": "/path/to/codeindex-mcp",
      "args": ["--root", "."]
    }
  }
}

对于全局配置,请添加到 ~/.claude.json:

{
  "mcpServers": {
    "codeindex": {
      "command": "/path/to/codeindex-mcp",
      "args": ["--root", "/path/to/project"]
    }
  }
}

Claude Code将自动使用 codeindex_search, codeindex_files, codeindex_read, codeindex_status,以及 codeindex_reindex 工具。

CLI标志

标志 默认值 描述
--root DIR 当前目录 要索引的项目根目录
--exclude PATTERN (无) 额外的忽略模式,可重复(例如。 --exclude "*.generated.go" --exclude "vendor/")
--force-include PATTERN (无) 强制包含模式覆盖所有排除,可重复(例如。 --force-include "*.log")
--max-file-size N 1048576 (1 MB) 最大文件大小(字节);跳过较大的文件
--max-results N 50 默认最大搜索结果数
--log-enabled false 启用日志记录(禁用时不创建日志文件)
--log-level LEVEL info 日志级别: debug, info, warn, error
--log-file PATH <root>/codeindex-mcp.log 日志文件路径
--sync-interval N 300 周期性索引同步验证间隔(秒)(0=禁用)
--ast false 启用AST符号索引(增加5 codeindex_ast_* 工具)
--ast-languages LIST go,typescript,python,javascript AST索引的语言。仅在轻量级版本中 go 可用; typescript, python, javascript 需要 -tags ast
--ast-max-file-size-kb N 500 AST索引的最大文件大小(KB)

例子

# Index the current directory
./codeindex-mcp

# Specify project root with extra exclusions
./codeindex-mcp --root ~/myproject \
  --exclude "*.generated.go" \
  --exclude "testdata/"

# Force-include log files (overrides the default *.log exclusion)
./codeindex-mcp --root . --force-include "*.log"

# Multiple force-include patterns (additive)
./codeindex-mcp --root . --force-include "*.log" --force-include "vendor/*.go"

# Combine exclude and force-include
./codeindex-mcp --root ~/myproject \
  --exclude "*.generated.go" \
  --force-include "*.log"

# Enable debug logging to a specific file
./codeindex-mcp --root . --log-enabled --log-level debug --log-file /tmp/codeindex.log

# Disable periodic sync verification (enabled every 300s by default)
./codeindex-mcp --root . --sync-interval 0

# Allow larger files (5 MB)
./codeindex-mcp --root . --max-file-size 5242880

# Enable AST symbol indexing
./codeindex-mcp --root . --ast

# AST indexing for Go only (faster, smaller memory footprint)
./codeindex-mcp --root . --ast --ast-languages go

MCP工具

服务器注册了5个工具:

1. codeindex_search --内容搜索

从内存中检索所有索引文件内容的等效搜索。

参数:

名称 类型 必填 描述
query string yes 搜索查询(见下面的格式)
filePath string no 在单个文件中搜索的精确相对路径(覆盖 fileGlob)
fileGlob string no 用于过滤文件的Glob模式(例如。 **/*.go)
maxResults int no 文件结果的最大数量(默认值:50)
contextLines int no 每次匹配前后的上下文行(默认值:2, 0 =仅匹配行)
maxMatchesPerFile int no 每个文件呈现的最大匹配项数(默认值:10);实际总数仍在报告中
outputMode string 否 content (默认)=带行号的大块; files =仅路径; count =具有匹配计数的路径
caseSensitive bool no 纯文本和正则表达式查询的区分大小写匹配(默认值:false)

查询格式:

格式 示例 行为
纯文本 handleRequest 文字子字符串匹配,不区分大小写——完全召回, mutex 发现 sync.RWMutex
"quoted" "func main" 精确的文字匹配,区分大小写
/regex/ /func\s+\w+Handler/ RE2正则表达式,每行匹配,默认不区分大小写

输出示例 (content 模式-- N: 标记一场比赛, N- 标记上下文, -- 分开大块):

3 matches in 2 files:
main.go
  4- import "fmt"
  5-
  6: func main() {
  7-     fmt.Println("hello world")
  --
  21- // entry helper
  22: func mainHelper() {
  23-     setup()
  ... +4 more matches

server/server.go
  13-
  14: func main() {
  15-     startServer()

files mode每行返回一条路径; count 模式返回 path: matchCount 每行--当您只需要位置时,两者都可以保存令牌。

2. codeindex_files --文件搜索

在索引中进行基于全局的文件搜索。

参数:

名称 类型 必填 描述
pattern string yes 球状模式(例如。 **/*.ts, src/**/*.go)
nameOnly bool 否 如果 true,仅返回不带元数据的文件路径
maxResults int no 最大结果数(默认值:50)

输出示例:

src/main.go (Go, 2.1 KB, 85L)
src/utils/helper.go (Go, 1.3 KB, 42L)
src/server/handler.go (Go, 4.7 KB, 156L)
src/config/config.go (Go, 892 B, 31L)

3. codeindex_read --从索引读取文件

直接从内存索引中读取文件内容。零磁盘I/O——比内置的读取工具更快。

参数:

名称 类型 必填 描述
filePath string yes 要读取的相对文件路径(例如。 src/main.go)

输出示例:

1: package main
2:
3: import "fmt"
4:
5: func main() {
6:     fmt.Println("hello")
7: }

4. codeindex_status --指标状态

显示当前索引统计信息。

参数: 无

输出示例:

root: /home/user/myproject
version: 0.6.0
uptime: 45s
files: 1234 (8.5 MB)
memory: 24.7 MB
watcher: 87 dirs
sync: every 300s
languages: TypeScript:456, Go:312, JavaScript:189, Python:98

5. codeindex_reindex --强制重新索引

清除索引并从头开始重建。也重新加载 .gitignore 和 .claudeignore 规则。

参数: 无

输出示例:

reindexed: 1234 files (8.5 MB) in 1.234s

AST工具(可选, --ast 旗帜)

当开始时 --ast,服务器注册了5个用于结构代码导航的附加工具。

构建 语言 如何构建
重量轻(make build) 只去--通过 go/parser,没有CGo go build .
全AST(make build-ast) Go+TypeScript+Python+JavaScript go build -tags ast .

这两个版本都公开了相同的5个工具——区别在于哪些语言会被索引。

1. codeindex_ast_search_symbols --按名称搜索符号

参数:

名称 类型 必填 描述
query string yes 符号名称(不区分大小写的子字符串匹配)
kind string no 按种类筛选: class, interface, enum, function, method, field, variable, constant, type_alias
language string no 按语言筛选: go, typescript, python, javascript
limit int no 最大结果(默认值:20)

输出示例:

3 symbols matching "handler":
function  HandleRequest        server/handler.go:12  go
method    HandleError          server/handler.go:45  go
function  handleWatcherEvents  indexing.go:98        go

2. codeindex_ast_file_symbols --列出文件中的符号

参数:

名称 类型 必填 描述
file string yes 相对文件路径

输出示例:

6 symbols in server/handler.go:
class     Server          line 8
method    Start           line 15   parent: Server
method    Stop            line 28   parent: Server
function  HandleRequest   line 45
function  handleError     line 67
variable  defaultTimeout  line 5

3. codeindex_ast_find_usages --查找引用符号的文件

在所有索引文件中以文本模式搜索符号名称。返回可能引用它的文件(不是完整的类型感知分析)。

参数:

名称 类型 必填 描述
symbol string yes 要搜索的符号名称
kind string no 可选类型提示(仅供参考)

输出示例:

5 files reference "HandleRequest":
server/handler.go
server/handler_test.go
main.go
tools/proxy.go
docs/api.md

4. codeindex_ast_get_imports --列出文件的导入

参数:

名称 类型 必填 描述
file string yes 相对文件路径

输出示例:

4 imports in server/handler.go:
fmt
net/http
github.com/lexandro/codeindex-mcp/index
log/slog

5. codeindex_ast_stats --AST指数统计

参数: 无

输出示例:

AST index stats:
files:    142
symbols:  1847
by kind:  function:623 method:441 class:187 variable:312 constant:98 ...
by lang:  go:1203 typescript:489 python:155

忽略系统

服务器使用多层过滤系统来确定要索引哪些文件:

1.内置默认模式

自动跳过,无需任何配置:

类别 图案
版本控制 .git, .svn, .hg
依赖关系 node_modules, vendor, bower_components, .yarn
构建输出 dist, build, out, target, bin, obj
IDE文件 .idea, .vscode, .vs
二进制文件 *.exe, *.dll, *.so, *.dylib, *.class, *.jar
图片 *.png, *.jpg, *.gif, *.webp, *.ico
字体 *.woff, *.woff2, *.ttf, *.eot
媒体中心 *.mp3, *.mp4, *.avi, *.mov
文件 *.pdf, *.doc, *.xlsx, *.pptx
锁定文件 package-lock.json, yarn.lock, go.sum, Cargo.lock
档案 *.zip, *.tar, *.tar.gz, *.rar, *.7z
缩小 *.min.js, *.min.css
源地图 *.map
缓存 .cache, .next, .nuxt, .parcel-cache
日志 *.log
数据库 *.sqlite, *.sqlite3, *.db
环境/秘密 .env, .env.*, *.env (使用 --force-include 有意索引)

2. .gitignore 支持

完全尊重 .gitignore 模式 在每个目录级别 (嵌套 .gitignore 包括文件),带globs,否定(!important.log),以及git的优先级规则:最接近路径的忽略文件获胜。

3. .claudeignore 支持

.claudeignore 文件使用与相同的语法和相同的层次匹配 .gitignore。使用它们从git中的索引中排除与AI代码搜索无关的文件。

示例 .claudeignore:

# Generated files
*.generated.go
*.pb.go

# Large test fixtures
testdata/large/

# Archived migrations
migrations/archive/

4.CLI --exclude 模式

通过运行时排除 --exclude 标志:

./codeindex-mcp --exclude "*.generated.go" --exclude "vendor/"

5.CLI --force-include 模式

强制包括模式覆盖 全部 排除规则(内置默认值, .gitignore, .claudeignore,以及 --exclude).多个 --force-include 标志是累加的。二进制检测和文件大小限制仍然适用。

# Index *.log files even though they are excluded by default
./codeindex-mcp --force-include "*.log"

# Force-include vendor Go files while still excluding the rest of vendor/
./codeindex-mcp --force-include "vendor/*.go"

当强制包含模式处于活动状态时,可能包含匹配文件的目录在遍历过程中不会被修剪。这 .git 无论强制包含模式如何,目录都会被跳过。

6.二进制文件检测

扫描每个文件的前512个字节以查找空字节。如果找到,该文件将被视为二进制文件并跳过。这独立于 .gitignore.

7.文件大小限制

可通过以下方式配置 --max-file-size (默认值:1 MB)。大于此值的文件将被跳过。

优先级

过滤器按顺序应用:

  1. --force-include 模式 (最高优先级——如果匹配,则无论规则2-5如何,文件都会被包含在内)
  2. 内置默认模式
  3. .gitignore 规则
  4. .claudeignore 规则
  5. 命令行界面 --exclude 模式
  6. 二进制检测(始终适用,即使是强制包含的文件)
  7. 文件大小限制(始终适用,即使是强制包含的文件)

如果强制包含模式匹配,则文件将绕过所有排除规则(2-5)。二进制检测和文件大小限制是始终适用的安全检查。

建筑

MCP Client (stdio) <──> MCP Server <──> Index Engine
                                            │
                                    ┌───────┼────────┐
                                    │       │        │
                                ContentMap FileMap  Watcher
                               (line scan) (path)  (fsnotify)

双指标设计

索引 技术 目的
内容索引 去吧 map 预拆分行 完全在内存中扫描的精确grep风格内容搜索(子字符串/短语/RE2正则表达式)
文件路径索引 去吧 map +排序切片 使用glob模式搜索文件名/路径

搜索路径中没有标记器或倒排索引:查询被编译为单个RE2匹配器,并在内存行上进行扫描。这保证了grep相同的结果(标识符内部的子字符串没有回调间隙),同时比基于磁盘的grep快得多。

文件监视器

  • 用途 Fsnotify (在Windows上: ReadDirectoryChangesW API
  • 递归:在启动时监视所有未被忽略的子目录
  • 100ms去抖动窗口:编辑器在保存时生成多个事件——这些事件被合并为一个
  • 监视新创建的目录树 递归地 并且已经在其中的文件被索引(封面复制/解压缩/ git checkout 爆裂)
  • 自动重新加载忽略任何规则 .gitignore 或 .claudeignore 更改,然后根据新规则重新同步索引
  • 定期同步验证(默认值:每300秒一次)通过将索引与磁盘进行比较来修复任何遗漏的事件

启动顺序

  1. 解析CLI标志
  2. 创建忽略匹配器(内置+分层.gitignore/.claudeignore+CLI模式)
  3. 初始化内存内容索引和文件路径索引
  4. 使用8个worker goroutines进行并行索引
  5. 启动文件监视器和定期同步验证
  6. 在stdio传输上启动MCP服务器

项目结构

codeindex-mcp/
├── main.go                  # Entry point, CLI flags, component wiring
├── indexing.go              # Directory walking, parallel indexing, watcher events
├── sync.go                  # Periodic background index sync verification
├── server/
│   └── server.go            # MCP server setup, tool registration
├── index/
│   ├── content.go           # In-memory content index (CRUD operations)
│   ├── content_search.go    # Line-scan search logic, query parsing, hunk building
│   ├── content_test.go
│   ├── files.go             # File path index (glob search) + IndexedFile type
│   └── files_test.go
├── watcher/
│   ├── watcher.go           # Recursive fsnotify wrapper
│   └── debouncer.go         # 100ms event collapsing
├── ignore/
│   ├── ignore.go            # .gitignore + .claudeignore + custom patterns
│   ├── ignore_test.go
│   └── defaults.go          # Built-in ignore patterns
├── register/
│   ├── register.go          # Auto-register subcommand for Claude Code config
│   └── register_test.go
├── tools/
│   ├── search.go            # codeindex_search handler
│   ├── files.go             # codeindex_files handler
│   ├── read.go              # codeindex_read handler
│   ├── status.go            # codeindex_status handler
│   ├── reindex.go           # codeindex_reindex handler
│   └── format.go            # Output formatting
├── ast/                     # AST symbol indexing (--ast flag)
│   ├── symbols.go           # Symbol, SymbolKind, SymbolTable
│   ├── extractor.go         # LanguageExtractor interface
│   ├── extractor_go.go      # Go extractor — go/parser, always compiled
│   ├── extractor_typescript.go  # TypeScript extractor — tree-sitter, build tag: ast
│   ├── extractor_python.go  # Python extractor — tree-sitter, build tag: ast
│   ├── extractor_javascript.go  # JavaScript extractor — tree-sitter, build tag: ast
│   ├── languages_noast.go   # Extractor registry, Go only (build tag: !ast)
│   ├── languages_ast.go     # Extractor registry, all 4 languages (build tag: ast)
│   ├── module.go            # Module wiring: OnFileChanged/Removed, RegisterTools
│   ├── tools.go             # 5 codeindex_ast_* MCP tool handlers
│   └── symbols_test.go
├── scripts/
│   ├── setup_build.sh       # Linux/macOS: full build environment setup
│   ├── setup_build.ps1      # Windows: full build environment setup
│   └── setup-gcc.ps1        # Windows: GCC-only install helper
├── Makefile                 # build / build-ast / test / test-ast / run / run-ast
└── language/
    ├── detect.go            # Extension → language mapping (70+)
    ├── detect_test.go
    ├── binary.go            # Binary file detection
    └── binary_test.go

依赖项

库 版本 目的
modelcontextprotocol/go-sdk v1.3.0 MCP服务器(stdio传输)
Fsnotify/Fsnotify v1.9.0 文件系统监视
bmatcuk/双星/v4 v4.10.0版本 ** glob支持
异常/go-gitignore 最新 .gitignore/.claudeignore解析
树保姆 v0.25.0 CGo树保姆绑定(-tags ast 仅)
树保姆/树保姆打字稿 v0.23.2 TypeScript语法(-tags ast 仅)
树保姆/树保姆python v0.25.0 Python语法(-tags ast 仅)
树保姆/树保姆javascript v0.25.0 JavaScript语法(-tags ast 仅)

演出

度量 约5k个文件 约10k个文件
初始索引 ~1s ~1-2s
内存使用率 ≈2×索引文件总大小 ≈1×索引文件的总大小
文本/正则表达式搜索 <30ms <60ms
全球搜索 <2ms <5ms
增量更新 <5ms/文件 <5ms/文件

搜索是一种线性内存扫描,编译为单个RE2匹配器——没有反向索引来构建或保持一致,因此索引很快,内存保持接近原始语料库大小。

支持的语言

语言检测可识别70多个文件扩展名,包括:

Go、TypeScript、JavaScript、Python、Rust、Java、Kotlin、C、C++、C#、Swift、Dart、Ruby、PHP、Shell、PowerShell、HTML、CSS、SCSS、Sass、Less、JSON、YAML、TOML、XML、SQL、GraphQL、Protobuf、Terraform、Lua、R、Scala、Elixir、Erlang、Haskell、Zig、Vue、Svelte、Markdown、Dockerfile、Makefile、CMake、Batch等等。

许可证

麻省理工学院