I ended up writing this as the primary MCP library from https://modelcontextprotocol.io/ tends to require ASP.net core hosting. Because of this requirement you are unable to embed that functionality very easily into a DLL that is used for a plugin. I build this POC server that supports .NET framework (not core) so AI can be easily integrated into any application plugin.
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 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 |
using Microsoft.Win32; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Web.Script.Serialization; using System.Windows.Forms; using static MCPHttpServerDotNetFramework.Form1; namespace DotNetPlugin { partial class Plugin { [Command("Booltestcmd")] public static bool testcmd(bool boolargs) { Console.WriteLine("testcmd!"); return boolargs; } [Command("stringTestcmder")] public static string testcmder(string stringargs) { Console.WriteLine("testcmder!"); return stringargs; } [Command("StrArraytestcmder")] public static string[] arraytestcmder(string[] args) //"Uses pipes to delimit arrays { Console.WriteLine("arraytestcmder!"); return args; } } } namespace MCPHttpServerDotNetFramework { public partial class Form1: Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Replace Plugin with your actual class type var server = new SimpleMcpServer(typeof(DotNetPlugin.Plugin)); server.Start(); Console.ReadLine(); // Keep it running } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class CommandAttribute : Attribute { public string Name { get; } public bool DebugOnly { get; set; } public CommandAttribute(string name) { Name = name; } } } public class SimpleMcpServer { private readonly HttpListener _listener = new HttpListener(); private readonly Dictionary<string, MethodInfo> _commands = new Dictionary<string, MethodInfo>(StringComparer.OrdinalIgnoreCase); private readonly Type _targetType; public SimpleMcpServer(Type commandSourceType) { //DisableServerHeader(); //Prob not needed _targetType = commandSourceType; _listener.Prefixes.Add("http://localhost:3001/sse/"); //Request come in without a trailing '/' but are still handled _listener.Prefixes.Add("http://localhost:3001/message/"); // Reflect and register [Command] methods foreach (var method in commandSourceType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) { var attr = method.GetCustomAttribute<CommandAttribute>(); if (attr != null) _commands[attr.Name] = method; } } public static void DisableServerHeader() { const string keyPath = @"SYSTEM\CurrentControlSet\Services\HTTP\Parameters"; const string valueName = "DisableServerHeader"; const int desiredValue = 2; try { using (var key = Registry.LocalMachine.CreateSubKey(keyPath, true)) { if (key == null) { Console.WriteLine("Failed to open or create the registry key."); return; } var currentValue = key.GetValue(valueName); if (currentValue == null || (int)currentValue != desiredValue) { key.SetValue(valueName, desiredValue, RegistryValueKind.DWord); Console.WriteLine("Registry value updated. Restarting HTTP service..."); RestartHttpService(); } else { Console.WriteLine("DisableServerHeader is already set to 2. No changes made."); } } } catch (Exception ex) { Console.WriteLine("Error modifying registry: " + ex.Message); } } private static void RestartHttpService() { try { ExecuteCommand("net stop http"); ExecuteCommand("net start http"); } catch (Exception ex) { Console.WriteLine("Failed to restart HTTP service. Try rebooting manually. Error: " + ex.Message); } } private static void ExecuteCommand(string command) { var process = new Process { StartInfo = new ProcessStartInfo("cmd.exe", "/c " + command) { Verb = "runas", // Run as administrator CreateNoWindow = true, UseShellExecute = true, WindowStyle = ProcessWindowStyle.Hidden } }; process.Start(); process.WaitForExit(); } public void Start() { _listener.Start(); Console.WriteLine("MCP server running"); _listener.BeginGetContext(OnRequest, null); } private static readonly Dictionary<string, StreamWriter> _sseSessions = new Dictionary<string, StreamWriter>(); private async void OnRequest(IAsyncResult ar) // Make async void for simplicity here, consider Task for robustness { HttpListenerContext ctx = _listener.EndGetContext(ar); _listener.BeginGetContext(OnRequest, null); // loop Console.WriteLine("=== Incoming Request ==="); Console.WriteLine($"Method: {ctx.Request.HttpMethod}"); Console.WriteLine($"URL: {ctx.Request.Url}"); Console.WriteLine($"Headers:"); foreach (string key in ctx.Request.Headers) { Console.WriteLine($" {key}: {ctx.Request.Headers[key]}"); } string requestBody = null; // Variable to store the body Console.WriteLine("========================="); ctx.Response.Headers["Server"] = "Kestrel"; if (ctx.Request.HttpMethod == "POST") { var path = ctx.Request.Url.AbsolutePath.ToLowerInvariant(); if (path.StartsWith("/message")) { var query = ctx.Request.QueryString["sessionId"]; if (string.IsNullOrWhiteSpace(query) || !_sseSessions.ContainsKey(query)) { ctx.Response.StatusCode = 400; ctx.Response.OutputStream.Close(); return; } using (var reader = new StreamReader(ctx.Request.InputStream)) { var jsonBody = reader.ReadToEnd(); if (ctx.Request.HasEntityBody) { Console.WriteLine("Body:"); Console.WriteLine(jsonBody); } else { Console.WriteLine("No body."); } var json = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(jsonBody); string method = json["method"]?.ToString(); var @params = json.ContainsKey("params") ? json["params"] as object[] : null; if (method == "rpc.discover") { var toolList = new List<object>(); foreach (var cmd in _commands) { toolList.Add(new { name = cmd.Key, parameters = new[] { "string[]" } }); } var response = new { jsonrpc = "2.0", id = json["id"], result = toolList }; var sseData = new JavaScriptSerializer().Serialize(response); lock (_sseSessions) { var writer = _sseSessions[query]; writer.Write($"id: {json["id"]}\n"); writer.Write($"data: {sseData}\n\n"); writer.Flush(); } ctx.Response.StatusCode = 202; ctx.Response.Close(); } else if (method == "initialize") { //POST / message?sessionId=nn-PaJBhGnUTSs8Wi9IYeA HTTP / 1.1 //Host: localhost: 3001 //Content-Type: application/json; charset=utf-8 //Content-Length: 202 //{ "jsonrpc":"2.0","id":"7b9343b583174f88bf926c1341bdf2a3-1","method":"initialize","params":{ "protocolVersion":"2024-11-05","capabilities":{ },"clientInfo":{ "name":"QuickstartClient","version":"1.0.0.0"} } } // HTTP / 1.1 202 Accepted // Date: Wed, 02 Apr 2025 03:44:44 GMT // Server: Kestrel //Transfer - Encoding: chunked //Accepted ctx.Response.SendChunked = true; ctx.Response.StatusCode = 202; //ctx.Response.ContentType = "text/plain; charset=utf-8"; using (var responseWriter = new StreamWriter(ctx.Response.OutputStream, new UTF8Encoding(false))) { responseWriter.Write($"Accepted"); responseWriter.Flush(); try { var discoverResponse = new JavaScriptSerializer().Serialize(new { jsonrpc = "2.0", id = json["id"], result = new { protocolVersion = "2024-11-05", capabilities = new { tools = new { } }, serverInfo = new { name = "AspNetCoreSseServer", version = "1.0.0.0" }, instructions = "" } }); StreamWriter writer; lock (_sseSessions) { writer = _sseSessions[query]; writer.Write($"data: {discoverResponse}\n\n"); writer.Flush(); } Debug.WriteLine("Responding with Session:" + query); } catch (Exception ex) { Console.WriteLine($"SSE connection error: {ex.Message}"); } finally { //lock (_sseSessions) // _sseSessions.Remove(sessionId); //ctx.Response.Close(); } //responseWriter.Write("Accepted"); //responseWriter.Flush(); //responseWriter.Close(); // Don't close the writer or ctx.Response — keep it open for future use //await Task.Delay(-1); // keep this handler alive forever (or until cancelled) } } else if (method == "notifications/initialized") { //POST / message?sessionId=nn-PaJBhGnUTSs8Wi9IYeA HTTP / 1.1 //Host: localhost: 3001 //Content-Type: application/json; charset=utf-8 //Content-Length: 202 //{ "jsonrpc":"2.0","id":"7b9343b583174f88bf926c1341bdf2a3-1","method":"initialize","params":{ "protocolVersion":"2024-11-05","capabilities":{ },"clientInfo":{ "name":"QuickstartClient","version":"1.0.0.0"} } } // HTTP / 1.1 202 Accepted // Date: Wed, 02 Apr 2025 03:44:44 GMT // Server: Kestrel //Transfer - Encoding: chunked //Accepted ctx.Response.SendChunked = true; ctx.Response.StatusCode = 202; //ctx.Response.ContentType = "text/plain; charset=utf-8"; using (var responseWriter = new StreamWriter(ctx.Response.OutputStream, new UTF8Encoding(false))) { responseWriter.Write("Accepted"); responseWriter.BaseStream.Flush(); } } else if (method == "tools/list") { //POST /message?sessionId=nn-PaJBhGnUTSs8Wi9IYeA HTTP/1.1 //Host: localhost: 3001 //Content-Type: application/json; charset=utf-8 //Content-Length: 202 //{"jsonrpc":"2.0","id":"d95cc745587346b4bf7df2b13ec0890a-2","method":"tools/list"} //Accepted ctx.Response.SendChunked = true; ctx.Response.StatusCode = 202; //ctx.Response.ContentType = "text/plain; charset=utf-8"; using (var responseWriter = new StreamWriter(ctx.Response.OutputStream, new UTF8Encoding(false))) { responseWriter.Write("Accepted"); responseWriter.BaseStream.Flush(); } try { // Dynamically get all Command methods var toolsList = new List<object>(); // Use _commands dictionary which should contain all registered commands foreach (var command in _commands) { string commandName = command.Key; MethodInfo methodInfo = command.Value; // Get the Command attribute to access its properties var attribute = methodInfo.GetCustomAttribute<CommandAttribute>(); if (attribute != null && (!attribute.DebugOnly || Debugger.IsAttached)) { // Get parameter info for the method var parameters = methodInfo.GetParameters(); var properties = new Dictionary<string, object>(); var required = new List<string>(); foreach (var param in parameters) { string paramName = param.Name; string paramType = GetJsonSchemaType(param.ParameterType); properties[paramName] = new { type = paramType, description = $"Parameter for {commandName}" }; if (!param.IsOptional) { required.Add(paramName); } } // Create the tool definition var tool = new { name = commandName, description = $"Command: {commandName}", inputSchema = new { title = commandName, description = $"Command: {commandName}", type = "object", properties = properties, required = required.ToArray() } }; toolsList.Add(tool); } } // Add the default tools for Diag toolsList.Add( new { name = "Echo", description = "Echoes the input back to the client.", inputSchema = new { title = "Echo", description = "Echoes the input back to the client.", type = "object", properties = new { message = new { type = "string" } }, required = new[] { "message" } } } ); var discoverResponse = new JavaScriptSerializer().Serialize(new { jsonrpc = "2.0", id = json["id"], result = new { tools = toolsList.ToArray() } }); StreamWriter writer; lock (_sseSessions) { writer = _sseSessions[query]; writer.Write($"data: {discoverResponse}\n\n"); writer.Flush(); } Debug.WriteLine("Responding with Session:" + query); } catch (Exception ex) { Console.WriteLine($"SSE connection error: {ex.Message}"); } finally { //lock (_sseSessions) // _sseSessions.Remove(sessionId); //ctx.Response.Close(); } } else if (method == "tools/call") { //POST / message?sessionId=nn-PaJBhGnUTSs8Wi9IYeA HTTP / 1.1 //Host: localhost: 3001 //Content-Type: application/json; charset=utf-8 //Content-Length: 202 //{ "jsonrpc":"2.0","id":"d95cc745587346b4bf7df2b13ec0890a-3","method":"tools/call","params":{ "name":"Echo","arguments":{ "message":"tesrt"} } } //Accepted ctx.Response.SendChunked = true; ctx.Response.StatusCode = 202; //ctx.Response.ContentType = "text/plain; charset=utf-8"; using (var responseWriter = new StreamWriter(ctx.Response.OutputStream, new UTF8Encoding(false))) { responseWriter.Write("Accepted"); responseWriter.BaseStream.Flush(); } try { Debug.WriteLine("Params: " + json["params"]); string toolName = null; Dictionary<string, object> arguments = null; string resultText = null; bool isError = false; try { // JavaScriptSerializer likely returns Dictionary<string, object> // rather than a strongly typed object, so use dictionary access var paramsDict = json["params"] as Dictionary<string, object>; if (paramsDict != null && paramsDict.ContainsKey("name")) { toolName = paramsDict["name"].ToString(); if (paramsDict.ContainsKey("arguments")) { arguments = paramsDict["arguments"] as Dictionary<string, object>; } } if (toolName == null || arguments == null) { throw new ArgumentException("Invalid request format: missing name or arguments"); } // Handle Echo command specially if (toolName == "Echo") { // Get the message using dictionary access if (arguments.ContainsKey("message")) { var message = arguments["message"]?.ToString(); resultText = "hello " + message; } else { throw new ArgumentException("Echo command requires a 'message' argument"); } } // Dynamically invoke registered commands else if (_commands.TryGetValue(toolName, out var methodInfo)) { try { // Get parameter info for the method var parameters = methodInfo.GetParameters(); var paramValues = new object[parameters.Length]; // Build parameters for the method call for (int i = 0; i < parameters.Length; i++) { var param = parameters[i]; var argName = param.Name; // Try to get the argument value using dictionary access if (arguments.ContainsKey(argName)) { var argValue = arguments[argName]; // Handle arrays specially if (param.ParameterType.IsArray && argValue != null) { // If argValue is already an array or ArrayList var argList = argValue as System.Collections.IList; if (argList != null) { var elementType = param.ParameterType.GetElementType(); var typedArray = Array.CreateInstance(elementType, argList.Count); for (int j = 0; j < argList.Count; j++) { var element = argList[j]; try { // Convert element to the correct type var convertedValue = Convert.ChangeType(element, elementType); typedArray.SetValue(convertedValue, j); } catch (Exception ex) { throw new ArgumentException($"Cannot convert element at index {j} to type {elementType.Name}: {ex.Message}"); } } paramValues[i] = typedArray; } else { throw new ArgumentException($"Parameter '{argName}' should be an array"); } } else if (argValue != null) { try { // Convert single value to the correct type paramValues[i] = Convert.ChangeType(argValue, param.ParameterType); } catch (Exception ex) { throw new ArgumentException($"Cannot convert parameter '{argName}' to type {param.ParameterType.Name}: {ex.Message}"); } } } else if (param.IsOptional) { // Use default value for optional parameters paramValues[i] = param.DefaultValue; } else { // Missing required parameter throw new ArgumentException($"Required parameter '{argName}' is missing"); } } // Invoke the method var result = methodInfo.Invoke(null, paramValues); // Convert result to string resultText = result?.ToString() ?? "Command executed successfully"; } catch (Exception ex) { resultText = $"Error executing command: {ex.Message}"; isError = true; } } else { resultText = $"Command '{toolName}' not found"; isError = true; } } catch (Exception ex) { resultText = $"Error processing command: {ex.Message}"; isError = true; } var responseJson = new JavaScriptSerializer().Serialize(new { jsonrpc = "2.0", id = json["id"], result = new { content = new object[] { new { type = "text", text = resultText } }, isError = isError } }); StreamWriter writer; lock (_sseSessions) { writer = _sseSessions[query]; writer.Write($"data: {responseJson}\n\n"); writer.Flush(); } Debug.WriteLine("Responding with Session:" + query); } catch (Exception ex) { // Handle general errors var errorJson = new JavaScriptSerializer().Serialize(new { jsonrpc = "2.0", id = json["id"], result = new { content = new object[] { new { type = "text", text = $"Error processing request: {ex.Message}" } }, isError = true } }); StreamWriter writer; lock (_sseSessions) { writer = _sseSessions[query]; writer.Write($"data: {errorJson}\n\n"); writer.Flush(); } Console.WriteLine($"Error processing tools/call: {ex.Message}"); } finally { //lock (_sseSessions) // _sseSessions.Remove(sessionId); //ctx.Response.Close(); } } else if (_commands.TryGetValue(method, out var methodInfo)) { try { string[] args = Array.ConvertAll(@params ?? new object[0], p => p?.ToString() ?? ""); var result = methodInfo.Invoke(null, new object[] { args }); var response = new { jsonrpc = "2.0", id = json["id"], result = result }; var sseData = new JavaScriptSerializer().Serialize(response); lock (_sseSessions) { var writer = _sseSessions[query]; writer.Write($"id: {json["id"]}\n"); writer.Write($"data: {sseData}\n\n"); writer.Flush(); } ctx.Response.StatusCode = 202; ctx.Response.Close(); } catch (Exception ex) { var response = new { jsonrpc = "2.0", id = json["id"], error = new { code = -32603, message = ex.Message } }; var sseData = new JavaScriptSerializer().Serialize(response); lock (_sseSessions) { var writer = _sseSessions[query]; writer.Write($"id: {json["id"]}\n"); writer.Write($"data: {sseData}\n\n"); writer.Flush(); } ctx.Response.StatusCode = 500; ctx.Response.Close(); } } else { var response = new { jsonrpc = "2.0", id = json["id"], error = new { code = -32601, message = "Unknown method" } }; var sseData = new JavaScriptSerializer().Serialize(response); lock (_sseSessions) { var writer = _sseSessions[query]; writer.Write($"id: {json["id"]}\n"); writer.Write($"data: {sseData}\n\n"); writer.Flush(); } ctx.Response.StatusCode = 404; ctx.Response.Close(); } } } else { ctx.Response.StatusCode = 404; ctx.Response.Close(); } } if (ctx.Request.HttpMethod == "GET") { var path = ctx.Request.Url.AbsolutePath.ToLowerInvariant(); if (path.EndsWith("/discover") || path.EndsWith("/mcp/")) { var toolList = new List<object>(); foreach (var cmd in _commands) { toolList.Add(new { name = cmd.Key, parameters = new[] { "string[]" } }); } var json = new JavaScriptSerializer().Serialize(new { jsonrpc = "2.0", id = (string)null, result = toolList }); var buffer = Encoding.UTF8.GetBytes(json); ctx.Response.ContentType = "application/json"; ctx.Response.ContentLength64 = buffer.Length; ctx.Response.OutputStream.Write(buffer, 0, buffer.Length); ctx.Response.Close(); } else if (path.EndsWith("/sse/") || path.EndsWith("/sse")) { ctx.Response.ContentType = "text/event-stream"; ctx.Response.StatusCode = 200; ctx.Response.SendChunked = true; ctx.Response.Headers.Add("Cache-Control", "no-store"); string sessionId = ""; using (var rng = RandomNumberGenerator.Create()) { // Create a byte array of appropriate length (16 bytes = 128 bits) // This will result in a 22-character base64 string after encoding byte[] randomBytes = new byte[16]; // Fill the array with random bytes rng.GetBytes(randomBytes); // Convert to Base64 string string base64String = Convert.ToBase64String(randomBytes); // Remove any padding characters (=) and replace any characters that could be problematic in URLs string result = base64String.TrimEnd('=').Replace('/', 'A').Replace('+', '-'); sessionId = result; } var writer = new StreamWriter(ctx.Response.OutputStream); lock (_sseSessions) _sseSessions[sessionId] = writer; // Write required handshake format writer.Write($"event: endpoint\n"); writer.Write($"data: /message?sessionId={sessionId}\n\n"); writer.Flush(); //string sessionId = "yMy7lcIzpSQT0ZCTrlGbkw"; //Guid.NewGuid().ToString("N"); } else { ctx.Response.StatusCode = 404; ctx.Response.Close(); } } } // Helper method to convert C# types to JSON schema types private string GetJsonSchemaType(Type type) { if (type == typeof(string)) return "string"; else if (type == typeof(int) || type == typeof(long) || type == typeof(short) || type == typeof(uint) || type == typeof(ulong) || type == typeof(ushort)) return "integer"; else if (type == typeof(float) || type == typeof(double) || type == typeof(decimal)) return "number"; else if (type == typeof(bool)) return "boolean"; else if (type.IsArray) return "array"; else return "object"; } } } |