|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections; |
| 6 | +using System.Diagnostics; |
| 7 | +using System.IO; |
| 8 | +using System.Text; |
| 9 | +using nanoFramework.Json; |
| 10 | + |
| 11 | +namespace nanoFramework.WebServer.Mcp |
| 12 | +{ |
| 13 | + /// <summary> |
| 14 | + /// McpServerController class provides endpoints for handling requests related to MCP (Model Context Protocol) tools. |
| 15 | + /// </summary> |
| 16 | + public class McpServerController |
| 17 | + { |
| 18 | + /// <summary> |
| 19 | + /// The supported version of the MCP protocol. |
| 20 | + /// </summary> |
| 21 | + public const string SupportedVersion = "2025-03-26"; |
| 22 | + |
| 23 | + /// <summary> |
| 24 | + /// Gets or sets the server name. |
| 25 | + /// </summary> |
| 26 | + public static string ServerName { get; set; } = "nanoFramework"; |
| 27 | + |
| 28 | + /// <summary> |
| 29 | + /// Gets or sets the server version. |
| 30 | + /// </summary> |
| 31 | + public static string ServerVersion { get; set; } = "1.0.0"; |
| 32 | + |
| 33 | + /// <summary> |
| 34 | + /// Gets or sets the instructions for using the MCP server. |
| 35 | + /// </summary> |
| 36 | + public static string Instructions { get; set; } = "This is an embedded device and only 1 request at a time should be sent."; |
| 37 | + |
| 38 | + /// <summary> |
| 39 | + /// Handles POST requests to the "mcp" route. |
| 40 | + /// Processes the incoming request, invokes the specified tool with provided parameters, and writes the result to the response stream in JSON format. |
| 41 | + /// </summary> |
| 42 | + /// <param name="e">The web server event arguments containing the HTTP context and request/response information.</param> |
| 43 | + [Route("mcp"), Method("POST")] |
| 44 | + public void HandleMcpRequest(WebServerEventArgs e) |
| 45 | + { |
| 46 | + e.Context.Response.ContentType = "application/json"; |
| 47 | + int id = 0; |
| 48 | + StringBuilder sb = new StringBuilder(); |
| 49 | + |
| 50 | + try |
| 51 | + { |
| 52 | + // Read the POST body from the request stream |
| 53 | + var requestStream = e.Context.Request.InputStream; |
| 54 | + byte[] buffer = new byte[requestStream.Length]; |
| 55 | + requestStream.Read(buffer, 0, buffer.Length); |
| 56 | + string requestBody = Encoding.UTF8.GetString(buffer, 0, buffer.Length); |
| 57 | + |
| 58 | + Debug.WriteLine($"Request Body: {requestBody}"); |
| 59 | + |
| 60 | + Hashtable request = (Hashtable)JsonConvert.DeserializeObject(requestBody, typeof(Hashtable)); |
| 61 | + |
| 62 | + // Sets jsonrpc version |
| 63 | + sb.Append("{\"jsonrpc\": \"2.0\""); |
| 64 | + // Check if we have an id if yes, add it to the answer |
| 65 | + if (request.ContainsKey("id")) |
| 66 | + { |
| 67 | + id = Convert.ToInt32(request["id"].ToString()); |
| 68 | + sb.Append($",\"id\":{id}"); |
| 69 | + } |
| 70 | + |
| 71 | + if (request.ContainsKey("method")) |
| 72 | + { |
| 73 | + // Case the server us initilaized |
| 74 | + if (request["method"].ToString() == "notifications/initialized") |
| 75 | + { |
| 76 | + WebServer.OutputHttpCode(e.Context.Response, System.Net.HttpStatusCode.OK); |
| 77 | + return; |
| 78 | + } |
| 79 | + |
| 80 | + if (request["method"].ToString() == "initialize") |
| 81 | + { |
| 82 | + // Check if client sent params with protocolVersion |
| 83 | + if (request.ContainsKey("params") && request["params"] is Hashtable initParams) |
| 84 | + { |
| 85 | + if (initParams.ContainsKey("protocolVersion")) |
| 86 | + { |
| 87 | + string clientVersion = initParams["protocolVersion"].ToString(); |
| 88 | + if (clientVersion != SupportedVersion) |
| 89 | + { |
| 90 | + sb.Append($",\"error\":{{\"code\":-32602,\"message\":\"Unsupported protocol version\",\"data\":{{\"supported\":[\"{SupportedVersion}\"],\"requested\":\"{clientVersion}\"}}}}}}"); |
| 91 | + WebServer.OutPutStream(e.Context.Response, sb.ToString()); |
| 92 | + return; |
| 93 | + } |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + sb.Append($",\"result\":{{\"protocolVersion\":\"{SupportedVersion}\""); |
| 98 | + |
| 99 | + // Add capabilities |
| 100 | + sb.Append($",\"capabilities\":{{\"logging\":{{}},\"prompts\":{{\"listChanged\":false}},\"resources\":{{\"subscribe\":false,\"listChanged\":false}},\"tools\":{{\"listChanged\":false}}}}"); |
| 101 | + |
| 102 | + // Add serverInfo |
| 103 | + sb.Append($",\"serverInfo\":{{\"name\":\"{ServerName}\",\"version\":\"{ServerVersion}\"}}"); |
| 104 | + |
| 105 | + // Add instructions |
| 106 | + sb.Append($",\"instructions\":\"{Instructions}\"}}}}"); |
| 107 | + } |
| 108 | + else if (request["method"].ToString() == "tools/list") |
| 109 | + { |
| 110 | + // This is a request for the list of tools |
| 111 | + string toolListJson = McpToolRegistry.GetToolMetadataJson(); |
| 112 | + sb.Append($",\"result\":{{{toolListJson}}}}}"); |
| 113 | + } |
| 114 | + else if (request["method"].ToString() == "tools/call") |
| 115 | + { |
| 116 | + string toolName = ((Hashtable)request["params"])["name"].ToString(); |
| 117 | + Hashtable param = ((Hashtable)request["params"])["arguments"] == null ? null : (Hashtable)((Hashtable)request["params"])["arguments"]; |
| 118 | + |
| 119 | + string result = McpToolRegistry.InvokeTool(toolName, param); |
| 120 | + |
| 121 | + sb.Append($",\"result\":{{\"content\":[{{\"type\":\"text\",\"text\":{result}}}]}}}}"); |
| 122 | + } |
| 123 | + else |
| 124 | + { |
| 125 | + sb.Append($",\"error\":{{\"code\":-32601,\"message\":\"Method not found\"}}}}"); |
| 126 | + } |
| 127 | + |
| 128 | + WebServer.OutPutStream(e.Context.Response, sb.ToString()); |
| 129 | + return; |
| 130 | + } |
| 131 | + } |
| 132 | + catch (Exception ex) |
| 133 | + { |
| 134 | + WebServer.OutPutStream(e.Context.Response, $"{{\"jsonrpc\":\"2.0\",\"id\":{id},\"error\":{{\"code\":-32602,\"message\":\"{ex.Message}\"}}}}"); |
| 135 | + } |
| 136 | + } |
| 137 | + } |
| 138 | +} |
0 commit comments