#include "McpServer.h" #include "HostedPluginManager.h" // httplib included in exactly ONE .cpp #define CPPHTTPLIB_THREAD_POOL_COUNT 2 #include "httplib.h" #include "json.hpp" using json = nlohmann::json; McpServer::McpServer(int port, HostedPluginManager& pluginManager) : server(std::make_unique()), port(port), pluginManager(pluginManager) { setupRoutes(); } McpServer::~McpServer() { stop(); } void McpServer::setupRoutes() { // Single MCP endpoint server->Post("/mcp", [this](const httplib::Request& req, httplib::Response& res) { res.set_header("Access-Control-Allow-Origin", "http://localhost"); try { auto body = json::parse(req.body); std::string method = body.value("method", ""); std::string responseStr; if (method == "initialize") { responseStr = handleInitialize(req.body); } else if (method == "notifications/initialized") { initialized = true; res.status = 204; return; } else if (method == "tools/list") { responseStr = handleToolsList(req.body); } else if (method == "tools/call") { responseStr = handleToolsCall(req.body); } else { json errResponse = { {"jsonrpc", "2.0"}, {"id", body.value("id", json(nullptr))}, {"error", {{"code", -32601}, {"message", "Method not found"}}} }; responseStr = errResponse.dump(); } if (!responseStr.empty()) res.set_content(responseStr, "application/json"); } catch (const json::exception&) { json errResponse = { {"jsonrpc", "2.0"}, {"id", nullptr}, {"error", {{"code", -32700}, {"message", "Parse error"}}} }; res.set_content(errResponse.dump(), "application/json"); } }); // Health check server->Get("/health", [this](const httplib::Request&, httplib::Response& res) { json health = { {"status", "ok"}, {"port", port}, {"initialized", initialized}, {"plugin", pluginManager.isLoaded() ? pluginManager.getPluginName().toStdString() : "none"}, {"params", pluginManager.getParameterCount()} }; res.set_content(health.dump(), "application/json"); }); // CORS preflight server->Options("/mcp", [](const httplib::Request&, httplib::Response& res) { res.set_header("Access-Control-Allow-Origin", "http://localhost"); res.set_header("Access-Control-Allow-Methods", "POST, OPTIONS"); res.set_header("Access-Control-Allow-Headers", "Content-Type, Mcp-Session-Id"); res.status = 204; }); } void McpServer::start() { if (running.load()) return; serverThread = std::thread([this]() { running.store(true); server->listen("127.0.0.1", port); running.store(false); }); server->wait_until_ready(); } void McpServer::stop() { if (server && server->is_running()) server->stop(); if (serverThread.joinable()) serverThread.join(); running.store(false); } bool McpServer::isRunning() const { return running.load(); } // --- MCP Protocol Handlers --- std::string McpServer::handleInitialize(const std::string& requestBody) { auto body = json::parse(requestBody); sessionId = "pb-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()); json response = { {"jsonrpc", "2.0"}, {"id", body.value("id", json(nullptr))}, {"result", { {"protocolVersion", "2025-06-18"}, {"capabilities", {{"tools", {{"listChanged", false}}}}}, {"serverInfo", {{"name", "PluginBridge"}, {"version", "0.2.0"}}} }} }; return response.dump(); } std::string McpServer::handleToolsList(const std::string& requestBody) { auto body = json::parse(requestBody); json response = { {"jsonrpc", "2.0"}, {"id", body.value("id", json(nullptr))}, {"result", { {"tools", json::array({ { {"name", "list_plugins"}, {"description", "List loaded plugin instances"}, {"inputSchema", {{"type", "object"}, {"properties", json::object()}}} }, { {"name", "search_param"}, {"description", "Search plugin parameters by keyword. Returns matching param IDs and values."}, {"inputSchema", { {"type", "object"}, {"properties", { {"plugin", {{"type", "string"}, {"description", "Plugin name"}}}, {"keyword", {{"type", "string"}, {"description", "Search term (e.g. 'band 1', 'gain', 'cutoff')"}}} }}, {"required", json::array({"plugin", "keyword"})} }} }, { {"name", "get_params"}, {"description", "Get current values for parameter IDs"}, {"inputSchema", { {"type", "object"}, {"properties", { {"plugin", {{"type", "string"}}}, {"ids", {{"type", "array"}, {"items", {{"type", "integer"}}}}} }}, {"required", json::array({"plugin", "ids"})} }} }, { {"name", "set_params"}, {"description", "Set parameter values by ID (batch). Values are 0.0-1.0 normalized."}, {"inputSchema", { {"type", "object"}, {"properties", { {"plugin", {{"type", "string"}}}, {"values", {{"type", "object"}, {"description", "Map of param_index (string) to value (0.0-1.0)"}}} }}, {"required", json::array({"plugin", "values"})} }} }, { {"name", "get_analysis"}, {"description", "Get real-time audio analysis (LUFS, frequency bands, stereo width)"}, {"inputSchema", {{"type", "object"}, {"properties", json::object()}}} } })} }} }; return response.dump(); } std::string McpServer::handleToolsCall(const std::string& requestBody) { auto body = json::parse(requestBody); auto params = body["params"]; std::string toolName = params["name"]; auto args = params.value("arguments", json::object()); std::string resultText; bool isError = false; if (toolName == "list_plugins") { resultText = toolListPlugins(); } else if (toolName == "search_param") { resultText = toolSearchParam( args.value("plugin", ""), args.value("keyword", "")); } else if (toolName == "get_params") { resultText = toolGetParams( args.value("plugin", ""), args.value("ids", json::array()).dump()); } else if (toolName == "set_params") { resultText = toolSetParams( args.value("plugin", ""), args.value("values", json::object()).dump()); } else if (toolName == "get_analysis") { resultText = toolGetAnalysis(); } else { resultText = "unknown tool: " + toolName; isError = true; } json response = { {"jsonrpc", "2.0"}, {"id", body.value("id", json(nullptr))}, {"result", { {"content", json::array({{{"type", "text"}, {"text", resultText}}})}, {"isError", isError} }} }; return response.dump(); } // --- Tool Implementations --- std::string McpServer::toolListPlugins() { if (!pluginManager.isLoaded()) return "[]"; json result = json::array({pluginManager.getPluginName().toStdString()}); return result.dump(); } std::string McpServer::toolSearchParam(const std::string& /*plugin*/, const std::string& keyword) { if (!pluginManager.isLoaded()) return "no plugin loaded"; auto results = pluginManager.searchParams(juce::String(keyword)); if (results.empty()) return "no matches for '" + keyword + "'"; // Compact output: [{id, name, value}] json output = json::array(); for (auto& p : results) { output.push_back({ {"i", p.index}, {"n", p.name.toStdString()}, {"v", std::round(p.value * 1000.0f) / 1000.0f}, {"t", p.displayText.toStdString()} }); } return output.dump(); } std::string McpServer::toolGetParams(const std::string& /*plugin*/, const std::string& idsJson) { if (!pluginManager.isLoaded()) return "no plugin loaded"; auto idsArray = json::parse(idsJson); std::vector ids; for (auto& id : idsArray) ids.push_back(id.get()); auto results = pluginManager.getParams(ids); // Compact: {id: value, id: value} json output = json::object(); for (auto& [idx, val] : results) output[std::to_string(idx)] = std::round(val * 1000.0f) / 1000.0f; return output.dump(); } std::string McpServer::toolSetParams(const std::string& /*plugin*/, const std::string& valuesJson) { if (!pluginManager.isLoaded()) return "no plugin loaded"; auto valuesObj = json::parse(valuesJson); std::map values; for (auto& [key, val] : valuesObj.items()) values[std::stoi(key)] = val.get(); bool ok = pluginManager.setParams(values); return ok ? "ok" : "error"; } std::string McpServer::toolGetAnalysis() { // Sprint 4: will return real analysis return "silent"; }