Repository navigation
Expand file tree
/
Copy pathCodeMasterMcpServer.cs
More file actions
255 lines (220 loc) · 9.99 KB
/
Copy pathCodeMasterMcpServer.cs
File metadata and controls
255 lines (220 loc) · 9.99 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
using System.Collections.Concurrent;
using System.Text.Json;
using System.Threading.Channels;
using CodeMaster.Mcp.Protocol;
using CodeMaster.Mcp.Tools;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace CodeMaster.Mcp;
public interface ICodeMasterMcpServer
{
Task<McpRpcResponse> HandleRequestAsync(McpRpcRequest request, CancellationToken ct = default);
Task HandleSseConnectionAsync(HttpContext context, CancellationToken ct = default);
Task HandlePostMessageAsync(HttpContext context, string? sessionId, CancellationToken ct = default);
}
public class CodeMasterMcpServer : ICodeMasterMcpServer
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<CodeMasterMcpServer> _logger;
private readonly ConcurrentDictionary<string, ChannelWriter<string>> _activeSessions = new();
public CodeMasterMcpServer(IServiceScopeFactory scopeFactory, ILogger<CodeMasterMcpServer> logger)
{
_scopeFactory = scopeFactory;
_logger = logger;
}
public async Task<McpRpcResponse> HandleRequestAsync(McpRpcRequest request, CancellationToken ct = default)
{
if (request == null)
{
return McpRpcResponse.CreateError(null, -32600, "Invalid Request");
}
try
{
switch (request.Method)
{
case "initialize":
string? clientVersion = null;
if (request.Params.HasValue && request.Params.Value.TryGetProperty("protocolVersion", out var pv))
{
clientVersion = pv.GetString();
}
var negotiatedVersion = McpProtocolConstants.NegotiateVersion(clientVersion);
var initResult = new
{
protocolVersion = negotiatedVersion,
capabilities = new
{
tools = new { listChanged = false }
},
serverInfo = new
{
name = "codemaster",
version = "1.0.0"
}
};
return McpRpcResponse.Success(request.Id, initResult);
case "notifications/initialized":
return McpRpcResponse.Success(request.Id, new { });
case "ping":
return McpRpcResponse.Success(request.Id, new { });
case "tools/list":
{
using var scope = _scopeFactory.CreateScope();
var doorTools = scope.ServiceProvider.GetRequiredService<IDoorTools>();
var tools = doorTools.GetToolDefinitions();
return McpRpcResponse.Success(request.Id, new { tools });
}
case "tools/call":
{
if (!request.Params.HasValue)
{
return McpRpcResponse.CreateError(request.Id, -32602, "Missing params object for tools/call");
}
var p = request.Params.Value;
if (!p.TryGetProperty("name", out var toolNameProp) || string.IsNullOrWhiteSpace(toolNameProp.GetString()))
{
return McpRpcResponse.CreateError(request.Id, -32602, "Missing required param: 'name'");
}
var toolName = toolNameProp.GetString()!;
JsonElement? toolArgs = null;
if (p.TryGetProperty("arguments", out var argsProp))
{
toolArgs = argsProp;
}
using var scope = _scopeFactory.CreateScope();
var doorTools = scope.ServiceProvider.GetRequiredService<IDoorTools>();
var callResult = await doorTools.ExecuteToolAsync(toolName, toolArgs, ct);
return McpRpcResponse.Success(request.Id, callResult);
}
default:
_logger.LogWarning("Unsupported MCP RPC method: {Method}", request.Method);
return McpRpcResponse.CreateError(request.Id, -32601, $"Method not found: '{request.Method}'");
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error processing MCP request method '{Method}'", request.Method);
return McpRpcResponse.CreateError(request.Id, -32603, $"Internal error: {ex.Message}");
}
}
public async Task HandleSseConnectionAsync(HttpContext context, CancellationToken ct = default)
{
context.Response.Headers.ContentType = "text/event-stream";
context.Response.Headers.CacheControl = "no-cache";
context.Response.Headers.Connection = "keep-alive";
var sessionId = Guid.NewGuid().ToString("N");
var channel = Channel.CreateUnbounded<string>(new UnboundedChannelOptions { SingleReader = true, SingleWriter = false });
_activeSessions[sessionId] = channel.Writer;
_logger.LogInformation("New MCP SSE client connected. SessionId={SessionId}", sessionId);
try
{
var endpointMessage = $"event: endpoint\ndata: /mcp/messages?sessionId={sessionId}\n\n";
await context.Response.WriteAsync(endpointMessage, ct);
await context.Response.Body.FlushAsync(ct);
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(15));
var reader = channel.Reader;
while (!ct.IsCancellationRequested)
{
var readTask = reader.WaitToReadAsync(ct).AsTask();
var timerTask = timer.WaitForNextTickAsync(ct).AsTask();
var completed = await Task.WhenAny(readTask, timerTask);
if (completed == readTask)
{
while (reader.TryRead(out var msg))
{
await context.Response.WriteAsync(msg, ct);
await context.Response.Body.FlushAsync(ct);
}
}
else
{
// Keepalive ping comment
await context.Response.WriteAsync(": ping\n\n", ct);
await context.Response.Body.FlushAsync(ct);
}
}
}
catch (OperationCanceledException)
{
// Expected on client disconnect
}
catch (Exception ex)
{
_logger.LogWarning(ex, "MCP SSE connection terminated unexpectedly for SessionId={SessionId}", sessionId);
}
finally
{
_activeSessions.TryRemove(sessionId, out _);
_logger.LogInformation("MCP SSE client disconnected. SessionId={SessionId}", sessionId);
}
}
public async Task HandlePostMessageAsync(HttpContext context, string? sessionId, CancellationToken ct = default)
{
using var reader = new StreamReader(context.Request.Body);
var body = await reader.ReadToEndAsync(ct);
if (string.IsNullOrWhiteSpace(body))
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
await context.Response.WriteAsJsonAsync(McpRpcResponse.CreateError(null, -32700, "Parse error: empty request body"), ct);
return;
}
McpRpcRequest? rpcRequest;
try
{
rpcRequest = JsonSerializer.Deserialize<McpRpcRequest>(body, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
}
catch (Exception ex)
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
await context.Response.WriteAsJsonAsync(McpRpcResponse.CreateError(null, -32700, $"Parse error: {ex.Message}"), ct);
return;
}
if (rpcRequest == null)
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
await context.Response.WriteAsJsonAsync(McpRpcResponse.CreateError(null, -32600, "Invalid Request"), ct);
return;
}
var rpcResponse = await HandleRequestAsync(rpcRequest, ct);
var responseJson = JsonSerializer.Serialize(rpcResponse);
// If session exists, broadcast on SSE channel as well
if (!string.IsNullOrWhiteSpace(sessionId) && _activeSessions.TryGetValue(sessionId, out var sessionWriter))
{
var sseEvent = $"event: message\ndata: {responseJson}\n\n";
sessionWriter.TryWrite(sseEvent);
}
context.Response.ContentType = "application/json";
context.Response.StatusCode = StatusCodes.Status200OK;
await context.Response.WriteAsync(responseJson, ct);
}
}
public static class McpServerExtensions
{
public static IServiceCollection AddCodeMasterMcp(this IServiceCollection services)
{
services.AddScoped<IDoorTools, DoorTools>();
services.AddSingleton<ICodeMasterMcpServer, CodeMasterMcpServer>();
return services;
}
public static IEndpointRouteBuilder MapMcpEndpoints(this IEndpointRouteBuilder endpoints)
{
endpoints.MapGet("/mcp/sse", async (HttpContext context, ICodeMasterMcpServer server, CancellationToken ct) =>
{
await server.HandleSseConnectionAsync(context, ct);
});
endpoints.MapPost("/mcp/messages", async (HttpContext context, ICodeMasterMcpServer server, CancellationToken ct) =>
{
var sessionId = context.Request.Query["sessionId"].ToString();
await server.HandlePostMessageAsync(context, sessionId, ct);
});
// Convenience alias endpoints
endpoints.MapGet("/sse", async (HttpContext context, ICodeMasterMcpServer server, CancellationToken ct) =>
{
await server.HandleSseConnectionAsync(context, ct);
});
return endpoints;
}
}