-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCodeContextTools.cs
More file actions
343 lines (300 loc) · 12.4 KB
/
Copy pathCodeContextTools.cs
File metadata and controls
343 lines (300 loc) · 12.4 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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
using System.ComponentModel;
using System.Text;
using CodeContext.Configuration;
using CodeContext.Interfaces;
using CodeContext.Services;
using CodeContext.Utils;
using ModelContextProtocol.Server;
namespace CodeContext.Mcp;
/// <summary>
/// MCP server tools for CodeContext functionality.
/// Provides intelligent code context generation with token budget optimization.
/// </summary>
[McpServerToolType]
public class CodeContextTools
{
private readonly IConsoleWriter _console;
public CodeContextTools(IConsoleWriter console)
{
_console = console;
}
/// <summary>
/// Gets optimized code context for a specific task within a token budget.
/// </summary>
[McpServerTool]
[Description("Get optimized code context for a task. Intelligently selects most relevant files within token budget.")]
public string GetCodeContext(
[Description("Path to the project directory to analyze")] string projectPath,
[Description("Description of the task (e.g., 'fix authentication bug', 'add payment feature')")] string taskDescription,
[Description("Maximum number of tokens to use (default: 50000)")] int tokenBudget = 50000,
[Description("Include project structure in output (default: true)")] bool includeStructure = true,
[Description("Selection strategy: GreedyByScore, ValueOptimized, or Balanced (default: ValueOptimized)")]
string strategy = "ValueOptimized")
{
try
{
// Validate inputs
Guard.DirectoryExists(projectPath, nameof(projectPath));
// Initialize services
var filterConfig = new FilterConfiguration();
var gitIgnoreParser = GitHelper.FindRepositoryRoot(projectPath) switch
{
null => GitIgnoreParser.Empty,
var gitRoot => GitIgnoreParser.FromFile(Path.Combine(gitRoot, ".gitignore"))
};
var fileChecker = new FileFilterService(filterConfig, gitIgnoreParser);
var scanner = new ProjectScanner(fileChecker, _console);
var scorer = new FileRelevanceScorer(projectPath);
var optimizer = new TokenBudgetOptimizer();
// Parse strategy
var strategyEnum = Enum.TryParse<TokenBudgetOptimizer.SelectionStrategy>(strategy, true, out var s)
? s
: TokenBudgetOptimizer.SelectionStrategy.ValueOptimized;
// Scan and score files (synchronous I/O, no Task.Run needed)
var files = GetAllProjectFiles(scanner, projectPath);
var scoredFiles = files
.Select(f => scorer.ScoreFile(f.path, f.content, taskDescription))
.ToList();
// Optimize selection
var result = optimizer.OptimizeSelection(
scoredFiles,
tokenBudget,
strategyEnum,
includeStructure);
// Build output
var output = new StringBuilder();
output.AppendLine("# Code Context");
output.AppendLine($"Project: {Path.GetFileName(projectPath)}");
output.AppendLine($"Task: {taskDescription}");
output.AppendLine();
output.AppendLine(TokenBudgetOptimizer.GenerateSummary(result));
output.AppendLine();
output.AppendLine(new string('=', 80));
output.AppendLine();
// Include structure if requested
if (includeStructure)
{
output.AppendLine("## Project Structure");
output.AppendLine();
var structure = scanner.GetProjectStructure(projectPath);
output.AppendLine(structure);
output.AppendLine();
output.AppendLine(new string('=', 80));
output.AppendLine();
}
// Include selected files
output.AppendLine("## Selected Files");
output.AppendLine();
foreach (var file in result.SelectedFiles.OrderByDescending(f => f.RelevanceScore))
{
output.AppendLine($"### {file.FilePath}");
output.AppendLine($"Relevance: {file.RelevanceScore:F3} | Tokens: {file.TokenCount:N0}");
output.AppendLine(new string('-', 80));
output.AppendLine(file.Content);
output.AppendLine();
}
return output.ToString();
}
catch (Exception ex)
{
return $"Error: {ex.Message}";
}
}
/// <summary>
/// Gets the project structure (directory tree).
/// </summary>
[McpServerTool]
[Description("Get the hierarchical directory structure of a project")]
public string GetProjectStructure(
[Description("Path to the project directory")] string projectPath)
{
try
{
Guard.DirectoryExists(projectPath, nameof(projectPath));
var filterConfig = new FilterConfiguration();
var gitIgnoreParser = GitHelper.FindRepositoryRoot(projectPath) switch
{
null => GitIgnoreParser.Empty,
var gitRoot => GitIgnoreParser.FromFile(Path.Combine(gitRoot, ".gitignore"))
};
var fileChecker = new FileFilterService(filterConfig, gitIgnoreParser);
var scanner = new ProjectScanner(fileChecker, _console);
return scanner.GetProjectStructure(projectPath);
}
catch (Exception ex)
{
return $"Error: {ex.Message}";
}
}
/// <summary>
/// Lists all files in a project with metadata.
/// </summary>
[McpServerTool]
[Description("List all files in a project with token counts and basic metadata")]
public string ListProjectFiles(
[Description("Path to the project directory")] string projectPath,
[Description("Optional query to filter/rank files")] string? query = null)
{
try
{
Guard.DirectoryExists(projectPath, nameof(projectPath));
var filterConfig = new FilterConfiguration();
var gitIgnoreParser = GitHelper.FindRepositoryRoot(projectPath) switch
{
null => GitIgnoreParser.Empty,
var gitRoot => GitIgnoreParser.FromFile(Path.Combine(gitRoot, ".gitignore"))
};
var fileChecker = new FileFilterService(filterConfig, gitIgnoreParser);
var scanner = new ProjectScanner(fileChecker, _console);
// Synchronous I/O, no Task.Run needed
var files = GetAllProjectFiles(scanner, projectPath);
var output = new StringBuilder();
output.AppendLine($"# Project Files: {Path.GetFileName(projectPath)}");
output.AppendLine();
if (!string.IsNullOrWhiteSpace(query))
{
// Score and sort by relevance
var scorer = new FileRelevanceScorer(projectPath);
var scored = files
.Select(f => scorer.ScoreFile(f.path, f.content, query))
.OrderByDescending(f => f.RelevanceScore)
.ToList();
output.AppendLine($"Filtered by: {query}");
output.AppendLine($"Total files: {scored.Count}");
output.AppendLine();
output.AppendLine("Path | Relevance | Tokens");
output.AppendLine(new string('-', 80));
foreach (var file in scored)
{
output.AppendLine($"{file.FilePath} | {file.RelevanceScore:F3} | {file.TokenCount:N0}");
}
}
else
{
// Just list all files
output.AppendLine($"Total files: {files.Count}");
output.AppendLine();
output.AppendLine("Path | Tokens");
output.AppendLine(new string('-', 80));
foreach (var (path, content) in files)
{
var tokens = TokenCounter.EstimateTokensForFile(path, content);
output.AppendLine($"{path} | {tokens:N0}");
}
}
return output.ToString();
}
catch (Exception ex)
{
return $"Error: {ex.Message}";
}
}
/// <summary>
/// Gets the content of specific files.
/// </summary>
[McpServerTool]
[Description("Get the content of specific files by path")]
public string GetFileContent(
[Description("Path to the project directory")] string projectPath,
[Description("Comma-separated list of file paths relative to project root")] string filePaths)
{
try
{
Guard.DirectoryExists(projectPath, nameof(projectPath));
var paths = filePaths.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var output = new StringBuilder();
output.AppendLine("# File Contents");
output.AppendLine();
foreach (var relativePath in paths)
{
// Validate path to prevent path traversal attacks
if (!PathSecurity.TryValidatePathWithinRoot(projectPath, relativePath, out var fullPath))
{
output.AppendLine($"## {relativePath}");
output.AppendLine("❌ Security error: Path traversal detected");
output.AppendLine();
continue;
}
if (!File.Exists(fullPath))
{
output.AppendLine($"## {relativePath}");
output.AppendLine("❌ File not found");
output.AppendLine();
continue;
}
var content = File.ReadAllText(fullPath);
var tokens = TokenCounter.EstimateTokensForFile(relativePath, content);
output.AppendLine($"## {relativePath}");
output.AppendLine($"Tokens: {tokens:N0}");
output.AppendLine(new string('-', 80));
output.AppendLine(content);
output.AppendLine();
}
return output.ToString();
}
catch (Exception ex)
{
return $"Error: {ex.Message}";
}
}
/// <summary>
/// Helper method to get all project files with content.
/// </summary>
private static List<(string path, string content)> GetAllProjectFiles(
ProjectScanner scanner,
string projectPath)
{
var files = new List<(string path, string content)>();
var context = GitHelper.FindRepositoryRoot(projectPath) ?? projectPath;
CollectFiles(scanner, projectPath, context, files);
return files;
}
private static void CollectFiles(
ProjectScanner scanner,
string currentPath,
string rootPath,
List<(string path, string content)> files)
{
try
{
var entries = Directory.EnumerateFileSystemEntries(currentPath)
.Where(e => !scanner.GetType()
.GetField("_fileChecker", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)?
.GetValue(scanner) is IFileChecker checker ||
!checker.ShouldSkip(new FileInfo(e), rootPath))
.ToList();
foreach (var entry in entries)
{
if (Directory.Exists(entry))
{
CollectFiles(scanner, entry, rootPath, files);
}
else if (File.Exists(entry))
{
try
{
var content = File.ReadAllText(entry);
var relativePath = Path.GetRelativePath(rootPath, entry);
files.Add((relativePath, content));
}
catch (UnauthorizedAccessException)
{
// Skip files with permission issues
}
catch (IOException)
{
// Skip files that are locked or in use
}
}
}
}
catch (UnauthorizedAccessException)
{
// Skip directories with permission issues
}
catch (DirectoryNotFoundException)
{
// Skip if directory was deleted during scan
}
}
}