初始提交:codebase-memory-mcp - Codebase Memory MCP Server

Fork from https://github.com/DeusData/codebase-memory-mcp
Go 实现,提供代码库记忆功能的 MCP 服务器
This commit is contained in:
xiaowei
2026-07-30 09:18:35 +08:00
commit f1e40eebb4
2049 changed files with 38420279 additions and 0 deletions
+16
View File
@@ -0,0 +1,16 @@
pkgbase = codebase-memory-mcp
pkgdesc = Fast code intelligence engine for AI coding agents — single static binary MCP server
pkgver = 0.8.1
pkgrel = 1
url = https://github.com/DeusData/codebase-memory-mcp
arch = x86_64
arch = aarch64
license = MIT
provides = codebase-memory-mcp
conflicts = codebase-memory-mcp
source_x86_64 = codebase-memory-mcp-0.8.1-linux-amd64.tar.gz::https://github.com/DeusData/codebase-memory-mcp/releases/download/v0.8.1/codebase-memory-mcp-linux-amd64.tar.gz
sha256sums_x86_64 = dbd3b92ea870ef240b63059f26bda15015f76ef9978931bebc3a0f9d09470973
source_aarch64 = codebase-memory-mcp-0.8.1-linux-arm64.tar.gz::https://github.com/DeusData/codebase-memory-mcp/releases/download/v0.8.1/codebase-memory-mcp-linux-arm64.tar.gz
sha256sums_aarch64 = d2f842d1365da5c35d9c5796f57a821c9745267350994346735e1e6e04d46091
pkgname = codebase-memory-mcp
+28
View File
@@ -0,0 +1,28 @@
# Maintainer: DeusData <https://github.com/DeusData>
pkgname=codebase-memory-mcp
pkgver=0.8.1
pkgrel=1
pkgdesc="Fast code intelligence engine for AI coding agents — single static binary MCP server"
arch=('x86_64' 'aarch64')
url="https://github.com/DeusData/codebase-memory-mcp"
license=('MIT')
provides=("$pkgname")
conflicts=("$pkgname")
source_x86_64=("${pkgname}-${pkgver}-linux-amd64.tar.gz::https://github.com/DeusData/codebase-memory-mcp/releases/download/v${pkgver}/codebase-memory-mcp-linux-amd64.tar.gz")
source_aarch64=("${pkgname}-${pkgver}-linux-arm64.tar.gz::https://github.com/DeusData/codebase-memory-mcp/releases/download/v${pkgver}/codebase-memory-mcp-linux-arm64.tar.gz")
sha256sums_x86_64=('dbd3b92ea870ef240b63059f26bda15015f76ef9978931bebc3a0f9d09470973')
sha256sums_aarch64=('d2f842d1365da5c35d9c5796f57a821c9745267350994346735e1e6e04d46091')
package() {
install -Dm755 "${srcdir}/codebase-memory-mcp" \
"${pkgdir}/usr/bin/codebase-memory-mcp"
install -Dm644 "${srcdir}/LICENSE" \
"${pkgdir}/usr/share/licenses/${pkgname}/LICENSE"
# Third-party attribution bundle (present in archives since v0.8.1)
if [ -f "${srcdir}/THIRD_PARTY_NOTICES.md" ]; then
install -Dm644 "${srcdir}/THIRD_PARTY_NOTICES.md" \
"${pkgdir}/usr/share/licenses/${pkgname}/THIRD_PARTY_NOTICES.md"
fi
}
+35
View File
@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2015/06/nuspec.xsd">
<metadata>
<id>codebase-memory-mcp</id>
<version>0.8.1</version>
<title>codebase-memory-mcp</title>
<authors>DeusData</authors>
<projectUrl>https://github.com/DeusData/codebase-memory-mcp</projectUrl>
<licenseUrl>https://github.com/DeusData/codebase-memory-mcp/blob/main/LICENSE</licenseUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<projectSourceUrl>https://github.com/DeusData/codebase-memory-mcp</projectSourceUrl>
<bugTrackerUrl>https://github.com/DeusData/codebase-memory-mcp/issues</bugTrackerUrl>
<tags>mcp ai claude code-intelligence codebase developer-tools tree-sitter llm</tags>
<summary>Fast code intelligence engine for AI coding agents</summary>
<description>
codebase-memory-mcp is a single static binary MCP server that indexes codebases at
extreme speed and exposes 14 MCP tools for AI coding agents.
Full indexes an average repository in milliseconds, the Linux kernel (28M LOC) in
3 minutes. Answers structural queries in under 1ms. Supports 159 languages via
vendored tree-sitter grammars. Zero dependencies. Plug and play across 11 coding
agents including Claude Code, Codex CLI, Gemini CLI, and Zed.
After installation, run:
codebase-memory-mcp install
to configure your coding agents automatically.
</description>
<releaseNotes>https://github.com/DeusData/codebase-memory-mcp/releases/tag/v0.8.1</releaseNotes>
</metadata>
<files>
<file src="tools\**" target="tools" />
</files>
</package>
@@ -0,0 +1,25 @@
$ErrorActionPreference = 'Stop'
$packageName = 'codebase-memory-mcp'
$version = '0.8.1'
$url64 = "https://github.com/DeusData/codebase-memory-mcp/releases/download/v${version}/codebase-memory-mcp-windows-amd64.zip"
$checksum64 = 'a602ad090ed3f49d86c55472f73f27ad7055222806a82358f2e08513e027f00f'
$installDir = Join-Path $env:ChocolateyBinRoot $packageName
Install-ChocolateyZipPackage `
-PackageName $packageName `
-Url64bit $url64 `
-Checksum64 $checksum64 `
-ChecksumType64 'sha256' `
-UnzipLocation $installDir
# Shim the binary so it is on PATH
$binPath = Join-Path $installDir 'codebase-memory-mcp.exe'
Install-BinFile -Name 'codebase-memory-mcp' -Path $binPath
# Configure coding agents (non-fatal)
try {
& $binPath install -y 2>&1 | Out-Null
} catch {
Write-Warning "Agent configuration failed (non-fatal). Run manually: codebase-memory-mcp install"
}
@@ -0,0 +1,10 @@
$ErrorActionPreference = 'Stop'
$packageName = 'codebase-memory-mcp'
$installDir = Join-Path $env:ChocolateyBinRoot $packageName
Uninstall-BinFile -Name 'codebase-memory-mcp'
if (Test-Path $installDir) {
Remove-Item $installDir -Recurse -Force
}
+26
View File
@@ -0,0 +1,26 @@
# Glama MCP directory (glama.ai) check image — NOT required to run the tool.
#
# codebase-memory-mcp needs NO Docker to run. This image exists only so Glama
# can build a sandbox, launch the stdio MCP server, and run its introspection
# checks, which power the directory's score badge. The same image is exercised
# locally and in CI by pkg/glama/verify.sh to guard against drift.
#
# We pull the "-portable" release asset, which is fully statically linked
# (gcc -static) — unlike the standard asset, which dynamically links glibc/
# libstdc++ and would fail on an older base. Because it's static, the runtime
# base image is arbitrary. TARGETARCH is amd64 / arm64, matching the asset names.
FROM debian:bookworm-slim AS fetch
ARG TARGETARCH
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl ca-certificates \
&& curl -fsSL "https://github.com/DeusData/codebase-memory-mcp/releases/latest/download/codebase-memory-mcp-linux-${TARGETARCH}-portable.tar.gz" \
| tar -xz -C /tmp codebase-memory-mcp LICENSE THIRD_PARTY_NOTICES.md \
&& chmod +x /tmp/codebase-memory-mcp \
&& rm -rf /var/lib/apt/lists/*
FROM debian:bookworm-slim
COPY --from=fetch /tmp/codebase-memory-mcp /usr/local/bin/codebase-memory-mcp
COPY --from=fetch /tmp/LICENSE /tmp/THIRD_PARTY_NOTICES.md /usr/share/doc/codebase-memory-mcp/
ENV CBM_CACHE_DIR=/tmp/cbm
ENTRYPOINT ["codebase-memory-mcp"]
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
# Build the Glama check image and confirm the MCP stdio server starts and
# answers initialize + tools/list with no project indexed — exactly what
# Glama's directory check does. Used locally and by the CI smoke suite.
#
# Env:
# IMAGE image tag to build (default: cbm-glama-check)
# DOCKER_BUILD_ARGS extra args for `docker build` (e.g. --platform linux/amd64)
set -euo pipefail
IMAGE="${IMAGE:-cbm-glama-check}"
DIR="$(cd "$(dirname "$0")" && pwd)"
run_with_timeout() {
local t="$1"; shift
if command -v timeout >/dev/null 2>&1; then timeout "$t" "$@"
elif command -v gtimeout >/dev/null 2>&1; then gtimeout "$t" "$@"
else "$@"; fi
}
echo "==> building ${IMAGE} (${DIR}/Dockerfile)"
# shellcheck disable=SC2086
docker build ${DOCKER_BUILD_ARGS:-} -f "${DIR}/Dockerfile" -t "${IMAGE}" "${DIR}"
echo "==> MCP introspection handshake (initialize -> initialized -> tools/list)"
REQ="$(printf '%s\n%s\n%s\n' \
'{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"glama-verify","version":"1"}}}' \
'{"jsonrpc":"2.0","method":"notifications/initialized"}' \
'{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}')"
OUT="$(printf '%s' "${REQ}" | run_with_timeout 60 docker run -i --rm "${IMAGE}" || true)"
printf '%s\n' "${OUT}"
echo "==> assertions"
printf '%s' "${OUT}" | grep -q '"result"' || { echo "FAIL: no JSON-RPC result (server did not respond)"; exit 1; }
printf '%s' "${OUT}" | grep -q 'search_graph' || { echo "FAIL: tools/list missing expected tool 'search_graph'"; exit 1; }
COUNT="$(printf '%s' "${OUT}" | grep -o '"name"' | wc -l | tr -d ' ')"
echo "PASS: server started and introspected; ~${COUNT} name entries (>=14 tools expected)"
+935
View File
@@ -0,0 +1,935 @@
// codebase-memory-mcp — Go installer wrapper.
//
// On first run, downloads the pre-built binary for the current platform from
// GitHub Releases, caches it, and replaces the current process with it.
// Subsequent runs skip directly to exec.
//
// Install:
//
// go install github.com/DeusData/codebase-memory-mcp/pkg/go/cmd/codebase-memory-mcp@latest
package main
import (
"archive/tar"
"archive/zip"
"compress/gzip"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"syscall"
"time"
)
const (
repo = "DeusData/codebase-memory-mcp"
version = "0.8.1"
windowsLauncherName = "codebase-memory-mcp.exe"
windowsPayloadName = "codebase-memory-mcp.payload.exe"
maxRedirects = 5
requestTimeout = 2 * time.Minute
connectTimeout = 15 * time.Second
responseHeaderTimeout = 30 * time.Second
candidateTimeout = 15 * time.Second
maxChecksumManifestSize = 1024 * 1024
windowsPairLockName = ".codebase-memory-mcp-pair.lock"
windowsPairLockWait = 45 * time.Second
windowsPairOwnerlessStale = 30 * time.Second
windowsPairLockPoll = 25 * time.Millisecond
windowsPairLockOwnerFile = "owner"
windowsPairTransactionTagSize = 16
)
type windowsPairLock struct {
path string
token string
}
func main() {
executable, err := ensureBinary()
if err != nil {
fmt.Fprintf(os.Stderr, "codebase-memory-mcp: %v\n", err)
os.Exit(1)
}
if err := execBinary(executable, os.Args[1:]); err != nil {
if runtime.GOOS == "windows" {
if exitErr, ok := err.(*exec.ExitError); ok {
printPortableMutationGuidance(os.Args[1:])
os.Exit(exitErr.ExitCode())
}
}
fmt.Fprintf(os.Stderr, "codebase-memory-mcp: %v\n", err)
os.Exit(1)
}
}
func ensureBinary() (string, error) {
payload := binPath()
ready := regularFileExists(payload)
if runtime.GOOS == "windows" {
ready = ready && regularFileExists(windowsLauncherPath())
if ready {
ready = verifyCandidate(windowsLauncherPath()) == nil
}
}
if ready {
return executionPathForOS(payload, runtime.GOOS), nil
}
if err := download(payload); err != nil {
return "", err
}
return executionPathForOS(payload, runtime.GOOS), nil
}
func binPath() string {
name := "codebase-memory-mcp"
if runtime.GOOS == "windows" {
// The payload remains the immutable exact-version pair's readiness
// signal. executionPathForOS selects its adjacent permanent launcher.
name = windowsPayloadName
}
return filepath.Join(cacheDir(), version, name)
}
func executionPathForOS(payload, targetOS string) string {
if targetOS == "windows" {
return filepath.Join(filepath.Dir(payload), windowsLauncherName)
}
return payload
}
func windowsLauncherPath() string {
return filepath.Join(filepath.Dir(binPath()), windowsLauncherName)
}
func regularFileExists(path string) bool {
info, err := os.Stat(path)
return err == nil && info.Mode().IsRegular()
}
func printPortableMutationGuidance(args []string) {
action := portableMutationAction(args)
if action == "" {
return
}
packageCommand := "go install github.com/DeusData/codebase-memory-mcp/pkg/go/cmd/codebase-memory-mcp@latest"
if action == "uninstall" {
packageCommand = "Remove-Item (Get-Command codebase-memory-mcp).Source"
}
fmt.Fprintf(
os.Stderr,
"This Go Windows copy is portable. Use %q for package maintenance, or run %q once to create a managed launcher with coordinated self-update/uninstall.\n",
packageCommand,
"codebase-memory-mcp install --yes",
)
}
func portableMutationAction(args []string) string {
for _, argument := range args {
switch argument {
case "cli", "hook-augment", "config", "install", "--help", "-h", "--version":
return ""
case "update", "uninstall":
return argument
}
}
return ""
}
func cacheDir() string {
if d := os.Getenv("CBM_CACHE_DIR"); d != "" {
return d
}
switch runtime.GOOS {
case "windows":
if d := os.Getenv("LOCALAPPDATA"); d != "" {
return filepath.Join(d, "codebase-memory-mcp")
}
case "darwin":
if home, err := os.UserHomeDir(); err == nil {
return filepath.Join(home, "Library", "Caches", "codebase-memory-mcp")
}
}
if d := os.Getenv("XDG_CACHE_HOME"); d != "" {
return filepath.Join(d, "codebase-memory-mcp")
}
if home, err := os.UserHomeDir(); err == nil {
return filepath.Join(home, ".cache", "codebase-memory-mcp")
}
return filepath.Join(os.TempDir(), "codebase-memory-mcp")
}
func goos() string {
switch runtime.GOOS {
case "darwin":
return "darwin"
case "linux":
return "linux"
case "windows":
return "windows"
default:
return runtime.GOOS
}
}
func goarch() string {
switch runtime.GOARCH {
case "amd64":
return "amd64"
case "arm64":
return "arm64"
default:
return runtime.GOARCH
}
}
func download(dest string) error {
platform := goos()
arch := goarch()
ext := "tar.gz"
if platform == "windows" {
ext = "zip"
}
portable := ""
if platform == "linux" {
portable = "-portable"
}
archive := fmt.Sprintf("codebase-memory-mcp-%s-%s%s.%s", platform, arch, portable, ext)
url := fmt.Sprintf("https://github.com/%s/releases/download/v%s/%s", repo, version, archive)
checksumURL := fmt.Sprintf("https://github.com/%s/releases/download/v%s/checksums.txt", repo, version)
fmt.Fprintf(os.Stderr, "codebase-memory-mcp: downloading v%s for %s/%s...\n", version, platform, arch)
tmp, err := os.MkdirTemp("", "cbm-install-*")
if err != nil {
return err
}
defer os.RemoveAll(tmp)
archivePath := filepath.Join(tmp, "cbm."+ext)
if err := httpGet(url, archivePath); err != nil {
return fmt.Errorf("download failed: %w", err)
}
// A release binary is executable input, so checksum verification is a
// mandatory precondition rather than a best-effort warning.
checksums, err := fetchChecksums(checksumURL)
if err != nil {
return fmt.Errorf("checksum manifest unavailable: %w", err)
}
expected, ok := checksums[archive]
if !ok {
return fmt.Errorf("checksum manifest has no entry for %s", archive)
}
if err := verifyChecksum(archivePath, expected); err != nil {
return err
}
binName := "codebase-memory-mcp"
requiredNames := []string{binName}
archiveNames := requiredNames
if platform == "windows" {
binName = windowsPayloadName
requiredNames = []string{windowsLauncherName, windowsPayloadName}
archiveNames = []string{
windowsLauncherName,
windowsPayloadName,
"LICENSE",
"install.ps1",
"THIRD_PARTY_NOTICES.md",
}
}
if ext == "tar.gz" {
if err := extractTarGz(archivePath, tmp, binName); err != nil {
return fmt.Errorf("extraction failed: %w", err)
}
} else {
if err := extractZip(archivePath, tmp, archiveNames, requiredNames); err != nil {
return fmt.Errorf("extraction failed: %w", err)
}
}
for _, name := range requiredNames {
extracted := filepath.Join(tmp, name)
if err := os.Chmod(extracted, 0755); err != nil {
return fmt.Errorf("could not set candidate permissions for %s: %w", name, err)
}
}
if platform == "windows" {
// In portable mode the canonical launcher must successfully resolve the
// adjacent payload before the pair is cached.
if err := verifyCandidate(filepath.Join(tmp, windowsLauncherName)); err != nil {
return fmt.Errorf("downloaded launcher failed verification: %w", err)
}
} else if err := verifyCandidate(filepath.Join(tmp, binName)); err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
return fmt.Errorf("could not create cache dir: %w", err)
}
if platform == "windows" {
if err := installWindowsPairAtomically(tmp, filepath.Dir(dest)); err != nil {
return fmt.Errorf("could not install Windows release pair: %w", err)
}
} else if err := installCandidateAtomically(filepath.Join(tmp, binName), dest); err != nil {
return fmt.Errorf("could not install binary: %w", err)
}
return nil
}
// validateURLScheme rejects non-https URLs before any fetch (defense-in-depth).
func validateURLScheme(rawURL string) error {
parsed, err := url.Parse(rawURL)
if err != nil || parsed.Scheme != "https" || parsed.Host == "" || parsed.User != nil {
return fmt.Errorf("refusing non-https URL: %s", rawURL)
}
return nil
}
// httpsOnlyClient returns an HTTP client that rejects non-HTTPS redirects.
var httpsOnlyClient = &http.Client{
Timeout: requestTimeout,
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{Timeout: connectTimeout}).DialContext,
ForceAttemptHTTP2: true,
TLSHandshakeTimeout: connectTimeout,
ResponseHeaderTimeout: responseHeaderTimeout,
ExpectContinueTimeout: time.Second,
},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if err := validateURLScheme(req.URL.String()); err != nil {
return fmt.Errorf("refusing unsafe redirect: %w", err)
}
if len(via) > maxRedirects {
return fmt.Errorf("too many redirects")
}
return nil
},
}
func httpGet(rawURL, dest string) error {
if err := validateURLScheme(rawURL); err != nil {
return err
}
resp, err := httpsOnlyClient.Get(rawURL) //nolint:gosec
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("HTTP %d for %s", resp.StatusCode, rawURL)
}
f, err := os.Create(dest)
if err != nil {
return err
}
_, copyErr := io.Copy(f, resp.Body)
closeErr := f.Close()
if copyErr != nil {
return copyErr
}
return closeErr
}
func fetchChecksums(url string) (map[string]string, error) {
if err := validateURLScheme(url); err != nil {
return nil, err
}
resp, err := httpsOnlyClient.Get(url) //nolint:gosec
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("HTTP %d", resp.StatusCode)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, maxChecksumManifestSize+1))
if err != nil {
return nil, err
}
if len(body) > maxChecksumManifestSize {
return nil, fmt.Errorf("checksums.txt exceeds the 1 MiB safety limit")
}
result := make(map[string]string)
for _, line := range strings.Split(string(body), "\n") {
parts := strings.Fields(line)
if len(parts) == 2 {
name := parts[1]
if strings.HasPrefix(name, "*") {
name = name[1:]
}
digest := strings.ToLower(parts[0])
if len(digest) != sha256.Size*2 {
return nil, fmt.Errorf("invalid SHA-256 checksum for %s", name)
}
if _, err := hex.DecodeString(digest); err != nil {
return nil, fmt.Errorf("invalid SHA-256 checksum for %s: %w", name, err)
}
if prior, exists := result[name]; exists && prior != digest {
return nil, fmt.Errorf("conflicting SHA-256 checksums for %s", name)
}
result[name] = digest
}
}
return result, nil
}
func verifyChecksum(path, expected string) error {
expected = strings.ToLower(expected)
if len(expected) != sha256.Size*2 {
return fmt.Errorf("invalid SHA-256 checksum length")
}
if _, err := hex.DecodeString(expected); err != nil {
return fmt.Errorf("invalid SHA-256 checksum: %w", err)
}
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return err
}
actual := hex.EncodeToString(h.Sum(nil))
if actual != expected {
return fmt.Errorf("checksum mismatch: expected %s, got %s", expected, actual)
}
return nil
}
func extractTarGz(archivePath, destDir, targetFile string) error {
f, err := os.Open(archivePath)
if err != nil {
return err
}
defer f.Close()
gz, err := gzip.NewReader(f)
if err != nil {
return err
}
defer gz.Close()
tr := tar.NewReader(gz)
found := false
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
name := strings.ReplaceAll(hdr.Name, "\\", "/")
if name == targetFile {
if found {
os.Remove(filepath.Join(destDir, targetFile))
return fmt.Errorf("duplicate %s in archive", targetFile)
}
found = true
out, err := os.OpenFile(
filepath.Join(destDir, targetFile),
os.O_WRONLY|os.O_CREATE|os.O_EXCL,
0600,
)
if err != nil {
return err
}
_, copyErr := io.Copy(out, tr) //nolint:gosec
closeErr := out.Close()
if copyErr != nil {
os.Remove(filepath.Join(destDir, targetFile))
return copyErr
}
if closeErr != nil {
os.Remove(filepath.Join(destDir, targetFile))
return closeErr
}
}
}
if !found {
return fmt.Errorf("%s not found in archive", targetFile)
}
return nil
}
func extractZip(
archivePath, destDir string,
archiveNames, extractNames []string,
) error {
r, err := zip.OpenReader(archivePath)
if err != nil {
return err
}
defer r.Close()
seen := make(map[string]struct{}, len(r.File))
required := make(map[string]struct{}, len(archiveNames))
targets := make(map[string]*zip.File, len(extractNames))
for _, name := range archiveNames {
required[name] = struct{}{}
}
for _, f := range r.File {
name, err := validateWindowsZipMember(f.Name)
if err != nil {
return err
}
key := strings.ToLower(strings.TrimSuffix(name, "/"))
if _, ok := seen[key]; ok {
return fmt.Errorf("duplicate or case-conflicting zip entry: %q", f.Name)
}
seen[key] = struct{}{}
if _, ok := required[name]; !ok || f.FileInfo().IsDir() {
return fmt.Errorf(
"archive must contain only the exact root files: %s",
strings.Join(archiveNames, ", "),
)
}
for _, extractName := range extractNames {
if name == extractName {
targets[name] = f
}
}
}
if len(seen) != len(archiveNames) || len(targets) != len(extractNames) {
return fmt.Errorf(
"archive must contain exactly one of each required root file: %s",
strings.Join(archiveNames, ", "),
)
}
for _, name := range extractNames {
target := targets[name]
rc, err := target.Open()
if err != nil {
return err
}
outputPath := filepath.Join(destDir, name)
out, err := os.OpenFile(
outputPath,
os.O_WRONLY|os.O_CREATE|os.O_EXCL,
0600,
)
if err != nil {
rc.Close()
return err
}
_, copyErr := io.Copy(out, rc) //nolint:gosec
closeOutErr := out.Close()
closeReadErr := rc.Close()
if copyErr != nil {
os.Remove(outputPath)
return copyErr
}
if closeOutErr != nil {
os.Remove(outputPath)
return closeOutErr
}
if closeReadErr != nil {
os.Remove(outputPath)
return closeReadErr
}
}
return nil
}
func validateWindowsZipMember(raw string) (string, error) {
name := strings.ReplaceAll(raw, "\\", "/")
segmentsName := strings.TrimSuffix(name, "/")
if segmentsName == "" || strings.HasPrefix(name, "/") || strings.Contains(name, ":") {
return "", fmt.Errorf("unsafe zip entry path: %q", raw)
}
for _, segment := range strings.Split(segmentsName, "/") {
if segment == "" || segment == "." || segment == ".." ||
strings.HasSuffix(segment, ".") || strings.HasSuffix(segment, " ") {
return "", fmt.Errorf("unsafe zip entry path: %q", raw)
}
}
return name, nil
}
func verifyCandidate(path string) error {
ctx, cancel := context.WithTimeout(context.Background(), candidateTimeout)
defer cancel()
cmd := exec.CommandContext(ctx, path, "--version")
cmd.Stdin = nil
cmd.Stdout = io.Discard
cmd.Stderr = io.Discard
if err := cmd.Run(); err != nil {
if ctx.Err() != nil {
return fmt.Errorf("downloaded binary verification timed out: %w", ctx.Err())
}
return fmt.Errorf("downloaded binary failed to run: %w", err)
}
return nil
}
func fileSHA256(path string) ([sha256.Size]byte, error) {
var digest [sha256.Size]byte
source, err := os.Open(path)
if err != nil {
return digest, err
}
defer source.Close()
hash := sha256.New()
if _, err := io.Copy(hash, source); err != nil {
return digest, err
}
copy(digest[:], hash.Sum(nil))
return digest, nil
}
func filesEqualSHA256(left, right string) (bool, error) {
leftInfo, err := os.Stat(left)
if err != nil {
return false, err
}
rightInfo, err := os.Stat(right)
if err != nil {
return false, err
}
if !leftInfo.Mode().IsRegular() || !rightInfo.Mode().IsRegular() ||
leftInfo.Size() != rightInfo.Size() {
return false, nil
}
leftDigest, err := fileSHA256(left)
if err != nil {
return false, err
}
rightDigest, err := fileSHA256(right)
if err != nil {
return false, err
}
return leftDigest == rightDigest, nil
}
func installCandidateAtomically(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
pattern := "." + filepath.Base(dst) + ".*.tmp"
if runtime.GOOS == "windows" {
pattern += ".exe"
}
out, err := os.CreateTemp(filepath.Dir(dst), pattern)
if err != nil {
return err
}
staged := out.Name()
defer os.Remove(staged)
if _, err := io.Copy(out, in); err != nil {
out.Close()
return err
}
if err := out.Chmod(0755); err != nil {
out.Close()
return err
}
if err := out.Sync(); err != nil {
out.Close()
return err
}
if err := out.Close(); err != nil {
return err
}
if err := verifyCandidate(staged); err != nil {
return err
}
if err := os.Rename(staged, dst); err != nil {
identical, compareErr := filesEqualSHA256(staged, dst)
if compareErr == nil && identical {
return verifyCandidate(dst)
}
return err
}
return nil
}
func windowsPairToken() (string, error) {
raw := make([]byte, windowsPairTransactionTagSize)
if _, err := rand.Read(raw); err != nil {
return "", err
}
return hex.EncodeToString(raw), nil
}
func windowsPairLockOwner(lockPath string) (int, string, bool) {
data, err := os.ReadFile(filepath.Join(lockPath, windowsPairLockOwnerFile))
if err != nil {
return 0, "", false
}
var pid int
var token string
var extra string
count, _ := fmt.Sscanf(string(data), "%d %s %s", &pid, &token, &extra)
decoded, decodeErr := hex.DecodeString(token)
if count != 2 || pid <= 0 || decodeErr != nil ||
len(decoded) != windowsPairTransactionTagSize {
return 0, "", false
}
return pid, token, true
}
func windowsPairTryReclaimLock(lockPath, contenderToken string) bool {
pid, _, ownerOK := windowsPairLockOwner(lockPath)
reclaim := ownerOK && !cbmWindowsLockProcessAlive(pid)
if !ownerOK {
status, err := os.Stat(lockPath)
if os.IsNotExist(err) {
return true
}
if err != nil {
return false
}
reclaim = time.Since(status.ModTime()) >= windowsPairOwnerlessStale
}
if !reclaim {
return false
}
reclaimed := lockPath + ".reclaimed-" + contenderToken
if err := os.Rename(lockPath, reclaimed); err != nil {
return os.IsNotExist(err)
}
_ = os.RemoveAll(reclaimed)
return true
}
func acquireWindowsPairLock(dstDir string) (*windowsPairLock, error) {
token, err := windowsPairToken()
if err != nil {
return nil, err
}
lockPath := filepath.Join(dstDir, windowsPairLockName)
deadline := time.Now().Add(windowsPairLockWait)
for {
if err := os.Mkdir(lockPath, 0700); err == nil {
owner := []byte(fmt.Sprintf("%d %s\n", os.Getpid(), token))
ownerPath := filepath.Join(lockPath, windowsPairLockOwnerFile)
if err := os.WriteFile(ownerPath, owner, 0600); err != nil {
_ = os.RemoveAll(lockPath)
return nil, err
}
return &windowsPairLock{path: lockPath, token: token}, nil
} else if !os.IsExist(err) {
return nil, err
}
if windowsPairTryReclaimLock(lockPath, token) {
continue
}
if !time.Now().Before(deadline) {
return nil, fmt.Errorf(
"timed out waiting for Windows package-cache publication lock")
}
time.Sleep(windowsPairLockPoll)
}
}
func releaseWindowsPairLock(lock *windowsPairLock) error {
if lock == nil {
return fmt.Errorf("missing Windows package-cache publication lock")
}
pid, token, ok := windowsPairLockOwner(lock.path)
if !ok || pid != os.Getpid() || token != lock.token {
return fmt.Errorf("Windows package-cache publication lock ownership changed")
}
if err := os.Remove(filepath.Join(lock.path, windowsPairLockOwnerFile)); err != nil {
return err
}
return os.Remove(lock.path)
}
func windowsPairReady(dstDir string, verifier func(string) error) bool {
launcher := filepath.Join(dstDir, windowsLauncherName)
payload := filepath.Join(dstDir, windowsPayloadName)
launcherStatus, launcherErr := os.Lstat(launcher)
payloadStatus, payloadErr := os.Lstat(payload)
return launcherErr == nil && payloadErr == nil &&
launcherStatus.Mode().IsRegular() && payloadStatus.Mode().IsRegular() &&
verifier(launcher) == nil
}
func copyWindowsPairStage(src, dst string) error {
input, err := os.Open(src)
if err != nil {
return err
}
output, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
_ = input.Close()
return err
}
_, copyErr := io.Copy(output, input)
closeInputErr := input.Close()
chmodErr := output.Chmod(0755)
syncErr := output.Sync()
closeOutputErr := output.Close()
for _, candidate := range []error{
copyErr, closeInputErr, chmodErr, syncErr, closeOutputErr,
} {
if candidate != nil {
return candidate
}
}
return nil
}
func pathMatchesSHA256(path string, expected [sha256.Size]byte) bool {
status, err := os.Lstat(path)
if err != nil || !status.Mode().IsRegular() {
return false
}
actual, err := fileSHA256(path)
return err == nil && actual == expected
}
func installWindowsPairAtomicallyWithVerifier(
srcDir, dstDir string, verifier func(string) error,
) (result error) {
names := []string{windowsLauncherName, windowsPayloadName}
if err := verifier(filepath.Join(srcDir, windowsLauncherName)); err != nil {
return fmt.Errorf("source Windows release pair failed verification: %w", err)
}
lock, err := acquireWindowsPairLock(dstDir)
if err != nil {
return err
}
defer func() {
if releaseErr := releaseWindowsPairLock(lock); result == nil && releaseErr != nil {
result = releaseErr
}
}()
// A contender may have committed while this process waited. Preserve that
// complete pair regardless of whether its authenticated release variant is
// byte-identical to this contender.
if windowsPairReady(dstDir, verifier) {
return nil
}
transaction, err := windowsPairToken()
if err != nil {
return err
}
staged := make(map[string]string, len(names))
stagedDigests := make(map[string][sha256.Size]byte, len(names))
backups := make(map[string]string, len(names))
publishedDigests := make(map[string][sha256.Size]byte, len(names))
defer func() {
for _, stagedPath := range staged {
_ = os.Remove(stagedPath)
}
}()
operationErr := func() error {
for _, name := range names {
stagePath := filepath.Join(
dstDir, ".cbm-pair-stage-"+transaction+"-"+name)
if err := copyWindowsPairStage(
filepath.Join(srcDir, name), stagePath); err != nil {
return err
}
staged[name] = stagePath
digest, err := fileSHA256(stagePath)
if err != nil {
return err
}
stagedDigests[name] = digest
}
for _, name := range names {
target := filepath.Join(dstDir, name)
status, err := os.Lstat(target)
if os.IsNotExist(err) {
continue
}
if err != nil {
return err
}
if !status.Mode().IsRegular() {
return fmt.Errorf(
"refusing unsafe Windows package-cache target: %s", target)
}
backup := filepath.Join(
dstDir, ".cbm-pair-backup-"+transaction+"-"+name)
if err := os.Rename(target, backup); err != nil {
return err
}
backups[name] = backup
}
// Payload is the readiness signal and is deliberately published last.
for _, name := range names {
target := filepath.Join(dstDir, name)
if err := os.Rename(staged[name], target); err != nil {
return err
}
delete(staged, name)
publishedDigests[name] = stagedDigests[name]
}
if !windowsPairReady(dstDir, verifier) {
return fmt.Errorf("published Windows package-cache pair failed verification")
}
return nil
}()
if operationErr == nil || windowsPairReady(dstDir, verifier) {
for _, backup := range backups {
_ = os.Remove(backup)
}
return nil
}
// Roll back only files whose digest proves this transaction published them.
for index := len(names) - 1; index >= 0; index-- {
name := names[index]
digest, ok := publishedDigests[name]
target := filepath.Join(dstDir, name)
if ok && pathMatchesSHA256(target, digest) {
_ = os.Remove(target)
}
}
for _, name := range names {
backup, ok := backups[name]
if !ok {
continue
}
target := filepath.Join(dstDir, name)
if _, err := os.Lstat(target); os.IsNotExist(err) {
_ = os.Rename(backup, target)
}
}
return operationErr
}
func installWindowsPairAtomically(srcDir, dstDir string) error {
return installWindowsPairAtomicallyWithVerifier(
srcDir, dstDir, verifyCandidate)
}
func execBinary(executable string, args []string) error {
if runtime.GOOS == "windows" {
cmd := exec.Command(executable, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
return syscall.Exec(executable, append([]string{executable}, args...), os.Environ())
}
+197
View File
@@ -0,0 +1,197 @@
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"testing"
)
func TestExecutionPathForOSUsesAdjacentWindowsLauncher(t *testing.T) {
payload := filepath.Join("cache", version, windowsPayloadName)
want := filepath.Join("cache", version, windowsLauncherName)
if got := executionPathForOS(payload, "windows"); got != want {
t.Fatalf("Windows execution path = %q, want adjacent launcher %q", got, want)
}
if got := executionPathForOS(payload, "linux"); got != payload {
t.Fatalf("non-Windows execution path = %q, want payload %q", got, payload)
}
}
func TestPortableMutationActionPreservesPackageManagerRefusal(t *testing.T) {
cases := []struct {
args []string
want string
}{
{args: []string{"update", "--yes"}, want: "update"},
{args: []string{"uninstall", "--yes"}, want: "uninstall"},
{args: []string{"install", "--yes"}, want: ""},
{args: []string{"cli", "update"}, want: ""},
}
for _, testCase := range cases {
if got := portableMutationAction(testCase.args); got != testCase.want {
t.Errorf("portableMutationAction(%q) = %q, want %q", testCase.args, got, testCase.want)
}
}
}
func writeTestWindowsPair(t *testing.T, directory, tag string) {
t.Helper()
if err := os.MkdirAll(directory, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(
filepath.Join(directory, windowsLauncherName),
[]byte("launcher:"+tag), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(
filepath.Join(directory, windowsPayloadName),
[]byte("payload:"+tag), 0755); err != nil {
t.Fatal(err)
}
}
func verifyTestWindowsPair(launcherPath string) error {
launcher, err := os.ReadFile(launcherPath)
if err != nil {
return err
}
payload, err := os.ReadFile(
filepath.Join(filepath.Dir(launcherPath), windowsPayloadName))
if err != nil {
return err
}
const prefix = "launcher:"
if !strings.HasPrefix(string(launcher), prefix) {
return fmt.Errorf("invalid launcher test fixture")
}
tag := strings.TrimPrefix(string(launcher), prefix)
if string(payload) != "payload:"+tag {
return fmt.Errorf("launcher/payload test fixture mismatch")
}
return nil
}
func assertTestWindowsPair(t *testing.T, directory, tag string) {
t.Helper()
launcher, err := os.ReadFile(filepath.Join(directory, windowsLauncherName))
if err != nil {
t.Fatal(err)
}
payload, err := os.ReadFile(filepath.Join(directory, windowsPayloadName))
if err != nil {
t.Fatal(err)
}
if string(launcher) != "launcher:"+tag || string(payload) != "payload:"+tag {
t.Fatalf("pair = %q / %q, want coherent tag %q", launcher, payload, tag)
}
}
func TestWindowsPairPublicationRepairsCorruptAndPartialCaches(t *testing.T) {
tests := []struct {
name string
setup func(t *testing.T, destination string)
}{
{
name: "corrupt launcher",
setup: func(t *testing.T, destination string) {
writeTestWindowsPair(t, destination, "old")
if err := os.WriteFile(
filepath.Join(destination, windowsLauncherName),
[]byte("corrupt"), 0755); err != nil {
t.Fatal(err)
}
},
},
{
name: "corrupt payload",
setup: func(t *testing.T, destination string) {
writeTestWindowsPair(t, destination, "old")
if err := os.WriteFile(
filepath.Join(destination, windowsPayloadName),
[]byte("corrupt"), 0755); err != nil {
t.Fatal(err)
}
},
},
{
name: "launcher only",
setup: func(t *testing.T, destination string) {
if err := os.MkdirAll(destination, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(
filepath.Join(destination, windowsLauncherName),
[]byte("launcher:partial"), 0755); err != nil {
t.Fatal(err)
}
},
},
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
root := t.TempDir()
source := filepath.Join(root, "source")
destination := filepath.Join(root, "destination")
writeTestWindowsPair(t, source, "candidate")
testCase.setup(t, destination)
if err := installWindowsPairAtomicallyWithVerifier(
source, destination, verifyTestWindowsPair); err != nil {
t.Fatal(err)
}
assertTestWindowsPair(t, destination, "candidate")
})
}
}
func TestWindowsPairPublicationSerializesConcurrentCandidates(t *testing.T) {
root := t.TempDir()
destination := filepath.Join(root, "destination")
if err := os.MkdirAll(destination, 0755); err != nil {
t.Fatal(err)
}
sources := []string{filepath.Join(root, "source-a"), filepath.Join(root, "source-b")}
writeTestWindowsPair(t, sources[0], "a")
writeTestWindowsPair(t, sources[1], "b")
start := make(chan struct{})
errors := make(chan error, len(sources))
var wait sync.WaitGroup
for _, source := range sources {
wait.Add(1)
go func(candidate string) {
defer wait.Done()
<-start
errors <- installWindowsPairAtomicallyWithVerifier(
candidate, destination, verifyTestWindowsPair)
}(source)
}
close(start)
wait.Wait()
close(errors)
for err := range errors {
if err != nil {
t.Fatal(err)
}
}
if err := verifyTestWindowsPair(
filepath.Join(destination, windowsLauncherName)); err != nil {
t.Fatal(err)
}
launcher, err := os.ReadFile(filepath.Join(destination, windowsLauncherName))
if err != nil {
t.Fatal(err)
}
tag := strings.TrimPrefix(string(launcher), "launcher:")
if tag != "a" && tag != "b" {
t.Fatalf("unexpected concurrent winner tag %q", tag)
}
assertTestWindowsPair(t, destination, tag)
}
@@ -0,0 +1,10 @@
//go:build !windows
package main
// Windows pair publication is never invoked by a non-Windows wrapper. Keeping
// the fallback conservative also lets platform-neutral transaction tests run
// without introducing a second process-liveness policy.
func cbmWindowsLockProcessAlive(pid int) bool {
return pid > 0
}
@@ -0,0 +1,21 @@
//go:build windows
package main
import "syscall"
func cbmWindowsLockProcessAlive(pid int) bool {
if pid <= 0 {
return false
}
// PROCESS_QUERY_LIMITED_INFORMATION is sufficient for an existence probe and
// is available on every Windows version supported by the package wrapper.
handle, err := syscall.OpenProcess(0x1000, false, uint32(pid))
if err == nil {
_ = syscall.CloseHandle(handle)
return true
}
// ERROR_INVALID_PARAMETER is the documented result for a process identifier
// that no longer exists. Access denial is conservatively treated as live.
return err != syscall.Errno(87)
}
+3
View File
@@ -0,0 +1,3 @@
module github.com/DeusData/codebase-memory-mcp/pkg/go
go 1.26.1
@@ -0,0 +1,49 @@
class CodebaseMemoryMcp < Formula
desc "Fast code intelligence engine for AI coding agents"
homepage "https://github.com/DeusData/codebase-memory-mcp"
version "0.8.1"
license "MIT"
on_macos do
on_arm do
url "https://github.com/DeusData/codebase-memory-mcp/releases/download/v#{version}/codebase-memory-mcp-darwin-arm64.tar.gz"
sha256 "fbd047509852021b5446a11141bcb0a3d1dcaebf6e5112460960f29f052c1c58"
end
on_intel do
url "https://github.com/DeusData/codebase-memory-mcp/releases/download/v#{version}/codebase-memory-mcp-darwin-amd64.tar.gz"
sha256 "fb62da3016ea12b948351208759b5c083fb1446cf6e78d6db8b7cd28fe86fd54"
end
end
on_linux do
on_arm do
url "https://github.com/DeusData/codebase-memory-mcp/releases/download/v#{version}/codebase-memory-mcp-linux-arm64.tar.gz"
sha256 "d2f842d1365da5c35d9c5796f57a821c9745267350994346735e1e6e04d46091"
end
on_intel do
url "https://github.com/DeusData/codebase-memory-mcp/releases/download/v#{version}/codebase-memory-mcp-linux-amd64.tar.gz"
sha256 "dbd3b92ea870ef240b63059f26bda15015f76ef9978931bebc3a0f9d09470973"
end
end
def install
bin.install "codebase-memory-mcp"
# Third-party attribution bundle (present in archives since v0.8.1)
doc.install "THIRD_PARTY_NOTICES.md" if File.exist?("THIRD_PARTY_NOTICES.md")
end
def caveats
<<~EOS
Run the following to configure your coding agents:
codebase-memory-mcp install
To tap this formula directly:
brew tap deusdata/codebase-memory-mcp https://github.com/DeusData/codebase-memory-mcp
brew install codebase-memory-mcp
EOS
end
test do
assert_match "codebase-memory-mcp", shell_output("#{bin}/codebase-memory-mcp --version")
end
end
+96
View File
@@ -0,0 +1,96 @@
# codebase-memory-mcp
[![npm](https://img.shields.io/npm/v/codebase-memory-mcp?style=flat&color=blue)](https://www.npmjs.com/package/codebase-memory-mcp)
[![GitHub Release](https://img.shields.io/github/v/release/DeusData/codebase-memory-mcp?style=flat&color=blue)](https://github.com/DeusData/codebase-memory-mcp/releases/latest)
[![License](https://img.shields.io/badge/license-MIT-green)](https://github.com/DeusData/codebase-memory-mcp/blob/main/LICENSE)
[![Platform](https://img.shields.io/badge/macOS_%7C_Linux_%7C_Windows-supported-lightgrey)](https://github.com/DeusData/codebase-memory-mcp/releases/latest)
**The fastest and most efficient code intelligence engine for AI coding agents.** Full-indexes an average repository in milliseconds, the Linux kernel (28M LOC, 75K files) in 3 minutes. Answers structural queries in under 1ms. Ships as a single static binary — this package downloads and runs it automatically.
High-quality parsing through [tree-sitter](https://tree-sitter.github.io/tree-sitter/) AST analysis across 159 languages — producing a persistent knowledge graph of functions, classes, call chains, HTTP routes, and cross-service links. 14 MCP tools. Zero dependencies. Plug and play across 43 automatic/conditional client surfaces.
## Installation
```bash
npm install -g codebase-memory-mcp
```
The binary for your platform is downloaded automatically at install time. Then configure your coding agents:
```bash
codebase-memory-mcp install
```
Restart your agent. Say **"Index this project"** — done.
## Why codebase-memory-mcp
- **Extreme indexing speed** — Linux kernel (28M LOC, 75K files) in 3 minutes. RAM-first pipeline with LZ4 compression and in-memory SQLite.
- **Plug and play** — single static binary for macOS (arm64/amd64), Linux (arm64/amd64), and Windows (amd64). No Docker, no runtime dependencies, no API keys.
- **159 languages** — vendored tree-sitter grammars compiled into the binary. Nothing to install, nothing that breaks.
- **120x fewer tokens** — 5 structural queries: ~3,400 tokens vs ~412,000 via file-by-file search.
- **43 supported automatic/conditional client surfaces** — `install` configures the appropriate MCP, durable-context, and documented hook surfaces without widening client permissions.
- **Detected automatically (37)** — Claude Code, Codex CLI, Gemini CLI, Zed, OpenCode, Antigravity, Aider, KiloCode, VS Code, Cursor, Windsurf, Augment / Auggie, OpenClaw, Kiro, Junie, Hermes, OpenHands, Cline, Warp, Qwen Code, GitHub Copilot CLI, Factory Droid, Crush, Goose, Mistral Vibe, Qoder CLI, Kimi Code CLI, GitLab Duo CLI, Rovo Dev CLI, Amp, Devin CLI / Local, Tabnine, Amazon Q Developer IDE, CodeBuddy Code CLI, IBM Bob Shell, Pochi, and Pi.
- **Conditional or explicit (6)** — Continue / cn, Visual Studio, TRAE, Roo Code, IBM Bob IDE, and Sourcegraph Cody. Bob IDE is touched only when `~/.bob/mcp.json` already exists.
- **New documented adapters** — CodeBuddy uses `~/.codebuddy/.mcp.json` while preserving active older files; Bob Shell uses `~/.bob/mcp_settings.json`; Pochi uses the `mcp` section in `~/.pochi/config.jsonc`; Amazon Q Developer IDE defaults to `~/.aws/amazonq/default.json` while preserving either documented alternative.
- **Lifecycle hooks stay conservative** — Kimi uses `UserPromptSubmit`; on macOS/Linux, GitLab Duo gets a fail-open user `SessionStart`, while Devin gets `UserPromptSubmit`, `PostCompaction`, and a deduplicated `SessionStart` when Claude does not already provide it. Qoder, GitLab Duo, Devin, and Factory hooks are withheld on Windows without a documented shell/executor contract. Cline's auto-activating file hooks are withheld because their context output is not reliably consumed, CodeBuddy beta hooks are not auto-installed, and Cursor context hooks remain withheld.
- **Subagent access is explicit** — Claude, Gemini, Kiro, Qwen, CodeBuddy, KiloCode, Mistral Vibe, Qoder, Junie, and Factory get documented graph profiles with the narrowest tool/server filters their schemas support. KiloCode and Vibe enumerate read-only query tools rather than using server wildcards. Cursor, Rovo, Pochi, and Cline use explicit parent handoff where child MCP is unavailable or unsafe; IBM Bob receives no invented hook or agent.
- **Manual, UI, cloud, or repository-managed (not counted)** — Qodo, Warp MCP, JetBrains AI/ACP, GitHub Copilot coding agent, Jules, CodeRabbit, Replit, BLACKBOX AI, Plandex, and SWE-agent. Warp is counted above for its detected skill installation; its MCP connection remains manual.
- **14 MCP tools** — search, trace, architecture, impact analysis, Cypher queries, dead code detection, cross-service HTTP linking, ADR management, and more.
## Supported Platforms
| OS | Architecture |
|---------|-------------|
| macOS | arm64, amd64 |
| Linux | arm64, amd64 |
| Windows | amd64 |
## Usage
```bash
codebase-memory-mcp install # configure all detected coding agents
codebase-memory-mcp --version
codebase-memory-mcp --help
codebase-memory-mcp update # update to latest release
codebase-memory-mcp uninstall # remove agent configs
```
### CLI Mode
Every MCP tool is also available directly from the command line:
```bash
codebase-memory-mcp cli index_repository '{"repo_path": "/path/to/repo"}'
codebase-memory-mcp cli search_graph '{"name_pattern": ".*Handler.*", "label": "Function"}'
codebase-memory-mcp cli trace_call_path '{"function_name": "main", "direction": "both"}'
codebase-memory-mcp cli get_architecture '{}'
```
## MCP Tools
| Category | Tools |
|----------|-------|
| **Indexing** | `index_repository`, `list_projects`, `delete_project`, `index_status` |
| **Querying** | `search_graph`, `trace_call_path`, `detect_changes`, `query_graph` |
| **Analysis** | `get_architecture`, `get_graph_schema`, `get_code_snippet`, `search_code` |
| **Advanced** | `manage_adr`, `ingest_traces` |
## Performance
Benchmarked on Apple M3 Pro:
| Operation | Time |
|-----------|------|
| Linux kernel full index (28M LOC, 75K files) | 3 min |
| Django full index | ~6s |
| Cypher query | <1ms |
| Trace call path (depth=5) | <10ms |
## Full Documentation
See [github.com/DeusData/codebase-memory-mcp](https://github.com/DeusData/codebase-memory-mcp) for the full README including all MCP tools, configuration options, graph data model, and language support details.
## License
MIT
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env node
'use strict';
// CLI shim: resolves the downloaded binary and replaces the current process with it.
// If the binary is missing (e.g. --ignore-scripts), attempts a one-time download.
const path = require('path');
const fs = require('fs');
const { spawnSync } = require('child_process');
const isWindows = process.platform === 'win32';
// npm is a portable one-shot wrapper. Every platform ships exactly ONE binary,
// so the cached file is the executed file — there is no launcher pair to keep
// in sync and no adjacent payload to validate.
const binName = isWindows ? 'codebase-memory-mcp.exe' : 'codebase-memory-mcp';
const binPath = path.join(__dirname, 'bin', binName);
const executionPath = binPath;
const cacheReady = () => {
if (!fs.existsSync(binPath)) {
return false;
}
if (!isWindows) return true;
// A cached Windows binary that cannot report its own version is not usable.
const probe = spawnSync(binPath, ['--version'], {
stdio: 'ignore',
timeout: 15_000,
windowsHide: true,
});
return !probe.error && probe.status === 0;
};
if (!cacheReady()) {
// Binary missing — try running the install script (handles --ignore-scripts case)
process.stderr.write('codebase-memory-mcp: binary not found, downloading...\n');
const installResult = spawnSync(process.execPath, [path.join(__dirname, 'install.js')], {
stdio: 'inherit',
});
if (installResult.status !== 0 || !cacheReady()) {
process.stderr.write(
'codebase-memory-mcp: download failed.\n' +
'Try reinstalling: npm install -g codebase-memory-mcp\n'
);
process.exit(1);
}
}
function portableMutationAction(args) {
for (const argument of args) {
if (['cli', 'hook-augment', 'config', 'install', '--help', '-h', '--version'].includes(argument)) {
return null;
}
if (argument === 'update' || argument === 'uninstall') return argument;
}
return null;
}
const result = spawnSync(executionPath, process.argv.slice(2), {
stdio: 'inherit',
windowsHide: false,
});
if (result.error) {
process.stderr.write(`codebase-memory-mcp: ${result.error.message}\n`);
process.exit(1);
}
const mutation = isWindows && result.status !== 0
? portableMutationAction(process.argv.slice(2))
: null;
if (mutation) {
const packageCommand = mutation === 'update'
? 'npm install codebase-memory-mcp@latest'
: 'npm uninstall codebase-memory-mcp';
process.stderr.write(
`This npm Windows copy is portable. Use "${packageCommand}" for package ` +
'maintenance (add -g for a global install), or run ' +
'"codebase-memory-mcp install --yes" once for a managed install with its ' +
'own install.ps1 for updates.\n',
);
}
process.exit(result.status ?? 0);
+684
View File
@@ -0,0 +1,684 @@
#!/usr/bin/env node
'use strict';
// Postinstall script: downloads the platform-appropriate binary from GitHub Releases.
// Runs automatically via `postinstall` in package.json.
const https = require('https');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const os = require('os');
const { execFileSync } = require('child_process');
const { pipeline } = require('stream');
const REPO = 'DeusData/codebase-memory-mcp';
const VERSION = require('./package.json').version;
const BIN_DIR = path.join(__dirname, 'bin');
const MAX_REDIRECTS = 5;
const DOWNLOAD_HOP_TIMEOUT_MS = 120_000;
const CANDIDATE_TIMEOUT_MS = 15_000;
const MAX_CHECKSUM_MANIFEST_BYTES = 1024 * 1024;
const WINDOWS_BINARY_NAME = 'codebase-memory-mcp.exe';
const UNIX_ARCHIVE_NAMES = [
'codebase-memory-mcp',
'LICENSE',
'install.sh',
'THIRD_PARTY_NOTICES.md',
];
const WINDOWS_ARCHIVE_NAMES = [
WINDOWS_BINARY_NAME,
'LICENSE',
'install.ps1',
'THIRD_PARTY_NOTICES.md',
];
const WINDOWS_PAIR_LOCK_NAME = '.codebase-memory-mcp-pair.lock';
const WINDOWS_PAIR_LOCK_WAIT_MS = 45_000;
const WINDOWS_PAIR_OWNERLESS_STALE_MS = 30_000;
const WINDOWS_PAIR_LOCK_POLL_MS = 25;
const SLEEP_WORD = new Int32Array(new SharedArrayBuffer(4));
function getPlatform() {
switch (process.platform) {
case 'linux': return 'linux';
case 'darwin': return 'darwin';
case 'win32': return 'windows';
default: throw new Error(`Unsupported platform: ${process.platform}`);
}
}
function getArch() {
switch (process.arch) {
case 'arm64': return 'arm64';
case 'x64': return 'amd64';
default: throw new Error(`Unsupported architecture: ${process.arch}`);
}
}
// Security: only follow HTTPS URLs (defense-in-depth). Parse the URL instead
// of relying on a string prefix so every redirect is checked unambiguously.
function validateUrl(rawUrl) {
let parsed;
try {
parsed = new URL(rawUrl);
} catch (err) {
throw new Error(`Invalid download URL ${rawUrl}: ${err.message}`);
}
if (parsed.protocol !== 'https:' || !parsed.hostname || parsed.username || parsed.password) {
throw new Error(`Refusing non-HTTPS or credentialed URL: ${rawUrl}`);
}
return parsed.href;
}
function validateExactTarMemberListing(listing, expectedNames) {
if (listing.includes('\0')) {
throw new Error('tar member listing contains a NUL byte');
}
const members = listing.split(/\r?\n/);
if (members[members.length - 1] === '') members.pop();
const expected = new Set(expectedNames);
const seen = new Set();
for (const member of members) {
if (!member || !expected.has(member) || seen.has(member)) {
throw new Error(`archive contains an unexpected or duplicate root member: ${JSON.stringify(member)}`);
}
seen.add(member);
}
if (members.length !== expectedNames.length || seen.size !== expected.size) {
throw new Error(
`archive must contain exactly these root files: ${expectedNames.join(', ')}`,
);
}
}
function extractExactTarArchive(
archivePath, destPath, expectedNames, targetName, runFile = execFileSync,
) {
const listing = runFile('tar', ['-tzf', archivePath], {
encoding: 'utf8',
maxBuffer: MAX_CHECKSUM_MANIFEST_BYTES,
windowsHide: true,
});
validateExactTarMemberListing(listing, expectedNames);
// Extract only the fixed root executable. Even a malformed tar implementation
// cannot write an unvalidated companion member outside the private temp tree.
runFile('tar', ['-xzf', archivePath, '-C', destPath, targetName], {
stdio: 'inherit',
windowsHide: true,
});
}
function downloadHop(url, dest, maxBytes) {
return new Promise((resolve, reject) => {
let settled = false;
let response = null;
let timer = null;
function finish(err, result) {
if (settled) return;
settled = true;
if (timer) clearTimeout(timer);
if (err) reject(err);
else resolve(result);
}
const req = https.get(url, (res) => {
response = res;
res.on('error', (err) => finish(err));
const redirectCodes = new Set([301, 302, 303, 307, 308]);
if (redirectCodes.has(res.statusCode)) {
const location = res.headers.location;
if (!location) {
res.destroy();
finish(new Error(`Redirect with no location for ${url}`));
return;
}
let next;
try {
next = validateUrl(new URL(location, url).href);
} catch (err) {
res.destroy();
finish(err);
return;
}
res.destroy();
finish(null, { redirect: next });
return;
}
if (res.statusCode !== 200) {
res.destroy();
finish(new Error(`HTTP ${res.statusCode} for ${url}`));
return;
}
let received = 0;
res.on('data', (chunk) => {
received += chunk.length;
if (maxBytes && received > maxBytes) {
res.destroy(new Error(`Download exceeds the ${maxBytes}-byte safety limit`));
}
});
const file = fs.createWriteStream(dest, { flags: 'w' });
pipeline(res, file, (err) => {
finish(err, { redirect: null });
});
});
req.on('error', (err) => finish(err));
timer = setTimeout(() => {
const err = new Error(`Download hop timed out after ${DOWNLOAD_HOP_TIMEOUT_MS} ms: ${url}`);
req.destroy(err);
if (response) response.destroy(err);
}, DOWNLOAD_HOP_TIMEOUT_MS);
});
}
async function download(rawUrl, dest, maxBytes = 0) {
let url = validateUrl(rawUrl);
for (let redirects = 0; redirects <= MAX_REDIRECTS; redirects += 1) {
const result = await downloadHop(url, dest, maxBytes);
if (!result.redirect) return;
if (redirects === MAX_REDIRECTS) throw new Error('Too many redirects');
url = result.redirect;
}
}
function parseExpectedChecksum(manifest, archiveName) {
let expected = null;
for (const line of manifest.split('\n')) {
const fields = line.trim().split(/\s+/);
if (fields.length < 2) continue;
if (fields[1] !== archiveName && fields[1] !== `*${archiveName}`) continue;
const digest = fields[0].toLowerCase();
if (!/^[0-9a-f]{64}$/.test(digest)) {
throw new Error(`Invalid SHA-256 checksum for ${archiveName}`);
}
if (expected !== null && expected !== digest) {
throw new Error(`Conflicting SHA-256 checksums for ${archiveName}`);
}
expected = digest;
}
if (expected === null) {
throw new Error(`No checksum for ${archiveName} in checksums.txt`);
}
return expected;
}
function verifyCandidate(candidatePath) {
execFileSync(candidatePath, ['--version'], {
stdio: ['ignore', 'pipe', 'pipe'],
timeout: CANDIDATE_TIMEOUT_MS,
windowsHide: true,
});
}
function fileSha256(candidatePath) {
const digest = crypto.createHash('sha256');
const fd = fs.openSync(candidatePath, 'r');
const buffer = Buffer.allocUnsafe(64 * 1024);
try {
for (;;) {
const count = fs.readSync(fd, buffer, 0, buffer.length, null);
if (count === 0) break;
digest.update(buffer.subarray(0, count));
}
} finally {
fs.closeSync(fd);
}
return digest.digest('hex');
}
function filesEqualSha256(leftPath, rightPath) {
try {
const left = fs.statSync(leftPath);
const right = fs.statSync(rightPath);
return left.isFile()
&& right.isFile()
&& left.size === right.size
&& fileSha256(leftPath) === fileSha256(rightPath);
} catch (_) {
return false;
}
}
function sleepSync(milliseconds) {
Atomics.wait(SLEEP_WORD, 0, 0, milliseconds);
}
function processIsAlive(pid) {
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
try {
process.kill(pid, 0);
return true;
} catch (err) {
// Access denial is conservative evidence of a live process. Only an
// explicit missing-process result permits reclamation.
return err && err.code !== 'ESRCH';
}
}
function readBinaryLockOwner(lockPath) {
try {
const owner = JSON.parse(
fs.readFileSync(path.join(lockPath, 'owner.json'), 'utf8'),
);
if (!Number.isSafeInteger(owner.pid) || owner.pid <= 0 ||
typeof owner.token !== 'string' || !/^[0-9a-f]{32}$/.test(owner.token)) {
return null;
}
return owner;
} catch (_) {
return null;
}
}
function tryReclaimBinaryLock(lockPath, contenderToken) {
let reclaim = false;
const owner = readBinaryLockOwner(lockPath);
if (owner) {
reclaim = !processIsAlive(owner.pid);
} else {
try {
const age = Date.now() - fs.statSync(lockPath).mtimeMs;
reclaim = age >= WINDOWS_PAIR_OWNERLESS_STALE_MS;
} catch (_) {
return true; // The owner released it between observation and inspection.
}
}
if (!reclaim) return false;
const reclaimed = `${lockPath}.reclaimed-${contenderToken}`;
try {
fs.renameSync(lockPath, reclaimed);
} catch (err) {
if (err.code === 'ENOENT') return true;
return false;
}
fs.rmSync(reclaimed, { recursive: true, force: true });
return true;
}
function acquireWindowsBinaryLock(destDir) {
const lockPath = path.join(destDir, WINDOWS_PAIR_LOCK_NAME);
const token = crypto.randomBytes(16).toString('hex');
const deadline = Date.now() + WINDOWS_PAIR_LOCK_WAIT_MS;
for (;;) {
try {
fs.mkdirSync(lockPath, { mode: 0o700 });
try {
fs.writeFileSync(
path.join(lockPath, 'owner.json'),
`${JSON.stringify({ pid: process.pid, token })}\n`,
{ encoding: 'utf8', flag: 'wx', mode: 0o600 },
);
} catch (err) {
fs.rmSync(lockPath, { recursive: true, force: true });
throw err;
}
return { lockPath, token };
} catch (err) {
if (err.code !== 'EEXIST') throw err;
if (tryReclaimBinaryLock(lockPath, token)) continue;
if (Date.now() >= deadline) {
throw new Error('timed out waiting for Windows package-cache publication lock');
}
sleepSync(WINDOWS_PAIR_LOCK_POLL_MS);
}
}
}
function releaseWindowsBinaryLock(lock) {
const owner = readBinaryLockOwner(lock.lockPath);
if (!owner || owner.token !== lock.token || owner.pid !== process.pid) {
throw new Error('Windows package-cache publication lock ownership changed');
}
fs.unlinkSync(path.join(lock.lockPath, 'owner.json'));
fs.rmdirSync(lock.lockPath);
}
function windowsBinaryReady(destDir, verifier = verifyCandidate) {
const binary = path.join(destDir, WINDOWS_BINARY_NAME);
try {
const status = fs.lstatSync(binary);
if (!status.isFile() || status.isSymbolicLink()) {
return false;
}
verifier(binary);
return true;
} catch (_) {
return false;
}
}
function pathMatchesDigest(candidatePath, expectedDigest) {
try {
const status = fs.lstatSync(candidatePath);
return status.isFile() && !status.isSymbolicLink() &&
fileSha256(candidatePath) === expectedDigest;
} catch (_) {
return false;
}
}
function removeOwnedPublishedBinary(destDir, publishedDigests) {
for (const name of [WINDOWS_BINARY_NAME]) {
const digest = publishedDigests.get(name);
const target = path.join(destDir, name);
if (digest && pathMatchesDigest(target, digest)) {
try { fs.unlinkSync(target); } catch (_) { /* recovery continues below */ }
}
}
}
function restoreBinaryBackups(destDir, backups) {
for (const name of [WINDOWS_BINARY_NAME]) {
const backup = backups.get(name);
const target = path.join(destDir, name);
if (!backup || fs.existsSync(target)) continue;
try { fs.renameSync(backup, target); } catch (_) { /* preserve backup */ }
}
}
function installWindowsBinaryAtomically(sourceDir, destDir, verifier = verifyCandidate) {
// Authenticate the source binary before it can contend for the cache.
verifier(path.join(sourceDir, WINDOWS_BINARY_NAME));
const lock = acquireWindowsBinaryLock(destDir);
let operationError = null;
try {
// A contender may have completed while this process waited. Its executable
// wins and is never moved or deleted.
if (windowsBinaryReady(destDir, verifier)) return;
const transaction = crypto.randomBytes(16).toString('hex');
const stagedPaths = new Map();
const stagedDigests = new Map();
const backups = new Map();
const publishedDigests = new Map();
try {
for (const name of [WINDOWS_BINARY_NAME]) {
const staged = path.join(destDir, `.cbm-pair-stage-${transaction}-${name}`);
fs.copyFileSync(path.join(sourceDir, name), staged, fs.constants.COPYFILE_EXCL);
fs.chmodSync(staged, 0o755);
stagedPaths.set(name, staged);
stagedDigests.set(name, fileSha256(staged));
}
for (const name of [WINDOWS_BINARY_NAME]) {
const target = path.join(destDir, name);
const status = fs.lstatSync(target, { throwIfNoEntry: false });
if (!status) continue;
if (!status.isFile() || status.isSymbolicLink()) {
throw new Error(`refusing unsafe Windows package-cache target: ${target}`);
}
const backup = path.join(destDir, `.cbm-pair-backup-${transaction}-${name}`);
fs.renameSync(target, backup);
backups.set(name, backup);
}
for (const name of [WINDOWS_BINARY_NAME]) {
const target = path.join(destDir, name);
fs.renameSync(stagedPaths.get(name), target);
stagedPaths.delete(name);
publishedDigests.set(name, stagedDigests.get(name));
}
if (!windowsBinaryReady(destDir, verifier)) {
throw new Error('published Windows package-cache binary failed verification');
}
for (const backup of backups.values()) {
try { fs.unlinkSync(backup); } catch (_) { /* valid binary is already committed */ }
}
return;
} catch (err) {
// If a non-cooperating contender nevertheless published a valid binary,
// preserve that winner. Otherwise remove only our exact staged bytes and
// restore the prior files when their target names are still absent.
if (windowsBinaryReady(destDir, verifier)) {
for (const backup of backups.values()) {
try { fs.unlinkSync(backup); } catch (_) { /* winner remains authoritative */ }
}
return;
}
removeOwnedPublishedBinary(destDir, publishedDigests);
restoreBinaryBackups(destDir, backups);
throw err;
} finally {
for (const staged of stagedPaths.values()) {
try { fs.unlinkSync(staged); } catch (_) { /* renamed or already absent */ }
}
}
} catch (err) {
operationError = err;
throw err;
} finally {
try {
releaseWindowsBinaryLock(lock);
} catch (releaseError) {
if (!operationError) throw releaseError;
}
}
}
function extractZipOnWindows(archivePath, destPath, requiredNames, extractNames) {
// -EncodedCommand is a constant program. Paths travel only through the child
// environment and are consumed with -LiteralPath, so PowerShell never parses
// user/TEMP path bytes as source code or wildcard syntax.
const script = [
"$ErrorActionPreference = 'Stop'",
'Add-Type -AssemblyName System.IO.Compression.FileSystem',
'$zip = [System.IO.Compression.ZipFile]::OpenRead($env:CBM_NPM_ARCHIVE_PATH)',
"$seen = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)",
"$requiredNames = @($env:CBM_NPM_REQUIRED_NAMES.Split('|'))",
'$targetCounts = @{}',
'foreach ($requiredName in $requiredNames) { $targetCounts[$requiredName] = 0 }',
'try { foreach ($entry in $zip.Entries) { ' +
"$name = $entry.FullName.Replace('\\', '/'); " +
"$directory = $name.EndsWith('/'); " +
"$segmentsPath = if ($directory) { $name.TrimEnd('/') } else { $name }; " +
"$segments = @($segmentsPath.Split('/')); " +
"if ([string]::IsNullOrEmpty($segmentsPath) -or $name.StartsWith('/') -or " +
"$name.Contains(':') -or $segments -contains '' -or " +
"$segments -contains '.' -or $segments -contains '..' -or " +
"@($segments | Where-Object { $_.EndsWith('.') -or $_.EndsWith(' ') }).Count -gt 0) { " +
"throw \"unsafe zip entry path: $($entry.FullName)\" }; " +
'if (-not $seen.Add($segmentsPath)) { ' +
"throw \"duplicate or case-conflicting zip entry: $($entry.FullName)\" }; " +
'foreach ($requiredName in $requiredNames) { ' +
'if ($name -ceq $requiredName) { ' +
'$targetCounts[$requiredName] = $targetCounts[$requiredName] + 1 } } ' +
'} } finally { $zip.Dispose() }',
'foreach ($requiredName in $requiredNames) { ' +
'if ($targetCounts[$requiredName] -ne 1) { ' +
'throw "archive must contain exactly one $requiredName" } }',
'if ($seen.Count -ne $requiredNames.Count) { ' +
'throw "archive does not match the exact release root-file allowlist" }',
"$extractNames = @($env:CBM_NPM_EXTRACT_NAMES.Split('|'))",
'$extractZip = [System.IO.Compression.ZipFile]::OpenRead($env:CBM_NPM_ARCHIVE_PATH)',
'try { foreach ($extractName in $extractNames) { ' +
'$entry = @($extractZip.Entries | Where-Object { $_.FullName -ceq $extractName })[0]; ' +
'[System.IO.Compression.ZipFileExtensions]::ExtractToFile(' +
'$entry, (Join-Path $env:CBM_NPM_DEST_PATH $extractName), $false) ' +
'} } finally { $extractZip.Dispose() }',
].join('; ');
const encoded = Buffer.from(script, 'utf16le').toString('base64');
execFileSync('powershell', [
'-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', encoded,
], {
env: {
...process.env,
CBM_NPM_ARCHIVE_PATH: archivePath,
CBM_NPM_DEST_PATH: destPath,
CBM_NPM_REQUIRED_NAMES: requiredNames.join('|'),
CBM_NPM_EXTRACT_NAMES: extractNames.join('|'),
},
stdio: 'inherit',
windowsHide: true,
});
}
// Fetch checksums.txt and verify the archive hash.
async function verifyChecksum(archivePath, archiveName) {
const url = `https://github.com/${REPO}/releases/download/v${VERSION}/checksums.txt`;
const tmpChecksums = archivePath + '.checksums';
try {
await download(url, tmpChecksums, MAX_CHECKSUM_MANIFEST_BYTES);
const manifestSize = fs.statSync(tmpChecksums).size;
if (manifestSize > MAX_CHECKSUM_MANIFEST_BYTES) {
throw new Error('checksums.txt exceeds the 1 MiB safety limit');
}
const expected = parseExpectedChecksum(
fs.readFileSync(tmpChecksums, 'utf-8'), archiveName,
);
const actual = crypto
.createHash('sha256')
.update(fs.readFileSync(archivePath))
.digest('hex');
if (expected !== actual) {
throw new Error(
`Checksum mismatch for ${archiveName}:\n expected: ${expected}\n actual: ${actual}`,
);
}
process.stdout.write('codebase-memory-mcp: checksum verified.\n');
} finally {
try { fs.unlinkSync(tmpChecksums); } catch (_) { /* ignore */ }
}
}
async function main() {
const platform = getPlatform();
const arch = getArch();
const ext = platform === 'windows' ? 'zip' : 'tar.gz';
// Package-manager shims are portable one-shot instances: one cached binary
// per platform, entered directly.
const binName = platform === 'windows'
? WINDOWS_BINARY_NAME
: 'codebase-memory-mcp';
const binPath = path.join(BIN_DIR, binName);
const cacheNames = platform === 'windows'
? [WINDOWS_BINARY_NAME]
: [binName];
const extractedNames = platform === 'windows'
? [WINDOWS_BINARY_NAME]
: [binName];
const archiveNames = platform === 'windows'
? WINDOWS_ARCHIVE_NAMES
: UNIX_ARCHIVE_NAMES;
const cachePaths = cacheNames.map((name) => path.join(BIN_DIR, name));
if (platform === 'windows' && windowsBinaryReady(BIN_DIR)) return;
if (platform !== 'windows' &&
cachePaths.every((candidate) => fs.existsSync(candidate))) {
try {
verifyCandidate(binPath);
return; // already installed and runnable, nothing to do
} catch (_) {
// Fall through and atomically replace the invalid binary.
}
}
fs.mkdirSync(BIN_DIR, { recursive: true });
// Linux ships a fully-static "-portable" build; the standard linux binary
// dynamically links glibc 2.38+ and fails on older distros. macOS/Windows
// have no such variant. Keep in sync with install.sh / pypi _cli.py / cli.c.
const variant = platform === 'linux' ? '-portable' : '';
// Opt into the UI build (embedded graph visualization) with CBM_VARIANT=ui.
// Default is the standard (headless) build. Mirrors install.sh --ui.
const ui = (process.env.CBM_VARIANT || '').toLowerCase() === 'ui' ? 'ui-' : '';
const archive = `codebase-memory-mcp-${ui}${platform}-${arch}${variant}.${ext}`;
const url = `https://github.com/${REPO}/releases/download/v${VERSION}/${archive}`;
const uiLabel = ui ? '(ui) ' : '';
process.stdout.write(`codebase-memory-mcp: downloading v${VERSION} ${uiLabel}for ${platform}/${arch}...\n`);
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cbm-install-'));
const tmpArchive = path.join(tmpDir, `cbm.${ext}`);
try {
await download(url, tmpArchive);
await verifyChecksum(tmpArchive, archive);
// Validate the complete archive namespace, then extract only executables.
if (ext === 'tar.gz') {
extractExactTarArchive(
tmpArchive, tmpDir, archiveNames, binName,
);
} else {
extractZipOnWindows(tmpArchive, tmpDir, archiveNames, extractedNames);
}
// Validate extracted paths don't escape tmpDir (tar-slip defense).
const resolvedTmpDir = path.resolve(tmpDir);
const extractedPaths = new Map();
for (const name of extractedNames) {
const extracted = path.join(tmpDir, name);
const resolvedExtracted = path.resolve(extracted);
if (!resolvedExtracted.startsWith(resolvedTmpDir + path.sep)) {
throw new Error(`Path traversal detected in archive: ${name}`);
}
const status = fs.lstatSync(extracted, { throwIfNoEntry: false });
if (!status || !status.isFile() || status.isSymbolicLink()) {
throw new Error(`Required binary not found as a regular file: ${extracted}`);
}
fs.chmodSync(extracted, 0o755);
extractedPaths.set(name, extracted);
}
if (platform === 'windows') {
// The launcher resolves the adjacent portable payload in this directory.
verifyCandidate(extractedPaths.get(WINDOWS_BINARY_NAME));
} else {
verifyCandidate(extractedPaths.get(binName));
}
if (platform === 'windows') {
installWindowsBinaryAtomically(tmpDir, BIN_DIR);
} else {
const staged = path.join(
BIN_DIR,
`.${binName}.${process.pid}.${crypto.randomBytes(8).toString('hex')}.tmp`,
);
try {
fs.copyFileSync(extractedPaths.get(binName), staged, fs.constants.COPYFILE_EXCL);
fs.chmodSync(staged, 0o755);
verifyCandidate(staged);
try {
fs.renameSync(staged, binPath);
} catch (publishError) {
if (!filesEqualSha256(staged, binPath)) throw publishError;
}
verifyCandidate(binPath);
} finally {
try { fs.unlinkSync(staged); } catch (_) { /* renamed or already absent */ }
}
}
process.stdout.write('codebase-memory-mcp: ready.\n');
if (platform === 'windows') {
process.stdout.write(
'Windows package cache is portable. Run "codebase-memory-mcp install --yes" ' +
'to create the managed launcher (use "npx codebase-memory-mcp install --yes" ' +
'for a local npm install). Package updates/removal remain ' +
'"npm install codebase-memory-mcp@latest" and ' +
'"npm uninstall codebase-memory-mcp" (add -g for a global install).\n',
);
}
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
}
if (require.main === module || module.parent == null) {
main().catch((err) => {
process.stderr.write(`\ncodebase-memory-mcp: install failed — ${err.message}\n`);
process.stderr.write(`You can install manually: https://github.com/${REPO}#installation\n`);
process.exit(1);
});
}
module.exports = {
UNIX_ARCHIVE_NAMES,
WINDOWS_BINARY_NAME,
extractExactTarArchive,
installWindowsBinaryAtomically,
validateExactTarMemberListing,
windowsBinaryReady,
};
+42
View File
@@ -0,0 +1,42 @@
{
"name": "codebase-memory-mcp",
"version": "0.8.1",
"description": "Fast code intelligence engine for AI coding agents — single static binary MCP server",
"mcpName": "io.github.DeusData/codebase-memory-mcp",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/DeusData/codebase-memory-mcp.git"
},
"homepage": "https://github.com/DeusData/codebase-memory-mcp",
"bugs": {
"url": "https://github.com/DeusData/codebase-memory-mcp/issues"
},
"keywords": [
"mcp",
"claude",
"code-intelligence",
"codebase",
"memory",
"ai",
"llm",
"tree-sitter"
],
"bin": {
"codebase-memory-mcp": "./bin.js"
},
"scripts": {
"test": "node --test test/*.test.js",
"postinstall": "node install.js"
},
"engines": {
"node": ">=18"
},
"os": ["linux", "darwin", "win32"],
"cpu": ["x64", "arm64"],
"files": [
"bin.js",
"install.js",
"README.md"
]
}
+53
View File
@@ -0,0 +1,53 @@
'use strict';
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const test = require('node:test');
const vm = require('node:vm');
test('postinstall exits nonzero when installation fails', async () => {
const installPath = path.join(__dirname, '..', 'install.js');
const source = fs.readFileSync(installPath, 'utf8');
const output = { stdout: '', stderr: '' };
const observed = { exitCode: undefined };
const fakeProcess = {
// Force a deterministic failure before any filesystem or network access.
platform: 'unsupported-test-platform',
arch: 'x64',
env: {},
pid: 12345,
stdout: { write: (text) => { output.stdout += String(text); } },
stderr: { write: (text) => { output.stderr += String(text); } },
exit: (code) => { observed.exitCode = code; },
exitCode: undefined,
};
const sandbox = {
Buffer,
URL,
__dirname: path.dirname(installPath),
__filename: installPath,
clearTimeout,
console,
exports: {},
module: { exports: {} },
process: fakeProcess,
require: (specifier) => {
if (specifier === './package.json') return { version: '0.0.0-test' };
return require(specifier);
},
setTimeout,
};
vm.runInNewContext(source, sandbox, { filename: installPath });
await new Promise((resolve) => setImmediate(resolve));
const exitCode = observed.exitCode ?? fakeProcess.exitCode ?? 0;
assert.match(output.stderr, /install failed/);
assert.notEqual(
exitCode,
0,
'npm postinstall reported success after a deterministic installation failure',
);
});
+117
View File
@@ -0,0 +1,117 @@
'use strict';
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const test = require('node:test');
const {
UNIX_ARCHIVE_NAMES,
WINDOWS_BINARY_NAME,
extractExactTarArchive,
installWindowsBinaryAtomically,
validateExactTarMemberListing,
} = require('../install.js');
function exactUnixListing(extra = []) {
return [...UNIX_ARCHIVE_NAMES, ...extra].join('\n') + '\n';
}
test('Unix archive validation rejects traversal and unexpected members', () => {
assert.throws(
() => validateExactTarMemberListing(
exactUnixListing(['../../.ssh/authorized_keys']), UNIX_ARCHIVE_NAMES,
),
/unexpected or duplicate/,
);
assert.throws(
() => validateExactTarMemberListing(
exactUnixListing(['unexpected-root-file']), UNIX_ARCHIVE_NAMES,
),
/unexpected or duplicate/,
);
});
test('Unix extraction requests only the validated root executable', () => {
const calls = [];
const runner = (command, args) => {
calls.push({ command, args: [...args] });
return calls.length === 1 ? exactUnixListing() : Buffer.alloc(0);
};
extractExactTarArchive(
'/tmp/release.tar.gz', '/tmp/extract', UNIX_ARCHIVE_NAMES,
'codebase-memory-mcp', runner,
);
assert.deepEqual(calls[0].args, ['-tzf', '/tmp/release.tar.gz']);
assert.deepEqual(
calls[1].args,
['-xzf', '/tmp/release.tar.gz', '-C', '/tmp/extract', 'codebase-memory-mcp'],
);
});
function writeBinary(directory, tag) {
fs.mkdirSync(directory, { recursive: true });
fs.writeFileSync(path.join(directory, WINDOWS_BINARY_NAME), `binary:${tag}`);
}
function fakeBinaryVerifier(binaryPath) {
const binary = fs.readFileSync(binaryPath, 'utf8');
if (!/^binary:(.+)$/.test(binary)) {
throw new Error('cached Windows binary failed verification');
}
}
function withBinaryDirectories(callback) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cbm-npm-binary-test-'));
const source = path.join(root, 'source');
const destination = path.join(root, 'destination');
fs.mkdirSync(destination);
try {
callback({ source, destination });
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
}
function assertBinary(directory, tag) {
assert.equal(
fs.readFileSync(path.join(directory, WINDOWS_BINARY_NAME), 'utf8'),
`binary:${tag}`,
);
}
test('Windows publication repairs a corrupt cached binary', () => {
withBinaryDirectories(({ source, destination }) => {
writeBinary(source, 'candidate');
writeBinary(destination, 'old');
fs.writeFileSync(path.join(destination, WINDOWS_BINARY_NAME), 'corrupt');
installWindowsBinaryAtomically(source, destination, fakeBinaryVerifier);
assertBinary(destination, 'candidate');
});
});
test('Windows publication installs into an empty cache', () => {
withBinaryDirectories(({ source, destination }) => {
writeBinary(source, 'candidate');
installWindowsBinaryAtomically(source, destination, fakeBinaryVerifier);
assertBinary(destination, 'candidate');
});
});
test('Windows publication preserves a valid concurrent winner', () => {
withBinaryDirectories(({ source, destination }) => {
writeBinary(source, 'loser');
writeBinary(destination, 'winner');
installWindowsBinaryAtomically(source, destination, fakeBinaryVerifier);
assertBinary(destination, 'winner');
});
});
+118
View File
@@ -0,0 +1,118 @@
'use strict';
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const test = require('node:test');
const vm = require('node:vm');
class ExitSignal extends Error {
constructor(code) {
super(`process.exit(${code})`);
this.code = code;
}
}
function runShim(targetPlatform, arguments_, childStatus) {
const shimPath = path.join(__dirname, '..', 'bin.js');
const source = fs.readFileSync(shimPath, 'utf8').replace(/^#![^\n]*\n/, '');
const calls = [];
let stderr = '';
const fakeProcess = {
platform: targetPlatform,
argv: ['node.exe', shimPath, ...arguments_],
execPath: 'node.exe',
stderr: { write: (text) => { stderr += String(text); } },
exit: (code) => { throw new ExitSignal(code); },
};
const fakeFs = {
existsSync: () => true,
};
const fakeChildProcess = {
spawnSync: (executable, args, options) => {
calls.push({ executable, args, options });
return { status: calls.length === 1 ? 0 : childStatus };
},
};
const sandbox = {
__dirname: path.dirname(shimPath),
__filename: shimPath,
Buffer,
clearTimeout,
console,
exports: {},
module: { exports: {} },
process: fakeProcess,
require: (specifier) => {
if (specifier === 'fs') return fakeFs;
if (specifier === 'child_process') return fakeChildProcess;
return require(specifier);
},
setTimeout,
};
let exitCode = null;
try {
vm.runInNewContext(source, sandbox, { filename: shimPath });
} catch (error) {
if (!(error instanceof ExitSignal)) throw error;
exitCode = error.code;
}
return { calls, exitCode, stderr };
}
test('Windows npm shim probes and executes the cached launcher', () => {
const observed = runShim('win32', ['--version'], 0);
assert.equal(observed.exitCode, 0);
assert.equal(observed.calls.length, 2);
for (const call of observed.calls) {
assert.equal(path.basename(call.executable), 'codebase-memory-mcp.exe');
assert.notEqual(
path.basename(call.executable),
'codebase-memory-mcp.payload.exe',
);
}
assert.deepEqual(Array.from(observed.calls[1].args), ['--version']);
assert.equal(observed.calls[1].options.stdio, 'inherit');
});
test('Windows npm shim keeps package-manager guidance after launcher refusal', () => {
const observed = runShim('win32', ['update'], 1);
assert.equal(observed.exitCode, 1);
assert.equal(path.basename(observed.calls[1].executable), 'codebase-memory-mcp.exe');
assert.match(observed.stderr, /npm install codebase-memory-mcp@latest/);
assert.match(observed.stderr, /install --yes/);
});
test('non-Windows npm shim keeps its native payload execution path', () => {
const observed = runShim('darwin', ['--version'], 0);
assert.equal(observed.exitCode, 0);
assert.equal(observed.calls.length, 1);
assert.equal(path.basename(observed.calls[0].executable), 'codebase-memory-mcp');
});
test('PowerShell install mutation runs through the downloaded binary', () => {
const installer = fs.readFileSync(
path.join(__dirname, '..', '..', '..', 'install.ps1'),
'utf8',
);
assert.match(
installer,
/^\s*\$candidateVersion\s*=\s*&\s*\$DownloadedBinary\s+--version\b/m,
);
assert.match(
installer,
/^\s*&\s*\$DownloadedBinary\s+@InstallArgs\b/m,
);
// One binary ships per platform — no launcher/payload pair to resolve.
assert.doesNotMatch(installer, /payload/i);
// A running .exe cannot be overwritten, so an in-place update has to retire
// the existing binary by renaming it aside first. This script IS the Windows
// update path, so losing that step would silently break every update.
assert.match(installer, /Move-Item[\s\S]{0,80}\$Dest[\s\S]{0,40}\$retired/);
});
+34
View File
@@ -0,0 +1,34 @@
# codebase-memory-mcp
mcp-name: io.github.DeusData/codebase-memory-mcp
**Fast code intelligence engine for AI coding agents.** Indexes an average repository in milliseconds, the Linux kernel (28M LOC) in 3 minutes. Answers structural queries in under 1ms.
This package installs the `codebase-memory-mcp` binary from [GitHub Releases](https://github.com/DeusData/codebase-memory-mcp/releases). The binary is downloaded on first run and cached in your OS cache directory.
## Installation
```bash
pip install codebase-memory-mcp
# or
pipx install codebase-memory-mcp
```
## Usage
```bash
codebase-memory-mcp install # configure your coding agents
codebase-memory-mcp --help
```
## Supported platforms
| OS | Architecture |
|---------|-------------|
| macOS | arm64, amd64 |
| Linux | arm64, amd64 |
| Windows | amd64 |
## Full documentation
See [github.com/DeusData/codebase-memory-mcp](https://github.com/DeusData/codebase-memory-mcp)
+35
View File
@@ -0,0 +1,35 @@
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "codebase-memory-mcp"
version = "0.8.1"
description = "Fast code intelligence engine for AI coding agents — single static binary MCP server"
readme = "README.md"
license = { text = "MIT" }
requires-python = ">=3.8"
keywords = ["mcp", "claude", "code-intelligence", "codebase", "memory", "ai", "llm"]
classifiers = [
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: MacOS",
"Operating System :: POSIX :: Linux",
"Operating System :: Microsoft :: Windows",
"Programming Language :: Python :: 3",
"Topic :: Software Development",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
]
[project.urls]
Homepage = "https://github.com/DeusData/codebase-memory-mcp"
Repository = "https://github.com/DeusData/codebase-memory-mcp"
Issues = "https://github.com/DeusData/codebase-memory-mcp/issues"
[project.scripts]
codebase-memory-mcp = "codebase_memory_mcp:main"
[tool.hatch.build.targets.wheel]
packages = ["src/codebase_memory_mcp"]
@@ -0,0 +1,17 @@
"""
codebase-memory-mcp — Fast code intelligence engine for AI coding agents.
Downloads and runs the codebase-memory-mcp binary from GitHub Releases.
"""
try:
from importlib.metadata import version, PackageNotFoundError
try:
__version__ = version("codebase-memory-mcp")
except PackageNotFoundError:
__version__ = "unknown"
except ImportError:
__version__ = "unknown"
from ._cli import main
__all__ = ["main", "__version__"]
@@ -0,0 +1,4 @@
from ._cli import main
if __name__ == "__main__":
main()
+535
View File
@@ -0,0 +1,535 @@
"""Downloads codebase-memory-mcp on first run, then runs its native entry point."""
import hashlib
import os
import platform
import shutil
import stat
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
REPO = "DeusData/codebase-memory-mcp"
_WINDOWS_BINARY_NAME = "codebase-memory-mcp.exe"
_WINDOWS_ARCHIVE_NAMES = (
_WINDOWS_BINARY_NAME,
"LICENSE",
"install.ps1",
"THIRD_PARTY_NOTICES.md",
)
# Security: only permit https fetches. urllib's default handlers accept
# file://, ftp://, and custom schemes — a redirect or tainted URL source
# could otherwise turn a download into an arbitrary-local-file read.
_ALLOWED_SCHEMES = frozenset({"https"})
_MAX_REDIRECTS = 5
_NETWORK_TIMEOUT_SECONDS = 120
_CANDIDATE_TIMEOUT_SECONDS = 15
_MAX_CHECKSUM_MANIFEST_BYTES = 1024 * 1024
_REDIRECT_CODES = frozenset({301, 302, 303, 307, 308})
class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):
"""Expose redirects to _download_https for explicit per-hop validation."""
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
_HTTPS_OPENER = urllib.request.build_opener(_NoRedirectHandler())
def _validate_url_scheme(url: str) -> None:
"""Reject non-https URLs before any network fetch."""
parsed = urllib.parse.urlparse(url)
if (
parsed.scheme not in _ALLOWED_SCHEMES
or not parsed.hostname
or parsed.username is not None
or parsed.password is not None
):
sys.exit(
f"codebase-memory-mcp: refusing to fetch invalid, credentialed, or "
f"non-https URL: {url}"
)
def _download_https(url: str, dest: str, max_bytes: int = 0) -> None:
"""Download through a bounded HTTPS-only opener into dest."""
current_url = url
for redirect_count in range(_MAX_REDIRECTS + 1):
_validate_url_scheme(current_url)
request = urllib.request.Request(
current_url, headers={"User-Agent": "codebase-memory-mcp-installer"}
)
try:
response = _HTTPS_OPENER.open(
request, timeout=_NETWORK_TIMEOUT_SECONDS
)
except urllib.error.HTTPError as exc:
if exc.code not in _REDIRECT_CODES:
raise
location = exc.headers.get("Location")
exc.close()
if not location:
raise RuntimeError(f"redirect has no Location: {current_url}")
if redirect_count == _MAX_REDIRECTS:
raise RuntimeError("too many redirects")
current_url = urllib.parse.urljoin(current_url, location)
_validate_url_scheme(current_url)
continue
with response:
_validate_url_scheme(response.geturl())
deadline = time.monotonic() + _NETWORK_TIMEOUT_SECONDS
total = 0
with open(dest, "wb") as out:
while True:
if time.monotonic() >= deadline:
raise TimeoutError(
f"download hop timed out: {current_url}"
)
chunk = response.read(65536)
if not chunk:
return
total += len(chunk)
if max_bytes and total > max_bytes:
raise RuntimeError(
f"download exceeds the {max_bytes}-byte safety limit"
)
out.write(chunk)
raise RuntimeError("too many redirects")
def _verify_candidate(path: Path) -> None:
"""Require a staged native candidate to execute successfully."""
try:
subprocess.run(
[str(path), "--version"],
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True,
timeout=_CANDIDATE_TIMEOUT_SECONDS,
)
except (OSError, subprocess.SubprocessError) as exc:
raise RuntimeError(f"downloaded binary failed to run: {exc}") from exc
def _file_sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as source:
for chunk in iter(lambda: source.read(65536), b""):
digest.update(chunk)
return digest.hexdigest()
def _files_equal_sha256(left: Path, right: Path) -> bool:
try:
return (
left.is_file()
and right.is_file()
and left.stat().st_size == right.stat().st_size
and _file_sha256(left) == _file_sha256(right)
)
except OSError:
return False
def _safe_extract_tar(tf, dest: str) -> None:
"""Extract a tarfile to dest, rejecting path-traversal entries.
Uses the tarfile data filter on Python >=3.12 (PEP 706), falls back to
manual per-member path validation on older Pythons. Mitigates the
classic tar-slip / Zip Slip vulnerability (CWE-22).
"""
if hasattr(tf, "extraction_filter") or sys.version_info >= (3, 12):
tf.extractall(dest, filter="data")
return
dest_abs = os.path.abspath(dest)
for member in tf.getmembers():
if member.issym() or member.islnk():
sys.exit(
f"codebase-memory-mcp: refusing unsafe tar entry "
f"(link: {member.name!r})"
)
member_abs = os.path.abspath(os.path.join(dest_abs, member.name))
if not (member_abs == dest_abs or member_abs.startswith(dest_abs + os.sep)):
sys.exit(
f"codebase-memory-mcp: refusing unsafe tar entry "
f"(escapes dest: {member.name!r})"
)
tf.extractall(dest)
def _safe_extract_zip(zf, dest: str, archive_names=(), extract_names=()) -> None:
"""Extract a zipfile after validating its Windows-style namespace.
Windows treats paths case-insensitively. Rejecting duplicate/case-conflicting
members before extraction prevents archive order from selecting the binary
that a portable package-manager shim eventually executes.
"""
dest_abs = os.path.abspath(dest)
seen = set()
required = tuple(archive_names)
required_set = set(required)
found = set()
for info in zf.infolist():
raw_name = info.filename
name = raw_name.replace("\\", "/")
segments_name = name[:-1] if name.endswith("/") else name
segments = segments_name.split("/")
if (
not segments_name
or name.startswith("/")
or ":" in name
or any(segment in ("", ".", "..") for segment in segments)
or any(segment.endswith((".", " ")) for segment in segments)
):
sys.exit(
f"codebase-memory-mcp: refusing unsafe zip entry "
f"(invalid path: {raw_name!r})"
)
folded = segments_name.casefold()
if folded in seen:
sys.exit(
f"codebase-memory-mcp: refusing unsafe zip entry "
f"(duplicate or case conflict: {raw_name!r})"
)
seen.add(folded)
if name not in required_set or info.is_dir():
sys.exit(
f"codebase-memory-mcp: archive must contain only the exact "
f"root files: {', '.join(required)}"
)
found.add(name)
member_abs = os.path.abspath(os.path.join(dest_abs, *segments))
if not (member_abs == dest_abs or member_abs.startswith(dest_abs + os.sep)):
sys.exit(
f"codebase-memory-mcp: refusing unsafe zip entry "
f"(escapes dest: {raw_name!r})"
)
missing = required_set - found
if missing or len(seen) != len(required):
sys.exit(
f"codebase-memory-mcp: archive must contain exactly one of each "
f"required root file: {', '.join(required)}"
)
# Extract only the two validated executable files. This avoids relying on
# platform-specific zip path rewriting and always creates regular files.
for name in extract_names:
target = os.path.join(dest_abs, name)
with zf.open(name) as source, open(target, "xb") as output:
shutil.copyfileobj(source, output)
def _verify_checksum(archive_path: str, archive_name: str, version: str) -> None:
"""Verify SHA256 checksum against checksums.txt from the release."""
url = f"https://github.com/{REPO}/releases/download/v{version}/checksums.txt"
tmp_path = None
try:
_validate_url_scheme(url)
with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as tmp:
tmp_path = tmp.name
_download_https(url, tmp_path, _MAX_CHECKSUM_MANIFEST_BYTES)
expected = None
with open(tmp_path, encoding="utf-8") as f:
for line in f:
fields = line.split()
if len(fields) < 2 or fields[1] not in (
archive_name,
f"*{archive_name}",
):
continue
digest = fields[0].lower()
if len(digest) != 64 or any(
ch not in "0123456789abcdef" for ch in digest
):
sys.exit(
f"codebase-memory-mcp: invalid SHA256 checksum for "
f"{archive_name}"
)
if expected is not None and expected != digest:
sys.exit(
f"codebase-memory-mcp: conflicting SHA256 checksums for "
f"{archive_name}"
)
expected = digest
if expected is None:
sys.exit(
f"codebase-memory-mcp: no checksum for {archive_name} in checksums.txt"
)
h = hashlib.sha256()
with open(archive_path, "rb") as af:
for chunk in iter(lambda: af.read(65536), b""):
h.update(chunk)
actual = h.hexdigest()
if expected != actual:
sys.exit(
f"codebase-memory-mcp: CHECKSUM MISMATCH for {archive_name}\n"
f" expected: {expected}\n"
f" actual: {actual}"
)
print("codebase-memory-mcp: checksum verified.", file=sys.stderr)
except SystemExit:
raise
except Exception as exc:
sys.exit(f"codebase-memory-mcp: checksum verification failed: {exc}")
finally:
if tmp_path is not None:
try:
os.unlink(tmp_path)
except Exception:
pass
def _version() -> str:
try:
from importlib.metadata import version
return version("codebase-memory-mcp")
except Exception:
return "0.8.1"
def _os_name() -> str:
p = sys.platform
if p == "linux":
return "linux"
if p == "darwin":
return "darwin"
if p == "win32":
return "windows"
sys.exit(f"codebase-memory-mcp: unsupported platform: {p}")
def _arch() -> str:
m = platform.machine().lower()
if m in ("arm64", "aarch64"):
return "arm64"
if m in ("x86_64", "amd64"):
return "amd64"
sys.exit(f"codebase-memory-mcp: unsupported architecture: {m}")
def _cache_dir() -> Path:
if sys.platform == "win32":
base = Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local"))
elif sys.platform == "darwin":
base = Path.home() / "Library" / "Caches"
else:
base = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache"))
return base / "codebase-memory-mcp"
def _bin_path(version: str) -> Path:
# One binary per platform: the cached file is the executed file.
name = (
_WINDOWS_BINARY_NAME
if sys.platform == "win32"
else "codebase-memory-mcp"
)
return _cache_dir() / version / name
def _execution_path(binary: Path, target_platform: str) -> Path:
"""The cached binary is executed directly on every platform."""
return binary
def _windows_binary_ready(version: str) -> bool:
binary = _cache_dir() / version / _WINDOWS_BINARY_NAME
if not binary.is_file():
return False
try:
_verify_candidate(binary)
except RuntimeError:
return False
return True
def _download(version: str) -> Path:
os_name = _os_name()
arch = _arch()
ext = "zip" if os_name == "windows" else "tar.gz"
# Linux ships a fully-static "-portable" build; the standard linux binary
# dynamically links glibc 2.38+ and fails on older distros. macOS/Windows
# have no such variant. Keep in sync with install.sh / install.js / cli.c.
variant = "-portable" if os_name == "linux" else ""
# Opt into the UI build (embedded graph visualization) with CBM_VARIANT=ui.
# Default is the standard (headless) build. Mirrors install.sh --ui.
ui = "ui-" if os.environ.get("CBM_VARIANT", "").lower() == "ui" else ""
archive = f"codebase-memory-mcp-{ui}{os_name}-{arch}{variant}.{ext}"
url = f"https://github.com/{REPO}/releases/download/v{version}/{archive}"
_validate_url_scheme(url)
dest = _bin_path(version)
dest.parent.mkdir(parents=True, exist_ok=True)
print(
f"codebase-memory-mcp: downloading v{version} for {os_name}/{arch}...",
file=sys.stderr,
)
with tempfile.TemporaryDirectory() as tmp:
tmp_archive = os.path.join(tmp, f"cbm.{ext}")
try:
_download_https(url, tmp_archive)
except (OSError, RuntimeError, urllib.error.URLError) as e:
sys.exit(
f"codebase-memory-mcp: download failed ({e})\n"
f"URL: {url}\n"
f"See https://github.com/{REPO}/releases for available versions."
)
_verify_checksum(tmp_archive, archive, version)
bin_name = (
_WINDOWS_BINARY_NAME if os_name == "windows" else "codebase-memory-mcp"
)
extraction_names = (bin_name,)
cache_names = extraction_names
publish_names = cache_names
if ext == "tar.gz":
import tarfile
with tarfile.open(tmp_archive) as tf:
_safe_extract_tar(tf, tmp)
else:
import zipfile
with zipfile.ZipFile(tmp_archive) as zf:
_safe_extract_zip(
zf,
tmp,
_WINDOWS_ARCHIVE_NAMES,
extraction_names,
)
extracted_paths = {}
for name in extraction_names:
extracted_path = Path(tmp) / name
if not extracted_path.is_file():
sys.exit(
f"codebase-memory-mcp: required binary not found after "
f"extraction: {name}"
)
current = extracted_path.stat().st_mode
extracted_path.chmod(
current | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
)
extracted_paths[name] = extracted_path
try:
_verify_candidate(extracted_paths[bin_name])
except RuntimeError as exc:
sys.exit(f"codebase-memory-mcp: {exc}")
staged_paths = {}
try:
for name in cache_names:
staged_suffix = ".tmp.exe" if sys.platform == "win32" else ".tmp"
with tempfile.NamedTemporaryFile(
dir=str(dest.parent),
prefix=f".{name}.",
suffix=staged_suffix,
delete=False,
) as staged:
staged_path = Path(staged.name)
shutil.copy2(extracted_paths[name], staged_path)
staged_mode = staged_path.stat().st_mode
staged_path.chmod(
staged_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
)
staged_paths[name] = staged_path
if os_name != "windows":
_verify_candidate(staged_paths[bin_name])
for name in publish_names:
target = dest.parent / name
try:
os.replace(staged_paths[name], target)
staged_paths.pop(name)
except OSError as publish_error:
# Never unlink a destination here: it may belong to a
# concurrent contender. A collision remains eligible only
# when its bytes match this authenticated stage; pair
# execution is checked after payload is published last.
if not _files_equal_sha256(staged_paths[name], target):
raise publish_error
if os_name == "windows":
_verify_candidate(dest.parent / _WINDOWS_BINARY_NAME)
else:
_verify_candidate(dest)
except RuntimeError as exc:
sys.exit(f"codebase-memory-mcp: {exc}")
finally:
for staged_path in staged_paths.values():
try:
staged_path.unlink()
except OSError:
pass
return dest
def main() -> None:
version = _version()
bin_path = _bin_path(version)
cache_ready = (
_windows_binary_ready(version)
if sys.platform == "win32"
else bin_path.is_file()
)
if not cache_ready:
bin_path = _download(version)
execution_path = _execution_path(bin_path, sys.platform)
# args is a list (not a shell string), so exec/subprocess treat each
# element as a discrete argv entry — no shell interpretation, no
# injection vector. sys.argv forwarding is the whole point of this
# shim, so tainted-input suppression is intentional.
args = [str(execution_path)] + sys.argv[1:]
if sys.platform != "win32":
os.execv(str(execution_path), args) # noqa: S606 — list form, no shell
else:
result = subprocess.run(args) # noqa: S603 — list form, no shell=True
mutation = _portable_mutation_action(sys.argv[1:])
if result.returncode != 0 and mutation is not None:
package_command = (
"python -m pip install --upgrade codebase-memory-mcp"
if mutation == "update"
else "python -m pip uninstall codebase-memory-mcp"
)
print(
f'This PyPI Windows copy is portable. Use "{package_command}" '
f'for package maintenance, or run "codebase-memory-mcp '
f'install --yes" once to create a managed launcher with '
f'coordinated self-update/uninstall.',
file=sys.stderr,
)
sys.exit(result.returncode)
def _portable_mutation_action(args):
for argument in args:
if argument in (
"cli",
"hook-augment",
"config",
"install",
"--help",
"-h",
"--version",
):
return None
if argument in ("update", "uninstall"):
return argument
return None
+36
View File
@@ -0,0 +1,36 @@
import sys
import unittest
from pathlib import Path
PACKAGE_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PACKAGE_ROOT / "src"))
from codebase_memory_mcp import _cli # noqa: E402
class BinarySelectionTests(unittest.TestCase):
"""One binary ships per platform: the cached file is the executed file."""
def test_windows_executes_the_cached_binary(self):
binary = Path("cache") / "0.8.1" / _cli._WINDOWS_BINARY_NAME
self.assertEqual(_cli._execution_path(binary, "win32"), binary)
def test_non_windows_executes_the_cached_binary(self):
binary = Path("cache") / "0.8.1" / "codebase-memory-mcp"
self.assertEqual(_cli._execution_path(binary, "linux"), binary)
def test_portable_mutation_guidance_classification_is_preserved(self):
self.assertEqual(_cli._portable_mutation_action(["update"]), "update")
self.assertEqual(
_cli._portable_mutation_action(["uninstall", "--yes"]),
"uninstall",
)
self.assertIsNone(_cli._portable_mutation_action(["install", "--yes"]))
self.assertIsNone(_cli._portable_mutation_action(["cli", "update"]))
if __name__ == "__main__":
unittest.main()
+30
View File
@@ -0,0 +1,30 @@
{
"version": "0.8.1",
"description": "Fast code intelligence engine for AI coding agents — single static binary MCP server",
"homepage": "https://github.com/DeusData/codebase-memory-mcp",
"license": "MIT",
"architecture": {
"64bit": {
"url": "https://github.com/DeusData/codebase-memory-mcp/releases/download/v0.8.1/codebase-memory-mcp-windows-amd64.zip",
"hash": "a602ad090ed3f49d86c55472f73f27ad7055222806a82358f2e08513e027f00f",
"bin": "codebase-memory-mcp.exe"
}
},
"post_install": [
"& \"$dir\\codebase-memory-mcp.exe\" install -y 2>&1 | Out-Null"
],
"checkver": {
"github": "https://github.com/DeusData/codebase-memory-mcp"
},
"autoupdate": {
"architecture": {
"64bit": {
"url": "https://github.com/DeusData/codebase-memory-mcp/releases/download/v$version/codebase-memory-mcp-windows-amd64.zip",
"hash": {
"url": "https://github.com/DeusData/codebase-memory-mcp/releases/download/v$version/checksums.txt",
"find": "([a-f0-9]{64})\\s+codebase-memory-mcp-windows-amd64\\.zip"
}
}
}
}
}
@@ -0,0 +1,17 @@
PackageIdentifier: DeusData.CodebaseMemoryMcp
PackageVersion: 0.8.1
InstallerLocale: en-US
InstallerType: zip
NestedInstallerType: portable
NestedInstallerFiles:
- RelativeFilePath: codebase-memory-mcp.exe
PortableCommandAlias: codebase-memory-mcp
Platform:
- Windows.Desktop
- Windows.Universal
Installers:
- Architecture: x64
InstallerUrl: https://github.com/DeusData/codebase-memory-mcp/releases/download/v0.8.1/codebase-memory-mcp-windows-amd64.zip
InstallerSha256: a602ad090ed3f49d86c55472f73f27ad7055222806a82358f2e08513e027f00f
ManifestType: installer
ManifestVersion: 1.6.0
@@ -0,0 +1,29 @@
PackageIdentifier: DeusData.CodebaseMemoryMcp
PackageVersion: 0.8.1
PackageLocale: en-US
Publisher: DeusData
PublisherUrl: https://github.com/DeusData
PublisherSupportUrl: https://github.com/DeusData/codebase-memory-mcp/issues
PackageName: codebase-memory-mcp
PackageUrl: https://github.com/DeusData/codebase-memory-mcp
License: MIT
LicenseUrl: https://github.com/DeusData/codebase-memory-mcp/blob/main/LICENSE
ShortDescription: Fast code intelligence engine for AI coding agents
Description: |-
codebase-memory-mcp is a single static binary MCP server that indexes codebases
at extreme speed and exposes 14 MCP tools for AI coding agents. Full indexes an
average repository in milliseconds, the Linux kernel (28M LOC) in 3 minutes.
Supports 155 languages via vendored tree-sitter grammars. Zero dependencies.
Plug and play across 11 coding agents including Claude Code, Codex CLI, and Zed.
Moniker: codebase-memory-mcp
Tags:
- mcp
- ai
- claude
- code-intelligence
- codebase
- developer-tools
- tree-sitter
ReleaseNotesUrl: https://github.com/DeusData/codebase-memory-mcp/releases/tag/v0.8.1
ManifestType: defaultLocale
ManifestVersion: 1.6.0
@@ -0,0 +1,5 @@
PackageIdentifier: DeusData.CodebaseMemoryMcp
PackageVersion: 0.8.1
DefaultLocale: en-US
ManifestType: version
ManifestVersion: 1.6.0