-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathsearch-handlers.ts
More file actions
250 lines (217 loc) · 7.76 KB
/
Copy pathsearch-handlers.ts
File metadata and controls
250 lines (217 loc) · 7.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import { searchManager } from '../search-manager.js';
import {
StartSearchArgsSchema,
GetMoreSearchResultsArgsSchema,
StopSearchArgsSchema
} from '../tools/schemas.js';
import { ServerResult } from '../types.js';
import { capture } from '../utils/capture.js';
/**
* Handle start_search command
*/
export async function handleStartSearch(args: unknown): Promise<ServerResult> {
const parsed = StartSearchArgsSchema.safeParse(args);
if (!parsed.success) {
return {
content: [{ type: "text", text: `Invalid arguments for start_search: ${parsed.error}` }],
isError: true,
};
}
try {
const result = await searchManager.startSearch({
rootPath: parsed.data.path,
pattern: parsed.data.pattern,
searchType: parsed.data.searchType,
filePattern: parsed.data.filePattern,
ignoreCase: parsed.data.ignoreCase,
maxResults: parsed.data.maxResults,
includeHidden: parsed.data.includeHidden,
contextLines: parsed.data.contextLines,
timeout: parsed.data.timeout_ms,
earlyTermination: parsed.data.earlyTermination,
});
const searchTypeText = parsed.data.searchType === 'content' ? 'content search' : 'file search';
let output = `Started ${searchTypeText} session: ${result.sessionId}\n`;
output += `Pattern: "${parsed.data.pattern}"\n`;
output += `Path: ${parsed.data.path}\n`;
output += `Status: ${result.isComplete ? 'COMPLETED' : 'RUNNING'}\n`;
output += `Runtime: ${Math.round(result.runtime)}ms\n`;
output += `Total results: ${result.totalResults}\n\n`;
if (result.results.length > 0) {
output += "Initial results:\n";
for (const searchResult of result.results.slice(0, 10)) {
if (searchResult.type === 'content') {
output += `📄 ${searchResult.file}:${searchResult.line} - ${searchResult.match?.substring(0, 100)}${searchResult.match && searchResult.match.length > 100 ? '...' : ''}\n`;
} else {
output += `📁 ${searchResult.file}\n`;
}
}
if (result.results.length > 10) {
output += `... and ${result.results.length - 10} more results\n`;
}
}
if (result.isComplete) {
output += `\n✅ Search completed.`;
} else {
output += `\n🔄 Search in progress. Use get_more_search_results to get more results.`;
}
return {
content: [{ type: "text", text: output }],
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
capture('search_session_start_error', { error: errorMessage });
return {
content: [{ type: "text", text: `Error starting search session: ${errorMessage}` }],
isError: true,
};
}
}
/**
* Handle get_more_search_results command
*/
export async function handleGetMoreSearchResults(args: unknown): Promise<ServerResult> {
const parsed = GetMoreSearchResultsArgsSchema.safeParse(args);
if (!parsed.success) {
return {
content: [{ type: "text", text: `Invalid arguments for get_more_search_results: ${parsed.error}` }],
isError: true,
};
}
try {
const results = searchManager.readSearchResults(
parsed.data.sessionId,
parsed.data.offset,
parsed.data.length
);
// Only return error if we have no results AND there's an actual error
// Permission errors should not block returning found results
if (results.isError && results.totalResults === 0 && results.error?.trim()) {
return {
content: [{
type: "text",
text: `Search session ${parsed.data.sessionId} encountered an error: ${results.error}`
}],
isError: true,
};
}
// Format results for display
let output = `Search session: ${parsed.data.sessionId}\n`;
output += `Status: ${results.isComplete ? 'COMPLETED' : 'IN PROGRESS'}\n`;
output += `Runtime: ${Math.round(results.runtime / 1000)}s\n`;
output += `Total results found: ${results.totalResults} (${results.totalMatches} matches)\n`;
const offset = parsed.data.offset;
if (offset < 0) {
// Negative offset - tail behavior
output += `Showing last ${results.returnedCount} results\n\n`;
} else {
// Positive offset - range behavior
const startPos = offset;
const endPos = startPos + results.returnedCount - 1;
output += `Showing results ${startPos}-${endPos}\n\n`;
}
if (results.results.length === 0) {
if (results.isComplete) {
output += results.totalResults === 0 ? "No matches found." : "No results in this range.";
} else {
output += "No results yet, search is still running...";
}
} else {
output += "Results:\n";
for (const result of results.results) {
if (result.type === 'content') {
output += `📄 ${result.file}:${result.line} - ${result.match?.substring(0, 100)}${result.match && result.match.length > 100 ? '...' : ''}\n`;
} else {
output += `📁 ${result.file}\n`;
}
}
}
// Add pagination hints
if (offset >= 0 && results.hasMoreResults) {
const nextOffset = offset + results.returnedCount;
output += `\n📖 More results available. Use get_more_search_results with offset: ${nextOffset}`;
}
if (results.isComplete) {
output += `\n✅ Search completed.`;
}
return {
content: [{ type: "text", text: output }],
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return {
content: [{ type: "text", text: `Error reading search results: ${errorMessage}` }],
isError: true,
};
}
}
/**
* Handle stop_search command
*/
export async function handleStopSearch(args: unknown): Promise<ServerResult> {
const parsed = StopSearchArgsSchema.safeParse(args);
if (!parsed.success) {
return {
content: [{ type: "text", text: `Invalid arguments for stop_search: ${parsed.error}` }],
isError: true,
};
}
try {
const success = searchManager.terminateSearch(parsed.data.sessionId);
if (success) {
return {
content: [{
type: "text",
text: `Search session ${parsed.data.sessionId} terminated successfully.`
}],
};
} else {
return {
content: [{
type: "text",
text: `Search session ${parsed.data.sessionId} not found or already completed.`
}],
};
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return {
content: [{ type: "text", text: `Error terminating search session: ${errorMessage}` }],
isError: true,
};
}
}
/**
* Handle list_searches command
*/
export async function handleListSearches(): Promise<ServerResult> {
try {
const sessions = searchManager.listSearchSessions();
if (sessions.length === 0) {
return {
content: [{ type: "text", text: "No active searches." }],
};
}
let output = `Active Searches (${sessions.length}):\n\n`;
for (const session of sessions) {
const status = session.isComplete
? (session.isError ? '❌ ERROR' : '✅ COMPLETED')
: '🔄 RUNNING';
output += `Session: ${session.id}\n`;
output += ` Type: ${session.searchType}\n`;
output += ` Pattern: "${session.pattern}"\n`;
output += ` Status: ${status}\n`;
output += ` Runtime: ${Math.round(session.runtime / 1000)}s\n`;
output += ` Results: ${session.totalResults}\n\n`;
}
return {
content: [{ type: "text", text: output }],
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return {
content: [{ type: "text", text: `Error listing search sessions: ${errorMessage}` }],
isError: true,
};
}
}