-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
183 lines (160 loc) · 6.97 KB
/
Program.cs
File metadata and controls
183 lines (160 loc) · 6.97 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
using System.Net;
using AzureDevopsMCPSharp.Configuration;
using AzureDevopsMCPSharp.Hosting;
using AzureDevopsMCPSharp.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Hosting.WindowsServices;
using Microsoft.Extensions.Logging;
using Serilog;
namespace AzureDevopsMCPSharp;
public static class Program
{
public static int Main(string[] args)
{
// When running as a Windows Service the working directory is
// C:\Windows\System32, so resolve config and logs relative to the exe.
var contentRoot = GetContentRoot();
var isService = WindowsServiceHelpers.IsWindowsService();
if (!isService)
{
McpSharpIcon.ApplyConsoleWindowIcon();
}
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.Console()
.WriteTo.File(
Path.Combine(contentRoot, "logs", "azdomcp-bootstrap-.log"),
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 7,
shared: true)
.CreateBootstrapLogger();
try
{
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
Args = args,
ContentRootPath = contentRoot,
});
builder.Configuration
.SetBasePath(contentRoot)
.AddJsonFile(ResolveConfigFile(contentRoot, "appsettings.json"), optional: true, reloadOnChange: true)
.AddJsonFile(ResolveConfigFile(contentRoot, $"appsettings.{builder.Environment.EnvironmentName}.json"), optional: true, reloadOnChange: true)
.AddJsonFile(ResolveConfigFile(contentRoot, "appsettings.Local.json"), optional: true, reloadOnChange: true)
.AddJsonFile(ResolveConfigFile(contentRoot, "AzureDevopsMCPSharp.json"), optional: true, reloadOnChange: true)
.AddJsonFile(ResolveConfigFile(contentRoot, $"AzureDevopsMCPSharp.{builder.Environment.EnvironmentName}.json"), optional: true, reloadOnChange: true)
.AddJsonFile(ResolveConfigFile(contentRoot, "AzureDevopsMCPSharp.Local.json"), optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.AddEnvironmentVariables(prefix: "AZDOMCP_")
.AddCommandLine(args);
if (isService)
{
var svcOptions = builder.Configuration.GetSection(ServerOptions.SectionName).Get<ServerOptions>() ?? new ServerOptions();
builder.Host.UseWindowsService(o => o.ServiceName = svcOptions.WindowsServiceName);
}
builder.Host.UseSerilog((ctx, services, cfg) => cfg
.ReadFrom.Configuration(ctx.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext());
builder.Services.Configure<AzureDevOpsOptions>(
builder.Configuration.GetSection(AzureDevOpsOptions.SectionName));
builder.Services.Configure<ServerOptions>(
builder.Configuration.GetSection(ServerOptions.SectionName));
builder.Services.AddSingleton<AzureDevOpsService>();
builder.Services
.AddMcpServer()
.WithHttpTransport()
.WithToolsFromAssembly();
var server = builder.Configuration.GetSection(ServerOptions.SectionName).Get<ServerOptions>() ?? new ServerOptions();
builder.WebHost.ConfigureKestrel(k =>
{
if (string.Equals(server.Host, "localhost", StringComparison.OrdinalIgnoreCase))
{
k.ListenLocalhost(server.Port);
}
else if (IPAddress.TryParse(server.Host, out var ip))
{
k.Listen(ip, server.Port);
}
else
{
k.ListenAnyIP(server.Port);
}
});
var app = builder.Build();
app.UseSerilogRequestLogging();
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
Log.Fatal(e.ExceptionObject as Exception, "Unhandled exception in AppDomain");
TaskScheduler.UnobservedTaskException += (_, e) =>
{
Log.Error(e.Exception, "Unobserved task exception");
e.SetObserved();
};
var azdo = app.Services.GetRequiredService<AzureDevOpsService>();
LogStartup(
"AzureDevopsMCPSharp",
$"http://{server.Host}:{server.Port}{server.Path}",
"HTTP",
isService ? "WindowsService" : "Console",
contentRoot,
$"Read-only: {azdo.IsReadOnly}");
app.UseMiddleware<McpPasswordMiddleware>();
app.MapFavicon();
app.MapGet("/healthz", () => new
{
status = "ok",
server = "AzureDevopsMCPSharp",
path = server.Path,
readOnly = azdo.IsReadOnly,
timeUtc = DateTimeOffset.UtcNow,
});
app.MapMcp(server.Path);
app.Run();
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Server terminated unexpectedly");
return 1;
}
finally
{
Log.CloseAndFlush();
}
}
private static void LogStartup(string serviceName, string endpoint, string transport, string mode, string contentRoot, params string[] details)
{
var startupLog = Log.ForContext("SourceContext", serviceName + ".Startup");
startupLog.Information("{ServiceName} startup", serviceName);
startupLog.Information(" Endpoint: {Endpoint}", endpoint);
startupLog.Information(" Transport: {Transport}", transport);
startupLog.Information(" Mode: {Mode}", mode);
foreach (var detail in details)
{
startupLog.Information(" {Detail}", detail);
}
startupLog.Information(" Content root: {ContentRoot}", contentRoot);
}
private static string GetContentRoot() =>
Path.GetDirectoryName(Environment.ProcessPath) ?? AppContext.BaseDirectory;
private static string ResolveConfigFile(string contentRoot, string fileName)
{
if (File.Exists(Path.Combine(contentRoot, fileName)))
{
return fileName;
}
try
{
var match = Directory.EnumerateFiles(contentRoot, "*", SearchOption.TopDirectoryOnly)
.FirstOrDefault(path => string.Equals(Path.GetFileName(path), fileName, StringComparison.OrdinalIgnoreCase));
return match is null ? fileName : Path.GetFileName(match);
}
catch (DirectoryNotFoundException)
{
return fileName;
}
}
}