directory-indexer 0.1.5 → 0.1.7

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/dist/cli.js CHANGED
@@ -4,539 +4,11 @@ import { fileURLToPath } from "url";
4
4
  import { readFileSync } from "fs";
5
5
  import { dirname, join } from "path";
6
6
  import { indexDirectories } from "./indexing.js";
7
- import { getChunkContent, getFileContent, findSimilarFiles, searchContent } from "./search.js";
7
+ import { searchContent, findSimilarFiles, getFileContent } from "./search.js";
8
8
  import { loadConfig } from "./config.js";
9
9
  import { getIndexStatus } from "./storage.js";
10
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
11
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
12
- import { ListToolsRequestSchema, CallToolRequestSchema } from "@modelcontextprotocol/sdk/types.js";
13
- function isIndexToolArgs(args) {
14
- return typeof args === "object" && args !== null && typeof args.directory_path === "string";
15
- }
16
- function isSearchToolArgs(args) {
17
- return typeof args === "object" && args !== null && typeof args.query === "string";
18
- }
19
- function isSimilarFilesToolArgs(args) {
20
- return typeof args === "object" && args !== null && typeof args.file_path === "string";
21
- }
22
- function isGetContentToolArgs(args) {
23
- return typeof args === "object" && args !== null && typeof args.file_path === "string";
24
- }
25
- function isGetChunkToolArgs(args) {
26
- return typeof args === "object" && args !== null && typeof args.file_path === "string" && typeof args.chunk_id === "string";
27
- }
28
- async function handleIndexTool(args, config) {
29
- if (!isIndexToolArgs(args)) {
30
- throw new Error("directory_path is required");
31
- }
32
- const paths = args.directory_path.split(",").map((p) => p.trim());
33
- const result = await indexDirectories(paths, config);
34
- let responseText = `Indexed ${result.indexed} files, skipped ${result.skipped} files, ${result.failed} failed`;
35
- if (result.errors.length > 0) {
36
- responseText += `
37
- Errors: [
38
- `;
39
- result.errors.forEach((error) => {
40
- responseText += ` '${error}'
41
- `;
42
- });
43
- responseText += `]`;
44
- }
45
- return {
46
- content: [
47
- {
48
- type: "text",
49
- text: responseText
50
- }
51
- ]
52
- };
53
- }
54
- async function validateWorkspace(workspace) {
55
- if (!workspace) return { workspace };
56
- const config = (await import("./config.js")).loadConfig();
57
- const { getAvailableWorkspaces } = await import("./config.js");
58
- const availableWorkspaces = getAvailableWorkspaces(config);
59
- if (availableWorkspaces.includes(workspace)) {
60
- return { workspace };
61
- }
62
- const message = availableWorkspaces.length > 0 ? `Note: Workspace '${workspace}' not found. Searching all content instead. Available workspaces: ${availableWorkspaces.join(", ")}. Use server_info tool to see workspace details.` : `Note: Workspace '${workspace}' not found and no workspaces are configured. Searching all indexed content.`;
63
- return { workspace: void 0, message };
64
- }
65
- async function handleSearchTool(args) {
66
- if (!isSearchToolArgs(args)) {
67
- throw new Error("query is required");
68
- }
69
- const { workspace, message } = await validateWorkspace(args.workspace);
70
- const results = await searchContent(args.query, { limit: args.limit || 10, workspace });
71
- const response = message ? `${message}
72
-
73
- ${JSON.stringify(results, null, 2)}` : JSON.stringify(results, null, 2);
74
- return {
75
- content: [{ type: "text", text: response }]
76
- };
77
- }
78
- async function handleSimilarFilesTool(args) {
79
- if (!isSimilarFilesToolArgs(args)) {
80
- throw new Error("file_path is required");
81
- }
82
- const { workspace, message } = await validateWorkspace(args.workspace);
83
- const results = await findSimilarFiles(args.file_path, args.limit || 10, workspace);
84
- const response = message ? `${message}
85
-
86
- ${JSON.stringify(results, null, 2)}` : JSON.stringify(results, null, 2);
87
- return {
88
- content: [{ type: "text", text: response }]
89
- };
90
- }
91
- async function handleGetContentTool(args) {
92
- if (!isGetContentToolArgs(args)) {
93
- throw new Error("file_path is required");
94
- }
95
- const content = await getFileContent(args.file_path, args.chunks);
96
- return {
97
- content: [
98
- {
99
- type: "text",
100
- text: content
101
- }
102
- ]
103
- };
104
- }
105
- async function handleGetChunkTool(args) {
106
- if (!isGetChunkToolArgs(args)) {
107
- throw new Error("file_path and chunk_id are required");
108
- }
109
- const content = await getChunkContent(args.file_path, args.chunk_id);
110
- return {
111
- content: [
112
- {
113
- type: "text",
114
- text: content
115
- }
116
- ]
117
- };
118
- }
119
- async function handleServerInfoTool(version) {
120
- const status = await getIndexStatus();
121
- return {
122
- content: [
123
- {
124
- type: "text",
125
- text: JSON.stringify({
126
- name: "directory-indexer",
127
- version,
128
- status
129
- }, null, 2)
130
- }
131
- ]
132
- };
133
- }
134
- function formatErrorResponse(error) {
135
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
136
- return {
137
- content: [
138
- {
139
- type: "text",
140
- text: `Error: ${errorMessage}`
141
- }
142
- ],
143
- isError: true
144
- };
145
- }
146
- const __dirname$1 = dirname(fileURLToPath(import.meta.url));
147
- const packageJsonPath$1 = join(__dirname$1, "../package.json");
148
- const packageJson$1 = JSON.parse(readFileSync(packageJsonPath$1, "utf-8"));
149
- const VERSION$1 = packageJson$1.version;
150
- const MCP_TOOLS = [
151
- {
152
- name: "index",
153
- description: `Index directories to make their files searchable. Processes files to create vector embeddings for semantic search.
154
-
155
- When to use this tool:
156
- - User specifically requests indexing a directory as a knowledge base
157
- - Adding new documentation, code repositories, or file collections to search
158
- - Updating index when many files have changed
159
-
160
- How it works:
161
- - Recursively scans directories for supported file types
162
- - Extracts text content and splits into chunks
163
- - Generates vector embeddings for semantic similarity
164
- - Stores in database for fast retrieval
165
-
166
- Examples:
167
- - Index documentation: "/home/user/docs/project-wiki"
168
- - Index codebase: "/home/user/projects/api-server"
169
- - Index multiple directories: "/home/user/docs,/home/user/configs"
170
-
171
- Indexing can take several minutes for large directories. Most users will already have directories indexed and can directly use search tool. Use server_info to check current indexing status first.`,
172
- inputSchema: {
173
- type: "object",
174
- properties: {
175
- directory_path: {
176
- type: "string",
177
- description: 'Comma-separated list of absolute directory paths to index. Must be absolute paths since MCP server runs independently. Examples: "/home/user/projects" (Unix) or "C:\\Users\\user\\projects" (Windows)'
178
- }
179
- },
180
- required: ["directory_path"]
181
- }
182
- },
183
- {
184
- name: "search",
185
- description: `Search indexed files using natural language queries. Finds files containing content semantically similar to the query.
186
-
187
- When to use this tool:
188
- - Find documentation, guides, or explanations about specific topics
189
- - Locate code files implementing certain functionality or patterns
190
- - Discover configuration files, scripts, or settings related to a topic
191
- - Search for files covering specific concepts or technologies
192
-
193
- How it works:
194
- - Converts query to vector embedding using semantic similarity
195
- - Searches all indexed file chunks for relevant content
196
- - Groups results by file and calculates average relevance scores
197
- - Returns files ranked by relevance score
198
-
199
- Examples:
200
- - "database configuration and connection pooling setup" - finds config files, documentation about DB setup
201
- - "comprehensive error handling patterns and exception management" - finds code files with exception handling
202
- - "JWT authentication implementation and session management" - finds auth-related code and docs
203
- - "REST API documentation and endpoint specifications" - finds API guides, endpoint definitions
204
- - "Docker deployment scripts and CI/CD pipeline configuration" - finds deployment automation
205
-
206
- Returns files with similarity scores and chunk information. Use get_content to retrieve full file content or get_chunk to retrieve specific chunk content by chunk ID.
207
- - Groups results by file to avoid duplicates from multiple matching sections
208
-
209
- Response format:
210
- - Returns lightweight metadata including file paths, relevance scores, and chunk IDs
211
- - Use 'get_chunk' or 'get_content' tools to fetch actual content from search results
212
- - Chunks are sorted by relevance score within each file
213
- - Average similarity score calculated across all matching chunks per file
214
-
215
- Example queries:
216
- - "error handling patterns and exception management strategies" (finds try/catch, error classes, logging)
217
- - "database migration scripts and schema versioning approaches" (finds SQL, schema changes, migration files)
218
- - "authentication middleware and JWT token validation logic" (finds auth logic, JWT handling, middleware functions)`,
219
- inputSchema: {
220
- type: "object",
221
- properties: {
222
- query: {
223
- type: "string",
224
- description: "Natural language search query describing what you are looking for. Can be concepts, functionality, or specific technical terms."
225
- },
226
- limit: {
227
- type: "number",
228
- description: "Maximum number of files to return (default: 10). Each file may contain multiple matching chunks.",
229
- default: 10
230
- },
231
- workspace: {
232
- type: "string",
233
- description: "Optional workspace name to filter search results. Only files within the workspace directories will be searched. IMPORTANT: Use server_info tool first to discover available workspace names - using invalid workspace names will result in empty results."
234
- }
235
- },
236
- required: ["query"]
237
- }
238
- },
239
- {
240
- name: "similar_files",
241
- description: `Find files with content similar to a reference file. Uses semantic similarity to find related documents, code files, or any text content.
242
-
243
- When to use this tool:
244
- - Find documentation similar to a specific guide or README
245
- - Locate related code files, configuration files, or scripts
246
- - Discover alternative implementations or approaches
247
- - Find files covering similar topics or concepts
248
-
249
- How it works:
250
- - Analyzes the semantic content of the reference file
251
- - Compares against all indexed files using vector similarity
252
- - Returns files ranked by content similarity score
253
-
254
- Examples:
255
- - Given "deployment-guide.md" - finds other deployment docs, CI/CD guides, infrastructure setup
256
- - Given "troubleshooting.md" - finds other troubleshooting guides, FAQ files, error documentation
257
- - Given "config.yaml" - finds other configuration files, settings, environment setups
258
- - Given "auth.py" - finds other authentication modules, security code, middleware
259
-
260
- Returns file paths with similarity scores. Use get_content to read full files or get_chunk for specific sections.`,
261
- inputSchema: {
262
- type: "object",
263
- properties: {
264
- file_path: {
265
- type: "string",
266
- description: "Absolute or relative path to the reference file. This file must have been previously indexed."
267
- },
268
- limit: {
269
- type: "number",
270
- description: "Maximum number of similar files to return (default: 10). Results are sorted by similarity score.",
271
- default: 10
272
- },
273
- workspace: {
274
- type: "string",
275
- description: "Optional workspace name to filter results. Only files within the workspace directories will be considered. IMPORTANT: Use server_info tool first to discover available workspace names - using invalid workspace names will result in empty results."
276
- }
277
- },
278
- required: ["file_path"]
279
- }
280
- },
281
- {
282
- name: "get_content",
283
- description: `Retrieve the full content of a file or specific chunks. Reads files directly from the filesystem.
284
-
285
- When to use this tool:
286
- - Get complete file content after finding files through search
287
- - Read documentation, code files, or configuration files for analysis
288
- - Extract specific sections of large files using chunk ranges
289
- - Access any text-based file content
290
-
291
- How it works:
292
- - Reads files directly from filesystem (not from search index)
293
- - Returns entire file by default
294
- - Can return specific chunk ranges for indexed files
295
- - Preserves original formatting and content
296
-
297
- Examples:
298
- - Get full file: file_path="/home/user/docs/api.md"
299
- - Get specific chunks: file_path="/home/user/code/main.py", chunks="2-5"
300
- - Get single chunk: file_path="/home/user/config.json", chunks="1"
301
-
302
- Returns file content as text. Use this after search or similar_files to read actual content.`,
303
- inputSchema: {
304
- type: "object",
305
- properties: {
306
- file_path: {
307
- type: "string",
308
- description: "Absolute or relative path to the file to retrieve. File must be readable and text-based."
309
- },
310
- chunks: {
311
- type: "string",
312
- description: 'Optional chunk range specification. Examples: "3" (single chunk), "2-5" (chunks 2 through 5), "1-3" (first three chunks). Only works for indexed files.'
313
- }
314
- },
315
- required: ["file_path"]
316
- }
317
- },
318
- {
319
- name: "get_chunk",
320
- description: `Retrieve content of a specific chunk from an indexed file. Gets exact text segments identified during search.
321
-
322
- When to use this tool:
323
- - Get specific relevant sections after performing a search
324
- - Access only the most pertinent parts of large files
325
- - Retrieve content from high-scoring chunks identified in search results
326
- - Avoid reading entire files when only specific sections are needed
327
-
328
- How it works:
329
- - Files are split into overlapping text chunks during indexing
330
- - Each chunk has a sequential ID ("0", "1", "2", etc.)
331
- - Search results include chunk IDs for relevant sections
332
- - Returns the exact content that was semantically matched
333
-
334
- Examples:
335
- - After search returns chunk "3" from "api-docs.md" with high score
336
- - Get chunk content: file_path="/docs/api-docs.md", chunk_id="3"
337
- - Returns the specific text segment that matched your query
338
-
339
- Returns chunk content as text. Use this with chunk IDs from search results to get precise content sections.`,
340
- inputSchema: {
341
- type: "object",
342
- properties: {
343
- file_path: {
344
- type: "string",
345
- description: "Absolute or relative path to the indexed file containing the desired chunk."
346
- },
347
- chunk_id: {
348
- type: "string",
349
- description: 'ID of the specific chunk to retrieve. This is typically obtained from search results and is a sequential string like "0", "1", "2", etc.'
350
- }
351
- },
352
- required: ["file_path", "chunk_id"]
353
- }
354
- },
355
- {
356
- name: "server_info",
357
- description: `Get information about server status and indexed content. Shows what directories and files are available for search.
358
-
359
- When to use this tool:
360
- - REQUIRED: Check available workspace names before using workspace parameter in search or similar_files tools
361
- - Check what content is already indexed before performing searches
362
- - Verify system is working properly
363
- - See indexing statistics and status
364
- - Understand scope of available searchable content
365
-
366
- How it works:
367
- - Reports total indexed directories, files, and chunks
368
- - Shows database size and last indexing time
369
- - Lists all indexed directories with file counts
370
- - Lists all configured workspaces with their paths and file counts
371
- - Reports any errors or issues
372
-
373
- Examples:
374
- - Check workspaces before searching: "What workspaces are available?"
375
- - Check before searching: "What content is indexed?"
376
- - Verify after indexing: "Did the indexing complete successfully?"
377
- - Monitor system: "How many files are searchable?"
378
-
379
- Returns server version, indexing statistics, directory list, workspace information, and any errors. IMPORTANT: Always use this tool first to discover available workspace names when you need to search within specific workspaces.`,
380
- inputSchema: {
381
- type: "object",
382
- properties: {},
383
- additionalProperties: false
384
- }
385
- }
386
- ];
387
- async function startMcpServer(config) {
388
- const server = new Server(
389
- {
390
- name: "directory-indexer",
391
- version: VERSION$1
392
- },
393
- {
394
- capabilities: {
395
- tools: {}
396
- }
397
- }
398
- );
399
- server.setRequestHandler(ListToolsRequestSchema, async () => {
400
- return {
401
- tools: MCP_TOOLS
402
- };
403
- });
404
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
405
- const { name, arguments: args } = request.params;
406
- try {
407
- switch (name) {
408
- case "index":
409
- return await handleIndexTool(args, config);
410
- case "search":
411
- return await handleSearchTool(args);
412
- case "similar_files":
413
- return await handleSimilarFilesTool(args);
414
- case "get_content":
415
- return await handleGetContentTool(args);
416
- case "get_chunk":
417
- return await handleGetChunkTool(args);
418
- case "server_info":
419
- return await handleServerInfoTool(VERSION$1);
420
- default:
421
- throw new Error(`Unknown tool: ${name}`);
422
- }
423
- } catch (error) {
424
- return formatErrorResponse(error);
425
- }
426
- });
427
- const transport = new StdioServerTransport();
428
- await server.connect(transport);
429
- if (config.verbose) {
430
- console.error("MCP server started successfully");
431
- }
432
- }
433
- class PrerequisiteError extends Error {
434
- constructor(message, cause) {
435
- super(message);
436
- this.cause = cause;
437
- this.name = "PrerequisiteError";
438
- }
439
- }
440
- async function checkQdrant(config) {
441
- try {
442
- const response = await fetch(`${config.storage.qdrantEndpoint}/healthz`);
443
- return response.ok;
444
- } catch {
445
- return false;
446
- }
447
- }
448
- async function checkOllama(config) {
449
- try {
450
- const response = await fetch(`${config.embedding.endpoint}/api/tags`);
451
- return response.ok;
452
- } catch {
453
- return false;
454
- }
455
- }
456
- async function checkOllamaModel(config) {
457
- try {
458
- const response = await fetch(`${config.embedding.endpoint}/api/tags`);
459
- if (!response.ok) return false;
460
- const data = await response.json();
461
- const models = data.models || [];
462
- return models.some((model) => model.name.includes(config.embedding.model));
463
- } catch {
464
- return false;
465
- }
466
- }
467
- async function checkOpenAI(config) {
468
- if (!process.env.OPENAI_API_KEY) return false;
469
- try {
470
- const response = await fetch("https://api.openai.com/v1/embeddings", {
471
- method: "POST",
472
- headers: {
473
- "Content-Type": "application/json",
474
- "Authorization": `Bearer ${process.env.OPENAI_API_KEY}`
475
- },
476
- body: JSON.stringify({
477
- model: config.embedding.model,
478
- input: "test"
479
- })
480
- });
481
- return response.ok;
482
- } catch {
483
- return false;
484
- }
485
- }
486
- function createErrorMessage(qdrantOk, embeddingOk, provider) {
487
- const errors = [];
488
- if (!qdrantOk) {
489
- errors.push("Qdrant database is inaccessible");
490
- }
491
- if (!embeddingOk) {
492
- if (provider === "ollama") {
493
- errors.push("Ollama embedding service is inaccessible or model unavailable");
494
- } else if (provider === "openai") {
495
- errors.push("OpenAI API is inaccessible or key invalid");
496
- }
497
- }
498
- errors.push("");
499
- errors.push("For setup instructions, see: https://github.com/peteretelej/directory-indexer#setup");
500
- return errors.join("\n");
501
- }
502
- async function validateIndexPrerequisites(config) {
503
- const [qdrantOk, embeddingOk] = await Promise.all([
504
- checkQdrant(config),
505
- checkEmbeddingService(config)
506
- ]);
507
- if (!qdrantOk || !embeddingOk) {
508
- throw new PrerequisiteError(createErrorMessage(qdrantOk, embeddingOk, config.embedding.provider));
509
- }
510
- }
511
- async function validateSearchPrerequisites(config) {
512
- const qdrantOk = await checkQdrant(config);
513
- if (!qdrantOk) {
514
- throw new PrerequisiteError(createErrorMessage(false, true, config.embedding.provider));
515
- }
516
- }
517
- async function checkEmbeddingService(config) {
518
- switch (config.embedding.provider) {
519
- case "ollama":
520
- return await checkOllama(config) && await checkOllamaModel(config);
521
- case "openai":
522
- return await checkOpenAI(config);
523
- case "mock":
524
- return true;
525
- default:
526
- return false;
527
- }
528
- }
529
- async function getServiceStatus(config) {
530
- const [qdrantOk, embeddingOk] = await Promise.all([
531
- checkQdrant(config),
532
- checkEmbeddingService(config)
533
- ]);
534
- return {
535
- qdrant: qdrantOk,
536
- embedding: embeddingOk,
537
- embeddingProvider: config.embedding.provider
538
- };
539
- }
10
+ import { startMcpServer } from "./mcp.js";
11
+ import { validateIndexPrerequisites, validateSearchPrerequisites, getServiceStatus } from "./prerequisites.js";
540
12
  const __dirname = dirname(fileURLToPath(import.meta.url));
541
13
  const packageJsonPath = join(__dirname, "../package.json");
542
14
  const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
@@ -550,7 +22,7 @@ async function main() {
550
22
  await validateIndexPrerequisites(config);
551
23
  console.log(`Indexing ${paths.length} ${paths.length === 1 ? "directory" : "directories"}: ${paths.join(", ")}`);
552
24
  const result = await indexDirectories(paths, config);
553
- console.log(`Indexed ${result.indexed} files, skipped ${result.skipped} files, ${result.failed} failed`);
25
+ console.log(`Indexed ${result.indexed} files, skipped ${result.skipped} files, cleaned up ${result.deleted} deleted files, ${result.failed} failed`);
554
26
  if (result.errors.length > 0) {
555
27
  console.log(`Errors: [`);
556
28
  result.errors.forEach((error) => {
@@ -684,6 +156,39 @@ async function main() {
684
156
  }
685
157
  });
686
158
  }
159
+ if (status.workspaces.length > 0) {
160
+ console.log("");
161
+ console.log("WORKSPACES:");
162
+ console.log(` • ${status.workspaceHealth.healthy} healthy, ${status.workspaceHealth.warnings} warnings, ${status.workspaceHealth.errors} errors`);
163
+ if (status.workspaceHealth.errors > 0) {
164
+ console.log("");
165
+ console.log("WORKSPACE ERRORS:");
166
+ status.workspaceHealth.criticalIssues.forEach((issue) => {
167
+ console.log(` ❌ ${issue}`);
168
+ });
169
+ }
170
+ if (status.workspaceHealth.recommendations.length > 0) {
171
+ console.log("");
172
+ console.log("WORKSPACE RECOMMENDATIONS:");
173
+ status.workspaceHealth.recommendations.forEach((rec) => {
174
+ console.log(` 💡 ${rec}`);
175
+ });
176
+ }
177
+ if (options.verbose) {
178
+ console.log("");
179
+ console.log("WORKSPACE DETAILS:");
180
+ status.workspaces.forEach((workspace) => {
181
+ console.log("");
182
+ console.log(` Workspace: ${workspace.name}`);
183
+ console.log(` • Status: ${workspace.health.status}`);
184
+ console.log(` • Paths: ${workspace.paths.join(", ")}`);
185
+ console.log(` • Files: ${workspace.filesCount}, Chunks: ${workspace.chunksCount}`);
186
+ if (workspace.health.issues.length > 0) {
187
+ console.log(` • Issues: ${workspace.health.issues.join("; ")}`);
188
+ }
189
+ });
190
+ }
191
+ }
687
192
  if (!status.qdrantConsistency.isConsistent) {
688
193
  console.log("");
689
194
  console.log("SYSTEM STATUS:");