Skip to content
facebookexperimentalPublic

About

semcode

Resources

Code of conduct

Contributing

Security policy

Stars

188 stars

Watchers

3 watching

Forks

Semcode - Semantic Code Search

Semcode is a semantic code search tool for C/C++ codebases that indexes your codebase and allows you to search for functions, types, and code patterns using both exact matches and semantic similarity.

News

Working directory overlay: queries now reflect uncommitted changes to tracked files automatically, no commit or re-index needed.

Rust indexing is now supported. This just uses treesitter, but all the semcode features are there.

Zig 0.16 indexing is now supported the same way: .zig files are parsed with tree-sitter, including 0.16 type builtins (@Int, @Struct, @Union, @Enum, @Tuple, @Pointer, @Fn, @EnumLiteral) and packed union backing integers.

Now with lore indexing! semcode-index --lore lkml,netdev (or any list names) will pull down the latest git archive from those lists. See the lore documentation for more details. This is a database schema change, so you'll need to reindex.

Recent commits introduced indexes for git commit history, as well as performance improvements. Unfortunately, these are a schema change and you'll need to reindex your database.

Features

  • Fast indexing of C/C++, Rust, Python, and Zig codebases using Tree-sitter
  • Interactive query interface with comprehensive command set
  • Semantic search of source code and lore email archives using an embed model
  • Call graph analysis with forward/reverse traversal
  • Data access analysis showing which functions access certain data
  • Type and macro discovery with detailed structural information
  • Diff analysis for understanding code changes and their impact
  • Pattern matching
  • MCP server for integration with AI code tools
  • GIT integration for incremental scans of new commits

Working Directory Overlay

All three tools (query, MCP server, LSP server) automatically detect uncommitted modifications to tracked files and overlay them on top of the indexed database. This means you can edit a file, and immediately query the new function definitions, callers, and types without committing or re-indexing.

  • Uses the git index for fast stat-based change detection (~500ms on a 93k-file kernel tree)
  • Only tracked files are checked; new files need git add to appear
  • Caches tree-sitter results across queries using mtime+size
  • The query tool's --git-only flag disables the overlay
  • The MCP server disables the overlay when an explicit git_sha or branch parameter is passed

While semcode provides both a query tool and an MCP server, the primary use case is via the MCP server. It gives AI code tools the ability to quickly find context about the kernel, and generally makes them more effective.

The MCP server can also be used by Kernel AI Review Prompts

Quick Start

Dependencies

# Ubuntu/Debian
sudo apt-get install build-essential libclang-dev protobuf-compiler libprotobuf-dev

# Fedora
sudo dnf install gcc-c++ clang-devel protobuf-compiler protobuf-devel

Note: The C++ compiler (g++/gcc-c++) is required for building dependencies.

Rust: Install from rustup.rs

Build

# Clone and build
git clone <repository-url>
cd semcode
cargo build --release

Binaries end up in target/release

(Optional) Installation

Install to your ~/.cargo/bin (if specified in your $SHELL profile)

# From the root of the semcode repository
cargo install --path .

Basic Usage

# Index a codebase

cd linux
semcode-index -s .

This assumes you have a linux git repo, and it puts the semcode database
into linux/.semcode.db (in the source directory)

# Start interactive query tool
semcode

You can index git ranges as well:

semcode-index -s . --git v6.14..v6.15

Once a git range is indexed, you can either use the --git arguments with individual commands in the query tools, or git checkout some_sha and run the query tool. It'll grab the current HEAD and return results against it.

Type help in the interactive shell for complete command documentation. Here are the most common commands:

Function and Macro Search:

func truncates the list of calls/callers by default, -v gives you everything

semcode> func printk                      # Find function by name
semcode> f EXPORT_SYMBOL                  # Find macro (short form)
semcode> function mutex_lock              # Find function (long form)
semcode> function btrfs_search.*          # Find function regex

Type and Typedef Search:

semcode> type struct task_struct          # Find struct by name
semcode> ty size_t                        # Find typedef (short form)
semcode> type pthread_mutex_t             # Find type by name

Call Graph Analysis:

These functions all have -v to show you paths and git file shas

semcode> callers mutex_lock               # Show what calls mutex_lock
semcode> calls schedule                   # Show what schedule calls
semcode --include-profile linux           # Enable Linux Kbuild include search roots
semcode --include-path include            # Add explicit repo-relative #include search root
semcode> calls -v xfs_attr_defer_add      # Show direct callees with TU-aware resolution
semcode> callchain kmalloc                # Show complete call graph (explicit caveats on non-proven/ambiguous hops)

Data access search:

semcode> accesses stack_vm                # Show what accesses stack_vm
semcode> accesses page flags              # Show what accesses page.flags

Commit searching:

You can search through all the commits, or through commit ranges. There are options for path regex (-p), symbol regex (-s) and verbose dumping of the commit diff (-v).

Note: All regex patterns in semcode are case-insensitive by default, including commit message searches, symbol patterns, and path patterns.

semcode> commit HEAD                      # show the HEAD commit
semcode> commit --git v6.16..v6.17 -s kmalloc # search for kmalloc in range
semcode> commit -p fs.btrfs -r filemap        # search fs/btrfs for commits mentioning filemap

Semantic Commit searching (requires vectors): All the same options as commit searching, but uses the embedded vectors. You can optionally add regex on top to filter the results.

Semantic searches are better for topics that aren't well suited to regex, such as find all the interface changes, or all the performance fixes.

semcode> vcommit -p fs.btrfs "all the interface changes"

Semantic Search (requires vectors):

semcode> vgrep btrfs search slot

Data Export:

semcode> dump-functions functions.json    # Export all functions
semcode> df funcs.json                    # Export functions (short form)
semcode> dump-types types.json            # Export all types
semcode> dt types.json                    # Export types (short form)
semcode> dump-typedefs typedefs.json      # Export all typedefs
semcode> dump-macros macros.json          # Export all macros
semcode> tables                           # Show available data tables

General Commands:

semcode> help                             # Show complete help with examples
semcode> h                                # Show help (short form)
semcode> quit                             # Exit the program
semcode> q                                # Exit (short form)

More Usage guides

Setting up semcode with claude: docs/claude-semcode-setup.md

Doing patch review in the kernel: docs/claude-patch-review.md

Data Storage

Semcode uses LanceDB to store:

  • Functions with signatures, bodies, call relationships, and optional embeddings
  • Types (structs, unions, enums) with field information
  • Typedefs with underlying type mappings
  • Macros (function-like only, for better signal-to-noise ratio)

Configuration

Performance Tuning

Use the -j flag to control parallelism:

The default is to try and saturate your cpus.

Proxy Support

The model setup scripts, and uv when it installs their dependencies, honor standard proxy environment variables:

export HTTP_PROXY=http://proxy.company.com:8080
export HTTPS_PROXY=http://proxy.company.com:8080
scripts/direct_download.py

MCP (Model Context Protocol) Server

Semcode includes an MCP server that exposes its query functionality to AI agents like Claude:

The MCP server provides these tools:

Basic Search:

  • find_function - Find functions and macros by exact name
  • find_type - Find types, structs, and typedefs by exact name

Call Graph Analysis:

  • find_callers - Find all functions that call a specific function
  • find_callees - Find all functions called by a specific function
  • find_callchain - Show complete call chain for a function
  • diff_functions - Extract and list functions from a unified diff
  • grep_functions - regex searches through function bodies
  • vgrep_functions - vector searches through function bodies

MCP Configuration

With stdio, each Claude instance starts its own semcode-mcp server.

cd linux
semcode-index -s .
claude --mcp-config mcp-config.json
> func btrfs_search_slot

mcp-config.json:

{"mcpServers":{"semcode":{"command":"/some_path/semcode-mcp"}}}

See examples/mcp-config.json for an example file

Verify MCP Tools Are Available

Ask Claude to list available tools:

User: "What semcode tools do you have access to?"
User: "What semcode-myproject tools are available?" # For specific server

Configuration Options

Required:

  • command: Absolute path to semcode-mcp binary Optional:
  • args: --database with the path to your indexed database and --git-repo for the repo

Streamable HTTP

Start a shared server and point your MCP client at http://127.0.0.1:8080/mcp.

./bin/semcode-mcp --listen 127.0.0.1:8080 --database /path/to/your.db --git-repo /path/to/repo

Leave out --listen for stdio. For a deployment behind a reverse proxy, use --http-allowed-host mcp.example.com if the proxy forwards that Host header. The listener accepts loopback Hosts by default. When bound to a specific IP, it also accepts that IP and port. Clients may omit Origin. To allow a specific Origin, pass --http-allowed-origin with its scheme, host, and port. Both allowlist options can be repeated. Use an authenticated TLS reverse proxy when exposing the endpoint to other machines. The built-in listener serves plain HTTP without authentication.

Manual Testing

You can test the MCP server outside of Claude:

# Start the MCP server manually
./bin/semcode-mcp --database /path/to/your.db

# It waits for JSON-RPC on stdin, one message per line; most clients start
# with an `initialize` request
# Press Ctrl+C to exit

Protocol Details

The server uses the official Rust MCP SDK (rmcp) for both transports. Background indexing progress is reported by the indexing_status tool and on stderr.

  • Concurrency: at most --max-concurrent-requests tool calls run at once (default 2). A call beyond that is refused immediately with JSON-RPC error -32001 and "data": {"retryable": true}. A slot is held until the call's work has stopped. In HTTP mode, all clients share this limit. For stdio, responses waiting to be written are unbounded, so a client that stops reading stdout while it keeps sending requests grows server memory.
  • Cancellation: a cancelled call stops at its next wait for I/O, such as a database query, and its slot is then freed. Computation between those points runs to the end first.
  • End of input: when stdin closes, responses to calls already running are written for up to 5 seconds; then the server exits without waiting for the rest.
  • Messages: HTTP POST bodies are limited to 16 MiB. With stdio, each JSON-RPC message is one line of at most 16 MiB. Longer lines and invalid JSON-RPC lines are dropped without a reply.
  • Stale index: a query against an index written by an older semcode is refused with an isError result. Its text gives the rebuild command, and its _meta carries the same facts as fields: index_stale (true), written_by and expected (schema versions), and command.

MCP tools can read data from the configured repository and database. The background indexer can write to the database.

Model Setup (for vector search)

Note: this is mostly untested, and not required for general usage. I've been trying nomic v2 and running it through model2vec to make things faster without a GPU. There are scripts, which need uv to install their dependencies:

scripts/direct_download.py
scripts/nomic2vec.py

Where env -S is unavailable (e.g. BusyBox), run them as uv run --script scripts/<name>.py. Without uv, install the dependencies with pip3 install -r scripts/requirements.txt and run them with python3.

Take the resulting model directory and move it to ~/.cache/semcode/models/model2vec.

Then do a index run: semcode-index -s .

Then do a vector run: semcode-index -s . --vectors

Then you can do vector searches with the vgrep command either in the query tool or MCP.

A model made by an older nomic2vec.py has an extra [UNK] token that moves every later token id one row off its embedding, and semcode refuses to load it ("embeddings has N rows, but the tokenizer has N+1 tokens"). Fix it in place. Vectors made with it used the wrong rows, so remove them and make them again:

scripts/fix_model2vec_tokenizer.py ~/.cache/semcode/models/model2vec
rm -rf .semcode.db/vectors.lance .semcode.db/commit_vectors.lance .semcode.db/lore_vectors.lance
semcode-index -s . --vectors

Model Storage

This is only relevant for vector searching

Models are stored in: ~/.cache/semcode/models/

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Kernel Style DCO contributions

This project is aimed at the kernel community, and they use the developer certificate of origin instead of CLAs.

The DCO is defined here: https://developercertificate.org/

If you'd like to use a DCO instead of completing the CLA on this repository, please send your pull request through:

https://github.com/rikvanriel/semcode

About

semcode

Resources

Code of conduct

Contributing

Security policy

Stars

188 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages