Line data Source code
1 : /*
2 : * SPDX-License-Identifier: GPL-3.0-only
3 : * MuseScore/Audacity CLA applies
4 : *
5 : * Copyright (C) 2026 MuseScore/Audacity and others
6 : *
7 : * This program is free software: you can redistribute it and/or modify
8 : * it under the terms of the GNU General Public License version 3 as
9 : * published by the Free Software Foundation.
10 : *
11 : * This program is distributed in the hope that it will be useful,
12 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 : * GNU General Public License for more details.
15 : *
16 : * You should have received a copy of the GNU General Public License
17 : * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 : */
19 :
20 : #include "mcpserver.h"
21 :
22 : #include "serialization/json.h"
23 :
24 : #include "transport/tcptransport.h"
25 : #include "transport/httptransport.h"
26 :
27 : #include "log.h"
28 :
29 : static const char* PROTOCOL_VERSION = "2025-11-25";
30 : static const char* SERVER_NAME = "MuseMCP";
31 :
32 : using ErrorCode = std::pair<int, const char*>;
33 :
34 : static constexpr ErrorCode PARSE_ERROR_CODE = { -32700, "Parse error" };
35 : static constexpr ErrorCode INVALID_REQUEST_CODE = { -32600, "Invalid request" };
36 : static constexpr ErrorCode METHOD_NOT_FOUND_CODE = { -32601, "Method not found" };
37 : static constexpr ErrorCode INVALID_PARAMS_CODE = { -32602, "Invalid params" };
38 : static constexpr ErrorCode INTERNAL_ERROR_CODE = { -32603, "Internal error" };
39 :
40 : using namespace muse::rcontrol::mcp;
41 :
42 0 : static std::map<std::string, muse::Val> toArgs(const muse::JsonObject& obj)
43 : {
44 0 : std::map<std::string, muse::Val> args;
45 0 : for (const auto& key : obj.keys()) {
46 0 : args[key] = obj[key].toVal();
47 0 : }
48 0 : return args;
49 0 : }
50 :
51 0 : static void replyError(const muse::JsonObject& request, const ErrorCode& errorCode,
52 : const std::function<void(const muse::JsonObject&)>& onResponse)
53 : {
54 0 : muse::JsonObject error;
55 0 : error["code"] = errorCode.first;
56 0 : error["message"] = errorCode.second;
57 :
58 0 : muse::JsonObject response;
59 0 : response["jsonrpc"] = "2.0";
60 0 : response["id"] = request.value("id");
61 0 : response["error"] = error;
62 :
63 0 : onResponse(response);
64 0 : }
65 :
66 0 : static void replyError(const muse::JsonObject& request, const ErrorCode& errorCode,
67 : const ITransport::ResponseHandler& onResponse)
68 : {
69 0 : replyError(request, errorCode, [onResponse](const muse::JsonObject& res) {
70 0 : onResponse(muse::JsonDocument(res).toJson(muse::JsonDocument::Format::Compact));
71 0 : });
72 0 : }
73 :
74 0 : McpServer::McpServer(const std::string& version, ITransport* transport)
75 0 : : m_version(version),
76 0 : m_transport(transport)
77 : {
78 0 : if (!m_transport) {
79 0 : m_transport = new HttpTransport();
80 : }
81 0 : }
82 :
83 0 : McpServer::~McpServer()
84 : {
85 0 : deinit();
86 0 : delete m_transport;
87 0 : m_transport = nullptr;
88 0 : }
89 :
90 0 : void McpServer::init()
91 : {
92 0 : IF_ASSERT_FAILED(m_transport) {
93 0 : return;
94 : }
95 :
96 0 : m_transport->onRequest([this](const ByteArray& request, const ITransport::ResponseHandler& onResponse) {
97 0 : std::string err;
98 0 : JsonDocument json = JsonDocument::fromJson(request, &err);
99 :
100 0 : if (!err.empty()) {
101 0 : LOGE() << "Parse error: " << err;
102 0 : replyError(JsonObject(), PARSE_ERROR_CODE, onResponse);
103 0 : return;
104 : }
105 :
106 0 : if (!json.isObject()) {
107 0 : LOGE() << "Invalid request: not an object";
108 0 : replyError(JsonObject(), INVALID_REQUEST_CODE, onResponse);
109 0 : return;
110 : }
111 :
112 0 : JsonObject req = json.rootObject();
113 0 : onRequest(req, [onResponse](const JsonObject& res) {
114 0 : JsonDocument doc(res);
115 0 : ByteArray json = doc.toJson(JsonDocument::Format::Compact);
116 0 : onResponse(json);
117 0 : });
118 0 : });
119 :
120 0 : m_transport->start();
121 : }
122 :
123 0 : void McpServer::deinit()
124 : {
125 0 : m_transport->stop();
126 0 : }
127 :
128 0 : void McpServer::onRequest(const JsonObject& request, const std::function<void(const JsonObject&)>& onResponse)
129 : {
130 0 : if (!request.contains("method")) {
131 0 : replyError(request, INVALID_REQUEST_CODE, onResponse);
132 0 : return;
133 : }
134 :
135 0 : const String method = request.value("method").toString();
136 0 : if (method == u"initialize") {
137 0 : onInitialize(request, onResponse);
138 0 : } else if (method == u"tools/list") {
139 0 : onToolsList(request, onResponse);
140 0 : } else if (method == u"tools/call") {
141 0 : onToolsCall(request, onResponse);
142 0 : } else if (method.startsWith(u"notifications/")) {
143 0 : onNotifications(method);
144 0 : onResponse(JsonObject());
145 : } else {
146 0 : LOGE() << "Unknown method: " << method;
147 0 : replyError(request, METHOD_NOT_FOUND_CODE, onResponse);
148 : }
149 0 : }
150 :
151 0 : void McpServer::onInitialize(const JsonObject& request, const std::function<void(const JsonObject&)>& onResponse)
152 : {
153 0 : JsonObject response;
154 0 : response["jsonrpc"] = "2.0";
155 0 : response["id"] = request.value("id");
156 :
157 0 : JsonObject result;
158 0 : result["protocolVersion"] = PROTOCOL_VERSION;
159 :
160 0 : JsonObject toolCapabilities;
161 0 : toolCapabilities["listChanged"] = false;
162 :
163 0 : JsonObject capabilities;
164 0 : capabilities["tools"] = toolCapabilities;
165 0 : result["capabilities"] = capabilities;
166 :
167 0 : JsonObject serverInfo;
168 0 : serverInfo["name"] = SERVER_NAME;
169 0 : serverInfo["version"] = m_version;
170 0 : result["serverInfo"] = serverInfo;
171 :
172 0 : response["result"] = result;
173 :
174 0 : onResponse(response);
175 0 : }
176 :
177 0 : void McpServer::onToolsListRequest(const ToolsListHandler& onToolsList)
178 : {
179 0 : m_onToolsList = onToolsList;
180 0 : }
181 :
182 0 : void McpServer::onToolsList(const JsonObject& request, const std::function<void(const JsonObject&)>& onResponse)
183 : {
184 0 : if (!m_onToolsList) {
185 0 : replyError(request, INTERNAL_ERROR_CODE, onResponse);
186 0 : return;
187 : }
188 :
189 0 : const JsonValue id = request.value("id");
190 0 : m_onToolsList([id, onResponse](const std::vector<Tool>& tools) {
191 0 : JsonObject response;
192 0 : response["jsonrpc"] = "2.0";
193 0 : response["id"] = id;
194 :
195 0 : JsonArray arr;
196 0 : for (const Tool& tool : tools) {
197 0 : JsonObject obj;
198 0 : obj["name"] = tool.name;
199 0 : obj["title"] = tool.title;
200 0 : obj["description"] = tool.description;
201 :
202 0 : auto propertiesSchema = [](const PropertiesSchema& schema) {
203 0 : JsonObject schemaObj;
204 0 : schemaObj["type"] = schema.type;
205 0 : JsonObject properties;
206 0 : for (const auto& [name, property] : schema.properties) {
207 0 : JsonObject propertyObj;
208 0 : propertyObj["type"] = to_string(property.type.type);
209 0 : if (property.type.format != Format::Undefined) {
210 0 : propertyObj["format"] = to_string(property.type.format);
211 : }
212 0 : propertyObj["description"] = property.description;
213 :
214 0 : if (property.enumValues) {
215 0 : propertyObj["enum"] = JsonArray::fromValList(*property.enumValues);
216 : }
217 0 : if (property.minimum) {
218 0 : propertyObj["minimum"] = JsonValue::fromVal(*property.minimum);
219 : }
220 0 : if (property.maximum) {
221 0 : propertyObj["maximum"] = JsonValue::fromVal(*property.maximum);
222 : }
223 0 : properties[name] = propertyObj;
224 0 : }
225 :
226 0 : if (!properties.empty()) {
227 0 : schemaObj["properties"] = properties;
228 :
229 0 : if (!schema.required.empty()) {
230 0 : schemaObj["required"] = JsonArray::fromStringList(schema.required);
231 : }
232 : }
233 :
234 0 : return schemaObj;
235 0 : };
236 :
237 0 : obj["inputSchema"] = propertiesSchema(tool.inputSchema);
238 :
239 0 : if (!tool.outputSchema.properties.empty()) {
240 0 : obj["outputSchema"] = propertiesSchema(tool.outputSchema);
241 : }
242 :
243 0 : JsonObject annotations;
244 0 : annotations["readOnlyHint"] = tool.annotations.readOnly;
245 0 : annotations["destructiveHint"] = tool.annotations.destructive;
246 0 : annotations["idempotentHint"] = tool.annotations.idempotent;
247 0 : annotations["openWorldHint"] = tool.annotations.openWorld;
248 0 : obj["annotations"] = annotations;
249 :
250 0 : arr << obj;
251 0 : }
252 :
253 0 : JsonObject result;
254 0 : result["tools"] = arr;
255 :
256 0 : response["result"] = result;
257 :
258 0 : onResponse(response);
259 0 : });
260 0 : }
261 :
262 0 : void McpServer::onToolsCallRequest(const ToolsCallHandler& onToolsCall)
263 : {
264 0 : m_onToolsCall = onToolsCall;
265 0 : }
266 :
267 0 : void McpServer::onToolsCall(const JsonObject& request, const std::function<void(const JsonObject&)>& onResponse)
268 : {
269 0 : if (!m_onToolsCall) {
270 0 : replyError(request, INTERNAL_ERROR_CODE, onResponse);
271 0 : return;
272 : }
273 :
274 0 : if (!request.contains("id")) {
275 0 : replyError(request, INVALID_REQUEST_CODE, onResponse);
276 0 : return;
277 : }
278 :
279 0 : if (!(request.contains("params") && request.value("params").isObject())) {
280 0 : replyError(request, INVALID_PARAMS_CODE, onResponse);
281 0 : return;
282 : }
283 :
284 0 : const JsonValue id = request.value("id");
285 0 : const JsonObject params = request.value("params").toObject();
286 :
287 0 : if (!(params.contains("name") && params.value("name").isString())) {
288 0 : replyError(request, INVALID_PARAMS_CODE, onResponse);
289 0 : return;
290 : }
291 :
292 0 : const std::string name = params.value("name").toString().toStdString();
293 0 : JsonObject arguments;
294 0 : if (params.contains("arguments") && !params.value("arguments").isNull()) {
295 0 : if (params.value("arguments").isObject()) {
296 0 : arguments = params.value("arguments").toObject();
297 : } else {
298 0 : replyError(request, INVALID_PARAMS_CODE, onResponse);
299 0 : return;
300 : }
301 : }
302 :
303 0 : m_onToolsCall(name, toArgs(arguments), [id, onResponse](const ToolResult& toolResult) {
304 0 : JsonObject response;
305 0 : response["jsonrpc"] = "2.0";
306 0 : response["id"] = id;
307 :
308 0 : JsonObject resObj;
309 0 : JsonArray content;
310 0 : bool isError = false;
311 :
312 0 : if (toolResult.ret) {
313 0 : JsonObject structuredContent;
314 0 : for (const auto& [name, val] : toolResult.result) {
315 0 : structuredContent[name] = JsonValue::fromVal(val);
316 : }
317 0 : resObj["structuredContent"] = structuredContent;
318 :
319 0 : JsonObject contentObj;
320 0 : contentObj["type"] = "text";
321 0 : contentObj["text"] = JsonDocument(structuredContent).toJson(JsonDocument::Format::Compact).constChar();
322 0 : content.append(contentObj);
323 0 : } else {
324 0 : isError = true;
325 0 : JsonObject errText;
326 0 : errText["type"] = "text";
327 0 : errText["text"] = toolResult.ret.toString();
328 0 : content.append(errText);
329 0 : }
330 :
331 0 : resObj["content"] = content;
332 0 : resObj["isError"] = isError;
333 :
334 0 : response["result"] = resObj;
335 0 : onResponse(response);
336 0 : });
337 0 : }
338 :
339 0 : void McpServer::onNotifications(const String& method)
340 : {
341 0 : LOGI() << "Notification: " << method;
342 0 : }
|