directory-indexer 1.0.0 → 1.1.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.
@@ -1,8 +1,9 @@
1
1
  import { indexDirectories } from "./indexing.js";
2
2
  import { getChunkContent, getFileContent, searchContent, findSimilarFiles } from "./search.js";
3
- import { initializeStorage, getIndexStatus, SQLiteStorage } from "./storage.js";
4
- import { validateIndexPrerequisites, validateSearchPrerequisites } from "./prerequisites.js";
3
+ import { getIndexStatus, initializeStorage } from "./storage.js";
4
+ import { validateSearchPrerequisites, validateIndexPrerequisites } from "./prerequisites.js";
5
5
  import { validatePathWithinIndexedDirs, resolveIndexedDirectories } from "./path-validation.js";
6
+ import { normalizePath } from "./utils.js";
6
7
  import { log } from "./logger.js";
7
8
  import { resolve, sep } from "path";
8
9
  import { realpathSync } from "fs";
@@ -10,6 +11,10 @@ let mcpServer = null;
10
11
  function setMcpServer(server) {
11
12
  mcpServer = server;
12
13
  }
14
+ function notifyClient(level, data) {
15
+ mcpServer?.sendLoggingMessage({ level, data })?.catch(() => {
16
+ });
17
+ }
13
18
  function normalizeMutexKey(dirPath) {
14
19
  let normalized;
15
20
  try {
@@ -23,6 +28,28 @@ function normalizeMutexKey(dirPath) {
23
28
  return normalized;
24
29
  }
25
30
  const indexingMutex = /* @__PURE__ */ new Map();
31
+ async function withDirectoryMutex(keys, fn) {
32
+ const holders = keys.map((key) => indexingMutex.get(key));
33
+ const prior = Promise.all(holders.map((holder) => holder ?? Promise.resolve()));
34
+ let release;
35
+ const done = new Promise((resolve2) => {
36
+ release = resolve2;
37
+ });
38
+ const ticket = prior.then(() => done);
39
+ for (const key of keys) indexingMutex.set(key, ticket);
40
+ if (holders.some(Boolean)) {
41
+ log("info", "Waiting for ongoing indexing", { directories: keys });
42
+ }
43
+ await prior;
44
+ try {
45
+ return await fn();
46
+ } finally {
47
+ release();
48
+ for (const key of keys) {
49
+ if (indexingMutex.get(key) === ticket) indexingMutex.delete(key);
50
+ }
51
+ }
52
+ }
26
53
  let indexedDirsCache = /* @__PURE__ */ new Set();
27
54
  let indexedDirsCacheInitialized = false;
28
55
  function refreshIndexedDirsCache(storage) {
@@ -31,12 +58,8 @@ function refreshIndexedDirsCache(storage) {
31
58
  }
32
59
  async function ensureIndexedDirsCache(config) {
33
60
  if (!indexedDirsCacheInitialized) {
34
- const sqlite = new SQLiteStorage(config);
35
- try {
36
- refreshIndexedDirsCache(sqlite);
37
- } finally {
38
- sqlite.close();
39
- }
61
+ const { sqlite } = await initializeStorage(config);
62
+ refreshIndexedDirsCache(sqlite);
40
63
  }
41
64
  }
42
65
  function isIndexToolArgs(args) {
@@ -61,78 +84,58 @@ async function handleIndexTool(args, config) {
61
84
  if (!isIndexToolArgs(args)) {
62
85
  throw new Error("directory_paths is required and must be an array");
63
86
  }
64
- await validateIndexPrerequisites(config);
65
87
  const paths = args.directory_paths.map((p) => p.trim());
66
88
  const mutexKeys = paths.map(normalizeMutexKey);
67
- log("info", "Index start", { directories: paths });
68
- mcpServer?.sendLoggingMessage({ level: "info", data: { event: "index_start", directories: paths } });
69
- for (const key of mutexKeys) {
70
- const existing = indexingMutex.get(key);
71
- if (existing) {
72
- log("info", "Waiting for ongoing indexing", { directory: key });
73
- await existing;
74
- }
75
- }
76
- let resolveIndexing;
77
- const indexingPromise = new Promise((resolve2) => {
78
- resolveIndexing = resolve2;
79
- });
80
- for (const key of mutexKeys) {
81
- indexingMutex.set(key, indexingPromise);
82
- }
83
- try {
84
- const result = await indexDirectories(paths, config);
85
- const { sqlite } = await initializeStorage(config);
89
+ return withDirectoryMutex(mutexKeys, async () => {
90
+ await validateIndexPrerequisites(config);
91
+ log("info", "Index start", { directories: paths });
92
+ notifyClient("info", { event: "index_start", directories: paths });
86
93
  try {
94
+ const result = await indexDirectories(paths, config);
95
+ const { sqlite } = await initializeStorage(config);
87
96
  refreshIndexedDirsCache(sqlite);
88
- } finally {
89
- sqlite.close();
90
- }
91
- log("info", "Index complete", { result });
92
- mcpServer?.sendLoggingMessage({ level: "info", data: { event: "index_complete", result } });
93
- let responseText = `Indexed ${result.indexed} files, skipped ${result.skipped} files, cleaned up ${result.deleted} deleted files, ${result.failed} failed`;
94
- if (result.errors.length > 0) {
95
- responseText += `
97
+ log("info", "Index complete", { result });
98
+ notifyClient("info", { event: "index_complete", result });
99
+ let responseText = `Indexed ${result.indexed} files, skipped ${result.skipped} files, cleaned up ${result.deleted} deleted files, ${result.failed} failed`;
100
+ if (result.errors.length > 0) {
101
+ responseText += `
96
102
  Errors: [
97
103
  `;
98
- result.errors.forEach((error) => {
99
- responseText += ` '${error}'
104
+ result.errors.forEach((error) => {
105
+ responseText += ` '${error}'
100
106
  `;
101
- });
102
- responseText += `]`;
103
- }
104
- return {
105
- content: [
106
- {
107
- type: "text",
108
- text: responseText
109
- }
110
- ]
111
- };
112
- } catch (error) {
113
- const errorMessage = error instanceof Error ? error.message : String(error);
114
- log("error", "Index error", { error: errorMessage, directories: paths });
115
- mcpServer?.sendLoggingMessage({ level: "error", data: { event: "index_error", error: errorMessage } });
116
- throw new Error(
117
- `Indexing failed for ${paths.join(", ")}. Verify the directory exists and is readable. Use 'server_info' to check current status.`
118
- );
119
- } finally {
120
- resolveIndexing();
121
- for (const key of mutexKeys) {
122
- indexingMutex.delete(key);
107
+ });
108
+ responseText += `]`;
109
+ }
110
+ return {
111
+ content: [
112
+ {
113
+ type: "text",
114
+ text: responseText
115
+ }
116
+ ]
117
+ };
118
+ } catch (error) {
119
+ const errorMessage = error instanceof Error ? error.message : String(error);
120
+ log("error", "Index error", { error: errorMessage, directories: paths });
121
+ notifyClient("error", { event: "index_error", error: errorMessage });
122
+ throw new Error(
123
+ `Indexing failed for ${paths.join(", ")}. Verify the directory exists and is readable. Use 'server_info' to check current status.`
124
+ );
123
125
  }
124
- }
126
+ });
125
127
  }
126
128
  async function validateWorkspace(workspace) {
127
- if (!workspace) return { workspace };
129
+ if (!workspace) return workspace;
128
130
  const config = (await import("./config.js")).loadConfig();
129
131
  const { getAvailableWorkspaces } = await import("./config.js");
130
132
  const availableWorkspaces = getAvailableWorkspaces(config);
131
133
  if (availableWorkspaces.includes(workspace)) {
132
- return { workspace };
134
+ return workspace;
133
135
  }
134
- 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.`;
135
- return { workspace: void 0, message };
136
+ throw new Error(
137
+ availableWorkspaces.length > 0 ? `Workspace '${workspace}' not found. Available workspaces: ${availableWorkspaces.join(", ")}` : `Workspace '${workspace}' not found and no workspaces are configured.`
138
+ );
136
139
  }
137
140
  async function handleSearchTool(args) {
138
141
  if (!isSearchToolArgs(args)) {
@@ -140,13 +143,10 @@ async function handleSearchTool(args) {
140
143
  }
141
144
  const config = (await import("./config.js")).loadConfig();
142
145
  await validateSearchPrerequisites(config);
143
- const { workspace, message } = await validateWorkspace(args.workspace);
146
+ const workspace = await validateWorkspace(args.workspace);
144
147
  const results = await searchContent(args.query, { limit: args.limit || 10, workspace });
145
- const response = message ? `${message}
146
-
147
- ${JSON.stringify(results, null, 2)}` : JSON.stringify(results, null, 2);
148
148
  return {
149
- content: [{ type: "text", text: response }]
149
+ content: [{ type: "text", text: JSON.stringify(results, null, 2) }]
150
150
  };
151
151
  }
152
152
  async function handleSimilarFilesTool(args) {
@@ -155,13 +155,12 @@ async function handleSimilarFilesTool(args) {
155
155
  }
156
156
  const config = (await import("./config.js")).loadConfig();
157
157
  await validateSearchPrerequisites(config);
158
- const { workspace, message } = await validateWorkspace(args.workspace);
158
+ await ensureIndexedDirsCache(config);
159
+ validatePathWithinIndexedDirs(args.file_path, indexedDirsCache);
160
+ const workspace = await validateWorkspace(args.workspace);
159
161
  const results = await findSimilarFiles(args.file_path, args.limit || 10, workspace);
160
- const response = message ? `${message}
161
-
162
- ${JSON.stringify(results, null, 2)}` : JSON.stringify(results, null, 2);
163
162
  return {
164
- content: [{ type: "text", text: response }]
163
+ content: [{ type: "text", text: JSON.stringify(results, null, 2) }]
165
164
  };
166
165
  }
167
166
  async function handleGetContentTool(args, config) {
@@ -237,27 +236,22 @@ async function handleDeleteIndexTool(args, config) {
237
236
  if (!isDeleteIndexToolArgs(args)) {
238
237
  throw new Error("directory_path is required");
239
238
  }
240
- const dirPath = args.directory_path.trim();
241
- const mutexKey = normalizeMutexKey(dirPath);
242
- const existing = indexingMutex.get(mutexKey);
243
- if (existing) {
244
- log("info", "Waiting for ongoing indexing before delete", { directory: dirPath });
245
- await existing;
246
- }
247
- let resolveDelete;
248
- const deletePromise = new Promise((r) => {
249
- resolveDelete = r;
250
- });
251
- indexingMutex.set(mutexKey, deletePromise);
252
- const { sqlite, qdrant } = await initializeStorage(config);
253
- try {
254
- const directory = await sqlite.getDirectory(dirPath);
239
+ const trimmedPath = args.directory_path.trim();
240
+ const dirPath = normalizePath(trimmedPath);
241
+ const mutexKey = normalizeMutexKey(trimmedPath);
242
+ return withDirectoryMutex([mutexKey], async () => {
243
+ const { sqlite, qdrant } = await initializeStorage(config);
244
+ let directory = await sqlite.getDirectory(dirPath);
245
+ if (!directory && process.platform === "win32") {
246
+ directory = await sqlite.getDirectoryByCaseInsensitive(dirPath);
247
+ }
255
248
  if (!directory) {
256
249
  throw new Error(
257
250
  `Directory '${dirPath}' is not indexed. Use 'server_info' to see indexed directories.`
258
251
  );
259
252
  }
260
- const files = await sqlite.getFilesByDirectory(dirPath);
253
+ const storedPath = directory.path;
254
+ const files = await sqlite.getFilesByDirectory(storedPath);
261
255
  const vectorErrors = [];
262
256
  for (const file of files) {
263
257
  try {
@@ -277,25 +271,21 @@ async function handleDeleteIndexTool(args, config) {
277
271
  ` + vectorErrors.join("\n")
278
272
  );
279
273
  }
280
- const deletedFiles = sqlite.deleteFilesByDirectory(dirPath);
281
- sqlite.deleteDirectory(dirPath);
274
+ const deletedFiles = sqlite.deleteFilesByDirectory(storedPath);
275
+ sqlite.deleteDirectory(storedPath);
282
276
  refreshIndexedDirsCache(sqlite);
283
277
  const chunksCount = files.reduce((sum, f) => sum + (f.chunks?.length || 0), 0);
284
- log("info", "Index deleted", { directory: dirPath, files: deletedFiles, chunks: chunksCount });
285
- mcpServer?.sendLoggingMessage({ level: "info", data: { event: "index_deleted", directory: dirPath } });
278
+ log("info", "Index deleted", { directory: storedPath, files: deletedFiles, chunks: chunksCount });
279
+ notifyClient("info", { event: "index_deleted", directory: storedPath });
286
280
  return {
287
281
  content: [
288
282
  {
289
283
  type: "text",
290
- text: `Deleted index for ${dirPath}: removed ${deletedFiles} files and ${chunksCount} chunks`
284
+ text: `Deleted index for ${storedPath}: removed ${deletedFiles} files and ${chunksCount} chunks`
291
285
  }
292
286
  ]
293
287
  };
294
- } finally {
295
- resolveDelete();
296
- indexingMutex.delete(mutexKey);
297
- sqlite.close();
298
- }
288
+ });
299
289
  }
300
290
  function formatErrorResponse(error) {
301
291
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-handlers.js","sources":["../src/mcp-handlers.ts"],"sourcesContent":["import { Config } from './config.js';\nimport { indexDirectories } from './indexing.js';\nimport { searchContent, findSimilarFiles, getFileContent, getChunkContent } from './search.js';\nimport { getIndexStatus, SQLiteStorage, initializeStorage } from './storage.js';\nimport { validateIndexPrerequisites, validateSearchPrerequisites } from './prerequisites.js';\nimport { validatePathWithinIndexedDirs, resolveIndexedDirectories } from './path-validation.js';\nimport { log } from './logger.js';\nimport { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport type { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { resolve, sep } from 'path';\nimport { realpathSync } from 'fs';\n\n// MCP server reference for sending client-visible log notifications\nlet mcpServer: Server | null = null;\n\n/**\n * Set the MCP server reference for logging notifications.\n * Called from startMcpServer() after server creation.\n */\nexport function setMcpServer(server: Server): void {\n mcpServer = server;\n}\n\n/**\n * Normalize a directory path for use as a mutex key.\n * Resolves symlinks, makes absolute, and strips trailing separators\n * so that '/repo', '/repo/', and symlinks all map to the same key.\n */\nfunction normalizeMutexKey(dirPath: string): string {\n let normalized: string;\n try {\n normalized = realpathSync(resolve(dirPath));\n } catch {\n // Directory may not exist yet; fall back to resolve only\n normalized = resolve(dirPath);\n }\n // Strip trailing separator (but keep root '/' or 'C:\\')\n while (normalized.length > 1 && normalized.endsWith(sep)) {\n normalized = normalized.slice(0, -sep.length);\n }\n return normalized;\n}\n\n// Workspace-level indexing mutex: keyed by normalized directory path\nconst indexingMutex = new Map<string, Promise<void>>();\n\n// Cached set of resolved indexed directory paths for path validation\nlet indexedDirsCache: Set<string> = new Set();\nlet indexedDirsCacheInitialized = false;\n\n/**\n * Refresh the indexed directories cache from storage.\n * Exported for testability.\n */\nexport function refreshIndexedDirsCache(storage: SQLiteStorage): void {\n indexedDirsCache = resolveIndexedDirectories(storage);\n indexedDirsCacheInitialized = true;\n}\n\n/**\n * Ensure the cache is populated, lazily initializing from SQLite only (no Qdrant).\n * Uses a boolean flag so an empty result doesn't re-trigger initialization.\n */\nasync function ensureIndexedDirsCache(config: Config): Promise<void> {\n if (!indexedDirsCacheInitialized) {\n const sqlite = new SQLiteStorage(config);\n try {\n refreshIndexedDirsCache(sqlite);\n } finally {\n sqlite.close();\n }\n }\n}\n\n// Type-safe interfaces for MCP tool arguments\ninterface IndexToolArgs {\n directory_paths: string[];\n}\n\ninterface SearchToolArgs {\n query: string;\n limit?: number;\n workspace?: string;\n}\n\ninterface SimilarFilesToolArgs {\n file_path: string;\n limit?: number;\n workspace?: string;\n}\n\ninterface GetContentToolArgs {\n file_path: string;\n chunks?: string;\n}\n\ninterface GetChunkToolArgs {\n file_path: string;\n chunk_id: string;\n}\n\ninterface DeleteIndexToolArgs {\n directory_path: string;\n}\n\n// Type guard functions\nfunction isIndexToolArgs(args: unknown): args is IndexToolArgs {\n return typeof args === 'object' && args !== null &&\n Array.isArray((args as IndexToolArgs).directory_paths);\n}\n\nfunction isSearchToolArgs(args: unknown): args is SearchToolArgs {\n return typeof args === 'object' && args !== null && \n typeof (args as SearchToolArgs).query === 'string';\n}\n\nfunction isSimilarFilesToolArgs(args: unknown): args is SimilarFilesToolArgs {\n return typeof args === 'object' && args !== null && \n typeof (args as SimilarFilesToolArgs).file_path === 'string';\n}\n\nfunction isGetContentToolArgs(args: unknown): args is GetContentToolArgs {\n return typeof args === 'object' && args !== null && \n typeof (args as GetContentToolArgs).file_path === 'string';\n}\n\nfunction isGetChunkToolArgs(args: unknown): args is GetChunkToolArgs {\n return typeof args === 'object' && args !== null &&\n typeof (args as GetChunkToolArgs).file_path === 'string' &&\n typeof (args as GetChunkToolArgs).chunk_id === 'string';\n}\n\nfunction isDeleteIndexToolArgs(args: unknown): args is DeleteIndexToolArgs {\n return typeof args === 'object' && args !== null &&\n typeof (args as DeleteIndexToolArgs).directory_path === 'string';\n}\n\nexport async function handleIndexTool(args: unknown, config: Config): Promise<CallToolResult> {\n if (!isIndexToolArgs(args)) {\n throw new Error('directory_paths is required and must be an array');\n }\n\n // Validate prerequisites before proceeding\n await validateIndexPrerequisites(config);\n\n const paths = args.directory_paths.map((p: string) => p.trim());\n const mutexKeys = paths.map(normalizeMutexKey);\n\n log('info', 'Index start', { directories: paths });\n mcpServer?.sendLoggingMessage({ level: 'info', data: { event: 'index_start', directories: paths } });\n\n // Per-directory mutex: serialize concurrent calls targeting the same directory\n for (const key of mutexKeys) {\n const existing = indexingMutex.get(key);\n if (existing) {\n log('info', 'Waiting for ongoing indexing', { directory: key });\n await existing;\n }\n }\n\n // Create a deferred promise for this indexing operation\n let resolveIndexing: () => void;\n const indexingPromise = new Promise<void>((resolve) => { resolveIndexing = resolve; });\n for (const key of mutexKeys) {\n indexingMutex.set(key, indexingPromise);\n }\n\n try {\n const result = await indexDirectories(paths, config);\n\n // Refresh the indexed directories cache after successful indexing\n const { sqlite } = await initializeStorage(config);\n try {\n refreshIndexedDirsCache(sqlite);\n } finally {\n sqlite.close();\n }\n\n log('info', 'Index complete', { result });\n mcpServer?.sendLoggingMessage({ level: 'info', data: { event: 'index_complete', result } });\n\n let responseText = `Indexed ${result.indexed} files, skipped ${result.skipped} files, cleaned up ${result.deleted} deleted files, ${result.failed} failed`;\n\n if (result.errors.length > 0) {\n responseText += `\\nErrors: [\\n`;\n result.errors.forEach(error => {\n responseText += ` '${error}'\\n`;\n });\n responseText += `]`;\n }\n\n return {\n content: [\n {\n type: 'text',\n text: responseText\n }\n ]\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n log('error', 'Index error', { error: errorMessage, directories: paths });\n mcpServer?.sendLoggingMessage({ level: 'error', data: { event: 'index_error', error: errorMessage } });\n throw new Error(\n `Indexing failed for ${paths.join(', ')}. Verify the directory exists and is readable. Use 'server_info' to check current status.`\n );\n } finally {\n resolveIndexing!();\n for (const key of mutexKeys) {\n indexingMutex.delete(key);\n }\n }\n}\n\nasync function validateWorkspace(workspace?: string): Promise<{ workspace?: string; message?: string }> {\n if (!workspace) return { workspace };\n \n const config = (await import('./config.js')).loadConfig();\n const { getAvailableWorkspaces } = await import('./config.js');\n const availableWorkspaces = getAvailableWorkspaces(config);\n \n if (availableWorkspaces.includes(workspace)) {\n return { workspace };\n }\n \n // Invalid workspace - search all content with informative message\n const message = availableWorkspaces.length > 0\n ? `Note: Workspace '${workspace}' not found. Searching all content instead. Available workspaces: ${availableWorkspaces.join(', ')}. Use server_info tool to see workspace details.`\n : `Note: Workspace '${workspace}' not found and no workspaces are configured. Searching all indexed content.`;\n \n return { workspace: undefined, message };\n}\n\nexport async function handleSearchTool(args: unknown): Promise<CallToolResult> {\n if (!isSearchToolArgs(args)) {\n throw new Error('query is required');\n }\n \n // Validate prerequisites before proceeding\n const config = (await import('./config.js')).loadConfig();\n await validateSearchPrerequisites(config);\n \n const { workspace, message } = await validateWorkspace(args.workspace);\n const results = await searchContent(args.query, { limit: args.limit || 10, workspace });\n \n const response = message \n ? `${message}\\n\\n${JSON.stringify(results, null, 2)}`\n : JSON.stringify(results, null, 2);\n \n return {\n content: [{ type: 'text', text: response }]\n };\n}\n\nexport async function handleSimilarFilesTool(args: unknown): Promise<CallToolResult> {\n if (!isSimilarFilesToolArgs(args)) {\n throw new Error('file_path is required');\n }\n \n // Validate prerequisites before proceeding\n const config = (await import('./config.js')).loadConfig();\n await validateSearchPrerequisites(config);\n \n const { workspace, message } = await validateWorkspace(args.workspace);\n const results = await findSimilarFiles(args.file_path, args.limit || 10, workspace);\n \n const response = message \n ? `${message}\\n\\n${JSON.stringify(results, null, 2)}`\n : JSON.stringify(results, null, 2);\n \n return {\n content: [{ type: 'text', text: response }]\n };\n}\n\nexport async function handleGetContentTool(args: unknown, config?: Config): Promise<CallToolResult> {\n if (!isGetContentToolArgs(args)) {\n throw new Error('file_path is required');\n }\n\n // Lazily populate cache and validate path\n const resolvedConfig = config || (await import('./config.js')).loadConfig();\n await ensureIndexedDirsCache(resolvedConfig);\n validatePathWithinIndexedDirs(args.file_path, indexedDirsCache);\n\n try {\n const content = await getFileContent(args.file_path, args.chunks);\n\n return {\n content: [\n {\n type: 'text',\n text: content\n }\n ]\n };\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n if (msg.includes('ENOENT') || msg.toLowerCase().includes('not found') || msg.toLowerCase().includes('no such file')) {\n throw new Error(\n `File not found: ${args.file_path}. The file may have been moved or deleted. Use 'search' to find similar content.`\n );\n }\n throw error;\n }\n}\n\nexport async function handleGetChunkTool(args: unknown, config?: Config): Promise<CallToolResult> {\n if (!isGetChunkToolArgs(args)) {\n throw new Error('file_path and chunk_id are required');\n }\n\n // Lazily populate cache and validate path\n const resolvedConfig = config || (await import('./config.js')).loadConfig();\n await ensureIndexedDirsCache(resolvedConfig);\n validatePathWithinIndexedDirs(args.file_path, indexedDirsCache);\n\n try {\n const content = await getChunkContent(args.file_path, args.chunk_id);\n\n return {\n content: [\n {\n type: 'text',\n text: content\n }\n ]\n };\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n if (msg.includes('ENOENT') || msg.toLowerCase().includes('not found') || msg.toLowerCase().includes('no such file')) {\n throw new Error(\n `File not found: ${args.file_path}. The file may have been moved or deleted. Use 'search' to find similar content.`\n );\n }\n throw error;\n }\n}\n\nexport async function handleServerInfoTool(version: string): Promise<CallToolResult> {\n const status = await getIndexStatus();\n \n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n name: 'directory-indexer',\n version: version,\n status: status\n }, null, 2)\n }\n ]\n };\n}\n\nexport async function handleDeleteIndexTool(args: unknown, config: Config): Promise<CallToolResult> {\n if (!isDeleteIndexToolArgs(args)) {\n throw new Error('directory_path is required');\n }\n\n const dirPath = args.directory_path.trim();\n const mutexKey = normalizeMutexKey(dirPath);\n\n // Acquire per-directory mutex to avoid racing with in-flight indexing\n const existing = indexingMutex.get(mutexKey);\n if (existing) {\n log('info', 'Waiting for ongoing indexing before delete', { directory: dirPath });\n await existing;\n }\n\n let resolveDelete: () => void;\n const deletePromise = new Promise<void>((r) => { resolveDelete = r; });\n indexingMutex.set(mutexKey, deletePromise);\n\n const { sqlite, qdrant } = await initializeStorage(config);\n\n try {\n // Check if the directory is actually indexed\n const directory = await sqlite.getDirectory(dirPath);\n if (!directory) {\n throw new Error(\n `Directory '${dirPath}' is not indexed. Use 'server_info' to see indexed directories.`\n );\n }\n\n // Get files for this directory to clean up Qdrant points\n const files = await sqlite.getFilesByDirectory(dirPath);\n const vectorErrors: string[] = [];\n for (const file of files) {\n try {\n await qdrant.deletePointsByFilePath(file.path);\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n log('warning', 'Failed to delete Qdrant points for file', {\n path: file.path,\n error: msg\n });\n vectorErrors.push(`${file.path}: ${msg}`);\n }\n }\n\n // If any vector deletions failed, abort to prevent orphaned vectors\n if (vectorErrors.length > 0) {\n throw new Error(\n `Aborting delete: failed to remove vector embeddings for ${vectorErrors.length} file(s). ` +\n `SQLite rows were NOT deleted to avoid orphaned vectors.\\n` +\n vectorErrors.join('\\n')\n );\n }\n\n // Delete file records and directory record from SQLite\n const deletedFiles = sqlite.deleteFilesByDirectory(dirPath);\n sqlite.deleteDirectory(dirPath);\n\n // Refresh the indexed directories cache\n refreshIndexedDirsCache(sqlite);\n\n const chunksCount = files.reduce((sum, f) => sum + (f.chunks?.length || 0), 0);\n\n log('info', 'Index deleted', { directory: dirPath, files: deletedFiles, chunks: chunksCount });\n mcpServer?.sendLoggingMessage({ level: 'info', data: { event: 'index_deleted', directory: dirPath } });\n\n return {\n content: [\n {\n type: 'text',\n text: `Deleted index for ${dirPath}: removed ${deletedFiles} files and ${chunksCount} chunks`\n }\n ]\n };\n } finally {\n resolveDelete!();\n indexingMutex.delete(mutexKey);\n sqlite.close();\n }\n}\n\nexport function formatErrorResponse(error: unknown): CallToolResult {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n log('error', 'Tool error', { error: errorMessage });\n return {\n content: [\n {\n type: 'text',\n text: `Error: ${errorMessage}`\n }\n ],\n isError: true\n };\n}"],"names":["resolve"],"mappings":";;;;;;;;AAaA,IAAI,YAA2B;AAMxB,SAAS,aAAa,QAAsB;AACjD,cAAY;AACd;AAOA,SAAS,kBAAkB,SAAyB;AAClD,MAAI;AACJ,MAAI;AACF,iBAAa,aAAa,QAAQ,OAAO,CAAC;AAAA,EAC5C,QAAQ;AAEN,iBAAa,QAAQ,OAAO;AAAA,EAC9B;AAEA,SAAO,WAAW,SAAS,KAAK,WAAW,SAAS,GAAG,GAAG;AACxD,iBAAa,WAAW,MAAM,GAAG,CAAC,IAAI,MAAM;AAAA,EAC9C;AACA,SAAO;AACT;AAGA,MAAM,oCAAoB,IAAA;AAG1B,IAAI,uCAAoC,IAAA;AACxC,IAAI,8BAA8B;AAM3B,SAAS,wBAAwB,SAA8B;AACpE,qBAAmB,0BAA0B,OAAO;AACpD,gCAA8B;AAChC;AAMA,eAAe,uBAAuB,QAA+B;AACnE,MAAI,CAAC,6BAA6B;AAChC,UAAM,SAAS,IAAI,cAAc,MAAM;A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kBAAc,OAAO,QAAQ;AAC7B,WAAO,MAAA;AAAA,EACT;AACF;AAEO,SAAS,oBAAoB,OAAgC;AAClE,QAAM,eAAe,iBAAiB,QAAQ,MAAM,UAAU;AAC9D,MAAI,SAAS,cAAc,EAAE,OAAO,cAAc;AAClD,SAAO;AAAA,IACL,SAAS;AAAA,MACP;AAAA,QACE,MAAM;AAAA,QACN,MAAM,UAAU,YAAY;AAAA,MAAA;AAAA,IAC9B;AAAA,IAEF,SAAS;AAAA,EAAA;AAEb;"}
1
+ {"version":3,"file":"mcp-handlers.js","sources":["../src/mcp-handlers.ts"],"sourcesContent":["import { Config } from './config.js';\nimport { indexDirectories } from './indexing.js';\nimport { searchContent, findSimilarFiles, getFileContent, getChunkContent } from './search.js';\nimport { getIndexStatus, SQLiteStorage, initializeStorage } from './storage.js';\nimport { validateIndexPrerequisites, validateSearchPrerequisites } from './prerequisites.js';\nimport { validatePathWithinIndexedDirs, resolveIndexedDirectories } from './path-validation.js';\nimport { normalizePath } from './utils.js';\nimport { log } from './logger.js';\nimport { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport type { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { resolve, sep } from 'path';\nimport { realpathSync } from 'fs';\n\n// MCP server reference for sending client-visible log notifications\nlet mcpServer: Server | null = null;\n\n/**\n * Set the MCP server reference for logging notifications.\n * Called from startMcpServer() after server creation.\n */\nexport function setMcpServer(server: Server): void {\n mcpServer = server;\n}\n\nfunction notifyClient(level: 'info' | 'error', data: Record<string, unknown>): void {\n mcpServer?.sendLoggingMessage({ level, data })?.catch(() => {});\n}\n\n/**\n * Normalize a directory path for use as a mutex key.\n * Resolves symlinks, makes absolute, and strips trailing separators\n * so that '/repo', '/repo/', and symlinks all map to the same key.\n */\nfunction normalizeMutexKey(dirPath: string): string {\n let normalized: string;\n try {\n normalized = realpathSync(resolve(dirPath));\n } catch {\n // Directory may not exist yet; fall back to resolve only\n normalized = resolve(dirPath);\n }\n // Strip trailing separator (but keep root '/' or 'C:\\')\n while (normalized.length > 1 && normalized.endsWith(sep)) {\n normalized = normalized.slice(0, -sep.length);\n }\n return normalized;\n}\n\n// Workspace-level indexing mutex: keyed by normalized directory path\nconst indexingMutex = new Map<string, Promise<void>>();\n\n/**\n * Serialize an operation against prior holders of the given mutex keys.\n * The registered ticket resolves only when this operation's `fn` finishes,\n * so later arrivals chain behind the whole operation instead of acquiring\n * at check time; `fn`'s rejection propagates to its own caller only, and\n * release runs unconditionally in the finally.\n */\nasync function withDirectoryMutex<T>(keys: string[], fn: () => Promise<T>): Promise<T> {\n const holders = keys.map(key => indexingMutex.get(key));\n const prior = Promise.all(holders.map(holder => holder ?? Promise.resolve()));\n let release!: () => void;\n const done = new Promise<void>(resolve => { release = resolve; });\n const ticket = prior.then(() => done);\n for (const key of keys) indexingMutex.set(key, ticket);\n if (holders.some(Boolean)) {\n log('info', 'Waiting for ongoing indexing', { directories: keys });\n }\n await prior;\n try {\n return await fn();\n } finally {\n release();\n for (const key of keys) {\n if (indexingMutex.get(key) === ticket) indexingMutex.delete(key);\n }\n }\n}\n\n// Cached set of resolved indexed directory paths for path validation\nlet indexedDirsCache: Set<string> = new Set();\nlet indexedDirsCacheInitialized = false;\n\n/**\n * Refresh the indexed directories cache from storage.\n * Exported for testability.\n */\nexport function refreshIndexedDirsCache(storage: SQLiteStorage): void {\n indexedDirsCache = resolveIndexedDirectories(storage);\n indexedDirsCacheInitialized = true;\n}\n\n/**\n * Ensure the cache is populated, lazily initializing from SQLite only (no Qdrant).\n * Uses a boolean flag so an empty result doesn't re-trigger initialization.\n */\nasync function ensureIndexedDirsCache(config: Config): Promise<void> {\n if (!indexedDirsCacheInitialized) {\n const { sqlite } = await initializeStorage(config);\n refreshIndexedDirsCache(sqlite);\n }\n}\n\n// Type-safe interfaces for MCP tool arguments\ninterface IndexToolArgs {\n directory_paths: string[];\n}\n\ninterface SearchToolArgs {\n query: string;\n limit?: number;\n workspace?: string;\n}\n\ninterface SimilarFilesToolArgs {\n file_path: string;\n limit?: number;\n workspace?: string;\n}\n\ninterface GetContentToolArgs {\n file_path: string;\n chunks?: string;\n}\n\ninterface GetChunkToolArgs {\n file_path: string;\n chunk_id: string;\n}\n\ninterface DeleteIndexToolArgs {\n directory_path: string;\n}\n\n// Type guard functions\nfunction isIndexToolArgs(args: unknown): args is IndexToolArgs {\n return typeof args === 'object' && args !== null &&\n Array.isArray((args as IndexToolArgs).directory_paths);\n}\n\nfunction isSearchToolArgs(args: unknown): args is SearchToolArgs {\n return typeof args === 'object' && args !== null && \n typeof (args as SearchToolArgs).query === 'string';\n}\n\nfunction isSimilarFilesToolArgs(args: unknown): args is SimilarFilesToolArgs {\n return typeof args === 'object' && args !== null && \n typeof (args as SimilarFilesToolArgs).file_path === 'string';\n}\n\nfunction isGetContentToolArgs(args: unknown): args is GetContentToolArgs {\n return typeof args === 'object' && args !== null && \n typeof (args as GetContentToolArgs).file_path === 'string';\n}\n\nfunction isGetChunkToolArgs(args: unknown): args is GetChunkToolArgs {\n return typeof args === 'object' && args !== null &&\n typeof (args as GetChunkToolArgs).file_path === 'string' &&\n typeof (args as GetChunkToolArgs).chunk_id === 'string';\n}\n\nfunction isDeleteIndexToolArgs(args: unknown): args is DeleteIndexToolArgs {\n return typeof args === 'object' && args !== null &&\n typeof (args as DeleteIndexToolArgs).directory_path === 'string';\n}\n\nexport async function handleIndexTool(args: unknown, config: Config): Promise<CallToolResult> {\n if (!isIndexToolArgs(args)) {\n throw new Error('directory_paths is required and must be an array');\n }\n\n const paths = args.directory_paths.map((p: string) => p.trim());\n const mutexKeys = paths.map(normalizeMutexKey);\n\n return withDirectoryMutex(mutexKeys, async () => {\n // Validate prerequisites before proceeding\n await validateIndexPrerequisites(config);\n\n log('info', 'Index start', { directories: paths });\n notifyClient('info', { event: 'index_start', directories: paths });\n\n try {\n const result = await indexDirectories(paths, config);\n\n // Refresh the indexed directories cache after successful indexing\n const { sqlite } = await initializeStorage(config);\n refreshIndexedDirsCache(sqlite);\n\n log('info', 'Index complete', { result });\n notifyClient('info', { event: 'index_complete', result });\n\n let responseText = `Indexed ${result.indexed} files, skipped ${result.skipped} files, cleaned up ${result.deleted} deleted files, ${result.failed} failed`;\n\n if (result.errors.length > 0) {\n responseText += `\\nErrors: [\\n`;\n result.errors.forEach(error => {\n responseText += ` '${error}'\\n`;\n });\n responseText += `]`;\n }\n\n return {\n content: [\n {\n type: 'text',\n text: responseText\n }\n ]\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n log('error', 'Index error', { error: errorMessage, directories: paths });\n notifyClient('error', { event: 'index_error', error: errorMessage });\n throw new Error(\n `Indexing failed for ${paths.join(', ')}. Verify the directory exists and is readable. Use 'server_info' to check current status.`\n );\n }\n });\n}\n\nasync function validateWorkspace(workspace?: string): Promise<string | undefined> {\n if (!workspace) return workspace;\n\n const config = (await import('./config.js')).loadConfig();\n const { getAvailableWorkspaces } = await import('./config.js');\n const availableWorkspaces = getAvailableWorkspaces(config);\n\n if (availableWorkspaces.includes(workspace)) {\n return workspace;\n }\n\n throw new Error(\n availableWorkspaces.length > 0\n ? `Workspace '${workspace}' not found. Available workspaces: ${availableWorkspaces.join(', ')}`\n : `Workspace '${workspace}' not found and no workspaces are configured.`\n );\n}\n\nexport async function handleSearchTool(args: unknown): Promise<CallToolResult> {\n if (!isSearchToolArgs(args)) {\n throw new Error('query is required');\n }\n\n // Validate prerequisites before proceeding\n const config = (await import('./config.js')).loadConfig();\n await validateSearchPrerequisites(config);\n\n const workspace = await validateWorkspace(args.workspace);\n const results = await searchContent(args.query, { limit: args.limit || 10, workspace });\n\n return {\n content: [{ type: 'text', text: JSON.stringify(results, null, 2) }]\n };\n}\n\nexport async function handleSimilarFilesTool(args: unknown): Promise<CallToolResult> {\n if (!isSimilarFilesToolArgs(args)) {\n throw new Error('file_path is required');\n }\n\n // Validate prerequisites before proceeding\n const config = (await import('./config.js')).loadConfig();\n await validateSearchPrerequisites(config);\n\n await ensureIndexedDirsCache(config);\n validatePathWithinIndexedDirs(args.file_path, indexedDirsCache);\n\n const workspace = await validateWorkspace(args.workspace);\n const results = await findSimilarFiles(args.file_path, args.limit || 10, workspace);\n\n return {\n content: [{ type: 'text', text: JSON.stringify(results, null, 2) }]\n };\n}\n\nexport async function handleGetContentTool(args: unknown, config?: Config): Promise<CallToolResult> {\n if (!isGetContentToolArgs(args)) {\n throw new Error('file_path is required');\n }\n\n // Lazily populate cache and validate path\n const resolvedConfig = config || (await import('./config.js')).loadConfig();\n await ensureIndexedDirsCache(resolvedConfig);\n validatePathWithinIndexedDirs(args.file_path, indexedDirsCache);\n\n try {\n const content = await getFileContent(args.file_path, args.chunks);\n\n return {\n content: [\n {\n type: 'text',\n text: content\n }\n ]\n };\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n if (msg.includes('ENOENT') || msg.toLowerCase().includes('not found') || msg.toLowerCase().includes('no such file')) {\n throw new Error(\n `File not found: ${args.file_path}. The file may have been moved or deleted. Use 'search' to find similar content.`\n );\n }\n throw error;\n }\n}\n\nexport async function handleGetChunkTool(args: unknown, config?: Config): Promise<CallToolResult> {\n if (!isGetChunkToolArgs(args)) {\n throw new Error('file_path and chunk_id are required');\n }\n\n // Lazily populate cache and validate path\n const resolvedConfig = config || (await import('./config.js')).loadConfig();\n await ensureIndexedDirsCache(resolvedConfig);\n validatePathWithinIndexedDirs(args.file_path, indexedDirsCache);\n\n try {\n const content = await getChunkContent(args.file_path, args.chunk_id);\n\n return {\n content: [\n {\n type: 'text',\n text: content\n }\n ]\n };\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n if (msg.includes('ENOENT') || msg.toLowerCase().includes('not found') || msg.toLowerCase().includes('no such file')) {\n throw new Error(\n `File not found: ${args.file_path}. The file may have been moved or deleted. Use 'search' to find similar content.`\n );\n }\n throw error;\n }\n}\n\nexport async function handleServerInfoTool(version: string): Promise<CallToolResult> {\n const status = await getIndexStatus();\n \n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n name: 'directory-indexer',\n version: version,\n status: status\n }, null, 2)\n }\n ]\n };\n}\n\nexport async function handleDeleteIndexTool(args: unknown, config: Config): Promise<CallToolResult> {\n if (!isDeleteIndexToolArgs(args)) {\n throw new Error('directory_path is required');\n }\n\n const trimmedPath = args.directory_path.trim();\n const dirPath = normalizePath(trimmedPath);\n const mutexKey = normalizeMutexKey(trimmedPath);\n\n return withDirectoryMutex([mutexKey], async () => {\n const { sqlite, qdrant } = await initializeStorage(config);\n\n // Check if the directory is actually indexed\n let directory = await sqlite.getDirectory(dirPath);\n if (!directory && process.platform === 'win32') {\n directory = await sqlite.getDirectoryByCaseInsensitive(dirPath);\n }\n if (!directory) {\n throw new Error(\n `Directory '${dirPath}' is not indexed. Use 'server_info' to see indexed directories.`\n );\n }\n\n const storedPath = directory.path;\n\n // Get files for this directory to clean up Qdrant points\n const files = await sqlite.getFilesByDirectory(storedPath);\n const vectorErrors: string[] = [];\n for (const file of files) {\n try {\n await qdrant.deletePointsByFilePath(file.path);\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n log('warning', 'Failed to delete Qdrant points for file', {\n path: file.path,\n error: msg\n });\n vectorErrors.push(`${file.path}: ${msg}`);\n }\n }\n\n // If any vector deletions failed, abort to prevent orphaned vectors\n if (vectorErrors.length > 0) {\n throw new Error(\n `Aborting delete: failed to remove vector embeddings for ${vectorErrors.length} file(s). ` +\n `SQLite rows were NOT deleted to avoid orphaned vectors.\\n` +\n vectorErrors.join('\\n')\n );\n }\n\n // Delete file records and directory record from SQLite\n const deletedFiles = sqlite.deleteFilesByDirectory(storedPath);\n sqlite.deleteDirectory(storedPath);\n\n // Refresh the indexed directories cache\n refreshIndexedDirsCache(sqlite);\n\n const chunksCount = files.reduce((sum, f) => sum + (f.chunks?.length || 0), 0);\n\n log('info', 'Index deleted', { directory: storedPath, files: deletedFiles, chunks: chunksCount });\n notifyClient('info', { event: 'index_deleted', directory: storedPath });\n\n return {\n content: [\n {\n type: 'text',\n text: `Deleted index for ${storedPath}: removed ${deletedFiles} files and ${chunksCount} chunks`\n }\n ]\n };\n });\n}\n\nexport function formatErrorResponse(error: unknown): CallToolResult {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n log('error', 'Tool error', { error: errorMessage });\n return {\n content: [\n {\n type: 'text',\n text: `Error: ${errorMessage}`\n }\n ],\n isError: true\n };\n}"],"names":["resolve"],"mappings":";;;;;;;;;AAcA,IAAI,YAA2B;AAMxB,SAAS,aAAa,QAAsB;AACjD,cAAY;AACd;AAEA,SAAS,aAAa,OAAyB,MAAqC;AAClF,aAAW,mBAAmB,EAAE,OAAO,MAAM,GAAG,MAAM,MAAM;AAAA,EAAC,CAAC;AAChE;AAOA,SAAS,kBAAkB,SAAyB;AAClD,MAAI;AACJ,MAAI;AACF,iBAAa,aAAa,QAAQ,OAAO,CAAC;AAAA,EAC5C,QAAQ;AAEN,iBAAa,QAAQ,OAAO;AAAA,EAC9B;AAEA,SAAO,WAAW,SAAS,KAAK,WAAW,SAAS,GAAG,GAAG;AACxD,iBAAa,WAAW,MAAM,GAAG,CAAC,IAAI,MAAM;AAAA,EAC9C;AACA,SAAO;AACT;AAGA,MAAM,oCAAoB,IAAA;AAS1B,eAAe,mBAAsB,MAAgB,IAAkC;AACrF,QAAM,UAAU,KAAK,IAAI,SAAO,cAAc,IAAI,GAAG,CAAC;AACtD,QAAM,QAAQ,QAAQ,IAAI,QAAQ,IAAI,YAAU,UAAU,QAAQ,QAAA,CAAS,CAAC;AAC5E,MAAI;AACJ,QAAM,OAAO,IAAI,QAAc,CAAAA,aAAW;AAAE,cAAUA;AAAAA,EAAS,CAAC;AAChE,QAAM,SAAS,MAAM,KAAK,MAAM,IAAI;AACpC,aAAW,OAAO,KAAM,eAAc,IAAI,KAAK,MAAM;AACrD,MAAI,QAAQ,KAAK,OAAO,GAAG;AACzB,QAAI,QAAQ,gCAAgC,EAAE,aAAa,MAAM;AAAA,EACnE;AACA,QAAM;AACN,MAAI;AACF,WAAO,MAAM,GA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AAA,UACX,OAAO;AAAA,QAAA,CACR;AACD,qBAAa,KAAK,GAAG,KAAK,IAAI,KAAK,GAAG,EAAE;AAAA,MAC1C;AAAA,IACF;AAGA,QAAI,aAAa,SAAS,GAAG;AAC3B,YAAM,IAAI;AAAA,QACR,2DAA2D,aAAa,MAAM;AAAA,IAE9E,aAAa,KAAK,IAAI;AAAA,MAAA;AAAA,IAE1B;AAGA,UAAM,eAAe,OAAO,uBAAuB,UAAU;AAC7D,WAAO,gBAAgB,UAAU;AAGjC,4BAAwB,MAAM;AAE9B,UAAM,cAAc,MAAM,OAAO,CAAC,KAAK,MAAM,OAAO,EAAE,QAAQ,UAAU,IAAI,CAAC;AAE7E,QAAI,QAAQ,iBAAiB,EAAE,WAAW,YAAY,OAAO,cAAc,QAAQ,aAAa;AAChG,iBAAa,QAAQ,EAAE,OAAO,iBAAiB,WAAW,YAAY;AAEtE,WAAO;AAAA,MACL,SAAS;AAAA,QACP;AAAA,UACE,MAAM;AAAA,UACN,MAAM,qBAAqB,UAAU,aAAa,YAAY,cAAc,WAAW;AAAA,QAAA;AAAA,MACzF;AAAA,IACF;AAAA,EAEJ,CAAC;AACH;AAEO,SAAS,oBAAoB,OAAgC;AAClE,QAAM,eAAe,iBAAiB,QAAQ,MAAM,UAAU;AAC9D,MAAI,SAAS,cAAc,EAAE,OAAO,cAAc;AAClD,SAAO;AAAA,IACL,SAAS;AAAA,MACP;AAAA,QACE,MAAM;AAAA,QACN,MAAM,UAAU,YAAY;AAAA,MAAA;AAAA,IAC9B;AAAA,IAEF,SAAS;AAAA,EAAA;AAEb;"}
package/dist/mcp.js CHANGED
@@ -6,7 +6,7 @@ import { dirname, join } from "path";
6
6
  import { fileURLToPath } from "url";
7
7
  import { closeAllStorage } from "./storage.js";
8
8
  import { initLogLevel, log } from "./logger.js";
9
- import { setMcpServer, handleDeleteIndexTool, handleServerInfoTool, handleGetChunkTool, handleGetContentTool, handleSimilarFilesTool, handleSearchTool, handleIndexTool, formatErrorResponse } from "./mcp-handlers.js";
9
+ import { handleDeleteIndexTool, handleServerInfoTool, handleGetChunkTool, handleGetContentTool, handleSimilarFilesTool, handleSearchTool, handleIndexTool, formatErrorResponse, setMcpServer } from "./mcp-handlers.js";
10
10
  const __dirname$1 = dirname(fileURLToPath(import.meta.url));
11
11
  const packageJsonPath = join(__dirname$1, "../package.json");
12
12
  const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
@@ -139,7 +139,7 @@ Example queries:
139
139
  },
140
140
  workspace: {
141
141
  type: "string",
142
- 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."
142
+ 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 - invalid workspace names are rejected with an error listing the available workspaces."
143
143
  }
144
144
  },
145
145
  required: ["query"]
@@ -186,7 +186,7 @@ Returns file paths with similarity scores. Use get_content to read full files or
186
186
  },
187
187
  workspace: {
188
188
  type: "string",
189
- 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."
189
+ 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 - invalid workspace names are rejected with an error listing the available workspaces."
190
190
  }
191
191
  },
192
192
  required: ["file_path"]
package/dist/mcp.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"mcp.js","sources":["../src/mcp.ts"],"sourcesContent":["import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { \n CallToolRequestSchema, \n ListToolsRequestSchema,\n Tool\n} from '@modelcontextprotocol/sdk/types.js';\nimport { readFileSync } from 'fs';\nimport { join, dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { Config } from './config.js';\nimport { closeAllStorage } from './storage.js';\nimport { initLogLevel, log } from './logger.js';\nimport {\n handleIndexTool,\n handleSearchTool,\n handleSimilarFilesTool,\n handleGetContentTool,\n handleGetChunkTool,\n handleServerInfoTool,\n handleDeleteIndexTool,\n formatErrorResponse,\n setMcpServer\n} from './mcp-handlers.js';\n\n// Read version from package.json\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst packageJsonPath = join(__dirname, '../package.json');\nconst packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));\nconst VERSION = packageJson.version;\n\nconst DELETE_INDEX_TOOL: Tool = {\n name: 'delete_index',\n description: `Remove the index for a directory. Deletes all file records, vector embeddings, and the directory entry from the database.\n\nWhen to use this tool:\n- User wants to remove a directory from the search index\n- Cleaning up old or irrelevant indexed content\n- Freeing database space by removing unused indexes\n\nHow it works:\n- Removes all file records for the specified directory from SQLite\n- Deletes corresponding vector embeddings from Qdrant\n- Removes the directory entry from the directories table\n- Does NOT delete the actual files on disk\n\nExamples:\n- Remove old project: directory_path=\"/home/user/old-project\"\n- Clean up test data: directory_path=\"/home/user/test-files\"\n\nUse server_info to see what directories are currently indexed before removing.`,\n inputSchema: {\n type: 'object',\n properties: {\n directory_path: {\n type: 'string',\n description: 'Absolute path of the directory whose index should be removed'\n }\n },\n required: ['directory_path']\n },\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false\n }\n};\n\nexport function getMcpTools(): Tool[] {\n const tools: Tool[] = [\n {\n name: 'index',\n description: `Index directories to make their files searchable. Processes files to create vector embeddings for semantic search.\n\nWhen to use this tool:\n- User specifically requests indexing a directory as a knowledge base\n- Adding new documentation, code repositories, or file collections to search\n- Updating index when many files have changed\n\nHow it works:\n- Recursively scans directories for supported file types\n- Extracts text content and splits into chunks\n- Generates vector embeddings for semantic similarity\n- Stores in database for fast retrieval\n\nExamples:\n- Index documentation: [\"/home/user/docs/project-wiki\"]\n- Index codebase: [\"/home/user/projects/api-server\"]\n- Index multiple directories: [\"/home/user/docs\", \"/home/user/configs\"]\n\nIndexing 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.`,\n inputSchema: {\n type: 'object',\n properties: {\n directory_paths: {\n type: 'array',\n items: { type: 'string' },\n description: 'Array 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)'\n }\n },\n required: ['directory_paths']\n },\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false\n }\n },\n {\n name: 'search',\n description: `Search indexed files using natural language queries. Finds files containing content semantically similar to the query.\n\nWhen to use this tool:\n- Find documentation, guides, or explanations about specific topics\n- Locate code files implementing certain functionality or patterns\n- Discover configuration files, scripts, or settings related to a topic\n- Search for files covering specific concepts or technologies\n\nHow it works:\n- Converts query to vector embedding using semantic similarity\n- Searches all indexed file chunks for relevant content\n- Groups results by file and calculates average relevance scores\n- Returns files ranked by relevance score\n\nExamples:\n- \"database configuration and connection pooling setup\" - finds config files, documentation about DB setup\n- \"comprehensive error handling patterns and exception management\" - finds code files with exception handling\n- \"JWT authentication implementation and session management\" - finds auth-related code and docs\n- \"REST API documentation and endpoint specifications\" - finds API guides, endpoint definitions\n- \"Docker deployment scripts and CI/CD pipeline configuration\" - finds deployment automation\n\nReturns 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.\n- Groups results by file to avoid duplicates from multiple matching sections\n\nResponse format:\n- Returns lightweight metadata including file paths, relevance scores, and chunk IDs\n- Use 'get_chunk' or 'get_content' tools to fetch actual content from search results\n- Chunks are sorted by relevance score within each file\n- Average similarity score calculated across all matching chunks per file\n\nExample queries:\n- \"error handling patterns and exception management strategies\" (finds try/catch, error classes, logging)\n- \"database migration scripts and schema versioning approaches\" (finds SQL, schema changes, migration files)\n- \"authentication middleware and JWT token validation logic\" (finds auth logic, JWT handling, middleware functions)`,\n inputSchema: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'Natural language search query describing what you are looking for. Can be concepts, functionality, or specific technical terms.'\n },\n limit: {\n type: 'number',\n description: 'Maximum number of files to return (default: 10). Each file may contain multiple matching chunks.',\n default: 10\n },\n workspace: {\n type: 'string',\n 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.'\n }\n },\n required: ['query']\n },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false\n }\n },\n {\n name: 'similar_files',\n description: `Find files with content similar to a reference file. Uses semantic similarity to find related documents, code files, or any text content.\n\nWhen to use this tool:\n- Find documentation similar to a specific guide or README\n- Locate related code files, configuration files, or scripts\n- Discover alternative implementations or approaches\n- Find files covering similar topics or concepts\n\nHow it works:\n- Analyzes the semantic content of the reference file\n- Compares against all indexed files using vector similarity\n- Returns files ranked by content similarity score\n\nExamples:\n- Given \"deployment-guide.md\" - finds other deployment docs, CI/CD guides, infrastructure setup\n- Given \"troubleshooting.md\" - finds other troubleshooting guides, FAQ files, error documentation\n- Given \"config.yaml\" - finds other configuration files, settings, environment setups\n- Given \"auth.py\" - finds other authentication modules, security code, middleware\n\nReturns file paths with similarity scores. Use get_content to read full files or get_chunk for specific sections.`,\n inputSchema: {\n type: 'object',\n properties: {\n file_path: {\n type: 'string',\n description: 'Absolute or relative path to the reference file. This file must have been previously indexed.'\n },\n limit: {\n type: 'number',\n description: 'Maximum number of similar files to return (default: 10). Results are sorted by similarity score.',\n default: 10\n },\n workspace: {\n type: 'string',\n 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.'\n }\n },\n required: ['file_path']\n },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false\n }\n },\n {\n name: 'get_content',\n description: `Retrieve the full content of a file or specific chunks. Reads files directly from the filesystem.\n\nWhen to use this tool:\n- Get complete file content after finding files through search\n- Read documentation, code files, or configuration files for analysis\n- Extract specific sections of large files using chunk ranges\n- Access any text-based file content\n\nHow it works:\n- Reads files directly from filesystem (not from search index)\n- Returns entire file by default\n- Can return specific chunk ranges for indexed files\n- Preserves original formatting and content\n\nExamples:\n- Get full file: file_path=\"/home/user/docs/api.md\"\n- Get specific chunks: file_path=\"/home/user/code/main.py\", chunks=\"2-5\"\n- Get single chunk: file_path=\"/home/user/config.json\", chunks=\"1\"\n\nReturns file content as text. Use this after search or similar_files to read actual content.`,\n inputSchema: {\n type: 'object',\n properties: {\n file_path: {\n type: 'string',\n description: 'Absolute or relative path to the file to retrieve. File must be readable and text-based.'\n },\n chunks: {\n type: 'string',\n 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.'\n }\n },\n required: ['file_path']\n },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false\n }\n },\n {\n name: 'get_chunk',\n description: `Retrieve content of a specific chunk from an indexed file. Gets exact text segments identified during search.\n\nWhen to use this tool:\n- Get specific relevant sections after performing a search\n- Access only the most pertinent parts of large files\n- Retrieve content from high-scoring chunks identified in search results\n- Avoid reading entire files when only specific sections are needed\n\nHow it works:\n- Files are split into overlapping text chunks during indexing\n- Each chunk has a sequential ID (\"0\", \"1\", \"2\", etc.)\n- Search results include chunk IDs for relevant sections\n- Returns the exact content that was semantically matched\n\nExamples:\n- After search returns chunk \"3\" from \"api-docs.md\" with high score\n- Get chunk content: file_path=\"/docs/api-docs.md\", chunk_id=\"3\"\n- Returns the specific text segment that matched your query\n\nReturns chunk content as text. Use this with chunk IDs from search results to get precise content sections.`,\n inputSchema: {\n type: 'object',\n properties: {\n file_path: {\n type: 'string',\n description: 'Absolute or relative path to the indexed file containing the desired chunk.'\n },\n chunk_id: {\n type: 'string',\n 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.'\n }\n },\n required: ['file_path', 'chunk_id']\n },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false\n }\n },\n {\n name: 'server_info',\n description: `Get information about server status and indexed content. Shows what directories and files are available for search.\n\nWhen to use this tool:\n- REQUIRED: Check available workspace names before using workspace parameter in search or similar_files tools\n- Check what content is already indexed before performing searches\n- Verify system is working properly\n- See indexing statistics and status\n- Understand scope of available searchable content\n\nHow it works:\n- Reports total indexed directories, files, and chunks\n- Shows database size and last indexing time\n- Lists all indexed directories with file counts\n- Lists all configured workspaces with their paths and file counts\n- Reports any errors or issues\n\nExamples:\n- Check workspaces before searching: \"What workspaces are available?\"\n- Check before searching: \"What content is indexed?\"\n- Verify after indexing: \"Did the indexing complete successfully?\"\n- Monitor system: \"How many files are searchable?\"\n\nReturns 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.`,\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false\n },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false\n }\n }\n ];\n\n // Include delete_index tool unless DISABLE_DESTRUCTIVE is set\n if (process.env.DISABLE_DESTRUCTIVE !== 'true') {\n tools.push(DELETE_INDEX_TOOL);\n }\n\n return tools;\n}\n\nexport async function startMcpServer(config: Config): Promise<void> {\n initLogLevel();\n\n const server = new Server(\n {\n name: 'directory-indexer',\n version: VERSION\n },\n {\n capabilities: {\n tools: {},\n logging: {}\n }\n }\n );\n\n setMcpServer(server);\n\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: getMcpTools()\n };\n });\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n\n try {\n switch (name) {\n case 'index':\n return await handleIndexTool(args, config);\n \n case 'search':\n return await handleSearchTool(args);\n \n case 'similar_files':\n return await handleSimilarFilesTool(args);\n \n case 'get_content':\n return await handleGetContentTool(args, config);\n\n case 'get_chunk':\n return await handleGetChunkTool(args, config);\n \n case 'server_info':\n return await handleServerInfoTool(VERSION);\n\n case 'delete_index':\n if (process.env.DISABLE_DESTRUCTIVE === 'true') {\n throw new Error('delete_index is disabled via DISABLE_DESTRUCTIVE environment variable');\n }\n return await handleDeleteIndexTool(args, config);\n\n default:\n throw new Error(`Unknown tool: ${name}`);\n }\n } catch (error) {\n return formatErrorResponse(error);\n }\n });\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n\n // Graceful shutdown: close all SQLite connections before exiting\n const cleanup = () => {\n log('info', 'Shutting down MCP server');\n closeAllStorage();\n process.exit(0);\n };\n process.on('SIGTERM', cleanup);\n process.on('SIGINT', cleanup);\n\n if (config.verbose) {\n console.error('MCP server started successfully');\n }\n\n log('info', 'MCP server started', { version: VERSION });\n}"],"names":["__dirname"],"mappings":";;;;;;;;;AA0BA,MAAMA,cAAY,QAAQ,cAAc,YAAY,GAAG,CAAC;AACxD,MAAM,kBAAkB,KAAKA,aAAW,iBAAiB;AACzD,MAAM,cAAc,KAAK,MAAM,aAAa,iBAAiB,OAAO,CAAC;AACrE,MAAM,UAAU,YAAY;AAE5B,MAAM,oBAA0B;AAAA,EAC9B,MAAM;AAAA,EACN,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBb,aAAa;AAAA,IACX,MAAM;AAAA,IACN,YAAY;AAAA,MACV,gBAAgB;AAAA,QACd,MAAM;AAAA,QACN,aAAa;AAAA,MAAA;AAAA,IACf;AAAA,IAEF,UAAU,CAAC,gBAAgB;AAAA,EAAA;AAAA,EAE7B,aAAa;AAAA,IACX,cAAc;AAAA,IACd,iBAAiB;AAAA,IACjB,gBAAgB;AAAA,IAChB,eAAe;AAAA,EAAA;AAEnB;AAEO,SAAS,cAAsB;AACpC,QAAM,QAAgB;AAAA,IACtB;AAAA,MACE,MAAM;AAAA,MACN,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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AM,uBAAuB,IAAI;AAAA,QAE1C,KAAK;AACH,iBAAO,MAAM,qBAAqB,MAAM,MAAM;AAAA,QAEhD,KAAK;AACH,iBAAO,MAAM,mBAAmB,MAAM,MAAM;AAAA,QAE9C,KAAK;AACH,iBAAO,MAAM,qBAAqB,OAAO;AAAA,QAE3C,KAAK;AACH,cAAI,QAAQ,IAAI,wBAAwB,QAAQ;AAC9C,kBAAM,IAAI,MAAM,uEAAuE;AAAA,UACzF;AACA,iBAAO,MAAM,sBAAsB,MAAM,MAAM;AAAA,QAEjD;AACE,gBAAM,IAAI,MAAM,iBAAiB,IAAI,EAAE;AAAA,MAAA;AAAA,IAE7C,SAAS,OAAO;AACd,aAAO,oBAAoB,KAAK;AAAA,IAClC;AAAA,EACF,CAAC;AAED,QAAM,YAAY,IAAI,qBAAA;AACtB,QAAM,OAAO,QAAQ,SAAS;AAG9B,QAAM,UAAU,MAAM;AACpB,QAAI,QAAQ,0BAA0B;AACtC,oBAAA;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,UAAQ,GAAG,WAAW,OAAO;AAC7B,UAAQ,GAAG,UAAU,OAAO;AAE5B,MAAI,OAAO,SAAS;AAClB,YAAQ,MAAM,iCAAiC;AAAA,EACjD;AAEA,MAAI,QAAQ,sBAAsB,EAAE,SAAS,SAAS;AACxD;"}
1
+ {"version":3,"file":"mcp.js","sources":["../src/mcp.ts"],"sourcesContent":["import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { \n CallToolRequestSchema, \n ListToolsRequestSchema,\n Tool\n} from '@modelcontextprotocol/sdk/types.js';\nimport { readFileSync } from 'fs';\nimport { join, dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { Config } from './config.js';\nimport { closeAllStorage } from './storage.js';\nimport { initLogLevel, log } from './logger.js';\nimport {\n handleIndexTool,\n handleSearchTool,\n handleSimilarFilesTool,\n handleGetContentTool,\n handleGetChunkTool,\n handleServerInfoTool,\n handleDeleteIndexTool,\n formatErrorResponse,\n setMcpServer\n} from './mcp-handlers.js';\n\n// Read version from package.json\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst packageJsonPath = join(__dirname, '../package.json');\nconst packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));\nconst VERSION = packageJson.version;\n\nconst DELETE_INDEX_TOOL: Tool = {\n name: 'delete_index',\n description: `Remove the index for a directory. Deletes all file records, vector embeddings, and the directory entry from the database.\n\nWhen to use this tool:\n- User wants to remove a directory from the search index\n- Cleaning up old or irrelevant indexed content\n- Freeing database space by removing unused indexes\n\nHow it works:\n- Removes all file records for the specified directory from SQLite\n- Deletes corresponding vector embeddings from Qdrant\n- Removes the directory entry from the directories table\n- Does NOT delete the actual files on disk\n\nExamples:\n- Remove old project: directory_path=\"/home/user/old-project\"\n- Clean up test data: directory_path=\"/home/user/test-files\"\n\nUse server_info to see what directories are currently indexed before removing.`,\n inputSchema: {\n type: 'object',\n properties: {\n directory_path: {\n type: 'string',\n description: 'Absolute path of the directory whose index should be removed'\n }\n },\n required: ['directory_path']\n },\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false\n }\n};\n\nexport function getMcpTools(): Tool[] {\n const tools: Tool[] = [\n {\n name: 'index',\n description: `Index directories to make their files searchable. Processes files to create vector embeddings for semantic search.\n\nWhen to use this tool:\n- User specifically requests indexing a directory as a knowledge base\n- Adding new documentation, code repositories, or file collections to search\n- Updating index when many files have changed\n\nHow it works:\n- Recursively scans directories for supported file types\n- Extracts text content and splits into chunks\n- Generates vector embeddings for semantic similarity\n- Stores in database for fast retrieval\n\nExamples:\n- Index documentation: [\"/home/user/docs/project-wiki\"]\n- Index codebase: [\"/home/user/projects/api-server\"]\n- Index multiple directories: [\"/home/user/docs\", \"/home/user/configs\"]\n\nIndexing 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.`,\n inputSchema: {\n type: 'object',\n properties: {\n directory_paths: {\n type: 'array',\n items: { type: 'string' },\n description: 'Array 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)'\n }\n },\n required: ['directory_paths']\n },\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false\n }\n },\n {\n name: 'search',\n description: `Search indexed files using natural language queries. Finds files containing content semantically similar to the query.\n\nWhen to use this tool:\n- Find documentation, guides, or explanations about specific topics\n- Locate code files implementing certain functionality or patterns\n- Discover configuration files, scripts, or settings related to a topic\n- Search for files covering specific concepts or technologies\n\nHow it works:\n- Converts query to vector embedding using semantic similarity\n- Searches all indexed file chunks for relevant content\n- Groups results by file and calculates average relevance scores\n- Returns files ranked by relevance score\n\nExamples:\n- \"database configuration and connection pooling setup\" - finds config files, documentation about DB setup\n- \"comprehensive error handling patterns and exception management\" - finds code files with exception handling\n- \"JWT authentication implementation and session management\" - finds auth-related code and docs\n- \"REST API documentation and endpoint specifications\" - finds API guides, endpoint definitions\n- \"Docker deployment scripts and CI/CD pipeline configuration\" - finds deployment automation\n\nReturns 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.\n- Groups results by file to avoid duplicates from multiple matching sections\n\nResponse format:\n- Returns lightweight metadata including file paths, relevance scores, and chunk IDs\n- Use 'get_chunk' or 'get_content' tools to fetch actual content from search results\n- Chunks are sorted by relevance score within each file\n- Average similarity score calculated across all matching chunks per file\n\nExample queries:\n- \"error handling patterns and exception management strategies\" (finds try/catch, error classes, logging)\n- \"database migration scripts and schema versioning approaches\" (finds SQL, schema changes, migration files)\n- \"authentication middleware and JWT token validation logic\" (finds auth logic, JWT handling, middleware functions)`,\n inputSchema: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'Natural language search query describing what you are looking for. Can be concepts, functionality, or specific technical terms.'\n },\n limit: {\n type: 'number',\n description: 'Maximum number of files to return (default: 10). Each file may contain multiple matching chunks.',\n default: 10\n },\n workspace: {\n type: 'string',\n 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 - invalid workspace names are rejected with an error listing the available workspaces.'\n }\n },\n required: ['query']\n },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false\n }\n },\n {\n name: 'similar_files',\n description: `Find files with content similar to a reference file. Uses semantic similarity to find related documents, code files, or any text content.\n\nWhen to use this tool:\n- Find documentation similar to a specific guide or README\n- Locate related code files, configuration files, or scripts\n- Discover alternative implementations or approaches\n- Find files covering similar topics or concepts\n\nHow it works:\n- Analyzes the semantic content of the reference file\n- Compares against all indexed files using vector similarity\n- Returns files ranked by content similarity score\n\nExamples:\n- Given \"deployment-guide.md\" - finds other deployment docs, CI/CD guides, infrastructure setup\n- Given \"troubleshooting.md\" - finds other troubleshooting guides, FAQ files, error documentation\n- Given \"config.yaml\" - finds other configuration files, settings, environment setups\n- Given \"auth.py\" - finds other authentication modules, security code, middleware\n\nReturns file paths with similarity scores. Use get_content to read full files or get_chunk for specific sections.`,\n inputSchema: {\n type: 'object',\n properties: {\n file_path: {\n type: 'string',\n description: 'Absolute or relative path to the reference file. This file must have been previously indexed.'\n },\n limit: {\n type: 'number',\n description: 'Maximum number of similar files to return (default: 10). Results are sorted by similarity score.',\n default: 10\n },\n workspace: {\n type: 'string',\n 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 - invalid workspace names are rejected with an error listing the available workspaces.'\n }\n },\n required: ['file_path']\n },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false\n }\n },\n {\n name: 'get_content',\n description: `Retrieve the full content of a file or specific chunks. Reads files directly from the filesystem.\n\nWhen to use this tool:\n- Get complete file content after finding files through search\n- Read documentation, code files, or configuration files for analysis\n- Extract specific sections of large files using chunk ranges\n- Access any text-based file content\n\nHow it works:\n- Reads files directly from filesystem (not from search index)\n- Returns entire file by default\n- Can return specific chunk ranges for indexed files\n- Preserves original formatting and content\n\nExamples:\n- Get full file: file_path=\"/home/user/docs/api.md\"\n- Get specific chunks: file_path=\"/home/user/code/main.py\", chunks=\"2-5\"\n- Get single chunk: file_path=\"/home/user/config.json\", chunks=\"1\"\n\nReturns file content as text. Use this after search or similar_files to read actual content.`,\n inputSchema: {\n type: 'object',\n properties: {\n file_path: {\n type: 'string',\n description: 'Absolute or relative path to the file to retrieve. File must be readable and text-based.'\n },\n chunks: {\n type: 'string',\n 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.'\n }\n },\n required: ['file_path']\n },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false\n }\n },\n {\n name: 'get_chunk',\n description: `Retrieve content of a specific chunk from an indexed file. Gets exact text segments identified during search.\n\nWhen to use this tool:\n- Get specific relevant sections after performing a search\n- Access only the most pertinent parts of large files\n- Retrieve content from high-scoring chunks identified in search results\n- Avoid reading entire files when only specific sections are needed\n\nHow it works:\n- Files are split into overlapping text chunks during indexing\n- Each chunk has a sequential ID (\"0\", \"1\", \"2\", etc.)\n- Search results include chunk IDs for relevant sections\n- Returns the exact content that was semantically matched\n\nExamples:\n- After search returns chunk \"3\" from \"api-docs.md\" with high score\n- Get chunk content: file_path=\"/docs/api-docs.md\", chunk_id=\"3\"\n- Returns the specific text segment that matched your query\n\nReturns chunk content as text. Use this with chunk IDs from search results to get precise content sections.`,\n inputSchema: {\n type: 'object',\n properties: {\n file_path: {\n type: 'string',\n description: 'Absolute or relative path to the indexed file containing the desired chunk.'\n },\n chunk_id: {\n type: 'string',\n 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.'\n }\n },\n required: ['file_path', 'chunk_id']\n },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false\n }\n },\n {\n name: 'server_info',\n description: `Get information about server status and indexed content. Shows what directories and files are available for search.\n\nWhen to use this tool:\n- REQUIRED: Check available workspace names before using workspace parameter in search or similar_files tools\n- Check what content is already indexed before performing searches\n- Verify system is working properly\n- See indexing statistics and status\n- Understand scope of available searchable content\n\nHow it works:\n- Reports total indexed directories, files, and chunks\n- Shows database size and last indexing time\n- Lists all indexed directories with file counts\n- Lists all configured workspaces with their paths and file counts\n- Reports any errors or issues\n\nExamples:\n- Check workspaces before searching: \"What workspaces are available?\"\n- Check before searching: \"What content is indexed?\"\n- Verify after indexing: \"Did the indexing complete successfully?\"\n- Monitor system: \"How many files are searchable?\"\n\nReturns 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.`,\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false\n },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false\n }\n }\n ];\n\n // Include delete_index tool unless DISABLE_DESTRUCTIVE is set\n if (process.env.DISABLE_DESTRUCTIVE !== 'true') {\n tools.push(DELETE_INDEX_TOOL);\n }\n\n return tools;\n}\n\nexport async function startMcpServer(config: Config): Promise<void> {\n initLogLevel();\n\n const server = new Server(\n {\n name: 'directory-indexer',\n version: VERSION\n },\n {\n capabilities: {\n tools: {},\n logging: {}\n }\n }\n );\n\n setMcpServer(server);\n\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: getMcpTools()\n };\n });\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n\n try {\n switch (name) {\n case 'index':\n return await handleIndexTool(args, config);\n \n case 'search':\n return await handleSearchTool(args);\n \n case 'similar_files':\n return await handleSimilarFilesTool(args);\n \n case 'get_content':\n return await handleGetContentTool(args, config);\n\n case 'get_chunk':\n return await handleGetChunkTool(args, config);\n \n case 'server_info':\n return await handleServerInfoTool(VERSION);\n\n case 'delete_index':\n if (process.env.DISABLE_DESTRUCTIVE === 'true') {\n throw new Error('delete_index is disabled via DISABLE_DESTRUCTIVE environment variable');\n }\n return await handleDeleteIndexTool(args, config);\n\n default:\n throw new Error(`Unknown tool: ${name}`);\n }\n } catch (error) {\n return formatErrorResponse(error);\n }\n });\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n\n // Graceful shutdown: close all SQLite connections before exiting\n const cleanup = () => {\n log('info', 'Shutting down MCP server');\n closeAllStorage();\n process.exit(0);\n };\n process.on('SIGTERM', cleanup);\n process.on('SIGINT', cleanup);\n\n if (config.verbose) {\n console.error('MCP server started successfully');\n }\n\n log('info', 'MCP server started', { version: VERSION });\n}"],"names":["__dirname"],"mappings":";;;;;;;;;AA0BA,MAAMA,cAAY,QAAQ,cAAc,YAAY,GAAG,CAAC;AACxD,MAAM,kBAAkB,KAAKA,aAAW,iBAAiB;AACzD,MAAM,cAAc,KAAK,MAAM,aAAa,iBAAiB,OAAO,CAAC;AACrE,MAAM,UAAU,YAAY;AAE5B,MAAM,oBAA0B;AAAA,EAC9B,MAAM;AAAA,EACN,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBb,aAAa;AAAA,IACX,MAAM;AAAA,IACN,YAAY;AAAA,MACV,gBAAgB;AAAA,QACd,MAAM;AAAA,QACN,aAAa;AAAA,MAAA;AAAA,IACf;AAAA,IAEF,UAAU,CAAC,gBAAgB;AAAA,EAAA;AAAA,EAE7B,aAAa;AAAA,IACX,cAAc;AAAA,IACd,iBAAiB;AAAA,IACjB,gBAAgB;AAAA,IAChB,eAAe;AAAA,EAAA;AAEnB;AAEO,SAAS,cAAsB;AACpC,QAAM,QAAgB;AAAA,IACtB;AAAA,MACE,MAAM;AAAA,MACN,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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AAM,qBAAqB,MAAM,MAAM;AAAA,QAEhD,KAAK;AACH,iBAAO,MAAM,mBAAmB,MAAM,MAAM;AAAA,QAE9C,KAAK;AACH,iBAAO,MAAM,qBAAqB,OAAO;AAAA,QAE3C,KAAK;AACH,cAAI,QAAQ,IAAI,wBAAwB,QAAQ;AAC9C,kBAAM,IAAI,MAAM,uEAAuE;AAAA,UACzF;AACA,iBAAO,MAAM,sBAAsB,MAAM,MAAM;AAAA,QAEjD;AACE,gBAAM,IAAI,MAAM,iBAAiB,IAAI,EAAE;AAAA,MAAA;AAAA,IAE7C,SAAS,OAAO;AACd,aAAO,oBAAoB,KAAK;AAAA,IAClC;AAAA,EACF,CAAC;AAED,QAAM,YAAY,IAAI,qBAAA;AACtB,QAAM,OAAO,QAAQ,SAAS;AAG9B,QAAM,UAAU,MAAM;AACpB,QAAI,QAAQ,0BAA0B;AACtC,oBAAA;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,UAAQ,GAAG,WAAW,OAAO;AAC7B,UAAQ,GAAG,UAAU,OAAO;AAE5B,MAAI,OAAO,SAAS;AAClB,YAAQ,MAAM,iCAAiC;AAAA,EACjD;AAEA,MAAI,QAAQ,sBAAsB,EAAE,SAAS,SAAS;AACxD;"}
@@ -20,7 +20,8 @@ function validatePathWithinIndexedDirs(filePath, indexedDirs) {
20
20
  if (resolved === dir) {
21
21
  return;
22
22
  }
23
- if (resolved.startsWith(dir + sep)) {
23
+ const prefix = dir.endsWith(sep) ? dir : dir + sep;
24
+ if (resolved.startsWith(prefix)) {
24
25
  return;
25
26
  }
26
27
  }
@@ -1 +1 @@
1
- {"version":3,"file":"path-validation.js","sources":["../src/path-validation.ts"],"sourcesContent":["import { realpathSync } from 'fs';\nimport { resolve, sep } from 'path';\nimport { SQLiteStorage } from './storage.js';\n\n/**\n * Validates that a file path falls within one of the indexed directories.\n * Prevents path traversal attacks by resolving symlinks and checking prefixes.\n */\nexport function validatePathWithinIndexedDirs(filePath: string, indexedDirs: Set<string>): void {\n // Reject null bytes\n if (filePath.includes('\\x00')) {\n throw new Error('Access denied: path contains null bytes');\n }\n\n // Validate Windows UNC path format if it starts with \\\\\n if (filePath.startsWith('\\\\\\\\')) {\n const uncParts = filePath.split('\\\\').filter(Boolean);\n if (uncParts.length < 2) {\n throw new Error('Invalid UNC path format: expected \\\\\\\\server\\\\share\\\\... pattern');\n }\n }\n\n // Resolve the path, following symlinks if the file exists\n let resolved: string;\n try {\n resolved = realpathSync(resolve(filePath));\n } catch {\n // File may not exist yet (ENOENT), fall back to resolve only\n resolved = resolve(filePath);\n }\n\n for (const dir of indexedDirs) {\n // Exact match (the directory itself)\n if (resolved === dir) {\n return;\n }\n // Prefix match with separator to prevent /docs-evil matching /docs\n if (resolved.startsWith(dir + sep)) {\n return;\n }\n }\n\n throw new Error(\n `Access denied: ${filePath} is outside indexed directories. Only files within indexed directories can be accessed.`\n );\n}\n\n/**\n * Resolves all indexed directory paths from storage, following symlinks where possible.\n * Returns a Set of resolved absolute paths.\n */\nexport function resolveIndexedDirectories(storage: SQLiteStorage): Set<string> {\n const dirs = storage.getDirectories();\n const resolved = new Set<string>();\n\n for (const dir of dirs) {\n try {\n resolved.add(realpathSync(resolve(dir)));\n } catch {\n // Directory may have been removed; keep the raw resolved path\n resolved.add(resolve(dir));\n }\n }\n\n return resolved;\n}\n"],"names":[],"mappings":";;AAQO,SAAS,8BAA8B,UAAkB,aAAgC;AAE9F,MAAI,SAAS,SAAS,IAAM,GAAG;AAC7B,UAAM,IAAI,MAAM,yCAAyC;AAAA,EAC3D;AAGA,MAAI,SAAS,WAAW,MAAM,GAAG;AAC/B,UAAM,WAAW,SAAS,MAAM,IAAI,EAAE,OAAO,OAAO;AACpD,QAAI,SAAS,SAAS,GAAG;AACvB,YAAM,IAAI,MAAM,kEAAkE;AAAA,IACpF;AAAA,EACF;AAGA,MAAI;AACJ,MAAI;AACF,eAAW,aAAa,QAAQ,QAAQ,CAAC;AAAA,EAC3C,QAAQ;AAEN,eAAW,QAAQ,QAAQ;AAAA,EAC7B;AAEA,aAAW,OAAO,aAAa;AAE7B,QAAI,aAAa,KAAK;AACpB;AAAA,IACF;AAEA,QAAI,SAAS,WAAW,MAAM,GAAG,GAAG;AAClC;AAAA,IACF;AAAA,EACF;AAEA,QAAM,IAAI;AAAA,IACR,kBAAkB,QAAQ;AAAA,EAAA;AAE9B;AAMO,SAAS,0BAA0B,SAAqC;AAC7E,QAAM,OAAO,QAAQ,eAAA;AACrB,QAAM,+BAAe,IAAA;AAErB,aAAW,OAAO,MAAM;AACtB,QAAI;AACF,eAAS,IAAI,aAAa,QAAQ,GAAG,CAAC,CAAC;AAAA,IACzC,QAAQ;AAEN,eAAS,IAAI,QAAQ,GAAG,CAAC;AAAA,IAC3B;AAAA,EACF;AAEA,SAAO;AACT;"}
1
+ {"version":3,"file":"path-validation.js","sources":["../src/path-validation.ts"],"sourcesContent":["import { realpathSync } from 'fs';\nimport { resolve, sep } from 'path';\nimport { SQLiteStorage } from './storage.js';\n\n/**\n * Validates that a file path falls within one of the indexed directories.\n * Prevents path traversal attacks by resolving symlinks and checking prefixes.\n */\nexport function validatePathWithinIndexedDirs(filePath: string, indexedDirs: Set<string>): void {\n // Reject null bytes\n if (filePath.includes('\\x00')) {\n throw new Error('Access denied: path contains null bytes');\n }\n\n // Validate Windows UNC path format if it starts with \\\\\n if (filePath.startsWith('\\\\\\\\')) {\n const uncParts = filePath.split('\\\\').filter(Boolean);\n if (uncParts.length < 2) {\n throw new Error('Invalid UNC path format: expected \\\\\\\\server\\\\share\\\\... pattern');\n }\n }\n\n // Resolve the path, following symlinks if the file exists\n let resolved: string;\n try {\n resolved = realpathSync(resolve(filePath));\n } catch {\n // File may not exist yet (ENOENT), fall back to resolve only\n resolved = resolve(filePath);\n }\n\n for (const dir of indexedDirs) {\n // Exact match (the directory itself)\n if (resolved === dir) {\n return;\n }\n // Prefix match with separator; roots already end with one, and the\n // separator prevents /docs-evil matching /docs\n const prefix = dir.endsWith(sep) ? dir : dir + sep;\n if (resolved.startsWith(prefix)) {\n return;\n }\n }\n\n throw new Error(\n `Access denied: ${filePath} is outside indexed directories. Only files within indexed directories can be accessed.`\n );\n}\n\n/**\n * Resolves all indexed directory paths from storage, following symlinks where possible.\n * Returns a Set of resolved absolute paths.\n */\nexport function resolveIndexedDirectories(storage: SQLiteStorage): Set<string> {\n const dirs = storage.getDirectories();\n const resolved = new Set<string>();\n\n for (const dir of dirs) {\n try {\n resolved.add(realpathSync(resolve(dir)));\n } catch {\n // Directory may have been removed; keep the raw resolved path\n resolved.add(resolve(dir));\n }\n }\n\n return resolved;\n}\n"],"names":[],"mappings":";;AAQO,SAAS,8BAA8B,UAAkB,aAAgC;AAE9F,MAAI,SAAS,SAAS,IAAM,GAAG;AAC7B,UAAM,IAAI,MAAM,yCAAyC;AAAA,EAC3D;AAGA,MAAI,SAAS,WAAW,MAAM,GAAG;AAC/B,UAAM,WAAW,SAAS,MAAM,IAAI,EAAE,OAAO,OAAO;AACpD,QAAI,SAAS,SAAS,GAAG;AACvB,YAAM,IAAI,MAAM,kEAAkE;AAAA,IACpF;AAAA,EACF;AAGA,MAAI;AACJ,MAAI;AACF,eAAW,aAAa,QAAQ,QAAQ,CAAC;AAAA,EAC3C,QAAQ;AAEN,eAAW,QAAQ,QAAQ;AAAA,EAC7B;AAEA,aAAW,OAAO,aAAa;AAE7B,QAAI,aAAa,KAAK;AACpB;AAAA,IACF;AAGA,UAAM,SAAS,IAAI,SAAS,GAAG,IAAI,MAAM,MAAM;AAC/C,QAAI,SAAS,WAAW,MAAM,GAAG;AAC/B;AAAA,IACF;AAAA,EACF;AAEA,QAAM,IAAI;AAAA,IACR,kBAAkB,QAAQ;AAAA,EAAA;AAE9B;AAMO,SAAS,0BAA0B,SAAqC;AAC7E,QAAM,OAAO,QAAQ,eAAA;AACrB,QAAM,+BAAe,IAAA;AAErB,aAAW,OAAO,MAAM;AACtB,QAAI;AACF,eAAS,IAAI,aAAa,QAAQ,GAAG,CAAC,CAAC;AAAA,IACzC,QAAQ;AAEN,eAAS,IAAI,QAAQ,GAAG,CAAC;AAAA,IAC3B;AAAA,EACF;AAEA,SAAO;AACT;"}
@@ -1,3 +1,4 @@
1
+ import { QdrantClient } from "./storage.js";
1
2
  class PrerequisiteError extends Error {
2
3
  constructor(message, cause) {
3
4
  super(message);
@@ -6,12 +7,8 @@ class PrerequisiteError extends Error {
6
7
  }
7
8
  }
8
9
  async function checkQdrant(config) {
9
- try {
10
- const response = await fetch(`${config.storage.qdrantEndpoint}/healthz`);
11
- return response.ok;
12
- } catch {
13
- return false;
14
- }
10
+ const qdrant = new QdrantClient(config);
11
+ return qdrant.healthCheck();
15
12
  }
16
13
  async function checkOllama(config) {
17
14
  try {
@@ -35,7 +32,7 @@ async function checkOllamaModel(config) {
35
32
  async function checkOpenAI(config) {
36
33
  if (!process.env.OPENAI_API_KEY) return false;
37
34
  try {
38
- const response = await fetch("https://api.openai.com/v1/embeddings", {
35
+ const response = await fetch(`${config.embedding.endpoint}/embeddings`, {
39
36
  method: "POST",
40
37
  headers: {
41
38
  "Content-Type": "application/json",
@@ -57,7 +54,7 @@ async function checkAllPrerequisitesDetailed(config) {
57
54
  services.push({
58
55
  service: "qdrant",
59
56
  status: qdrantOk ? "available" : "unavailable",
60
- details: qdrantOk ? void 0 : `Cannot connect to Qdrant at ${config.storage.qdrantEndpoint}`
57
+ details: qdrantOk ? void 0 : "Cannot connect to Qdrant"
61
58
  });
62
59
  let embeddingOk = false;
63
60
  let embeddingDetails;