Thanks to visit codestin.com
Credit goes to github.com

Skip to content

MCP Integration

Lisa edited this page Dec 25, 2025 · 36 revisions

CKB MCP Integration Guide

CKB exposes AI-native code navigation and architectural memory capabilities via the Model Context Protocol (MCP), enabling AI assistants like Claude Code to discover, understand, and navigate codebases with persistent knowledge.

Looking for tool documentation? See MCP-Tools for complete reference documentation of all 76 MCP tools.

Quick Setup

CKB works with any MCP-compatible AI coding tool.

Claude Code

# Install CKB
npm install -g @tastehub/ckb

# Configure for current project
ckb setup

# Or configure globally for all projects
ckb setup --global

# Verify configuration
claude mcp list

Or with npx (no install):

npx @tastehub/ckb setup

Manual configuration — add to .mcp.json in project root:

{
  "mcpServers": {
    "ckb": {
      "command": "npx",
      "args": ["@tastehub/ckb", "mcp"]
    }
  }
}

Cursor

Add to ~/.cursor/mcp.json (global) or .cursor/mcp.json (project):

{
  "mcpServers": {
    "ckb": {
      "command": "npx",
      "args": ["@tastehub/ckb", "mcp"]
    }
  }
}

Or go to Settings → Cursor Settings → MCP → Add new global MCP server.


Windsurf

Add to ~/.codeium/windsurf/mcp_config.json:

{
  "mcpServers": {
    "ckb": {
      "command": "npx",
      "args": ["@tastehub/ckb", "mcp"]
    }
  }
}

Or go to Windsurf Settings → Advanced Settings → Cascade → Manage MCP Servers.


VS Code

Add to your VS Code settings.json:

{
  "mcp": {
    "servers": {
      "ckb": {
        "type": "stdio",
        "command": "npx",
        "args": ["@tastehub/ckb", "mcp"]
      }
    }
  }
}

OpenCode

Add to opencode.json in project root:

{
  "mcp": {
    "ckb": {
      "type": "local",
      "command": ["npx", "@tastehub/ckb", "mcp"],
      "enabled": true
    }
  }
}

Note: OpenCode uses a different config format - command is an array and requires type: "local".


Claude Desktop

Claude Desktop is a standalone app without a project context, so CKB needs to know which repository to analyze.

Automatic setup (recommended):

cd /path/to/your/repo
ckb setup --tool=claude-desktop

This prompts for your repository path and configures everything automatically.

Manual configuration — add to ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or %APPDATA%\Claude\claude_desktop_config.json (Windows):

{
  "mcpServers": {
    "ckb": {
      "command": "npx",
      "args": ["-y", "@tastehub/ckb", "mcp"],
      "env": {
        "CKB_REPO": "/path/to/your/repo"
      }
    }
  }
}

The CKB_REPO environment variable tells CKB which repository to analyze. You can also use the --repo flag directly:

{
  "mcpServers": {
    "ckb": {
      "command": "npx",
      "args": ["-y", "@tastehub/ckb", "mcp", "--repo", "/path/to/your/repo"]
    }
  }
}

Important: Claude Desktop can only work with one repository at a time. To switch repositories, run ckb setup --tool=claude-desktop again or update the config manually.


Windows

On Windows, wrap the command with cmd /c in any of the configs above:

{
  "mcpServers": {
    "ckb": {
      "command": "cmd",
      "args": ["/c", "npx", "@tastehub/ckb", "mcp"]
    }
  }
}

Using a Local Binary

If you built from source or installed globally, use the binary directly:

{
  "mcpServers": {
    "ckb": {
      "command": "ckb",
      "args": ["mcp"]
    }
  }
}

Tool Presets (v7.4)

CKB exposes 76 tools, but most sessions only need a subset. Presets reduce token overhead by up to 83% by limiting exposed tools to task-relevant sets.

# List available presets
ckb mcp --list-presets

# Start with a preset
ckb mcp --preset=review
Preset Tools Use Case
core 14 Navigation and analysis (default)
review 19 PR reviews, ownership
refactor 19 Coupling, dead code
docs 20 Documentation coverage
ops 25 Jobs, webhooks, diagnostics
federation 28 Multi-repo queries
full 76 All tools

The AI can dynamically expand tools mid-session using expandToolset.

See Presets for complete documentation including tool lists for each preset, configuration examples, and token efficiency details.

Pagination

For MCP clients that support pagination, CKB uses cursor-based pagination with:

  • Page size: 15 tools per page
  • Core-first ordering: Page 1 always contains the complete core toolset
  • Cursor invalidation: Cursors rejected when preset or toolset changes

Non-paginating clients receive all tools in the current preset on the first request.


Platform Contracts

Backend Budget Classification

Tools are classified by performance budget. See MCP-Tools for the complete list organized by category.

Cheap Tools (P95 < 300ms)

searchSymbols · explainFile · listEntrypoints · explainPath · getSymbol · explainSymbol · getOwnership · getModuleResponsibilities · recordDecision · getDecisions · annotateModule · listFederations · federationStatus · federationRepos · daemonStatus · listSchedules · runSchedule · listWebhooks · testWebhook · webhookDeliveries · getFileComplexity · listContracts · suppressContractEdge · verifyContractEdge · getContractStats · getTelemetryStatus · getObservedUsage · explainOrigin · getDocsForSymbol · getSymbolsInDoc · getDocsForModule · federationAddRemote · federationRemoveRemote · federationListRemote · federationStatusRemote · federationListAllRepos

  • Max 1 hop traversal
  • Max 50 results
  • No callgraph expansion or deep git history

Heavy Tools (P95 < 2000ms)

traceUsage · getArchitecture · getHotspots · summarizeDiff · recentlyRelevant · listKeyConcepts · analyzeImpact · getCallGraph · findReferences · justifySymbol · federationSearchModules · federationSearchOwnership · federationGetHotspots · federationSearchDecisions · federationSync · analyzeContractImpact · getContractDependencies · findDeadCodeCandidates · analyzeCoupling · exportForLLM · auditRisk · indexDocs · checkDocStaleness · getDocCoverage · federationSyncRemote · federationSearchSymbolsHybrid

  • Up to depth 5 traversal
  • Up to 1000 git commits
  • Must include limitations field

Heavy Tools (P95 < 30000ms)

refreshArchitecture · summarizePr · getOwnershipDrift

  • refreshArchitecture: Supports async mode (v6.1) — returns jobId for polling
  • summarizePr: Analyze PR changes, suggest reviewers, assess risk
  • getOwnershipDrift: Compare CODEOWNERS vs actual git-blame ownership

Response Envelope (v7.4)

All 76 MCP tools now return responses wrapped in a standardized envelope with metadata:

{
  "schemaVersion": "1.0",
  "data": { /* tool-specific payload */ },
  "meta": {
    "confidence": {
      "score": 0.85,
      "tier": "medium",
      "reasons": ["SCIP+git hybrid"]
    },
    "provenance": {
      "backends": ["scip", "git"],
      "repoStateId": "abc123def456"
    },
    "freshness": {
      "indexAge": {
        "commitsBehind": 3,
        "staleReason": "behind-head"
      }
    },
    "truncation": {
      "isTruncated": true,
      "shown": 10,
      "total": 47,
      "reason": "max-results"
    }
  },
  "warnings": [
    { "code": "W001", "message": "Index slightly stale" }
  ],
  "error": null,
  "suggestedNextCalls": [
    {
      "tool": "getModuleOverview",
      "params": { "path": "internal/query" },
      "reason": "Explore top impacted module"
    }
  ]
}

Key Envelope Fields:

Field Description
schemaVersion Envelope format version (currently "1.0")
data Tool-specific response payload
meta.confidence How trustworthy the results are
meta.provenance Which backends contributed data
meta.freshness Index staleness information
meta.truncation When results are cut off by limits
warnings Non-fatal issues to be aware of
error Error message if request failed
suggestedNextCalls Structured follow-up recommendations

Confidence Tiers

Tier Score Range Conditions
high ≥ 0.95 Fresh SCIP index, full static analysis
medium 0.70 - 0.94 Stale SCIP, LSP fallback, partial analysis
low 0.30 - 0.69 Heuristics only, git-based analysis
speculative < 0.30 Cross-repo queries, uncommitted changes

Score Modifiers:

Condition Effect
Full static analysis (SCIP/LSP) Base 1.0
Partial static analysis Cap at 0.89
Heuristics only Cap at 0.79
Key backend missing Cap at 0.69
Multiple backends missing Cap at 0.39
Index > 5 commits behind Downgrade to medium
Cross-repo query Force speculative

Time Window Defaults

Tool Default
getHotspots 30 days
summarizeDiff 30 days
recentlyRelevant 7 days

Navigation Presets

Preset Focus
onboarding Broad, concept-first
bug-investigation Trace-focused, recent changes
refactor-safety Coupling and hotspots
review Diff-centric, risk signals

Recommended Workflows

New Codebase

getStatus() → listKeyConcepts() → getArchitecture() → listEntrypoints() → searchSymbols()

Bug Investigation

searchSymbols() → traceUsage() → getCallGraph() → recentlyRelevant()

Before Changes

searchSymbols() → explainSymbol() → findReferences() → analyzeImpact() → getHotspots()

Code Review

summarizeDiff() → getHotspots() → getOwnership() → traceUsage()

Dead Code

searchSymbols() → justifySymbol() → explainFile()

Understanding Module Ownership (v6.0)

getArchitecture() → getOwnership() → getModuleResponsibilities()

Recording Design Decisions (v6.0)

getDecisions() → recordDecision() → annotateModule()

Annotation-Aware Dead Code Detection (v6.5)

findDeadCodeCandidates() → justifySymbol() → [check for "investigate" with ADR reasoning]

If justifySymbol returns "investigate" with reasoning mentioning an ADR, the code isn't dead—it was an intentional architectural decision. Only "remove-candidate" without ADR context suggests safe removal.

Annotation-Aware Impact Analysis (v6.5)

analyzeImpact() → [check relatedDecisions] → getDecisions()

When analyzeImpact shows relatedDecisions, read them before making changes to understand the architectural context.

Risk Assessment (v6.0)

getHotspots() → getOwnership() → summarizeDiff()

CI/CD Integration (v6.1)

summarizePr() → getOwnershipDrift() → getHotspots()

Background Refresh (v6.1)

refreshArchitecture({ async: true }) → getJobStatus() → [poll until complete]

Cross-Repo Analysis (v6.2)

listFederations() → federationStatus() → federationSearchModules() → federationGetHotspots()

Organization-Wide Review (v6.2)

federationSearchOwnership() → federationSearchDecisions() → federationSync()

Daemon Monitoring (v6.2.1)

daemonStatus() → listSchedules() → listWebhooks() → webhookDeliveries()

Scheduled Automation (v6.2.1)

listSchedules() → runSchedule() → listJobs() → getJobStatus()

Contract Impact Analysis (v6.3)

listContracts() → analyzeContractImpact() → getContractDependencies() → getContractStats()

Before Changing Shared API (v6.3)

listContracts() → analyzeContractImpact() → [contact owners] → federationSync()

Dead Code Detection (v6.4)

getTelemetryStatus() → [verify coverage is medium+] → findDeadCodeCandidates() → justifySymbol()

Understanding Actual Usage (v6.4)

searchSymbols() → getObservedUsage() → analyzeImpact({ includeTelemetry: true })

Understand Why Code Exists (v6.5)

searchSymbols() → explainOrigin() → analyzeCoupling() → auditRisk()

Find Co-Change Patterns (v6.5)

analyzeCoupling() → getHotspots() → getOwnership()

LLM Context Generation (v6.5)

exportForLLM() → [paste to LLM for codebase understanding]

Risk Audit & Quick Wins (v6.5)

auditRisk() → auditRisk({ quickWins: true }) → explainOrigin()

Documentation Maintenance (v7.3)

indexDocs() → checkDocStaleness({ all: true }) → getDocsForSymbol() → getDocCoverage()

Before Renaming a Symbol (v7.3)

searchSymbols() → getDocsForSymbol() → [rename symbol] → checkDocStaleness()

Remote Federation Setup (v7.3)

federationAddRemote() → federationSyncRemote() → federationStatusRemote() → federationSearchSymbolsHybrid()

Cross-Organization Search (v7.3)

federationListRemote() → federationSearchSymbolsHybrid({ servers: [...] }) → federationListAllRepos()

Error Codes

Code Fix
SYMBOL_NOT_FOUND Use searchSymbols() first
BACKEND_UNAVAILABLE Check getStatus()
INDEX_STALE Run scip-go
QUERY_TIMEOUT Add scope/limit
BUDGET_EXCEEDED Use cheaper tool

What CKB Does NOT Do

  • ❌ Code mutation/refactoring
  • ❌ Test generation
  • ❌ Fix suggestions
  • ❌ Policy enforcement
  • ❌ Lint judgments

Navigation and comprehension only.


Implementation Status

v5.1 ✓

searchSymbols, getSymbol, findReferences, explainSymbol, justifySymbol, getCallGraph, getModuleOverview, analyzeImpact, getStatus, doctor

v5.2 ✓ (Complete)

All v5.2 tools are now implemented:

Phase 1: explainFile, traceUsage, listEntrypoints

Phase 2: summarizeDiff

Phase 3: getHotspots, getArchitecture

Phase 4: explainPath, listKeyConcepts, recentlyRelevant

v6.0 ✓ (Complete - Architectural Memory)

All v6.0 tools are implemented:

Phase 1: getArchitecture (enhanced), refreshArchitecture

Phase 2: getOwnership

Phase 3: getHotspots (enhanced with trends), getModuleResponsibilities

Phase 4: recordDecision, getDecisions, annotateModule

v6.1 ✓ (Complete - Production Ready)

All v6.1 tools are implemented:

Background Jobs: getJobStatus, listJobs, cancelJob

Async Operations: refreshArchitecture now supports async: true mode

CI/CD Integration: summarizePr, getOwnershipDrift

v6.2 ✓ (Complete - Federation)

All v6.2 tools are implemented:

Federation Management: listFederations, federationStatus, federationRepos, federationSync

Cross-Repo Queries: federationSearchModules, federationSearchOwnership, federationGetHotspots, federationSearchDecisions

v6.2.1 ✓ (Complete - Daemon Mode)

All v6.2.1 tools are implemented:

Daemon Status: daemonStatus

Scheduler: listSchedules, runSchedule

Webhooks: listWebhooks, testWebhook, webhookDeliveries

v6.2.2 ✓ (Complete - Tree-sitter Complexity)

Language-agnostic complexity metrics via getFileComplexity tool:

Supported Languages: Go, JavaScript, TypeScript (+ TSX), Python, Rust, Java, Kotlin

Metrics:

  • Cyclomatic complexity — decision points analysis
  • Cognitive complexity — nesting-weighted for maintainability

Integration: Complexity feeds into getHotspots risk scores

v6.3 ✓ (Complete - Contract-Aware Impact Analysis)

All v6.3 tools are implemented:

Contract Detection: listContracts

Impact Analysis: analyzeContractImpact, getContractDependencies

Edge Management: suppressContractEdge, verifyContractEdge

Statistics: getContractStats

v6.4 ✓ (Complete - Runtime Telemetry)

All v6.4 tools are implemented:

Telemetry Status: getTelemetryStatus

Usage Display: getObservedUsage

Dead Code Detection: findDeadCodeCandidates

Enhanced Tools:

  • analyzeImpact - Now includes includeTelemetry parameter for observed callers
  • getHotspots - Now includes observedUsage field when telemetry is enabled

v6.5 ✓ (Complete - Developer Intelligence)

All v6.5 tools are implemented:

Symbol Explanation: explainOrigin

Co-Change Analysis: analyzeCoupling

LLM Export: exportForLLM

Risk Audit: auditRisk

Annotation Integration: ADRs and module annotations are now wired into core tools:

  • explainSymbol - Now includes annotations field with related ADRs and module metadata
  • justifySymbol - Verdict considers ADRs; returns "investigate" instead of "remove-candidate" when an accepted/proposed ADR exists for the module
  • analyzeImpact - Now includes relatedDecisions field showing ADRs affecting impacted modules
  • getModuleOverview - Now includes annotations and relatedDecisions fields
  • getModuleResponsibilities - Declared annotations now override inferred responsibilities with higher confidence

v7.3 ✓ (Complete - Doc-Symbol Linking)

All v7.3 tools are implemented:

Documentation Indexing: indexDocs

Symbol Queries: getDocsForSymbol, getSymbolsInDoc, getDocsForModule

Staleness Detection: checkDocStaleness

Coverage Analysis: getDocCoverage

Features:

  • Backtick detection - Automatically detect Symbol.Name references in markdown
  • Directive support - <!-- ckb:symbol --> for explicit references, <!-- ckb:module --> for module linking
  • Fence scanning - Extract symbols from fenced code blocks (8 languages via tree-sitter)
  • Staleness detection - Find broken references when symbols are renamed or deleted
  • Rename awareness - Suggest new names when documented symbols are renamed via alias chain
  • CI enforcement - --fail-under flag for documentation coverage thresholds
  • known_symbols directive - Allow single-segment symbol detection

v7.3 ✓ (Complete - Remote Federation)

All v7.3 tools are implemented:

Server Management: federationAddRemote, federationRemoveRemote, federationListRemote

Synchronization: federationSyncRemote

Status & Health: federationStatusRemote

Hybrid Queries: federationSearchSymbolsHybrid, federationListAllRepos

Features:

  • Remote server connections with Bearer token auth
  • Environment variable expansion for tokens (${VAR} syntax)
  • Configurable cache TTL and request timeout per server
  • Hybrid local+remote queries with source attribution
  • Graceful degradation when remotes unavailable
  • Exponential backoff retry logic (max 3 retries)
  • SQLite caching layer for remote metadata

v7.3 ✓ (Complete - Multi-Repo Management)

All v7.3 multi-repo tools are implemented:

Registry Management: listRepos, getActiveRepo

Context Switching: switchRepo

Features:

  • Global repository registry at ~/.ckb/repos.json
  • Named shortcuts for quick context switching in MCP sessions
  • Multi-engine support (up to 5 engines in memory with LRU eviction)
  • Per-repo configuration loading from each repo's .ckb/config.json
  • Repo state tracking: valid, uninitialized, missing
  • --repo flag for ckb mcp and ckb serve to start with specific repo
  • Graceful engine lifecycle with in-flight operation tracking

CLI Commands:

  • ckb repo add [name] [path] - Register a repository
  • ckb repo list - List repos grouped by state
  • ckb repo remove <name> - Unregister a repo
  • ckb repo default [name] - Get or set default repo
  • ckb repo which - Print current repo (for scripts)
  • ckb repo check - Validate all registered repos

v7.4 ✓ (Complete - Standardized Response Envelope)

All 74 MCP tool responses now include structured metadata:

Envelope Features:

  • Schema version for forward compatibility
  • Confidence scoring with tiers (high/medium/low/speculative)
  • Provenance tracking (which backends contributed)
  • Freshness metadata (index staleness)
  • Truncation awareness (shown vs total counts)
  • Structured suggested next calls

Files Added:

  • internal/envelope/envelope.go — Core types and builder
  • internal/mcp/tool_helpers.go — MCP-specific response helpers

Total: 76 MCP tools available


Caveats & Platform Notes

The npx Sandbox Problem (Fixed in 7.3+)

Good news: As of CKB 7.3, this is handled automatically. The Node.js shim now detects your repo root and sets CKB_REPO for you.

Background: When npx runs CKB, it executes from a sandboxed temp directory (like ~/.npm/_npx/...), not your project directory. CKB needs to find .ckb/ in the project root.

How CKB 7.3+ fixes this: The npm package includes a shim that walks up from process.cwd() looking for .ckb/ or .git/ and automatically sets CKB_REPO. This means simple configs now work:

{
  "command": "npx",
  "args": ["@tastehub/ckb", "mcp"]
}

If auto-detection fails (rare edge cases), you can still set CKB_REPO explicitly:

{
  "command": "npx",
  "args": ["-y", "@tastehub/ckb", "mcp"],
  "env": {
    "CKB_REPO": "/path/to/your/repo"
  }
}

Tool-Specific Considerations

Tool Notes
Claude Code Works out of the box with npx
Cursor Works out of the box; global config auto-detects repo
Windsurf Global-only; auto-detection works in most cases
VS Code Works out of the box with npx
OpenCode Works out of the box with npx
Claude Desktop Auto-detection works if launched from a repo directory

Limitation: With auto-detected or explicit CKB_REPO, CKB works with one repository at a time. To switch repos, update the config or use project-scoped configuration.


NVM / asdf / Version Managers

If you use NVM, asdf, or other Node version managers, npx may not work correctly because these tools rely on shell initialization that MCP clients don't run.

Symptoms:

  • "command not found: npx"
  • Server starts but uses wrong Node version
  • Intermittent failures

Solution: Use absolute paths instead of npx:

{
  "mcpServers": {
    "ckb": {
      "command": "/Users/you/.nvm/versions/node/v22.11.0/bin/node",
      "args": [
        "/Users/you/.nvm/versions/node/v22.11.0/lib/node_modules/@tastehub/ckb/bin/ckb.js",
        "mcp"
      ]
    }
  }
}

Find your paths:

# Find node path
which node

# Find global package location
npm root -g

Alternative: Install CKB globally with the system Node (not NVM):

/usr/local/bin/npm install -g @tastehub/ckb

Environment Variables Not Passed

MCP clients typically only pass PATH to servers. Other environment variables like $HOME are NOT automatically available.

What works:

  • PATH (usually)
  • Variables explicitly listed in env config

What doesn't work:

  • $HOME, $USER, custom variables
  • Variable substitution (${VAR}) in config files
  • Shell expansion

If CKB needs specific variables, add them explicitly:

{
  "env": {
    "HOME": "/Users/you",
    "CKB_REPO": "/path/to/repo"
  }
}

Cursor-Specific Issues

Process orphaning: Cursor doesn't always terminate MCP servers when closing. You may need to manually kill orphaned processes:

pkill -f "ckb mcp"

Sandbox environment: When using npx, Cursor runs servers in a sandboxed temp directory. Use CKB_REPO or project-scoped config.

Logging disabled: Cursor breaks MCP logging connections. Debug by writing to a file instead:

ckb mcp 2>/tmp/ckb-debug.log

Windsurf-Specific Notes

Config location varies:

  • Official: ~/.codeium/windsurf/mcp_config.json
  • Legacy: ~/.codeium/mcp_config.json

CKB's setup command probes both locations and uses whichever exists.

Global-only: Windsurf only supports global MCP configuration, not per-project. Consider using CKB_REPO if you work with multiple repositories.


Troubleshooting

Server won't start

# Check if ckb is available
npx @tastehub/ckb version

# Test MCP server manually
echo '{"jsonrpc":"2.0","id":1,"method":"initialize"}' | npx @tastehub/ckb mcp

# If using NVM, check with absolute path
/path/to/node /path/to/ckb mcp --help

"MCP server disconnected" or "Connection closed"

Common causes:

  1. Wrong working directory — CKB can't find .ckb/ database

    # Fix: Add CKB_REPO to config
    "env": { "CKB_REPO": "/path/to/your/repo" }
  2. npx not found (NVM/asdf users)

    # Fix: Use absolute paths instead of npx
  3. Non-JSON output to stdout — Check for rogue print statements

    # Test: Should output only JSON
    echo '{}' | ckb mcp 2>/dev/null

No tools available

# Check CKB is initialized
ls -la .ckb/

# Initialize if missing
ckb init

# Check status
ckb status

Stale results

# Regenerate SCIP index
ckb index

# Check for issues
ckb doctor

# Force refresh architecture
ckb refresh --force

Debug MCP communication

# macOS: Watch MCP logs (Claude Desktop)
tail -f ~/Library/Logs/Claude/mcp*.log

# Write debug output to file
CKB_REPO=/path/to/repo ckb mcp 2>/tmp/ckb-mcp.log

Related Pages

Clone this wiki locally