-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathProgram.cs
More file actions
273 lines (231 loc) · 12.6 KB
/
Program.cs
File metadata and controls
273 lines (231 loc) · 12.6 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
using System.CommandLine;
using System.CommandLine.Parsing;
using System.Reflection;
using Microsoft.AspNetCore.HttpLogging;
using ModelContextProtocol.Protocol;
using Serilog;
using SharpTools.Tools.Extensions;
using SharpTools.Tools.Interfaces;
using SharpTools.Tools.Mcp.Tools;
using SharpTools.Tools.Services;
namespace SharpTools.SseServer;
using System.CommandLine;
using System.CommandLine.Parsing;
using System.Reflection;
using Microsoft.AspNetCore.HttpLogging;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
using Serilog;
using SharpTools.Tools.Interfaces;
using SharpTools.Tools.Mcp.Tools;
using SharpTools.Tools.Services;
public class Program {
// --- Application ---
public const string ApplicationName = "SharpToolsMcpSseServer";
public const string ApplicationVersion = "0.0.1";
public const string LogOutputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}";
public static async Task<int> Main(string[] args) {
// Ensure tool assemblies are loaded for MCP SDK's WithToolsFromAssembly
_ = typeof(SolutionTools);
_ = typeof(AnalysisTools);
_ = typeof(ModificationTools);
var portOption = new Option<int>("--port") {
Description = "The port number for the MCP server to listen on.",
DefaultValueFactory = x => 3001
};
var logFileOption = new Option<string?>("--log-file") {
Description = "Optional path to a log file. If not specified, logs only go to console."
};
var logLevelOption = new Option<Serilog.Events.LogEventLevel>("--log-level") {
Description = "Minimum log level for console and file.",
DefaultValueFactory = x => Serilog.Events.LogEventLevel.Information
};
var loadSolutionOption = new Option<string?>("--load-solution") {
Description = "Path to a solution file (.sln) to load immediately on startup."
};
var buildConfigurationOption = new Option<string?>("--build-configuration") {
Description = "Build configuration to use when loading the solution (Debug, Release, etc.)."
};
var disableGitOption = new Option<bool>("--disable-git") {
Description = "Disable Git integration.",
DefaultValueFactory = x => false
};
var listToolsOption = new Option<bool>("--list-tools") {
Description = "List available tool and prompt type names, then exit.",
DefaultValueFactory = x => false
};
var excludeToolTypesOption = new Option<List<string>>("--exclude-tool-types") {
Description = "List of tool type names to exclude (from --list-tools).",
AllowMultipleArgumentsPerToken = true
};
var rootCommand = new RootCommand("SharpTools MCP Server") {
portOption,
logFileOption,
logLevelOption,
loadSolutionOption,
buildConfigurationOption,
disableGitOption,
listToolsOption,
excludeToolTypesOption,
};
ParseResult? parseResult = rootCommand.Parse(args);
if (parseResult == null) {
Console.Error.WriteLine("Failed to parse command line arguments.");
return 1;
}
int port = parseResult.GetValue(portOption);
string? logFilePath = parseResult.GetValue(logFileOption);
Serilog.Events.LogEventLevel minimumLogLevel = parseResult.GetValue(logLevelOption);
string? solutionPath = parseResult.GetValue(loadSolutionOption);
string? buildConfiguration = parseResult.GetValue(buildConfigurationOption)!;
bool disableGit = parseResult.GetValue(disableGitOption);
string serverUrl = $"http://localhost:{port}";
bool listTools = parseResult.GetValue(listToolsOption);
List<string> excludeToolTypes = parseResult.GetValue(excludeToolTypesOption) ?? [];
var loggerConfiguration = new LoggerConfiguration()
.MinimumLevel.Is(minimumLogLevel) // Set based on command line
.MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning) // Default override
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", Serilog.Events.LogEventLevel.Information)
// For debugging connection issues, set AspNetCore to Information or Debug
.MinimumLevel.Override("Microsoft.AspNetCore", Serilog.Events.LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.AspNetCore.Hosting.Diagnostics", Serilog.Events.LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.AspNetCore.Routing", Serilog.Events.LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.AspNetCore.Server.Kestrel", Serilog.Events.LogEventLevel.Debug) // Kestrel connection logs
.MinimumLevel.Override("Microsoft.CodeAnalysis", Serilog.Events.LogEventLevel.Information)
.MinimumLevel.Override("ModelContextProtocol", Serilog.Events.LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.Async(a => a.Console(
outputTemplate: LogOutputTemplate,
standardErrorFromLevel: Serilog.Events.LogEventLevel.Verbose,
restrictedToMinimumLevel: minimumLogLevel));
if (!string.IsNullOrWhiteSpace(logFilePath)) {
var logDirectory = Path.GetDirectoryName(logFilePath);
if (!string.IsNullOrWhiteSpace(logDirectory) && !Directory.Exists(logDirectory)) {
Directory.CreateDirectory(logDirectory);
}
loggerConfiguration.WriteTo.Async(a => a.File(
logFilePath,
rollingInterval: RollingInterval.Day,
outputTemplate: LogOutputTemplate,
fileSizeLimitBytes: 10 * 1024 * 1024,
rollOnFileSizeLimit: true,
retainedFileCountLimit: 7,
restrictedToMinimumLevel: minimumLogLevel));
Console.WriteLine($"Logging to file: {Path.GetFullPath(logFilePath)} with minimum level {minimumLogLevel}");
}
Log.Logger = loggerConfiguration.CreateBootstrapLogger();
if (disableGit) {
Log.Information("Git integration is disabled.");
}
if (!string.IsNullOrEmpty(buildConfiguration)) {
Log.Information("Using build configuration: {BuildConfiguration}", buildConfiguration);
}
if (listTools) {
var toolAssembly = Assembly.Load("SharpTools.Tools");
Console.WriteLine("Tools:");
foreach (var t in toolAssembly.GetTypes()
.Where(t => t.GetCustomAttribute<McpServerToolTypeAttribute>() is not null)
.OrderBy(t => t.Name)) {
Console.WriteLine($" {t.Name}");
foreach (var m in t.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance)
.Where(m => m.GetCustomAttribute<McpServerToolAttribute>() is not null)
.OrderBy(m => m.Name)) {
var attr = m.GetCustomAttribute<McpServerToolAttribute>()!;
var name = string.IsNullOrEmpty(attr.Name) ? m.Name : attr.Name;
Console.WriteLine($" - {name}");
}
}
return 0;
}
try {
Log.Information("Configuring {AppName} v{AppVersion} to run on {ServerUrl} with minimum log level {LogLevel}",
ApplicationName, ApplicationVersion, serverUrl, minimumLogLevel);
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = args });
builder.Host.UseSerilog();
// Add W3CLogging for detailed HTTP request logging
// This logs to Microsoft.Extensions.Logging, which Serilog will capture.
builder.Services.AddW3CLogging(logging => {
logging.LoggingFields = W3CLoggingFields.All; // Log all available fields
logging.FileSizeLimit = 5 * 1024 * 1024; // 5 MB
logging.RetainedFileCountLimit = 2;
logging.FileName = "access-"; // Prefix for log files
// By default, logs to a 'logs' subdirectory of the app's content root.
// Can be configured: logging.RootPath = ...
});
builder.Services.WithSharpToolsServices(!disableGit, buildConfiguration);
builder.Services
.AddMcpServer(options => {
options.ServerInfo = new Implementation {
Name = ApplicationName,
Version = ApplicationVersion,
};
// For debugging, you can hook into handlers here if needed,
// but ModelContextProtocol's own Debug logging should be sufficient.
})
.WithHttpTransport()
.WithSharpTools(excludeToolTypes);
var app = builder.Build();
// Load solution if specified in command line arguments
if (!string.IsNullOrEmpty(solutionPath)) {
try {
var solutionManager = app.Services.GetRequiredService<ISolutionManager>();
var editorConfigProvider = app.Services.GetRequiredService<IEditorConfigProvider>();
Log.Information("Loading solution: {SolutionPath}", solutionPath);
await solutionManager.LoadSolutionAsync(solutionPath, CancellationToken.None);
var solutionDir = Path.GetDirectoryName(solutionPath);
if (!string.IsNullOrEmpty(solutionDir)) {
await editorConfigProvider.InitializeAsync(solutionDir, CancellationToken.None);
Log.Information("Solution loaded successfully: {SolutionPath}", solutionPath);
} else {
Log.Warning("Could not determine directory for solution path: {SolutionPath}", solutionPath);
}
} catch (Exception ex) {
Log.Error(ex, "Error loading solution: {SolutionPath}", solutionPath);
}
}
// --- ASP.NET Core Middleware ---
// 1. W3C Logging Middleware (if enabled and configured to log to a file separate from Serilog)
// If W3CLogging is configured to write to files, it has its own middleware.
// If it's just for ILogger, Serilog picks it up.
// app.UseW3CLogging(); // This is needed if W3CLogging is writing its own files.
// If it's just feeding ILogger, Serilog handles it.
// 2. Custom Request Logging Middleware (very early in the pipeline)
app.Use(async (context, next) => {
var logger = context.RequestServices.GetRequiredService<ILogger<Program>>();
logger.LogDebug("Incoming Request: {Method} {Path} {QueryString} from {RemoteIpAddress}",
context.Request.Method,
context.Request.Path,
context.Request.QueryString,
context.Connection.RemoteIpAddress);
// Log headers for more detail if needed (can be verbose)
// foreach (var header in context.Request.Headers) {
// logger.LogTrace("Header: {Key}: {Value}", header.Key, header.Value);
// }
try {
await next(context);
} catch (Exception ex) {
logger.LogError(ex, "Error processing request: {Method} {Path}", context.Request.Method, context.Request.Path);
throw; // Re-throw to let ASP.NET Core handle it
}
logger.LogDebug("Outgoing Response: {StatusCode} for {Method} {Path}",
context.Response.StatusCode,
context.Request.Method,
context.Request.Path);
});
// 3. Standard ASP.NET Core middleware (HTTPS redirection, routing, auth, etc. - not used here yet)
// if (app.Environment.IsDevelopment()) { }
// app.UseHttpsRedirection();
// 4. MCP Middleware
app.MapMcp(); // Maps the MCP endpoint (typically "/mcp")
Log.Information("Starting {AppName} server...", ApplicationName);
await app.RunAsync(serverUrl);
return 0;
} catch (Exception ex) {
Log.Fatal(ex, "{AppName} terminated unexpectedly.", ApplicationName);
return 1;
} finally {
Log.Information("{AppName} shutting down.", ApplicationName);
await Log.CloseAndFlushAsync();
}
}
}