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", ""); } } |