@softerist/heuristic-mcp 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +287 -0
- package/CONTRIBUTING.md +308 -0
- package/LICENSE +21 -0
- package/README.md +249 -0
- package/config.json +66 -0
- package/example.png +0 -0
- package/features/clear-cache.js +75 -0
- package/features/find-similar-code.js +127 -0
- package/features/hybrid-search.js +173 -0
- package/features/index-codebase.js +811 -0
- package/how-its-works.png +0 -0
- package/index.js +208 -0
- package/lib/cache.js +163 -0
- package/lib/config.js +257 -0
- package/lib/embedding-worker.js +67 -0
- package/lib/ignore-patterns.js +314 -0
- package/lib/project-detector.js +75 -0
- package/lib/tokenizer.js +142 -0
- package/lib/utils.js +301 -0
- package/package.json +65 -0
- package/scripts/clear-cache.js +31 -0
- package/test/clear-cache.test.js +288 -0
- package/test/embedding-model.test.js +230 -0
- package/test/helpers.js +128 -0
- package/test/hybrid-search.test.js +243 -0
- package/test/index-codebase.test.js +246 -0
- package/test/integration.test.js +223 -0
- package/test/tokenizer.test.js +225 -0
- package/vitest.config.js +29 -0
package/README.md
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
# Smart Coding MCP
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/smart-coding-mcp)
|
|
4
|
+
[](https://www.npmjs.com/package/smart-coding-mcp)
|
|
5
|
+
[](https://opensource.org/licenses/MIT)
|
|
6
|
+
[](https://nodejs.org/)
|
|
7
|
+
|
|
8
|
+
An extensible Model Context Protocol (MCP) server that provides intelligent semantic code search for AI assistants. Built with local AI models (RAG), inspired by Cursor's semantic search research.
|
|
9
|
+
|
|
10
|
+
## What This Does
|
|
11
|
+
|
|
12
|
+
AI coding assistants work better when they can find relevant code quickly. Traditional keyword search falls short - if you ask "where do we handle authentication?" but your code uses "login" and "session", keyword search misses it.
|
|
13
|
+
|
|
14
|
+
This MCP server solves that by indexing your codebase with AI embeddings. Your AI assistant can search by meaning instead of exact keywords, finding relevant code even when the terminology differs.
|
|
15
|
+
|
|
16
|
+

|
|
17
|
+
|
|
18
|
+
## Why Use This
|
|
19
|
+
|
|
20
|
+
**Better Code Understanding**
|
|
21
|
+
|
|
22
|
+
- Search finds code by concept, not just matching words
|
|
23
|
+
- Works with typos and variations in terminology
|
|
24
|
+
- Natural language queries like "where do we validate user input?"
|
|
25
|
+
|
|
26
|
+
**Performance**
|
|
27
|
+
|
|
28
|
+
- Pre-indexed embeddings are faster than scanning files at runtime
|
|
29
|
+
- Smart project detection skips dependencies automatically (node_modules, vendor, etc.)
|
|
30
|
+
- Incremental updates - only re-processes changed files
|
|
31
|
+
|
|
32
|
+
**Privacy**
|
|
33
|
+
|
|
34
|
+
- Everything runs locally on your machine
|
|
35
|
+
- Your code never leaves your system
|
|
36
|
+
- No API calls to external services
|
|
37
|
+
|
|
38
|
+
## Installation
|
|
39
|
+
|
|
40
|
+
Install globally via npm:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
npm install -g smart-coding-mcp
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
To update to the latest version:
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
npm update -g smart-coding-mcp
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Configuration
|
|
53
|
+
|
|
54
|
+
Add to your MCP configuration file. The location depends on your IDE and OS:
|
|
55
|
+
|
|
56
|
+
| IDE | OS | Config Path |
|
|
57
|
+
| -------------------- | ------- | ----------------------------------------------------------------- |
|
|
58
|
+
| **Claude Desktop** | macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |
|
|
59
|
+
| **Claude Desktop** | Windows | `%APPDATA%\Claude\claude_desktop_config.json` |
|
|
60
|
+
| **Cascade (Cursor)** | All | Configured via UI Settings > Features > MCP |
|
|
61
|
+
| **Antigravity** | macOS | `~/.gemini/antigravity/mcp_config.json` |
|
|
62
|
+
| **Antigravity** | Windows | `%USERPROFILE%\.gemini\antigravity\mcp_config.json` |
|
|
63
|
+
|
|
64
|
+
Add the server configuration to the `mcpServers` object in your config file:
|
|
65
|
+
|
|
66
|
+
### Option 1: Specific Project (Recommended)
|
|
67
|
+
|
|
68
|
+
```json
|
|
69
|
+
{
|
|
70
|
+
"mcpServers": {
|
|
71
|
+
"smart-coding-mcp": {
|
|
72
|
+
"command": "smart-coding-mcp",
|
|
73
|
+
"args": ["--workspace", "/absolute/path/to/your/project"]
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### Option 2: Multi-Project Support
|
|
80
|
+
|
|
81
|
+
```json
|
|
82
|
+
{
|
|
83
|
+
"mcpServers": {
|
|
84
|
+
"smart-coding-mcp-project-a": {
|
|
85
|
+
"command": "smart-coding-mcp",
|
|
86
|
+
"args": ["--workspace", "/path/to/project-a"]
|
|
87
|
+
},
|
|
88
|
+
"smart-coding-mcp-project-b": {
|
|
89
|
+
"command": "smart-coding-mcp",
|
|
90
|
+
"args": ["--workspace", "/path/to/project-b"]
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Environment Variables
|
|
97
|
+
|
|
98
|
+
Override configuration settings via environment variables in your MCP config:
|
|
99
|
+
|
|
100
|
+
| Variable | Type | Default | Description |
|
|
101
|
+
| -------------------------------- | ------- | ------------------------- | ------------------------------------- |
|
|
102
|
+
| `SMART_CODING_VERBOSE` | boolean | `false` | Enable detailed logging |
|
|
103
|
+
| `SMART_CODING_BATCH_SIZE` | number | `100` | Files to process in parallel |
|
|
104
|
+
| `SMART_CODING_MAX_FILE_SIZE` | number | `1048576` | Max file size in bytes (1MB) |
|
|
105
|
+
| `SMART_CODING_CHUNK_SIZE` | number | `25` | Lines of code per chunk |
|
|
106
|
+
| `SMART_CODING_MAX_RESULTS` | number | `5` | Max search results |
|
|
107
|
+
| `SMART_CODING_SMART_INDEXING` | boolean | `true` | Enable smart project detection |
|
|
108
|
+
| `SMART_CODING_WATCH_FILES` | boolean | `false` | Enable file watching for auto-reindex |
|
|
109
|
+
| `SMART_CODING_SEMANTIC_WEIGHT` | number | `0.7` | Weight for semantic similarity (0-1) |
|
|
110
|
+
| `SMART_CODING_EXACT_MATCH_BOOST` | number | `1.5` | Boost for exact text matches |
|
|
111
|
+
| `SMART_CODING_EMBEDDING_MODEL` | string | `Xenova/all-MiniLM-L6-v2` | AI embedding model to use |
|
|
112
|
+
| `SMART_CODING_WORKER_THREADS` | string | `auto` | Worker threads (`auto` or 1-32) |
|
|
113
|
+
|
|
114
|
+
**Example with environment variables:**
|
|
115
|
+
|
|
116
|
+
```json
|
|
117
|
+
{
|
|
118
|
+
"mcpServers": {
|
|
119
|
+
"smart-coding-mcp": {
|
|
120
|
+
"command": "smart-coding-mcp",
|
|
121
|
+
"args": ["--workspace", "/path/to/project"],
|
|
122
|
+
"env": {
|
|
123
|
+
"SMART_CODING_VERBOSE": "true",
|
|
124
|
+
"SMART_CODING_BATCH_SIZE": "200",
|
|
125
|
+
"SMART_CODING_MAX_FILE_SIZE": "2097152"
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
**Note**: The server starts instantly and indexes in the background, so your IDE won't be blocked waiting for indexing to complete.
|
|
133
|
+
|
|
134
|
+
## Available Tools
|
|
135
|
+
|
|
136
|
+
**semantic_search** - Find code by meaning
|
|
137
|
+
|
|
138
|
+
```
|
|
139
|
+
Query: "Where do we validate user input?"
|
|
140
|
+
Returns: Relevant validation code with file paths and line numbers
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
**index_codebase** - Manually trigger reindexing
|
|
144
|
+
|
|
145
|
+
```
|
|
146
|
+
Use after major refactoring or branch switches
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
**clear_cache** - Reset the embeddings cache
|
|
150
|
+
|
|
151
|
+
```
|
|
152
|
+
Useful when cache becomes corrupted or outdated
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
## How It Works
|
|
156
|
+
|
|
157
|
+
The server indexes your code in four steps:
|
|
158
|
+
|
|
159
|
+
1. **Discovery**: Scans your project for source files
|
|
160
|
+
2. **Chunking**: Breaks code into meaningful pieces (respecting function boundaries)
|
|
161
|
+
3. **Embedding**: Converts each chunk to a vector using a local AI model
|
|
162
|
+
4. **Storage**: Saves embeddings to `.smart-coding-cache/` for fast startup
|
|
163
|
+
|
|
164
|
+
When you search, your query is converted to the same vector format and compared against all code chunks using cosine similarity. The most relevant matches are returned.
|
|
165
|
+
|
|
166
|
+

|
|
167
|
+
|
|
168
|
+
## Examples
|
|
169
|
+
|
|
170
|
+
**Natural language search:**
|
|
171
|
+
|
|
172
|
+
Query: "How do we handle cache persistence?"
|
|
173
|
+
|
|
174
|
+
Result:
|
|
175
|
+
|
|
176
|
+
```javascript
|
|
177
|
+
// lib/cache.js (Relevance: 38.2%)
|
|
178
|
+
async save() {
|
|
179
|
+
await fs.writeFile(cacheFile, JSON.stringify(this.vectorStore));
|
|
180
|
+
await fs.writeFile(hashFile, JSON.stringify(this.fileHashes));
|
|
181
|
+
}
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
**Typo tolerance:**
|
|
185
|
+
|
|
186
|
+
Query: "embeding modle initializashun"
|
|
187
|
+
|
|
188
|
+
Still finds embedding model initialization code despite multiple typos.
|
|
189
|
+
|
|
190
|
+
**Conceptual search:**
|
|
191
|
+
|
|
192
|
+
Query: "error handling and exceptions"
|
|
193
|
+
|
|
194
|
+
Finds all try/catch blocks and error handling patterns.
|
|
195
|
+
|
|
196
|
+
## Privacy
|
|
197
|
+
|
|
198
|
+
- AI model runs entirely on your machine
|
|
199
|
+
- No network requests to external services
|
|
200
|
+
- No telemetry or analytics
|
|
201
|
+
- Cache stored locally in `.smart-coding-cache/`
|
|
202
|
+
|
|
203
|
+
## Technical Details
|
|
204
|
+
|
|
205
|
+
**Embedding Model**: all-MiniLM-L6-v2 via transformers.js
|
|
206
|
+
|
|
207
|
+
- Fast inference (CPU-friendly)
|
|
208
|
+
- Small model size (~100MB)
|
|
209
|
+
- Good accuracy for code search
|
|
210
|
+
|
|
211
|
+
**Vector Similarity**: Cosine similarity
|
|
212
|
+
|
|
213
|
+
- Efficient comparison of embeddings
|
|
214
|
+
- Normalized vectors for consistent scoring
|
|
215
|
+
|
|
216
|
+
**Hybrid Scoring**: Combines semantic similarity with exact text matching
|
|
217
|
+
|
|
218
|
+
- Semantic weight: 0.7 (configurable)
|
|
219
|
+
- Exact match boost: 1.5x (configurable)
|
|
220
|
+
|
|
221
|
+
## Research Background
|
|
222
|
+
|
|
223
|
+
This project builds on research from Cursor showing that semantic search improves AI coding agent performance by 12.5% on average across question-answering tasks. The key insight is that AI assistants benefit more from relevant context than from large amounts of context.
|
|
224
|
+
|
|
225
|
+
See: https://cursor.com/blog/semsearch
|
|
226
|
+
|
|
227
|
+
## License
|
|
228
|
+
|
|
229
|
+
MIT License
|
|
230
|
+
|
|
231
|
+
Copyright (c) 2025 Omar Haris
|
|
232
|
+
|
|
233
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
234
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
235
|
+
in the Software without restriction, including without limitation the rights
|
|
236
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
237
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
238
|
+
furnished to do so, subject to the following conditions:
|
|
239
|
+
|
|
240
|
+
The above copyright notice and this permission notice shall be included in all
|
|
241
|
+
copies or substantial portions of the Software.
|
|
242
|
+
|
|
243
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
244
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
245
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
246
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
247
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
248
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
249
|
+
SOFTWARE.
|
package/config.json
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
{
|
|
2
|
+
"searchDirectory": ".",
|
|
3
|
+
"fileExtensions": [
|
|
4
|
+
"js",
|
|
5
|
+
"ts",
|
|
6
|
+
"jsx",
|
|
7
|
+
"tsx",
|
|
8
|
+
"mjs",
|
|
9
|
+
"cjs",
|
|
10
|
+
"css",
|
|
11
|
+
"scss",
|
|
12
|
+
"sass",
|
|
13
|
+
"less",
|
|
14
|
+
"html",
|
|
15
|
+
"htm",
|
|
16
|
+
"xml",
|
|
17
|
+
"svg",
|
|
18
|
+
"py",
|
|
19
|
+
"pyw",
|
|
20
|
+
"java",
|
|
21
|
+
"kt",
|
|
22
|
+
"scala",
|
|
23
|
+
"c",
|
|
24
|
+
"cpp",
|
|
25
|
+
"h",
|
|
26
|
+
"hpp",
|
|
27
|
+
"cs",
|
|
28
|
+
"go",
|
|
29
|
+
"rs",
|
|
30
|
+
"rb",
|
|
31
|
+
"php",
|
|
32
|
+
"swift",
|
|
33
|
+
"sh",
|
|
34
|
+
"bash",
|
|
35
|
+
"json",
|
|
36
|
+
"yaml",
|
|
37
|
+
"yml",
|
|
38
|
+
"toml",
|
|
39
|
+
"sql"
|
|
40
|
+
],
|
|
41
|
+
"excludePatterns": [
|
|
42
|
+
"**/node_modules/**",
|
|
43
|
+
"**/dist/**",
|
|
44
|
+
"**/build/**",
|
|
45
|
+
"**/.git/**",
|
|
46
|
+
"**/coverage/**",
|
|
47
|
+
"**/.next/**",
|
|
48
|
+
"**/target/**",
|
|
49
|
+
"**/vendor/**",
|
|
50
|
+
"**/.smart-coding-cache/**"
|
|
51
|
+
],
|
|
52
|
+
"smartIndexing": true,
|
|
53
|
+
"chunkSize": 25,
|
|
54
|
+
"chunkOverlap": 5,
|
|
55
|
+
"batchSize": 100,
|
|
56
|
+
"maxFileSize": 1048576,
|
|
57
|
+
"maxResults": 5,
|
|
58
|
+
"enableCache": true,
|
|
59
|
+
"cacheDirectory": "./.smart-coding-cache",
|
|
60
|
+
"watchFiles": false,
|
|
61
|
+
"verbose": false,
|
|
62
|
+
"embeddingModel": "Xenova/all-MiniLM-L6-v2",
|
|
63
|
+
"semanticWeight": 0.7,
|
|
64
|
+
"exactMatchBoost": 1.5,
|
|
65
|
+
"workerThreads": "auto"
|
|
66
|
+
}
|
package/example.png
ADDED
|
Binary file
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
export class CacheClearer {
|
|
2
|
+
constructor(embedder, cache, config, indexer) {
|
|
3
|
+
this.cache = cache;
|
|
4
|
+
this.config = config;
|
|
5
|
+
this.indexer = indexer;
|
|
6
|
+
this.isClearing = false;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
async execute() {
|
|
10
|
+
// Check if indexing is in progress
|
|
11
|
+
if (this.indexer && this.indexer.isIndexing) {
|
|
12
|
+
throw new Error("Cannot clear cache while indexing is in progress. Please wait for indexing to complete.");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Check if cache is currently being saved (race condition prevention)
|
|
16
|
+
if (this.cache.isSaving) {
|
|
17
|
+
throw new Error("Cannot clear cache while cache is being saved. Please try again in a moment.");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Check if a clear operation is already in progress (prevent concurrent clears)
|
|
21
|
+
if (this.isClearing) {
|
|
22
|
+
throw new Error("Cache clear operation already in progress. Please wait for it to complete.");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
this.isClearing = true;
|
|
26
|
+
|
|
27
|
+
try {
|
|
28
|
+
await this.cache.clear();
|
|
29
|
+
return {
|
|
30
|
+
success: true,
|
|
31
|
+
message: `Cache cleared successfully. Next indexing will be a full rebuild.`,
|
|
32
|
+
cacheDirectory: this.config.cacheDirectory
|
|
33
|
+
};
|
|
34
|
+
} finally {
|
|
35
|
+
this.isClearing = false;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function getToolDefinition() {
|
|
41
|
+
return {
|
|
42
|
+
name: "c_clear_cache",
|
|
43
|
+
description: "Clears the embeddings cache, forcing a complete reindex on next search or manual index operation. Useful when encountering cache corruption or after major codebase changes.",
|
|
44
|
+
inputSchema: {
|
|
45
|
+
type: "object",
|
|
46
|
+
properties: {}
|
|
47
|
+
},
|
|
48
|
+
annotations: {
|
|
49
|
+
title: "Clear Embeddings Cache",
|
|
50
|
+
readOnlyHint: false,
|
|
51
|
+
destructiveHint: true,
|
|
52
|
+
idempotentHint: true,
|
|
53
|
+
openWorldHint: false
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function handleToolCall(request, cacheClearer) {
|
|
59
|
+
try {
|
|
60
|
+
const result = await cacheClearer.execute();
|
|
61
|
+
return {
|
|
62
|
+
content: [{
|
|
63
|
+
type: "text",
|
|
64
|
+
text: `${result.message}\n\nCache directory: ${result.cacheDirectory}`
|
|
65
|
+
}]
|
|
66
|
+
};
|
|
67
|
+
} catch (error) {
|
|
68
|
+
return {
|
|
69
|
+
content: [{
|
|
70
|
+
type: "text",
|
|
71
|
+
text: `Failed to clear cache: ${error.message}`
|
|
72
|
+
}]
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import path from "path";
|
|
2
|
+
import { dotSimilarity } from "../lib/utils.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* FindSimilarCode feature
|
|
6
|
+
* Given a code snippet, finds similar patterns elsewhere in the codebase
|
|
7
|
+
*/
|
|
8
|
+
export class FindSimilarCode {
|
|
9
|
+
constructor(embedder, cache, config) {
|
|
10
|
+
this.embedder = embedder;
|
|
11
|
+
this.cache = cache;
|
|
12
|
+
this.config = config;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async execute({ code, maxResults = 5, minSimilarity = 0.3 }) {
|
|
16
|
+
const vectorStore = this.cache.getVectorStore();
|
|
17
|
+
|
|
18
|
+
if (vectorStore.length === 0) {
|
|
19
|
+
return {
|
|
20
|
+
results: [],
|
|
21
|
+
message: "No code has been indexed yet. Please wait for initial indexing to complete."
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Generate embedding for the input code
|
|
26
|
+
const codeEmbed = await this.embedder(code, { pooling: "mean", normalize: true });
|
|
27
|
+
const codeVector = Array.from(codeEmbed.data);
|
|
28
|
+
|
|
29
|
+
// Score all chunks by similarity
|
|
30
|
+
const scoredChunks = vectorStore.map(chunk => {
|
|
31
|
+
const similarity = dotSimilarity(codeVector, chunk.vector);
|
|
32
|
+
return { ...chunk, similarity };
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
// Filter by minimum similarity and sort
|
|
36
|
+
const filteredResults = scoredChunks
|
|
37
|
+
.filter(chunk => chunk.similarity >= minSimilarity)
|
|
38
|
+
.sort((a, b) => b.similarity - a.similarity);
|
|
39
|
+
|
|
40
|
+
// Deduplicate: if input code is from indexed file, skip exact matches
|
|
41
|
+
const normalizedInput = code.trim().replace(/\s+/g, ' ');
|
|
42
|
+
const results = filteredResults
|
|
43
|
+
.filter(chunk => {
|
|
44
|
+
const normalizedChunk = chunk.content.trim().replace(/\s+/g, ' ');
|
|
45
|
+
// Skip if it's essentially the same code (>95% similar text)
|
|
46
|
+
return normalizedChunk !== normalizedInput;
|
|
47
|
+
})
|
|
48
|
+
.slice(0, maxResults);
|
|
49
|
+
|
|
50
|
+
return {
|
|
51
|
+
results,
|
|
52
|
+
message: results.length === 0 ? "No similar code found above the similarity threshold." : null
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
formatResults(results) {
|
|
57
|
+
if (results.length === 0) {
|
|
58
|
+
return "No similar code patterns found in the codebase.";
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return results.map((r, idx) => {
|
|
62
|
+
const relPath = path.relative(this.config.searchDirectory, r.file);
|
|
63
|
+
return `## Similar Code ${idx + 1} (Similarity: ${(r.similarity * 100).toFixed(1)}%)\n` +
|
|
64
|
+
`**File:** \`${relPath}\`\n` +
|
|
65
|
+
`**Lines:** ${r.startLine}-${r.endLine}\n\n` +
|
|
66
|
+
"```" + path.extname(r.file).slice(1) + "\n" +
|
|
67
|
+
r.content + "\n" +
|
|
68
|
+
"```\n";
|
|
69
|
+
}).join("\n");
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// MCP Tool definition
|
|
74
|
+
export function getToolDefinition(config) {
|
|
75
|
+
return {
|
|
76
|
+
name: "d_find_similar_code",
|
|
77
|
+
description: "Find similar code patterns in the codebase. Given a code snippet, returns other code chunks that are semantically similar. Useful for finding duplicate code, understanding patterns, and refactoring opportunities.",
|
|
78
|
+
inputSchema: {
|
|
79
|
+
type: "object",
|
|
80
|
+
properties: {
|
|
81
|
+
code: {
|
|
82
|
+
type: "string",
|
|
83
|
+
description: "The code snippet to find similar patterns for"
|
|
84
|
+
},
|
|
85
|
+
maxResults: {
|
|
86
|
+
type: "number",
|
|
87
|
+
description: "Maximum number of similar code chunks to return (default: 5)",
|
|
88
|
+
default: 5
|
|
89
|
+
},
|
|
90
|
+
minSimilarity: {
|
|
91
|
+
type: "number",
|
|
92
|
+
description: "Minimum similarity threshold 0-1 (default: 0.3 = 30%)",
|
|
93
|
+
default: 0.3
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
required: ["code"]
|
|
97
|
+
},
|
|
98
|
+
annotations: {
|
|
99
|
+
title: "Find Similar Code",
|
|
100
|
+
readOnlyHint: true,
|
|
101
|
+
destructiveHint: false,
|
|
102
|
+
idempotentHint: true,
|
|
103
|
+
openWorldHint: false
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Tool handler
|
|
109
|
+
export async function handleToolCall(request, findSimilarCode) {
|
|
110
|
+
const code = request.params.arguments.code;
|
|
111
|
+
const maxResults = request.params.arguments.maxResults || 5;
|
|
112
|
+
const minSimilarity = request.params.arguments.minSimilarity || 0.3;
|
|
113
|
+
|
|
114
|
+
const { results, message } = await findSimilarCode.execute({ code, maxResults, minSimilarity });
|
|
115
|
+
|
|
116
|
+
if (message) {
|
|
117
|
+
return {
|
|
118
|
+
content: [{ type: "text", text: message }]
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const formattedText = findSimilarCode.formatResults(results);
|
|
123
|
+
|
|
124
|
+
return {
|
|
125
|
+
content: [{ type: "text", text: formattedText }]
|
|
126
|
+
};
|
|
127
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import path from "path";
|
|
2
|
+
import fs from "fs/promises";
|
|
3
|
+
import { dotSimilarity } from "../lib/utils.js";
|
|
4
|
+
|
|
5
|
+
export class HybridSearch {
|
|
6
|
+
constructor(embedder, cache, config) {
|
|
7
|
+
this.embedder = embedder;
|
|
8
|
+
this.cache = cache;
|
|
9
|
+
this.config = config;
|
|
10
|
+
this.fileModTimes = new Map(); // Cache for file modification times
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
async populateFileModTimes(files) {
|
|
14
|
+
const uniqueFiles = new Set(files);
|
|
15
|
+
const missing = [];
|
|
16
|
+
|
|
17
|
+
for (const file of uniqueFiles) {
|
|
18
|
+
if (!this.fileModTimes.has(file)) {
|
|
19
|
+
missing.push(file);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
if (missing.length === 0) {
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const BATCH_SIZE = 200;
|
|
28
|
+
for (let i = 0; i < missing.length; i += BATCH_SIZE) {
|
|
29
|
+
const batch = missing.slice(i, i + BATCH_SIZE);
|
|
30
|
+
await Promise.all(batch.map(async file => {
|
|
31
|
+
try {
|
|
32
|
+
const stats = await fs.stat(file);
|
|
33
|
+
this.fileModTimes.set(file, stats.mtimeMs);
|
|
34
|
+
} catch {
|
|
35
|
+
this.fileModTimes.set(file, null);
|
|
36
|
+
}
|
|
37
|
+
}));
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Cache invalidation helper
|
|
42
|
+
clearFileModTime(file) {
|
|
43
|
+
this.fileModTimes.delete(file);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async search(query, maxResults) {
|
|
47
|
+
const vectorStore = this.cache.getVectorStore();
|
|
48
|
+
|
|
49
|
+
if (vectorStore.length === 0) {
|
|
50
|
+
return {
|
|
51
|
+
results: [],
|
|
52
|
+
message: "No code has been indexed yet. Please wait for initial indexing to complete."
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Generate query embedding
|
|
57
|
+
const queryEmbed = await this.embedder(query, { pooling: "mean", normalize: true });
|
|
58
|
+
const queryVector = Array.from(queryEmbed.data);
|
|
59
|
+
|
|
60
|
+
if (this.config.recencyBoost > 0) {
|
|
61
|
+
await this.populateFileModTimes(vectorStore.map(chunk => chunk.file));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Score all chunks (synchronous map now, much faster)
|
|
65
|
+
const scoredChunks = vectorStore.map(chunk => {
|
|
66
|
+
// Semantic similarity (vectors are normalized)
|
|
67
|
+
let score = dotSimilarity(queryVector, chunk.vector) * this.config.semanticWeight;
|
|
68
|
+
|
|
69
|
+
// Exact match boost
|
|
70
|
+
const lowerQuery = query.toLowerCase();
|
|
71
|
+
const lowerContent = chunk.content.toLowerCase();
|
|
72
|
+
|
|
73
|
+
if (lowerContent.includes(lowerQuery)) {
|
|
74
|
+
score += this.config.exactMatchBoost;
|
|
75
|
+
} else {
|
|
76
|
+
// Partial word matching
|
|
77
|
+
const queryWords = lowerQuery.split(/\s+/);
|
|
78
|
+
const matchedWords = queryWords.filter(word =>
|
|
79
|
+
word.length > 2 && lowerContent.includes(word)
|
|
80
|
+
).length;
|
|
81
|
+
score += (matchedWords / queryWords.length) * 0.3;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Recency boost - recently modified files rank higher
|
|
85
|
+
if (this.config.recencyBoost > 0) {
|
|
86
|
+
const mtime = this.fileModTimes.get(chunk.file);
|
|
87
|
+
if (typeof mtime === "number") {
|
|
88
|
+
const daysSinceModified = (Date.now() - mtime) / (1000 * 60 * 60 * 24);
|
|
89
|
+
const decayDays = this.config.recencyDecayDays || 30;
|
|
90
|
+
|
|
91
|
+
// Linear decay: full boost at 0 days, no boost after decayDays
|
|
92
|
+
const recencyScore = Math.max(0, 1 - (daysSinceModified / decayDays));
|
|
93
|
+
score += recencyScore * this.config.recencyBoost;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return { ...chunk, score };
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
// Get top results
|
|
101
|
+
const results = scoredChunks
|
|
102
|
+
.sort((a, b) => b.score - a.score)
|
|
103
|
+
.slice(0, maxResults);
|
|
104
|
+
|
|
105
|
+
return { results, message: null };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
formatResults(results) {
|
|
109
|
+
if (results.length === 0) {
|
|
110
|
+
return "No matching code found for your query.";
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return results.map((r, idx) => {
|
|
114
|
+
const relPath = path.relative(this.config.searchDirectory, r.file);
|
|
115
|
+
return `## Result ${idx + 1} (Relevance: ${(r.score * 100).toFixed(1)}%)\n` +
|
|
116
|
+
`**File:** \`${relPath}\`\n` +
|
|
117
|
+
`**Lines:** ${r.startLine}-${r.endLine}\n\n` +
|
|
118
|
+
"```" + path.extname(r.file).slice(1) + "\n" +
|
|
119
|
+
r.content + "\n" +
|
|
120
|
+
"```\n";
|
|
121
|
+
}).join("\n");
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// MCP Tool definition for this feature
|
|
126
|
+
export function getToolDefinition(config) {
|
|
127
|
+
return {
|
|
128
|
+
name: "a_semantic_search",
|
|
129
|
+
description: "Performs intelligent hybrid code search combining semantic understanding with exact text matching. Ideal for finding code by meaning (e.g., 'authentication logic', 'database queries') even with typos or variations. Returns the most relevant code snippets with file locations and line numbers.",
|
|
130
|
+
inputSchema: {
|
|
131
|
+
type: "object",
|
|
132
|
+
properties: {
|
|
133
|
+
query: {
|
|
134
|
+
type: "string",
|
|
135
|
+
description: "Search query - can be natural language (e.g., 'where do we handle user login') or specific terms"
|
|
136
|
+
},
|
|
137
|
+
maxResults: {
|
|
138
|
+
type: "number",
|
|
139
|
+
description: "Maximum number of results to return (default: from config)",
|
|
140
|
+
default: config.maxResults
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
required: ["query"]
|
|
144
|
+
},
|
|
145
|
+
annotations: {
|
|
146
|
+
title: "Semantic Code Search",
|
|
147
|
+
readOnlyHint: true,
|
|
148
|
+
destructiveHint: false,
|
|
149
|
+
idempotentHint: true,
|
|
150
|
+
openWorldHint: false
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Tool handler
|
|
156
|
+
export async function handleToolCall(request, hybridSearch) {
|
|
157
|
+
const query = request.params.arguments.query;
|
|
158
|
+
const maxResults = request.params.arguments.maxResults || hybridSearch.config.maxResults;
|
|
159
|
+
|
|
160
|
+
const { results, message } = await hybridSearch.search(query, maxResults);
|
|
161
|
+
|
|
162
|
+
if (message) {
|
|
163
|
+
return {
|
|
164
|
+
content: [{ type: "text", text: message }]
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const formattedText = hybridSearch.formatResults(results);
|
|
169
|
+
|
|
170
|
+
return {
|
|
171
|
+
content: [{ type: "text", text: formattedText }]
|
|
172
|
+
};
|
|
173
|
+
}
|