-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathProgram.cs
More file actions
143 lines (122 loc) · 5.38 KB
/
Program.cs
File metadata and controls
143 lines (122 loc) · 5.38 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
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using Elastic.Documentation.Assembler.Links;
using Elastic.Documentation.Assembler.Mcp;
using Elastic.Documentation.Configuration;
using Elastic.Documentation.LinkIndex;
using Elastic.Documentation.Links.InboundLinks;
using Elastic.Documentation.Mcp.Remote;
using Elastic.Documentation.Mcp.Remote.Telemetry;
using Elastic.Documentation.Search.Common;
using Elastic.Documentation.ServiceDefaults;
using Elastic.Documentation.ServiceDefaults.Telemetry;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ModelContextProtocol;
using OpenTelemetry.Trace;
try
{
var builder = WebApplication.CreateSlimBuilder(args);
_ = builder.AddDocumentationServiceDefaults();
_ = builder.AddDefaultHealthChecks();
_ = builder.AddEuidEnrichment();
_ = builder.Services.ConfigureOpenTelemetryTracerProvider(t =>
t.AddSource(McpToolTelemetry.McpToolSourceName));
// Only hardcode port 8080 when not running under Aspire/orchestration that sets ASPNETCORE_HTTP_PORTS
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ASPNETCORE_HTTP_PORTS")))
{
_ = builder.WebHost.ConfigureKestrel(serverOptions =>
{
serverOptions.ListenAnyIP(8080);
});
}
var environment = Environment.GetEnvironmentVariable("ENVIRONMENT");
Console.WriteLine($"Docs Environment: {environment}");
var env = SystemEnvironmentVariables.Instance;
var profile = McpServerProfile.Resolve(env.McpServerProfile);
profile.RegisterAllServices(builder.Services);
// CreateSlimBuilder disables reflection-based JSON serialization.
// The MCP SDK's legacy SSE handler uses Results.BadRequest(string) which needs
// ASP.NET Core's HTTP JSON options to have type metadata for System.String.
_ = builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.TypeInfoResolverChain.Insert(0, McpJsonUtilities.DefaultOptions.TypeInfoResolver!);
});
// Stateless mode: no Mcp-Session-Id header is issued or expected, which avoids a known
// Cursor bug where it opens the SSE stream without the session header and receives 400.
// Stateless mode is appropriate here because all tools are pure request/response (no
// server-initiated push) and the server runs behind a load balancer without session affinity.
var mcpBuilder = builder.Services
.AddMcpServer(options => options.ServerInstructions = profile.ComposeServerInstructions())
.WithHttpTransport(o => o.Stateless = true);
var prefixedTools = McpToolRegistration.CreatePrefixedTools(profile);
mcpBuilder = mcpBuilder.WithTools(prefixedTools);
var app = builder.Build();
var logger = app.Services.GetRequiredService<ILogger<Program>>();
LogElasticsearchConfiguration(app, logger);
var lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>();
_ = lifetime.ApplicationStarted.Register(() => logger.LogInformation("Application started"));
_ = lifetime.ApplicationStopping.Register(() => logger.LogWarning("Application is shutting down"));
_ = lifetime.ApplicationStopped.Register(() => logger.LogWarning("Application has stopped"));
_ = app.Environment.IsDevelopment()
? app.UseDeveloperExceptionPage()
: app.UseExceptionHandler(err => err.Run(context =>
{
var ex = context.Features.Get<IExceptionHandlerFeature>()?.Error;
if (ex != null)
logger.LogError(ex, "Unhandled exception on {Method} {Path}", context.Request.Method, context.Request.Path);
context.Response.StatusCode = 500;
return Task.CompletedTask;
}));
_ = app.UseMiddleware<McpBearerAuthMiddleware>();
_ = app.UseMiddleware<SseKeepAliveMiddleware>();
var mcpPrefix = SystemEnvironmentVariables.Instance.McpPrefix;
var mcp = app.MapGroup(mcpPrefix);
if (SystemEnvironmentVariables.Instance.McpOAuthIssuer is not null)
McpOAuthMetadata.MapEndpoints(mcp);
_ = mcp.MapHealthChecks("/health");
_ = mcp.MapHealthChecks("/alive", new HealthCheckOptions { Predicate = r => r.Tags.Contains("live") });
_ = mcp.MapMcp("");
Console.WriteLine("MCP server startup completed successfully");
app.Run();
}
catch (Exception ex)
{
Console.WriteLine($"FATAL ERROR: {ex}");
Console.WriteLine($"Exception type: {ex.GetType().FullName}");
Console.WriteLine($"Message: {ex.Message}");
if (ex.InnerException != null)
Console.WriteLine($"Inner exception: {ex.InnerException.GetType().FullName}: {ex.InnerException.Message}");
Console.WriteLine($"Stack trace: {ex.StackTrace}");
throw;
}
static void LogElasticsearchConfiguration(WebApplication app, ILogger logger)
{
try
{
var clientAccessor = app.Services.GetService<ElasticsearchClientAccessor>();
if (clientAccessor is not null)
{
logger.LogInformation(
"Elasticsearch configuration - Url: {Url}, SearchIndex: {SearchIndex}",
clientAccessor.Endpoint.Uri,
clientAccessor.SearchIndex
);
}
else
logger.LogWarning("ElasticsearchClientAccessor could not be resolved from DI");
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to resolve Elasticsearch configuration");
}
}
// Make the Program class accessible for integration testing
#pragma warning disable ASP0027
public partial class Program { }
#pragma warning restore ASP0027