codesearch-mcp 0.0.9-alpha → 0.0.11-alpha
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/README.md +26 -14
- package/dist/app.js +24 -143
- package/dist/src/commands/BackfillCommand.d.ts +7 -0
- package/dist/src/commands/BackfillCommand.js +27 -0
- package/dist/src/commands/ICommand.d.ts +3 -0
- package/dist/src/commands/ICommand.js +2 -0
- package/dist/src/commands/IndexCommand.d.ts +9 -0
- package/dist/src/commands/IndexCommand.js +75 -0
- package/dist/src/commands/McpCommand.d.ts +7 -0
- package/dist/src/commands/McpCommand.js +21 -0
- package/dist/src/commands/SetupCommand.d.ts +4 -0
- package/dist/src/commands/SetupCommand.js +10 -0
- package/dist/src/config.d.ts +1 -0
- package/dist/src/config.js +41 -2
- package/dist/src/container.d.ts +15 -0
- package/dist/src/container.js +21 -0
- package/dist/src/db/entities/code-chunk.entity.d.ts +1 -1
- package/dist/src/db/entities/code-chunk.entity.js +2 -2
- package/dist/src/db/entities/code-symbol.entity.d.ts +10 -0
- package/dist/src/db/entities/code-symbol.entity.js +59 -0
- package/dist/src/db/index.d.ts +1 -2
- package/dist/src/db/index.js +3 -6
- package/dist/src/file-utils.d.ts +2 -1
- package/dist/src/file-utils.js +10 -5
- package/dist/src/graph.js +5 -4
- package/dist/src/help.js +1 -1
- package/dist/src/interfaces/IAstParser.d.ts +24 -0
- package/dist/src/interfaces/IAstParser.js +2 -0
- package/dist/src/interfaces/IEmbedder.d.ts +4 -0
- package/dist/src/interfaces/IEmbedder.js +2 -0
- package/dist/src/interrupt.d.ts +1 -3
- package/dist/src/interrupt.js +14 -16
- package/dist/src/services/AstParserService.d.ts +14 -0
- package/dist/src/services/AstParserService.js +256 -0
- package/dist/src/services/DatabaseService.d.ts +14 -0
- package/dist/src/services/DatabaseService.js +133 -0
- package/dist/src/services/IndexerService.d.ts +39 -0
- package/dist/src/services/IndexerService.js +286 -0
- package/dist/src/services/LoggerService.d.ts +12 -0
- package/dist/src/services/LoggerService.js +73 -0
- package/dist/src/services/McpServer.d.ts +13 -0
- package/dist/src/services/McpServer.js +411 -0
- package/dist/src/services/OllamaEmbedder.d.ts +9 -0
- package/dist/src/services/OllamaEmbedder.js +27 -0
- package/dist/src/services/SearcherService.d.ts +91 -0
- package/dist/src/services/SearcherService.js +453 -0
- package/dist/src/setup.js +23 -7
- package/package.json +11 -10
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.McpServer = void 0;
|
|
37
|
+
const fs = __importStar(require("fs"));
|
|
38
|
+
const path = __importStar(require("path"));
|
|
39
|
+
const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
|
|
40
|
+
const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
|
|
41
|
+
const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
|
|
42
|
+
const LoggerService_1 = require("./LoggerService");
|
|
43
|
+
const PKG_VERSION = (() => {
|
|
44
|
+
try {
|
|
45
|
+
return JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf-8')).version ?? '0.0.0';
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return '0.0.0';
|
|
49
|
+
}
|
|
50
|
+
})();
|
|
51
|
+
const SERVER_INSTRUCTIONS = `
|
|
52
|
+
You have access to a local semantic code search server. Use these tools to navigate unfamiliar codebases.
|
|
53
|
+
|
|
54
|
+
## Tools
|
|
55
|
+
|
|
56
|
+
- **list_projects** — call this first to see what projects are indexed and their exact names.
|
|
57
|
+
- **search_codebase** — semantic search across indexed source files. Returns file path, line number, and a code chunk.
|
|
58
|
+
- **read_file_range** — read a specific line range from any indexed file. Use this to expand context around a search result.
|
|
59
|
+
- **get_dependencies** — show what files a given file imports (direct or transitive). Use to understand what a file depends on.
|
|
60
|
+
- **get_dependents** — show which files import a given file (reverse graph). Use before refactoring to find all callers.
|
|
61
|
+
- **find_symbol** — find where a symbol (function, class, type, interface, variable) is defined by exact name. Faster than semantic search when you know the name.
|
|
62
|
+
- **list_files** — browse the directory tree of a project path. Use to understand project structure before reading files.
|
|
63
|
+
- **read_file** — read a complete file by absolute path with line numbers. Truncates at max_lines with a hint to continue.
|
|
64
|
+
|
|
65
|
+
## Recommended workflow
|
|
66
|
+
|
|
67
|
+
1. Use \`list_projects\` to discover available projects before filtering by \`project\`.
|
|
68
|
+
2. Use \`search_codebase\` to find relevant code by meaning.
|
|
69
|
+
3. If a result looks **truncated or incomplete** (e.g. you see only the middle of a function), call \`read_file_range\` with the returned \`file_path\` and \`start_line\` set to the **Line** number shown in the result. Example: if the result shows **Line:** 150, pass \`start_line: 150\`.
|
|
70
|
+
4. For exploratory searches where you expect results to span chunk boundaries, pass \`include_neighbors: true\` to automatically include the chunk before and after each match.
|
|
71
|
+
5. Use \`find_symbol\` when you know the exact name of a function or class and want its definition location immediately — faster than semantic search.
|
|
72
|
+
6. Use \`list_files\` to explore project structure (src/, components/, etc.) before diving into files.
|
|
73
|
+
7. Use \`read_file\` to read a complete file when you have its absolute path from \`search_codebase\` results.
|
|
74
|
+
|
|
75
|
+
## When to use read_file_range vs include_neighbors
|
|
76
|
+
|
|
77
|
+
- **include_neighbors: true** — good when you already know the context will be fragmented (e.g. searching for a class definition that's likely split across chunks).
|
|
78
|
+
- **read_file_range** — better when you want to read a precise section, or when a result looks cut off and you want to expand just that one file.
|
|
79
|
+
|
|
80
|
+
## Handling Code Structure
|
|
81
|
+
- **Class/Function limits**: Chunks often end abruptly. Always use \`read_file_range\` to find the closing brace or the beginning of a method if you suspect you're seeing only a fragment.
|
|
82
|
+
- **Cross-file references**: If you see a method call like \`this.validator.validate(data)\`, use \`search_codebase\` to find the definition of that \`validator\` service.
|
|
83
|
+
|
|
84
|
+
## Relevance scores
|
|
85
|
+
|
|
86
|
+
Lower score = better match (cosine distance). Results above the configured threshold are filtered out automatically.
|
|
87
|
+
|
|
88
|
+
## Dependency graph
|
|
89
|
+
|
|
90
|
+
\`get_dependencies\` and \`get_dependents\` require \`file_path\` (as returned by \`search_codebase\`) and \`project\` (from \`list_projects\`). Pass \`transitive: true\` for the full dependency chain. depType values: \`import\` | \`import-default\` | \`import-namespace\` | \`reexport\` | \`reexport-namespace\`. \`fromSymbol\` — the top-level class or function in the importing file that uses this import (null if ambiguous or not tracked).
|
|
91
|
+
`.trim();
|
|
92
|
+
class McpServer {
|
|
93
|
+
searcher;
|
|
94
|
+
config;
|
|
95
|
+
logger;
|
|
96
|
+
constructor(searcher, config, logger = LoggerService_1.LoggerService.silent()) {
|
|
97
|
+
this.searcher = searcher;
|
|
98
|
+
this.config = config;
|
|
99
|
+
this.logger = logger;
|
|
100
|
+
}
|
|
101
|
+
async start() {
|
|
102
|
+
const server = new index_js_1.Server({ name: 'local-rag', version: PKG_VERSION }, { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS });
|
|
103
|
+
server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({
|
|
104
|
+
tools: [
|
|
105
|
+
{
|
|
106
|
+
name: 'search_codebase',
|
|
107
|
+
description: 'Search local project codebase by semantic similarity',
|
|
108
|
+
inputSchema: {
|
|
109
|
+
type: 'object',
|
|
110
|
+
properties: {
|
|
111
|
+
query: { type: 'string' },
|
|
112
|
+
limit: { type: 'number', description: `Max results (default ${this.config.search.defaultLimit}, max ${this.config.search.maxLimit})` },
|
|
113
|
+
project: { type: 'string', description: 'Filter by project name (optional). Use list_projects to see available names.' },
|
|
114
|
+
include_neighbors: { type: 'boolean', description: 'Also include the chunk before and after each result from the same file (Small-to-Big retrieval). Useful when results look truncated.' },
|
|
115
|
+
},
|
|
116
|
+
required: ['query'],
|
|
117
|
+
},
|
|
118
|
+
},
|
|
119
|
+
{
|
|
120
|
+
name: 'list_projects',
|
|
121
|
+
description: 'List all indexed projects with their chunk counts',
|
|
122
|
+
inputSchema: { type: 'object', properties: {} },
|
|
123
|
+
},
|
|
124
|
+
{
|
|
125
|
+
name: 'read_file_range',
|
|
126
|
+
description: 'Read a specific line range from an indexed source file. Use this when a search result looks incomplete — read the surrounding lines to get full context.',
|
|
127
|
+
inputSchema: {
|
|
128
|
+
type: 'object',
|
|
129
|
+
properties: {
|
|
130
|
+
file_path: { type: 'string', description: 'File path as returned by search_codebase' },
|
|
131
|
+
start_line: { type: 'number', description: 'First line to read (1-based). Use the **Line** number from search_codebase results. Default: 1.' },
|
|
132
|
+
end_line: { type: 'number', description: 'Last line to read (1-based, inclusive). Default: start_line + 99.' },
|
|
133
|
+
},
|
|
134
|
+
required: ['file_path'],
|
|
135
|
+
},
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
name: 'get_dependencies',
|
|
139
|
+
description: 'Show what files a given file imports (direct or transitive). Use to understand what a file depends on before modifying it. depType values: import | import-default | import-namespace | reexport | reexport-namespace.',
|
|
140
|
+
inputSchema: {
|
|
141
|
+
type: 'object',
|
|
142
|
+
properties: {
|
|
143
|
+
file_path: { type: 'string', description: 'File path as returned by search_codebase' },
|
|
144
|
+
project: { type: 'string', description: 'Project name (use list_projects to find it)' },
|
|
145
|
+
symbol: { type: 'string', description: 'Filter to a specific imported symbol name (optional)' },
|
|
146
|
+
transitive: { type: 'boolean', description: 'Include transitive (indirect) dependencies. Default: false.' },
|
|
147
|
+
},
|
|
148
|
+
required: ['file_path', 'project'],
|
|
149
|
+
},
|
|
150
|
+
},
|
|
151
|
+
{
|
|
152
|
+
name: 'get_dependents',
|
|
153
|
+
description: 'Show which files import a given file (reverse graph). Use before refactoring to find all callers and avoid breaking changes. depType values: import | import-default | import-namespace | reexport | reexport-namespace.',
|
|
154
|
+
inputSchema: {
|
|
155
|
+
type: 'object',
|
|
156
|
+
properties: {
|
|
157
|
+
file_path: { type: 'string', description: 'File path as returned by search_codebase' },
|
|
158
|
+
project: { type: 'string', description: 'Project name (use list_projects to find it)' },
|
|
159
|
+
symbol: { type: 'string', description: 'Exported symbol name. Two behaviors: (1) if graph dependents exist, narrows them to imports of this symbol; (2) if the import graph returns zero results, triggers a whole-word text-search fallback (grep -F -w) across all .ts/.tsx/.js/.jsx files in the project to find runtime usages — DI containers, singletons, dynamic lookups, string references. Capped at 200 matches.' },
|
|
160
|
+
transitive: { type: 'boolean', description: 'Include transitive (indirect) dependents. Default: false.' },
|
|
161
|
+
},
|
|
162
|
+
required: ['file_path', 'project'],
|
|
163
|
+
},
|
|
164
|
+
},
|
|
165
|
+
{
|
|
166
|
+
name: 'find_symbol',
|
|
167
|
+
description: 'Find TypeScript/JavaScript symbol definitions (functions, classes, types, interfaces, variables) by exact name. Use when you know the symbol name and want its definition location fast.',
|
|
168
|
+
inputSchema: {
|
|
169
|
+
type: 'object',
|
|
170
|
+
properties: {
|
|
171
|
+
name: { type: 'string', description: 'Exact symbol name (case-sensitive, whole-word match)' },
|
|
172
|
+
project: { type: 'string', description: 'Limit search to this project (optional). Use list_projects to find names.' },
|
|
173
|
+
kind: { type: 'string', enum: ['function', 'class', 'type', 'interface', 'variable', 'all'], description: 'Symbol kind filter. Default: all.' },
|
|
174
|
+
},
|
|
175
|
+
required: ['name'],
|
|
176
|
+
},
|
|
177
|
+
},
|
|
178
|
+
{
|
|
179
|
+
name: 'list_files',
|
|
180
|
+
description: 'List files and directories in a project path as an indented tree. Use to understand project structure before reading files.',
|
|
181
|
+
inputSchema: {
|
|
182
|
+
type: 'object',
|
|
183
|
+
properties: {
|
|
184
|
+
path: { type: 'string', description: 'Directory path relative to the project root (e.g. "src/components" or "." for root)' },
|
|
185
|
+
project: { type: 'string', description: 'Project name (from list_projects)' },
|
|
186
|
+
depth: { type: 'number', description: 'Tree depth: 1 = immediate children only, up to 5. Default: 2.' },
|
|
187
|
+
pattern: { type: 'string', description: 'Optional filename filter (substring or extension like ".ts"). Only matching files are shown.' },
|
|
188
|
+
},
|
|
189
|
+
required: ['path', 'project'],
|
|
190
|
+
},
|
|
191
|
+
},
|
|
192
|
+
{
|
|
193
|
+
name: 'read_file',
|
|
194
|
+
description: 'Read a file from the workspace by absolute path (as returned by search_codebase). Returns contents with line numbers. Truncates at max_lines with a hint to continue with read_file_range.',
|
|
195
|
+
inputSchema: {
|
|
196
|
+
type: 'object',
|
|
197
|
+
properties: {
|
|
198
|
+
file_path: { type: 'string', description: 'Absolute path to the file (as returned in filePath by search_codebase)' },
|
|
199
|
+
max_lines: { type: 'number', description: 'Maximum lines to return (default 300, max 1000)' },
|
|
200
|
+
},
|
|
201
|
+
required: ['file_path'],
|
|
202
|
+
},
|
|
203
|
+
},
|
|
204
|
+
],
|
|
205
|
+
}));
|
|
206
|
+
server.setRequestHandler(types_js_1.CallToolRequestSchema, async (req) => {
|
|
207
|
+
try {
|
|
208
|
+
if (req.params.name === 'list_projects') {
|
|
209
|
+
const rows = await this.searcher.listProjects();
|
|
210
|
+
if (rows.length === 0) {
|
|
211
|
+
return { content: [{ type: 'text', text: 'No indexed projects found.' }] };
|
|
212
|
+
}
|
|
213
|
+
return { content: [{ type: 'text', text: rows.map(r => {
|
|
214
|
+
const lines = [`${r.serviceName}: ${r.chunks} chunks`];
|
|
215
|
+
if (r.description)
|
|
216
|
+
lines.push(` description: ${r.description}`);
|
|
217
|
+
if (r.stack)
|
|
218
|
+
lines.push(` stack: ${r.stack}`);
|
|
219
|
+
if (r.notes)
|
|
220
|
+
lines.push(` notes: ${r.notes}`);
|
|
221
|
+
if (r.relations) {
|
|
222
|
+
for (const [key, val] of Object.entries(r.relations)) {
|
|
223
|
+
const list = Array.isArray(val) ? val.join(', ') : val;
|
|
224
|
+
lines.push(` ${key}: ${list}`);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return lines.join('\n');
|
|
228
|
+
}).join('\n\n') }] };
|
|
229
|
+
}
|
|
230
|
+
if (req.params.name === 'search_codebase') {
|
|
231
|
+
const raw = String(req.params.arguments?.query);
|
|
232
|
+
const limit = Math.min(Math.max(1, Number(req.params.arguments?.limit) || this.config.search.defaultLimit), this.config.search.maxLimit);
|
|
233
|
+
const project = req.params.arguments?.project ? String(req.params.arguments.project) : null;
|
|
234
|
+
const includeNeighbors = Boolean(req.params.arguments?.include_neighbors);
|
|
235
|
+
const { query, translated } = await this.searcher.prepareQuery(raw);
|
|
236
|
+
const results = await this.searcher.searchChunks(query, limit, project);
|
|
237
|
+
if (results.length === 0) {
|
|
238
|
+
return { content: [{ type: 'text', text: 'No relevant results found.' }] };
|
|
239
|
+
}
|
|
240
|
+
const header = translated ? `> Query translated: "${raw}" → "${query}"\n\n` : '';
|
|
241
|
+
if (includeNeighbors) {
|
|
242
|
+
const withNeighbors = await this.searcher.fetchNeighbors(results);
|
|
243
|
+
const blocks = withNeighbors.map(({ result, prevChunk, nextChunk }) => {
|
|
244
|
+
const parts = [];
|
|
245
|
+
if (prevChunk)
|
|
246
|
+
parts.push(this.formatChunk(prevChunk, 'prev chunk'));
|
|
247
|
+
parts.push(`${this.formatChunk(result)}\n**Relevance:** ${result.score}`);
|
|
248
|
+
if (nextChunk)
|
|
249
|
+
parts.push(this.formatChunk(nextChunk, 'next chunk'));
|
|
250
|
+
return parts.join('\n\n');
|
|
251
|
+
});
|
|
252
|
+
return { content: [{ type: 'text', text: header + blocks.join('\n\n---\n\n') }] };
|
|
253
|
+
}
|
|
254
|
+
const text = results
|
|
255
|
+
.map(r => `${this.formatChunk(r)}\n**Relevance:** ${r.score}`)
|
|
256
|
+
.join('\n\n---\n\n');
|
|
257
|
+
return { content: [{ type: 'text', text: header + text }] };
|
|
258
|
+
}
|
|
259
|
+
if (req.params.name === 'read_file_range') {
|
|
260
|
+
const filePath = String(req.params.arguments?.file_path);
|
|
261
|
+
const startLine = Math.max(1, Number(req.params.arguments?.start_line) || 1);
|
|
262
|
+
const endLine = Number(req.params.arguments?.end_line) || startLine + 99;
|
|
263
|
+
const range = await this.searcher.readFileRange(filePath, startLine, endLine);
|
|
264
|
+
if (!range.ok) {
|
|
265
|
+
const message = range.reason === 'invalid_path' ? `Invalid file path (outside workspace): ${filePath}` :
|
|
266
|
+
range.reason === 'not_indexed' ? `File is not indexed: ${filePath}. Run indexing first.` :
|
|
267
|
+
`File was deleted from disk after indexing: ${filePath}. Re-run indexing to update.`;
|
|
268
|
+
return { content: [{ type: 'text', text: message }] };
|
|
269
|
+
}
|
|
270
|
+
const numbered = range.lines.map((line, i) => `${startLine + i}: ${line}`).join('\n');
|
|
271
|
+
let text = `**File:** ${range.filePath}\n**Lines:** ${range.startLine}–${range.endLine}\n\`\`\`\n${numbered}\n\`\`\``;
|
|
272
|
+
if (range.hasMore) {
|
|
273
|
+
text += `\n\n[file has more lines — call read_file_range again with start_line: ${range.endLine + 1}]`;
|
|
274
|
+
}
|
|
275
|
+
return { content: [{ type: 'text', text }] };
|
|
276
|
+
}
|
|
277
|
+
if (req.params.name === 'get_dependencies') {
|
|
278
|
+
const filePath = String(req.params.arguments?.file_path);
|
|
279
|
+
const project = String(req.params.arguments?.project);
|
|
280
|
+
const symbol = req.params.arguments?.symbol ? String(req.params.arguments.symbol) : null;
|
|
281
|
+
const transitive = Boolean(req.params.arguments?.transitive);
|
|
282
|
+
const rows = await this.searcher.getDependencies(filePath, project, symbol, transitive);
|
|
283
|
+
if (rows.length === 0) {
|
|
284
|
+
return { content: [{ type: 'text', text: `No dependencies found for: ${filePath}` }] };
|
|
285
|
+
}
|
|
286
|
+
return { content: [{ type: 'text', text: this.formatDependencies(filePath, rows, transitive) }] };
|
|
287
|
+
}
|
|
288
|
+
if (req.params.name === 'get_dependents') {
|
|
289
|
+
const filePath = String(req.params.arguments?.file_path);
|
|
290
|
+
const project = String(req.params.arguments?.project);
|
|
291
|
+
const symbol = req.params.arguments?.symbol ? String(req.params.arguments.symbol) : null;
|
|
292
|
+
const transitive = Boolean(req.params.arguments?.transitive);
|
|
293
|
+
const rows = await this.searcher.getDependents(filePath, project, symbol, transitive);
|
|
294
|
+
if (rows.length > 0) {
|
|
295
|
+
return { content: [{ type: 'text', text: this.formatDependents(filePath, rows, transitive) }] };
|
|
296
|
+
}
|
|
297
|
+
const header = `**Dependents of** \`${filePath}\`\n\n**Direct:** No direct import dependents found.`;
|
|
298
|
+
if (!symbol) {
|
|
299
|
+
return { content: [{ type: 'text', text: `${header}\n\nTip: pass \`symbol\` to trigger a text-search fallback for runtime usages (e.g. via singleton or container).` }] };
|
|
300
|
+
}
|
|
301
|
+
const { matches, truncated } = this.searcher.grepSymbol(symbol, project, filePath);
|
|
302
|
+
if (matches.length === 0) {
|
|
303
|
+
return { content: [{ type: 'text', text: `${header}\n\n**Fallback \`[text search]\` for \`${symbol}\`:** No results.` }] };
|
|
304
|
+
}
|
|
305
|
+
const grouped = new Map();
|
|
306
|
+
for (const m of matches) {
|
|
307
|
+
if (!grouped.has(m.filePath))
|
|
308
|
+
grouped.set(m.filePath, []);
|
|
309
|
+
grouped.get(m.filePath).push(m.line);
|
|
310
|
+
}
|
|
311
|
+
const fallbackLines = [`\n**Fallback \`[text search]\` for \`${symbol}\`:**${truncated ? ' *(truncated to 200 results)*' : ''}`];
|
|
312
|
+
for (const [fp, lines] of grouped) {
|
|
313
|
+
fallbackLines.push(` ~ \`${fp}\`:${lines.join(', ')}`);
|
|
314
|
+
}
|
|
315
|
+
return { content: [{ type: 'text', text: header + fallbackLines.join('\n') }] };
|
|
316
|
+
}
|
|
317
|
+
if (req.params.name === 'find_symbol') {
|
|
318
|
+
const name = String(req.params.arguments?.name ?? '');
|
|
319
|
+
const project = req.params.arguments?.project ? String(req.params.arguments.project) : null;
|
|
320
|
+
const rawKind = req.params.arguments?.kind;
|
|
321
|
+
const validKinds = ['function', 'class', 'type', 'interface', 'variable', 'all'];
|
|
322
|
+
const kind = validKinds.includes(rawKind) ? rawKind : 'all';
|
|
323
|
+
const { hits, truncated } = await this.searcher.findSymbol(name, project, kind);
|
|
324
|
+
if (hits.length === 0) {
|
|
325
|
+
return { content: [{ type: 'text', text: `No definitions found for symbol: ${name}` }] };
|
|
326
|
+
}
|
|
327
|
+
const lines = [];
|
|
328
|
+
if (truncated)
|
|
329
|
+
lines.push(`*(truncated to ${hits.length} results)*\n`);
|
|
330
|
+
for (const h of hits) {
|
|
331
|
+
lines.push(`**${h.kind}** \`${h.filePath}\` line ${h.line}, col ${h.column}`);
|
|
332
|
+
lines.push(`\`\`\`\n${h.signature}\n\`\`\``);
|
|
333
|
+
}
|
|
334
|
+
return { content: [{ type: 'text', text: lines.join('\n') }] };
|
|
335
|
+
}
|
|
336
|
+
if (req.params.name === 'list_files') {
|
|
337
|
+
const relPath = String(req.params.arguments?.path ?? '.');
|
|
338
|
+
const project = String(req.params.arguments?.project ?? '');
|
|
339
|
+
const rawDepth = Number(req.params.arguments?.depth);
|
|
340
|
+
const depth = isNaN(rawDepth) || rawDepth < 1 ? 2 : Math.min(5, rawDepth);
|
|
341
|
+
const pattern = req.params.arguments?.pattern ? String(req.params.arguments.pattern) : null;
|
|
342
|
+
const { tree, error } = this.searcher.listFiles(relPath, project, depth, pattern);
|
|
343
|
+
if (error) {
|
|
344
|
+
return { content: [{ type: 'text', text: `list_files error: ${error}` }] };
|
|
345
|
+
}
|
|
346
|
+
return { content: [{ type: 'text', text: `**${project}/${relPath}**\n\`\`\`\n${tree}\n\`\`\`` }] };
|
|
347
|
+
}
|
|
348
|
+
if (req.params.name === 'read_file') {
|
|
349
|
+
const filePath = String(req.params.arguments?.file_path ?? '');
|
|
350
|
+
const rawMax = Number(req.params.arguments?.max_lines);
|
|
351
|
+
const maxLines = isNaN(rawMax) || rawMax < 1 ? 300 : Math.min(1000, rawMax);
|
|
352
|
+
const result = await this.searcher.readFileAbsolute(filePath, maxLines);
|
|
353
|
+
if (!result.ok) {
|
|
354
|
+
const message = result.reason === 'invalid_path' ? `Invalid path (outside workspace): ${filePath}` :
|
|
355
|
+
`File not found on disk: ${filePath}`;
|
|
356
|
+
return { content: [{ type: 'text', text: message }] };
|
|
357
|
+
}
|
|
358
|
+
const numbered = result.lines.map((line, i) => `${i + 1}: ${line}`).join('\n');
|
|
359
|
+
let text = `**File:** ${result.filePath}\n**Lines:** 1–${result.endLine}\n\`\`\`\n${numbered}\n\`\`\``;
|
|
360
|
+
if (result.hasMore) {
|
|
361
|
+
text += `\n\n[truncated: file has more lines — use read_file_range with file_path: "${result.filePath}", start_line: ${result.endLine + 1} to continue]`;
|
|
362
|
+
}
|
|
363
|
+
return { content: [{ type: 'text', text }] };
|
|
364
|
+
}
|
|
365
|
+
throw new Error(`Unknown tool: ${req.params.name}`);
|
|
366
|
+
}
|
|
367
|
+
catch (err) {
|
|
368
|
+
this.logger.error('McpServer: tool handler error', { tool: req.params.name, reason: err.message });
|
|
369
|
+
return { content: [{ type: 'text', text: `Tool error: ${err.message}` }] };
|
|
370
|
+
}
|
|
371
|
+
});
|
|
372
|
+
await server.connect(new stdio_js_1.StdioServerTransport());
|
|
373
|
+
}
|
|
374
|
+
formatChunk(r, label) {
|
|
375
|
+
return `${label ? `*(${label})*\n` : ''}**File:** ${r.filePath}\n**Project:** ${r.serviceName}\n**Line:** ${r.startLine}\n\`\`\`\n${r.content}\n\`\`\``;
|
|
376
|
+
}
|
|
377
|
+
formatDependencies(filePath, rows, transitive) {
|
|
378
|
+
const direct = rows.filter(r => !transitive || (r.depth ?? 1) === 1);
|
|
379
|
+
const indirect = transitive ? rows.filter(r => (r.depth ?? 1) > 1) : [];
|
|
380
|
+
const lines = [`**Dependencies of** \`${filePath}\`\n`, '**Direct:**'];
|
|
381
|
+
for (const r of direct) {
|
|
382
|
+
const sym = r.toSymbol ? ` (${r.depType} \`${r.toSymbol}\`)` : ` (${r.depType})`;
|
|
383
|
+
lines.push(` → \`${r.toFile}\`${sym}`);
|
|
384
|
+
}
|
|
385
|
+
if (indirect.length > 0) {
|
|
386
|
+
lines.push('\n**Transitive:**');
|
|
387
|
+
for (const r of indirect) {
|
|
388
|
+
const sym = r.toSymbol ? ` (\`${r.toSymbol}\`)` : '';
|
|
389
|
+
lines.push(` → \`${r.toFile}\`${sym} *(via ${r.via}, depth ${r.depth})*`);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
return lines.join('\n');
|
|
393
|
+
}
|
|
394
|
+
formatDependents(filePath, rows, transitive) {
|
|
395
|
+
const direct = rows.filter(r => !transitive || (r.depth ?? 1) === 1);
|
|
396
|
+
const indirect = transitive ? rows.filter(r => (r.depth ?? 1) > 1) : [];
|
|
397
|
+
const lines = [`**Dependents of** \`${filePath}\`\n`, '**Direct:**'];
|
|
398
|
+
for (const r of direct) {
|
|
399
|
+
const sym = r.toSymbol ? ` (imports \`${r.toSymbol}\`)` : '';
|
|
400
|
+
lines.push(` ← \`${r.fromFile}\`${sym}`);
|
|
401
|
+
}
|
|
402
|
+
if (indirect.length > 0) {
|
|
403
|
+
lines.push('\n**Transitive:**');
|
|
404
|
+
for (const r of indirect) {
|
|
405
|
+
lines.push(` ← \`${r.fromFile}\` *(via ${r.via}, depth ${r.depth})*`);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
return lines.join('\n');
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
exports.McpServer = McpServer;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Config } from '../config';
|
|
2
|
+
import type { IEmbedder } from '../interfaces/IEmbedder';
|
|
3
|
+
export declare class OllamaEmbedder implements IEmbedder {
|
|
4
|
+
private config;
|
|
5
|
+
private client;
|
|
6
|
+
constructor(config: Config);
|
|
7
|
+
embed(text: string): Promise<number[]>;
|
|
8
|
+
translate(text: string, model: string): Promise<string>;
|
|
9
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.OllamaEmbedder = void 0;
|
|
4
|
+
const ollama_1 = require("ollama");
|
|
5
|
+
class OllamaEmbedder {
|
|
6
|
+
config;
|
|
7
|
+
client;
|
|
8
|
+
constructor(config) {
|
|
9
|
+
this.config = config;
|
|
10
|
+
this.client = new ollama_1.Ollama({ host: config.ollama.host });
|
|
11
|
+
}
|
|
12
|
+
async embed(text) {
|
|
13
|
+
const { embedding } = await this.client.embeddings({
|
|
14
|
+
model: this.config.ollama.model,
|
|
15
|
+
prompt: text,
|
|
16
|
+
});
|
|
17
|
+
return embedding;
|
|
18
|
+
}
|
|
19
|
+
async translate(text, model) {
|
|
20
|
+
const response = await this.client.chat({
|
|
21
|
+
model,
|
|
22
|
+
messages: [{ role: 'user', content: `Translate the following text to English. Return only the translation, no explanations:\n${text}` }],
|
|
23
|
+
});
|
|
24
|
+
return response.message.content.trim();
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
exports.OllamaEmbedder = OllamaEmbedder;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { Config } from '../config';
|
|
2
|
+
import type { IEmbedder } from '../interfaces/IEmbedder';
|
|
3
|
+
import type { DatabaseService } from './DatabaseService';
|
|
4
|
+
import { type ProjectMeta } from '../file-utils';
|
|
5
|
+
import { LoggerService } from './LoggerService';
|
|
6
|
+
export interface ChunkRow {
|
|
7
|
+
serviceName: string;
|
|
8
|
+
filePath: string;
|
|
9
|
+
startLine: number;
|
|
10
|
+
content: string;
|
|
11
|
+
}
|
|
12
|
+
export interface SearchResult extends ChunkRow {
|
|
13
|
+
score: number;
|
|
14
|
+
}
|
|
15
|
+
export interface NeighborResult {
|
|
16
|
+
result: SearchResult;
|
|
17
|
+
prevChunk: ChunkRow | null;
|
|
18
|
+
nextChunk: ChunkRow | null;
|
|
19
|
+
}
|
|
20
|
+
export type FileRangeResult = {
|
|
21
|
+
ok: true;
|
|
22
|
+
filePath: string;
|
|
23
|
+
startLine: number;
|
|
24
|
+
endLine: number;
|
|
25
|
+
lines: string[];
|
|
26
|
+
hasMore: boolean;
|
|
27
|
+
} | {
|
|
28
|
+
ok: false;
|
|
29
|
+
reason: 'not_indexed' | 'not_on_disk' | 'invalid_path';
|
|
30
|
+
};
|
|
31
|
+
export interface DependencyRow {
|
|
32
|
+
fromFile: string;
|
|
33
|
+
fromSymbol: string | null;
|
|
34
|
+
toFile: string;
|
|
35
|
+
toSymbol: string | null;
|
|
36
|
+
depType: string;
|
|
37
|
+
depth?: number;
|
|
38
|
+
via?: string;
|
|
39
|
+
}
|
|
40
|
+
export interface ProjectRow extends ProjectMeta {
|
|
41
|
+
serviceName: string;
|
|
42
|
+
chunks: number;
|
|
43
|
+
}
|
|
44
|
+
export interface GrepMatch {
|
|
45
|
+
filePath: string;
|
|
46
|
+
line: number;
|
|
47
|
+
}
|
|
48
|
+
export type SymbolKind = 'function' | 'class' | 'type' | 'interface' | 'variable' | 'all';
|
|
49
|
+
export interface SymbolHit {
|
|
50
|
+
filePath: string;
|
|
51
|
+
line: number;
|
|
52
|
+
column: number;
|
|
53
|
+
kind: Exclude<SymbolKind, 'all'>;
|
|
54
|
+
signature: string;
|
|
55
|
+
}
|
|
56
|
+
export declare class SearcherService {
|
|
57
|
+
private db;
|
|
58
|
+
private embedder;
|
|
59
|
+
private config;
|
|
60
|
+
private logger;
|
|
61
|
+
constructor(db: DatabaseService, embedder: IEmbedder, config: Config, logger?: LoggerService);
|
|
62
|
+
prepareQuery(raw: string): Promise<{
|
|
63
|
+
query: string;
|
|
64
|
+
translated: boolean;
|
|
65
|
+
}>;
|
|
66
|
+
listProjects(): Promise<ProjectRow[]>;
|
|
67
|
+
searchChunks(query: string, limit: number, project: string | null): Promise<SearchResult[]>;
|
|
68
|
+
fetchNeighbors(results: SearchResult[]): Promise<NeighborResult[]>;
|
|
69
|
+
getDependencies(filePath: string, project: string, symbol?: string | null, transitive?: boolean): Promise<DependencyRow[]>;
|
|
70
|
+
getDependents(filePath: string, project: string, symbol?: string | null, transitive?: boolean): Promise<DependencyRow[]>;
|
|
71
|
+
grepSymbol(symbol: string, project: string, excludeFile: string): {
|
|
72
|
+
matches: GrepMatch[];
|
|
73
|
+
truncated: boolean;
|
|
74
|
+
};
|
|
75
|
+
findSymbol(name: string, project: string | null, kind: SymbolKind): Promise<{
|
|
76
|
+
hits: SymbolHit[];
|
|
77
|
+
truncated: boolean;
|
|
78
|
+
}>;
|
|
79
|
+
private findSymbolFromIndex;
|
|
80
|
+
private grepFindSymbol;
|
|
81
|
+
listFiles(relativePath: string, project: string, depth: number, pattern: string | null): {
|
|
82
|
+
tree: string;
|
|
83
|
+
error?: string;
|
|
84
|
+
};
|
|
85
|
+
readFileAbsolute(absPath: string, maxLines: number): Promise<FileRangeResult>;
|
|
86
|
+
readFileRange(filePath: string, startLine: number, endLine: number): Promise<FileRangeResult>;
|
|
87
|
+
private isNonEnglish;
|
|
88
|
+
private walkDir;
|
|
89
|
+
private buildFindSymbolPattern;
|
|
90
|
+
private inferKind;
|
|
91
|
+
}
|