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 |
public class GeminiAI { // --- Constants --- // Base URL is constant private const string ApiUrlBase = "https://generativelanguage.googleapis.com/v1beta/models/"; // --- Instance Fields --- // API Key and Model Name are specific to the instance, passed in constructor private readonly string apiKey; private readonly string modelName; // Conversation history is specific to the instance private readonly List<Content> chatHistory; // Concurrency flag specific to chat operations on this instance private bool isSending = false; // --- Static Fields --- // HttpClient can be static and shared for performance (ensure TLS is configured elsewhere) private static readonly HttpClient httpClient = new HttpClient(); #region Gemini API Data Classes // Nested or separate, these classes define the API contract // Added initializers '= null!;' or Array.Empty to satisfy CS8618 without full nullable context public class GeminiRequest { [JsonProperty("contents")] public Content[] Contents { get; set; } = Array.Empty<Content>(); } public class Content { [JsonProperty("role")] public string Role { get; set; } = "user"; [JsonProperty("parts")] public Part[] Parts { get; set; } = Array.Empty<Part>(); } public class Part { [JsonProperty("text")] public string Text { get; set; } = null!; } // Or string.Empty public class GeminiResponse { [JsonProperty("candidates")] public Candidate[] Candidates { get; set; } = Array.Empty<Candidate>(); [JsonProperty("promptFeedback")] public PromptFeedback PromptFeedback { get; set; } = null!; } public class Candidate { [JsonProperty("content")] public Content Content { get; set; } = null!; [JsonProperty("finishReason")] public string FinishReason { get; set; } = null!; [JsonProperty("index")] public int Index { get; set; } [JsonProperty("safetyRatings")] public SafetyRating[] SafetyRatings { get; set; } = Array.Empty<SafetyRating>(); } public class SafetyRating { [JsonProperty("category")] public string Category { get; set; } = null!; [JsonProperty("probability")] public string Probability { get; set; } = null!; } public class PromptFeedback { [JsonProperty("safetyRatings")] public SafetyRating[] SafetyRatings { get; set; } = Array.Empty<SafetyRating>(); } #endregion // Gemini API Data Classes /// <summary> /// Creates a new instance of the Gemini Chat Client. /// </summary> /// <param name="apiKey">Your Google API Key.</param> /// <param name="modelNameInput">The specific Gemini model to use (e.g., "gemini-1.5-pro-latest"). Uses default if null/empty.</param> /// <exception cref="ArgumentNullException">Thrown if apiKey is null or empty.</exception> public GeminiAI(string apiKey, string modelNameInput = "gemini-2.5-pro-preview-03-25") // Default to a stable model //gemini-1.5-pro-latest { if (string.IsNullOrEmpty(apiKey)) { throw new ArgumentNullException(nameof(apiKey), "API Key cannot be null or empty."); } this.apiKey = apiKey; // Assign constructor arg to instance field // Use the input model name, or the default if input is invalid if (string.IsNullOrEmpty(modelNameInput)) { this.modelName = "gemini-2.5-pro-preview-03-25"; // Use the default from parameter signature Debug.WriteLine($"Warning: Model name was empty, defaulting to {this.modelName}"); } else { this.modelName = modelNameInput; // Assign constructor arg to instance field } this.chatHistory = new List<Content>(); // Optional: Configure static HttpClient defaults once if needed // Consider thread safety if modifying static properties after startup // if (httpClient.Timeout == TimeSpan.Zero) { httpClient.Timeout = TimeSpan.FromSeconds(120); } } /// <summary> /// Sends a message as part of the ongoing conversation, maintaining history. /// </summary> /// <param name="userMessage">The user's message.</param> /// <returns>The model's response text as a Task<string?>, or null if an error occurred.</returns> public async Task<string?> SendChatMessageAsync(string userMessage) // Return nullable string { if (isSending) { Debug.WriteLine("Error: SendChatMessageAsync called while another request is in progress."); return null; } if (string.IsNullOrWhiteSpace(userMessage)) { Debug.WriteLine("Error: User message cannot be empty."); return null; } isSending = true; try { chatHistory.Add(new Content { Role = "user", Parts = new[] { new Part { Text = userMessage } } }); // Use instance field modelName string apiUrl = $"{ApiUrlBase}{this.modelName}:generateContent?key={this.apiKey}"; var requestPayload = new GeminiRequest { Contents = chatHistory.ToArray() }; string jsonPayload = JsonConvert.SerializeObject(requestPayload, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); Debug.WriteLine($"Sending chat request to {this.modelName} with {chatHistory.Count} history items..."); using (StringContent httpContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json")) { HttpResponseMessage response = await httpClient.PostAsync(apiUrl, httpContent); string jsonResponse = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { // --- Change variable type to nullable --- GeminiResponse? geminiResponse = JsonConvert.DeserializeObject<GeminiResponse>(jsonResponse); // ---------------------------------------- // Your existing null-conditional checks handle the rest correctly string? responseText = geminiResponse?.Candidates?.FirstOrDefault()? .Content?.Parts?.FirstOrDefault()?.Text; if (!string.IsNullOrEmpty(responseText)) { // ... rest of success logic ... chatHistory.Add(new Content { Role = "model", Parts = new[] { new Part { Text = responseText } } }); return responseText.Trim(); } else { Debug.WriteLine($"Warning: Gemini returned null or empty inference response object/text. Raw JSON:\n{jsonResponse}"); return string.Empty; } } // ... rest of method ... else { Debug.WriteLine($"API Error: {(int)response.StatusCode} - {response.ReasonPhrase}\nResponse: {jsonResponse}"); if (chatHistory.Any() && chatHistory.Last().Role == "user") { chatHistory.RemoveAt(chatHistory.Count - 1); } return null; } } } catch (HttpRequestException httpEx) { Debug.WriteLine($"Network Error sending chat: {httpEx.ToString()}"); if (chatHistory.Any() && chatHistory.Last().Role == "user") { chatHistory.RemoveAt(chatHistory.Count - 1); } return null; } catch (JsonException jsonEx) { Debug.WriteLine($"JSON Error processing chat response: {jsonEx.ToString()}"); return null; } // Use fully qualified name if needed, but removing the other using should fix ambiguity catch (Exception ex) { Debug.WriteLine($"Unexpected Error sending chat: {ex.ToString()}"); if (chatHistory.Any() && chatHistory.Last().Role == "user") { chatHistory.RemoveAt(chatHistory.Count - 1); } return null; } finally { isSending = false; } } /// <summary> /// Sends a single message for inference without using or modifying the conversation history. /// </summary> /// <param name="userMessage">The user's message/prompt.</param> /// <returns>The model's response text as a Task<string?>, or null if an error occurred.</returns> public async Task<string?> InferAsync(string userMessage) // Return nullable string { if (string.IsNullOrWhiteSpace(userMessage)) { Debug.WriteLine("Error: User message for inference cannot be empty."); return null; } try { // Use instance field modelName string apiUrl = $"{ApiUrlBase}{this.modelName}:generateContent?key={this.apiKey}"; var requestPayload = new GeminiRequest { Contents = new[] { new Content { Role = "user", Parts = new[] { new Part { Text = userMessage } } } } }; string jsonPayload = JsonConvert.SerializeObject(requestPayload, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); Debug.WriteLine($"Sending inference request to {this.modelName}..."); using (StringContent httpContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json")) { HttpResponseMessage response = await httpClient.PostAsync(apiUrl, httpContent); string jsonResponse = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { // --- Change variable type to nullable --- GeminiResponse? geminiResponse = JsonConvert.DeserializeObject<GeminiResponse>(jsonResponse); // ---------------------------------------- // Your existing null-conditional checks handle the rest correctly string? responseText = geminiResponse?.Candidates?.FirstOrDefault()? .Content?.Parts?.FirstOrDefault()?.Text; if (!string.IsNullOrEmpty(responseText)) { // ... rest of success logic ... return responseText.Trim(); } else { // Handle case where deserialization might have worked but responseText is still null/empty // Or if geminiResponse itself was null Debug.WriteLine($"Warning: Gemini returned null or empty response object/text. Raw JSON:\n{jsonResponse}"); if (chatHistory.Any() && chatHistory.Last().Role == "user") { chatHistory.RemoveAt(chatHistory.Count - 1); } return string.Empty; } } // ... rest of method ... else { Debug.WriteLine($"API Error during inference: {(int)response.StatusCode} - {response.ReasonPhrase}\nResponse: {jsonResponse}"); return null; } } } catch (HttpRequestException httpEx) { Debug.WriteLine($"Network Error during inference: {httpEx.ToString()}"); return null; } catch (JsonException jsonEx) { Debug.WriteLine($"JSON Error processing inference response: {jsonEx.ToString()}"); return null; } // Use fully qualified name if needed catch (Exception ex) { Debug.WriteLine($"Unexpected Error during inference: {ex.ToString()}"); return null; } } /// <summary> /// Clears the internal conversation history for this client instance. /// </summary> public void ClearHistory() { this.chatHistory.Clear(); Debug.WriteLine("Chat history cleared."); } // Optional: Add method to get current history if needed public IReadOnlyList<Content> GetHistory() => chatHistory.AsReadOnly(); } // End of GeminiAI class |
X64DBG MCP Server Plugin in C# prototype
With the great help of https://github.com/mrexodia/DotNetPluginCS by Adams85 and approx. ~20 hours of coding time I managed to create a starting point for a self-contained MCP Server for x64Dbg. I have some cleaning up of some of the code to do but is a perfect proof of concept of getting this thing to fly.
One of the larger hurdles that needed to be overcome was creating a self contained MCP server without the ASP.NET hosting core dependency.
I’ve validated a few commands so far and is currently working wonders. I’m very excited to get this into the hands of a capable LLM.
I will continue to work and make improvements on this project as I am currently using it as an opportunity to grow me experience with AI integration and implementation / security.
1 2 3 4 5 6 7 8 9 |
ExecuteDebuggerCommand command=init C:\PathTo\Binary.exe GetAllRegisters ReadMemAtAddress addressStr=0x000000014000153f, byteCount=5 ReadMemAtAddress addressStr=00007FFA1AC81000, byteCount=5 WriteMemToAddress addressStr=0x000000014000153f, byteString=90 90 90 90 90 90 CommentOrLabelAtAddress addressStr=0x000000014000153f, value=Test, mode=Comment #Removes the comment CommentOrLabelAtAddress addressStr=0x000000014000153f, value= GetLabel addressStr=0x000000014000153f |
There are a few commands I am actively working the kinks out on but it wont take me long to straighten out. I am release the source code to the public to assist them with streamlining their reverse engineering process and another useful tool to add into their collect for those whom don’t want to be directly dependent on Ghidra. *Cheers*
1 2 3 4 5 6 7 8 9 |
GetAllActiveThreads [GetAllActiveThreads] Found 4 active threads: TID: 121428560 | EntryPoint: 0x0 | TEB: 0x0 TID: 0 | EntryPoint: 0x0 | TEB: 0x0 TID: 0 | EntryPoint: 0x0 | TEB: 0x0 TID: 0 | EntryPoint: 0x0 | TEB: 0x0 GetCallStack GetAllModulesFromMemMap |



You can run the project and rebuild / modify from the source or copy the files (DotNetPluginCS\bin\x64\Debug) into the x64DBG plugin (x96\release\x64\plugins) folder to run
All of these files may not be necessary but it does not seem to impact x64DBG running at all. Once you run x64DBG, the plugin menu will appear and you may select “Start MCP Server”. From there you may connect to it with your MCP AI Client.

If any of you have any suggestions or would like help in creating your own integration feel free to drop me an email (information on contact page) as I am looking for additional opportunities to grow in this area.
Download the latest copy here: https://github.com/AgentSmithers/x64DbgMCPServer
Dynamic library-less MCP server to support use as a plugin (without ASP.net hosting required)
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"; } } } |
Updates MCP client to support Dynamic server command responses
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 |
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using ModelContextProtocol.Client; using ModelContextProtocol.Protocol.Transport; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json; using System.Threading.Tasks; // Create a command processor to handle dynamic commands public class CommandProcessor { // Helper class to store command information private class CommandInfo { public string Name { get; set; } public string Description { get; set; } public Dictionary<string, object?> Parameters { get; set; } public List<string> RequiredParameters { get; set; } public Dictionary<string, string> ParameterTypes { get; set; } public Dictionary<string, string> ParameterDescriptions { get; set; } public CommandInfo(string name, string description) { Name = name; Description = description; Parameters = new Dictionary<string, object?>(); RequiredParameters = new List<string>(); ParameterTypes = new Dictionary<string, string>(); ParameterDescriptions = new Dictionary<string, string>(); } } // Dictionary to store available commands private Dictionary<string, CommandInfo> availableCommands = new Dictionary<string, CommandInfo>(StringComparer.OrdinalIgnoreCase); private Dictionary<string, CommandInfo> commandAliases = new Dictionary<string, CommandInfo>(StringComparer.OrdinalIgnoreCase); // Call this when initializing the application or when you want to refresh the commands public async Task RefreshAvailableCommandsAsync(IMcpClient mcpClient) { availableCommands.Clear(); commandAliases.Clear(); try { var tools = await mcpClient.ListToolsAsync(); foreach (var tool in tools) { Console.WriteLine($"Registering tool: {tool.Name}"); var command = new CommandInfo(tool.Name, tool.Description); // Parse JSON schema to extract parameter information if (tool.JsonSchema.ValueKind == JsonValueKind.Object) { var properties = tool.JsonSchema.GetProperty("properties"); if (properties.ValueKind == JsonValueKind.Object) { foreach (var property in properties.EnumerateObject()) { string paramName = property.Name; string paramType = "string"; // Default type string paramDescription = ""; if (property.Value.TryGetProperty("type", out var typeElement)) { paramType = typeElement.GetString() ?? "string"; } if (property.Value.TryGetProperty("description", out var descElement)) { paramDescription = descElement.GetString() ?? ""; } command.ParameterTypes[paramName] = paramType; command.ParameterDescriptions[paramName] = paramDescription; } } // Get required parameters if (tool.JsonSchema.TryGetProperty("required", out var requiredElement) && requiredElement.ValueKind == JsonValueKind.Array) { foreach (var item in requiredElement.EnumerateArray()) { string? reqParam = item.GetString(); if (!string.IsNullOrEmpty(reqParam)) { command.RequiredParameters.Add(reqParam); } } } } // Add command to dictionary availableCommands[tool.Name] = command; // Add command alias (lowercase version) commandAliases[tool.Name.ToLowerInvariant()] = command; } Console.WriteLine($"Registered {availableCommands.Count} commands from the server."); Console.WriteLine($"-Here are some example call formats-"); Console.WriteLine($"sampleLLM prompt=hi, maxTokens=5"); Console.WriteLine($"MyarrayFunction arg=String1|String2|string3"); } catch (Exception ex) { Console.WriteLine($"Error refreshing commands: {ex.Message}"); } } // Process user input and map to appropriate commands public bool ProcessUserInput(string userInput, out string method, out Dictionary<string, object?> parameters) { method = string.Empty; parameters = new Dictionary<string, object?>(); if (string.IsNullOrWhiteSpace(userInput)) return false; // Split input into command and arguments string[] parts = userInput.Split(new[] { ' ' }, 2); string commandName = parts[0].ToLowerInvariant(); string args = parts.Length > 1 ? parts[1] : string.Empty; CommandInfo? command = null; // Check for direct command match if (availableCommands.TryGetValue(commandName, out command) || commandAliases.TryGetValue(commandName, out command)) { // Command found directly } else { Console.WriteLine($"Unknown command: {commandName}"); Console.WriteLine("Available commands:"); foreach (var cmd in availableCommands.Values.Distinct()) { Console.WriteLine($"- {cmd.Name}: {cmd.Description}"); } return false; } method = command.Name; // Parse parameters based on schema if (!TryParseParameters(args, command, parameters)) { return false; } // Check if all required parameters are provided foreach (var requiredParam in command.RequiredParameters) { if (!parameters.ContainsKey(requiredParam)) { Console.WriteLine($"Missing required parameter: {requiredParam}"); Console.WriteLine($"Usage: {command.Name} {string.Join(", ", command.RequiredParameters.Select(p => p + "=<value>"))}"); return false; } } return true; } // Helper method to parse parameters private bool TryParseParameters(string args, CommandInfo command, Dictionary<string, object?> parameters) { try { if (!string.IsNullOrEmpty(args)) { // Parse as key=value pairs var argPairs = args.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var pair in argPairs) { var keyValue = pair.Split(new[] { '=' }, 2); if (keyValue.Length == 2) { string key = keyValue[0].Trim(); string value = keyValue[1].Trim(); if (command.ParameterTypes.TryGetValue(key, out var paramType)) { // Convert value based on parameter type switch (paramType.ToLowerInvariant()) { case "integer": if (int.TryParse(value, out var intValue)) parameters[key] = intValue; else parameters[key] = 0; break; case "number": if (double.TryParse(value, out var doubleValue)) parameters[key] = doubleValue; else parameters[key] = 0.0; break; case "boolean": parameters[key] = value.ToLowerInvariant() == "true"; break; case "array": parameters[key] = value.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); break; default: parameters[key] = value; break; } } else { // If type is unknown, just use the string value parameters[key] = value; } } } } return true; } catch (Exception ex) { Console.WriteLine($"Error parsing command parameters: {ex.Message}"); return false; } } // Helper method to display information about available commands public void DisplayHelpInfo() { Console.WriteLine("Available commands:"); foreach (var cmd in availableCommands.Values) { Console.WriteLine($"- {cmd.Name}: {cmd.Description}"); if (cmd.RequiredParameters.Count > 0) { Console.WriteLine($" Required parameters: {string.Join(", ", cmd.RequiredParameters)}"); } if (cmd.ParameterTypes.Count > 0) { Console.WriteLine(" Parameters:"); foreach (var param in cmd.ParameterTypes) { string description = cmd.ParameterDescriptions.ContainsKey(param.Key) ? cmd.ParameterDescriptions[param.Key] : ""; Console.WriteLine($" {param.Key} ({param.Value}): {description}"); } } Console.WriteLine(); } Console.WriteLine("Special commands:"); Console.WriteLine("- help: Display this help information"); Console.WriteLine("- refresh: Refresh the list of available commands from the server"); Console.WriteLine("- exit: Exit the application"); } } // Main program class public class Program { public static async Task Main(string[] args) { var builder = Host.CreateApplicationBuilder(args); builder.Configuration .AddEnvironmentVariables() .AddUserSecrets<Program>(); var (command, arguments) = GetCommandAndArguments(args); await using var mcpClient = await McpClientFactory.CreateAsync(new() { Id = "demo-server", Name = "Demo Server", TransportType = TransportTypes.Sse, Location = "http://localhost:3001/sse", }); // Create a command processor var commandProcessor = new CommandProcessor(); // Initialize with available commands from the server await commandProcessor.RefreshAvailableCommandsAsync(mcpClient); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("MCP Client Started!"); Console.ResetColor(); PromptForInput(); while (Console.ReadLine() is string query && !"exit".Equals(query, StringComparison.OrdinalIgnoreCase)) { if (string.IsNullOrWhiteSpace(query)) { PromptForInput(); continue; } // Special commands if (query.Equals("help", StringComparison.OrdinalIgnoreCase)) { commandProcessor.DisplayHelpInfo(); PromptForInput(); continue; } else if (query.Equals("refresh", StringComparison.OrdinalIgnoreCase)) { await commandProcessor.RefreshAvailableCommandsAsync(mcpClient); PromptForInput(); continue; } // Process user command if (commandProcessor.ProcessUserInput(query, out string method, out Dictionary<string, object?> parameters)) { Console.WriteLine($"Invoking {method}..."); try { // Pass the parameters as IReadOnlyDictionary<string, object?> var response = await mcpClient.CallToolAsync(method, parameters); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Response:"); Console.ResetColor(); if (response is ModelContextProtocol.Protocol.Types.CallToolResponse toolResponse) { foreach (var content in toolResponse.Content) { if (!string.IsNullOrWhiteSpace(content.Text)) { Console.WriteLine(content.Text); } else if (content.Data is string data) { Console.WriteLine(data); } else if (content.Resource is { Uri: not null } resource) { Console.WriteLine($"[Resource]: {resource.Uri}"); } else { Console.WriteLine("[Unknown content format]"); } } } else { Console.WriteLine(response?.ToString() ?? "[null response]"); } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"Error calling method: {ex.Message}"); Console.ResetColor(); } } PromptForInput(); } } static void PromptForInput() { Console.WriteLine("Enter a command (or 'exit' to quit, 'help' for available commands):"); Console.ForegroundColor = ConsoleColor.Cyan; Console.Write("> "); Console.ResetColor(); } /// <summary> /// Determines the command (executable) to run and the script/path to pass to it. /// </summary> static (string command, string arguments) GetCommandAndArguments(string[] args) { return ("C:\\Users\\User\\source\\repos\\mcp-csharp-sdk\\artifacts\\bin\\QuickstartWeatherServer\\Debug\\net8.0\\QuickstartWeatherServer.exe", ""); } } |
Testing MCP connectivity over SSE without an LLM in the middle (Raw JSON request)
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 |
using Anthropic.SDK; using Anthropic.SDK.Messaging; using Microsoft.Extensions.AI; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using ModelContextProtocol.Client; using ModelContextProtocol.Protocol.Transport; var builder = Host.CreateApplicationBuilder(args); builder.Configuration .AddEnvironmentVariables() .AddUserSecrets<Program>(); var (command, arguments) = GetCommandAndArguments(args); await using var mcpClient = await McpClientFactory.CreateAsync(new() { Id = "demo-server", Name = "Demo Server", TransportType = TransportTypes.Sse, Location = "https://localhost:7133/sse", //TransportType = TransportTypes.StdIo, //TransportOptions = new() //{ // ["command"] = command, // ["arguments"] = arguments, //} }); var tools = await mcpClient.ListToolsAsync(); foreach (var tool in tools) { Console.WriteLine($"Connected to server with tools: {tool.Name}"); } //using var anthropicClient = new AnthropicClient(new APIAuthentication(builder.Configuration["ANTHROPIC_API_KEY"])) // .Messages // .AsBuilder() // .UseFunctionInvocation() // .Build(); //var options = new ChatOptions //{ // MaxOutputTokens = 1000, // ModelId = "claude-3-5-sonnet-20241022", // Tools = [.. tools] //}; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("MCP Client Started!"); Console.ResetColor(); PromptForInput(); while (Console.ReadLine() is string query && !"exit".Equals(query, StringComparison.OrdinalIgnoreCase)) { if (string.IsNullOrWhiteSpace(query)) { PromptForInput(); continue; } string method; Dictionary<string, object?> parameters; if (query.StartsWith("forecast", StringComparison.OrdinalIgnoreCase)) { method = "GetForecast"; parameters = new Dictionary<string, object?> { ["latitude"] = 39.7456, ["longitude"] = -97.0892 }; } else if (query.StartsWith("alerts", StringComparison.OrdinalIgnoreCase)) { method = "GetAlerts"; parameters = new Dictionary<string, object?> { ["state"] = "KS" }; } else if (query.StartsWith("echo ", StringComparison.OrdinalIgnoreCase)) { method = "Echo"; parameters = new() { ["message"] = query.Substring(5) }; } else if (query.StartsWith("sample ", StringComparison.OrdinalIgnoreCase)) { method = "sampleLLM"; var promptText = query.Substring(7).Trim(); if (string.IsNullOrEmpty(promptText)) { Console.WriteLine("Please provide a prompt, e.g. sample Hello AI"); PromptForInput(); continue; } parameters = new() { ["prompt"] = promptText, ["maxTokens"] = 100 }; } else { Console.WriteLine("Unknown command. Try: 'forecast' or 'alerts'"); PromptForInput(); continue; } Console.WriteLine($"Invoking {method}..."); var response = await mcpClient.CallToolAsync(method, parameters); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Response:"); Console.ResetColor(); if (response is ModelContextProtocol.Protocol.Types.CallToolResponse toolResponse) { foreach (var content in toolResponse.Content) { if (!string.IsNullOrWhiteSpace(content.Text)) { Console.WriteLine(content.Text); } else if (content.Data is string data) { Console.WriteLine(data); } else if (content.Resource is { Uri: not null } resource) { Console.WriteLine($"[Resource]: {resource.Uri}"); } else { Console.WriteLine("[Unknown content format]"); } } } else { Console.WriteLine(response?.ToString() ?? "[null response]"); } Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Response:"); Console.ResetColor(); Console.WriteLine(response); PromptForInput(); } static void PromptForInput() { Console.WriteLine("Enter a command (or 'exit' to quit):"); Console.ForegroundColor = ConsoleColor.Cyan; Console.Write("> "); Console.ResetColor(); } /// <summary> /// Determines the command (executable) to run and the script/path to pass to it. This allows different /// languages/runtime environments to be used as the MCP server. /// </summary> /// <remarks> /// This method uses the file extension of the first argument to determine the command, if it's py, it'll run python, /// if it's js, it'll run node, if it's a directory or a csproj file, it'll run dotnet. /// /// If no arguments are provided, it defaults to running the QuickstartWeatherServer project from the current repo. /// /// This method would only be required if you're creating a generic client, such as we use for the quickstart. /// </remarks> static (string command, string arguments) GetCommandAndArguments(string[] args) { return ("C:\\Users\\User\\source\\repos\\mcp-csharp-sdk\\artifacts\\bin\\QuickstartWeatherServer\\Debug\\net8.0\\QuickstartWeatherServer.exe", ""); //return args switch //{ // [var script] when script.EndsWith(".py") => ("python", script), // [var script] when script.EndsWith(".js") => ("node", script), // [var script] when Directory.Exists(script) || (File.Exists(script) && script.EndsWith(".csproj")) => ("dotnet", $"run --project {script} --no-build"), // _ => ("dotnet", "run --project ../../../QuickstartWeatherServer --no-build") //}; } |