-
-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathMcpServerHost.cs
More file actions
191 lines (158 loc) · 5.19 KB
/
McpServerHost.cs
File metadata and controls
191 lines (158 loc) · 5.19 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
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;
using Resgrid.Config;
using Sentry;
namespace Resgrid.Web.Mcp
{
/// <summary>
/// Hosted service that runs the MCP server
/// </summary>
public sealed class McpServerHost : IHostedService, IDisposable
{
private readonly ILogger<McpServerHost> _logger;
private readonly McpToolRegistry _toolRegistry;
private readonly IHostApplicationLifetime _applicationLifetime;
private McpServer _mcpServer;
private Task _executingTask;
private CancellationTokenSource _stoppingCts;
private bool _disposed;
public McpServerHost(
ILogger<McpServerHost> logger,
McpToolRegistry toolRegistry,
IHostApplicationLifetime applicationLifetime)
{
_logger = logger;
_toolRegistry = toolRegistry;
_applicationLifetime = applicationLifetime;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Starting Resgrid MCP Server...");
// Add Sentry breadcrumb for startup
SentrySdk.AddBreadcrumb("MCP Server starting", "server.lifecycle", level: BreadcrumbLevel.Info);
_stoppingCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
try
{
// Use McpConfig for server configuration
var serverName = McpConfig.ServerName;
var serverVersion = McpConfig.ServerVersion;
// Create MCP server with server information
_mcpServer = new McpServer(serverName, serverVersion, _logger);
// Register all tools from the registry
_toolRegistry.RegisterTools(_mcpServer);
var toolCount = _toolRegistry.GetToolCount();
_logger.LogInformation("MCP Server initialized with {ToolCount} tools", toolCount);
// Add Sentry breadcrumb for successful initialization
SentrySdk.AddBreadcrumb(
$"MCP Server initialized with {toolCount} tools",
"server.lifecycle",
data: new System.Collections.Generic.Dictionary<string, string>
{
{ "server_name", serverName },
{ "server_version", serverVersion },
{ "tool_count", toolCount.ToString() }
},
level: BreadcrumbLevel.Info);
// Start the server execution
_executingTask = ExecuteAsync(_stoppingCts.Token);
if (_executingTask.IsCompleted)
{
return _executingTask;
}
_logger.LogInformation("Resgrid MCP Server started successfully");
SentrySdk.AddBreadcrumb("MCP Server started successfully", "server.lifecycle", level: BreadcrumbLevel.Info);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to start MCP Server");
// Capture exception in Sentry
SentrySdk.CaptureException(ex, scope =>
{
scope.SetTag("component", "McpServerHost");
scope.SetTag("operation", "StartAsync");
scope.Level = SentryLevel.Fatal;
});
throw;
}
return Task.CompletedTask;
}
public async Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Stopping Resgrid MCP Server...");
SentrySdk.AddBreadcrumb("MCP Server stopping", "server.lifecycle", level: BreadcrumbLevel.Info);
if (_executingTask == null)
{
return;
}
try
{
_stoppingCts?.Cancel();
}
finally
{
await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken));
_stoppingCts?.Dispose();
_stoppingCts = null;
}
_logger.LogInformation("Resgrid MCP Server stopped");
SentrySdk.AddBreadcrumb("MCP Server stopped", "server.lifecycle", level: BreadcrumbLevel.Info);
}
private async Task ExecuteAsync(CancellationToken stoppingToken)
{
// Start a Sentry transaction for the MCP server execution
var transaction = SentrySdk.StartTransaction("mcp.server.execution", "mcp.lifecycle");
var transactionFinished = false;
try
{
_logger.LogInformation("MCP Server listening on stdio transport...");
SentrySdk.AddBreadcrumb("MCP Server started listening", "server.lifecycle", level: BreadcrumbLevel.Info);
// Run the server - this will handle stdio communication
await _mcpServer.RunAsync(stoppingToken);
transaction.Status = SpanStatus.Ok;
}
catch (OperationCanceledException)
{
_logger.LogInformation("MCP Server execution was cancelled");
SentrySdk.AddBreadcrumb("MCP Server execution cancelled", "server.lifecycle", level: BreadcrumbLevel.Info);
transaction.Status = SpanStatus.Cancelled;
}
catch (Exception ex)
{
_logger.LogError(ex, "Unexpected error in MCP Server execution");
// Capture exception in Sentry with context
SentrySdk.CaptureException(ex, scope =>
{
scope.SetTag("component", "McpServerHost");
scope.SetTag("operation", "ExecuteAsync");
scope.Level = SentryLevel.Fatal;
scope.AddBreadcrumb("Server execution failed", "server.error", level: BreadcrumbLevel.Error);
});
transaction.Status = SpanStatus.InternalError;
transaction.Finish(ex);
transactionFinished = true;
_applicationLifetime.StopApplication();
return;
}
finally
{
if (!transactionFinished)
{
transaction.Finish();
}
}
}
public void Dispose()
{
if (_disposed)
{
return;
}
_stoppingCts?.Dispose();
_disposed = true;
}
}
}