From 263447eb65d2f3325f09f640621761008690f2cf Mon Sep 17 00:00:00 2001 From: Gleb Pesin Date: Wed, 2 Dec 2026 19:24:59 +0200 Subject: [PATCH 1/2] feat(mcp): speak MCP 2026-07-28 next to the initialize-era versions A call in the 2026-07-28 form (the version and the client's capabilities in params._meta, the version also in MCP-Protocol-Version) now gets what that version defines: - server/discover: the supported version, the tools capability, cacheable for an hour by anyone; - results with resultType "complete" and the server in _meta["io.modelcontextprotocol/serverInfo"]; tools/list is not cached and private, since it follows the tool permissions behind the API key; - subscriptions/listen: an event stream that acknowledges no notifications (this server sends none) and ends with the result; - the checks and errors of the transport: Mcp-Method and, for tools/call, Mcp-Name (also in its "=?base64?...?=" form) must match the body (-32020), a version other than 2026-07-28 is -32022 with the supported list, missing capabilities or a wrong log level are -32602, all with HTTP 400; methods that version does not have here (initialize, ping, logging/setLevel, prompts, resources, completion) are -32601 with 404; - a Last-Event-ID is ignored, as the version has no stream resumption. Calls without the 2026-07-28 form are answered as before. Co-Authored-By: Claude Opus 5.5 --- server-cpp/src/ai/mcp.cpp | 179 ++++++++++++++++++++++++++++---------- server-cpp/src/ai/mcp.hpp | 6 ++ 2 files changed, 137 insertions(+), 48 deletions(-) diff --git a/server-cpp/src/ai/mcp.cpp b/server-cpp/src/ai/mcp.cpp index 5499f5ba3..080b39369 100644 --- a/server-cpp/src/ai/mcp.cpp +++ b/server-cpp/src/ai/mcp.cpp @@ -570,6 +570,42 @@ std::string response_error(const Id &id, int code, const std::string &message, c return out + "}}"; } +// The 2026-07-28 protocol: the fields every result starts with, the kind of result and who answers. +const std::string &modern_head() +{ + static const std::string head = std::string(R"("resultType":"complete","_meta":{"io.modelcontextprotocol/serverInfo":{"name":")") + + server_name + R"(","version":")" + server_version + R"("}})"; + return head; +} + +// A result object from its fields ("" for none), with the 2026-07-28 head when modern. +std::string result_object(bool modern, const std::string &fields) +{ + if (!modern) return "{" + fields + "}"; + return "{" + modern_head() + (fields.empty() ? "" : ",") + fields + "}"; +} + +// The versions the 2026-07-28 request form (a version in each request's _meta) is spoken in. +const std::vector modern_versions = {"2026-07-28"}; + +// The 2026-07-28 methods a client may call here: the server advertises tools only, so the prompt, resource and +// completion methods are not there, and the methods of the initialize era (initialize, ping, logging/setLevel, +// resources/subscribe) are gone from this version. +bool modern_method(const std::string &method) +{ + return method == "server/discover" || method == "tools/list" || method == "tools/call" || method == "subscriptions/listen"; +} + +// The Mcp-Name header's value: plain, or UTF-8 in the "=?base64?...?=" form for values a header cannot carry. +std::optional mcp_name_value(const std::string &header) +{ + constexpr std::string_view prefix = "=?base64?", suffix = "?="; + if (header.size() < prefix.size() + suffix.size() || header.compare(0, prefix.size(), prefix) != 0 || + header.compare(header.size() - suffix.size(), suffix.size(), suffix) != 0) + return header; + return base64::decode(std::string_view(header).substr(prefix.size(), header.size() - prefix.size() - suffix.size())); +} + HttpResponse text_error(int status, const std::string &text) { HttpResponse r; @@ -624,24 +660,25 @@ ToolResult ok_result() // The answer to a tools/call: the JSON-RPC envelope with the result written into it, once. A screenshot goes in as // base64, which MCP's image content is: encoded in place, with no string of it in between and no pass for JSON // escapes, which its alphabet does not need. -std::string tool_response(const Id &id, const ToolResult &r) +std::string tool_response(const Id &id, const ToolResult &r, bool modern = false) { - std::string out = "{\"jsonrpc\":\"2.0\",\"id\":" + id.json() + ",\"result\":"; + std::string out = "{\"jsonrpc\":\"2.0\",\"id\":" + id.json() + ",\"result\":{"; + if (modern) out += modern_head() + ","; if (!r.error.empty() || (!r.has_output && r.tool_error.empty())) { - out += R"({"content":[{"type":"text","text":)" + json::quote(r.error) + R"(}],"isError":true})"; + out += R"("content":[{"type":"text","text":)" + json::quote(r.error) + R"(}],"isError":true})"; return out + "}"; } std::string structured = json::marshal(r.output); if (!r.tool_error.empty()) { - out += R"({"content":[{"type":"text","text":)" + json::quote(r.tool_error) + "}]"; + out += R"("content":[{"type":"text","text":)" + json::quote(r.tool_error) + "}]"; } else if (!r.jpeg.empty()) { - static constexpr std::string_view head = R"({"content":[{"type":"image","mimeType":"image/jpeg","data":")"; + static constexpr std::string_view head = R"("content":[{"type":"image","mimeType":"image/jpeg","data":")"; out.reserve(out.size() + head.size() + base64::encoded_size(r.jpeg.size()) + structured.size() + 64); out += head; base64::append(out, r.jpeg); out += "\"}]"; } else { - out += R"({"content":[{"type":"text","text":)" + json::quote(structured) + "}]"; + out += R"("content":[{"type":"text","text":)" + json::quote(structured) + "}]"; } out += ",\"structuredContent\":"; out += structured; @@ -1706,6 +1743,8 @@ struct Session { Devices &devices; std::vector tools; const Caller &caller; + bool modern = false; // the 2026-07-28 form: results carry resultType and the server in _meta + std::string stream_head; // events a subscriptions/listen stream sends before its answer }; // What is wrong with the type of params or of one of its named members; "" when fine. @@ -1743,14 +1782,35 @@ std::string handle_call(Session &s, const Message &m) if (method == "tools/list" || method == "resources/list" || method == "prompts/list" || method == "resources/templates/list") fields = {{"cursor", Value::Kind::string}}; if (method == "tools/call") fields = {{"name", Value::Kind::string}}; + if (s.modern && method == "subscriptions/listen") fields = {{"notifications", Value::Kind::object}}; if (auto e = params_type_error(params, fields); !e.empty()) return invalid(e); + if (s.modern && method == "server/discover") { + std::string versions; + for (const auto &v : modern_versions) versions += (versions.empty() ? "" : ",") + json::quote(v, false); + // The versions and capabilities change only with the server's build: an hour of cache, the same for anyone. + return response_ok(m.id, result_object(true, R"("supportedVersions":[)" + versions + + R"(],"capabilities":{"tools":{}},"ttlMs":3600000,"cacheScope":"public")")); + } + if (s.modern && method == "subscriptions/listen") { + const Value *n = params.get("notifications"); + if (!n || !n->is_object()) return invalid("missing required \"notifications\""); + // This server sends no notifications (its tool list has no change events), so it agrees to none of those + // asked for, and the subscription ends at once: the acknowledgement, then the result. + std::string id_meta = "\"io.modelcontextprotocol/subscriptionId\":" + m.id.json(); + s.stream_head = R"({"jsonrpc":"2.0","method":"notifications/subscriptions/acknowledged","params":{"notifications":{},"_meta":{)" + + id_meta + "}}}"; + return response_ok(m.id, R"({"resultType":"complete","_meta":{)" + id_meta + R"(,"io.modelcontextprotocol/serverInfo":{"name":")" + + server_name + R"(","version":")" + server_version + R"("}}})"); + } if (method == "ping") return response_ok(m.id, "{}"); if (method == "tools/list" || method == "resources/list" || method == "prompts/list" || method == "resources/templates/list") { if (auto c = params.get("cursor"); c && c->is_string() && !c->str.empty()) return response_error(m.id, -32602, "invalid params"); std::string list; if (method == "tools/list") { for (const auto &t : s.tools) list += (list.empty() ? "" : ",") + t.json; + // The list follows the administrator's tool permissions behind this API key: not cached, not shared. + if (s.modern) return response_ok(m.id, result_object(true, R"("ttlMs":0,"cacheScope":"private","tools":[)" + list + "]")); return response_ok(m.id, R"({"ttlMs":0,"cacheScope":"public","tools":[)" + list + "]}"); } const char *key = method == "resources/list" ? "resources" : method == "prompts/list" ? "prompts" : "resourceTemplates"; @@ -1777,24 +1837,24 @@ std::string handle_call(Session &s, const Message &m) // A tool that exists but is not this caller's says why: a model then tells the user instead of trying // other names. if (s.caller.allowed && tools::find(name) && !s.caller.allowed(name)) - return tool_response(m.id, go_error("the tool " + name + " is not allowed for this client (Settings > AI > Tools)")); + return tool_response(m.id, go_error("the tool " + name + " is not allowed for this client (Settings > AI > Tools)"), s.modern); return response_error(m.id, -32602, "unknown tool " + text::quote(name)); } Value args = Value::object(); if (const Value *a = params.get("arguments"); a && !a->is_null()) { if (!a->is_object()) { ToolResult r = go_error("validating \"arguments\": \"arguments\" must be an object"); - return tool_response(m.id, r); + return tool_response(m.id, r, s.modern); } args = *a; } if (auto e = validate(args, it->input_schema, ""); !e.empty()) - return tool_response(m.id, go_error("validating \"arguments\": " + e)); + return tool_response(m.id, go_error("validating \"arguments\": " + e), s.modern); if (s.caller.admit) - if (auto refusal = s.caller.admit(name, args); !refusal.empty()) return tool_response(m.id, go_error(refusal)); + if (auto refusal = s.caller.admit(name, args); !refusal.empty()) return tool_response(m.id, go_error(refusal), s.modern); ToolResult result = run_tool(name, s.devices, args, s.caller); if (s.caller.done) s.caller.done(name, args, result.error.empty() && result.tool_error.empty(), result.jpeg); - return tool_response(m.id, result); + return tool_response(m.id, result, s.modern); } return response_error(m.id, -32601, "method not found: " + text::quote(method)); } @@ -1961,7 +2021,8 @@ HttpResponse serve(const HttpRequest &req, Devices &devices) } if (!json_ok || !stream_ok) return text_error(400, "Accept must contain both 'application/json' and 'text/event-stream'"); if (req.body.size() > max_request_body) return text_error(413, "request body exceeds " + std::to_string(max_request_body) + " bytes"); - if (!req.header_values("Last-Event-ID").empty()) return text_error(400, "can't send Last-Event-ID for POST request"); + // 2026-07-28 has no stream resumption: a Last-Event-ID is ignored there. + if (version < version_new && !req.header_values("Last-Event-ID").empty()) return text_error(400, "can't send Last-Event-ID for POST request"); if (req.body.empty()) return text_error(400, "POST requires a non-empty body"); // An array of messages, else one message. The parsed request stays here: the messages point into it. @@ -1987,48 +2048,69 @@ HttpResponse serve(const HttpRequest &req, Devices &devices) if (batch && effective >= "2025-06-18") return text_error(400, "JSON-RPC batching is not supported in 2025-06-18 and later (request version: " + effective + ")"); - bool calls = false; + bool calls = false, modern = false; for (const auto &m : messages) { if (!m.request) continue; + bool is_call = m.id.kind != Id::Kind::none; + const Value *meta = m.params && m.params->is_object() ? m.params->get("_meta") : nullptr; + if (meta && !meta->is_object()) meta = nullptr; + std::string meta_version; + if (meta) + if (auto v = meta->get("io.modelcontextprotocol/protocolVersion"); v && v->is_string()) meta_version = v->str; + // The 2026-07-28 protocol: each call carries the version in _meta and in the header, and the method (and + // the tool) in headers too. Its errors are JSON-RPC errors with their own HTTP status. + if (is_call && (effective >= version_new || !meta_version.empty())) { + auto refuse = [&](int status, int code, const std::string &message, const std::string &data = {}) { + HttpResponse r; + r.status = status; + r.content_type = "application/json"; + r.body = response_error(m.id, code, message, data); + return r; + }; + if (version.empty()) + return refuse(400, -32020, "MCP-Protocol-Version header is required for requests carrying \"io.modelcontextprotocol/protocolVersion\""); + if (meta_version.empty()) return refuse(400, -32602, "missing or invalid _meta field \"io.modelcontextprotocol/protocolVersion\""); + if (version != meta_version) + return refuse(400, -32020, "MCP-Protocol-Version header " + text::quote(version) + + " does not match request io.modelcontextprotocol/protocolVersion " + text::quote(meta_version)); + if (std::find(modern_versions.begin(), modern_versions.end(), meta_version) == modern_versions.end()) { + std::string list; + for (const auto &v : modern_versions) list += (list.empty() ? "" : ",") + json::quote(v, false); + return refuse(400, -32022, "unsupported protocol version " + text::quote(meta_version), + "{\"supported\":[" + list + "],\"requested\":" + json::quote(meta_version, false) + "}"); + } + const Value *caps = meta->get("io.modelcontextprotocol/clientCapabilities"); + if (!caps || !caps->is_object()) + return refuse(400, -32602, "missing or invalid _meta field \"io.modelcontextprotocol/clientCapabilities\""); + if (const Value *level = meta->get("io.modelcontextprotocol/logLevel")) { + static const std::set levels = {"debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"}; + if (!level->is_string() || !levels.contains(level->str)) + return refuse(400, -32602, "invalid _meta field \"io.modelcontextprotocol/logLevel\""); + } + std::string method = req.header("Mcp-Method"); + if (method.empty()) return refuse(400, -32020, "missing required Mcp-Method header"); + if (method != m.method) + return refuse(400, -32020, "header mismatch: Mcp-Method header value '" + method + "' does not match body value '" + m.method + "'"); + if (!modern_method(m.method)) return refuse(404, -32601, "method not found: " + text::quote(m.method)); + if (m.method == "tools/call") { + std::string name; + if (auto n = m.params->get("name"); n && n->is_string()) name = n->str; + auto header = req.header_values("Mcp-Name"); + if (header.empty()) return refuse(400, -32020, "missing required Mcp-Name header"); + auto value = mcp_name_value(header.front()); + if (!value || *value != name) + return refuse(400, -32020, "header mismatch: Mcp-Name header value '" + header.front() + "' does not match body value '" + name + "'"); + } + modern = calls = true; + continue; + } auto it = method_infos().find(m.method); if (it == method_infos().end()) return text_error(400, "JSON RPC not handled: " + text::quote(m.method) + " unsupported"); - bool is_call = m.id.kind != Id::Kind::none; if (it->second.notification && is_call) return text_error(400, "invalid request: unexpected id for " + text::quote(m.method)); if (!it->second.notification && !is_call) return text_error(400, "invalid request: missing id for " + text::quote(m.method)); if (!it->second.missing_params_ok && !m.params) return text_error(400, "invalid request: missing required \"params\""); - // The 2026-07-28 protocol: its calls carry the version in _meta and in the header. - std::string meta_version; - if (m.params && m.params->is_object()) - if (auto meta = m.params->get("_meta"); meta && meta->is_object()) - if (auto v = meta->get("io.modelcontextprotocol/protocolVersion"); v && v->is_string()) meta_version = v->str; - if ((is_call && effective >= version_new) || !meta_version.empty()) { - HttpResponse r; - r.status = 400; - r.content_type = "application/json"; - if (version.empty()) - r.body = response_error(m.id, -32020, "Mcp-Protocol-Version header is required for requests carrying \"io.modelcontextprotocol/protocolVersion\""); - else if (meta_version.empty()) - r.body = response_error(m.id, -32602, "missing or invalid _meta field \"io.modelcontextprotocol/protocolVersion\""); - else if (version != meta_version) - r.body = response_error(m.id, -32020, "Mcp-Protocol-Version header " + text::quote(version) + - " does not match request io.modelcontextprotocol/protocolVersion " + text::quote(meta_version)); - else - r.body = {}; - if (!r.body.empty()) return r; - } if (is_call) calls = true; } - if (!batch && messages.size() == 1 && effective >= version_new && messages[0].request) { - std::string method = req.header("Mcp-Method"); - HttpResponse r; - r.status = 400; - r.content_type = "application/json"; - if (method.empty()) r.body = response_error(messages[0].id, -32020, "missing required Mcp-Method header"); - else if (method != messages[0].method) - r.body = response_error(messages[0].id, -32020, "header mismatch: Mcp-Method header value '" + method + - "' does not match body value '" + messages[0].method + "'"); - if (!r.body.empty()) return r; - } if (!calls) { HttpResponse r; r.status = 202; @@ -2038,7 +2120,7 @@ HttpResponse serve(const HttpRequest &req, Devices &devices) // The external clients: the MCP mode, the operation slot, the MCP's host control switch and their permissions. Caller external; external.allowed = [permissions = tools::current()](const std::string &tool) { return permissions.allows(tools::Who::mcp, tool); }; - Session session{devices, tool_set(external, devices.text_available && devices.text_available(), devices), external}; + Session session{devices, tool_set(external, devices.text_available && devices.text_available(), devices), external, modern, {}}; std::vector responses; std::set answered; // a batch's calls by id: a repeated id is answered once bool listen = false; @@ -2054,7 +2136,8 @@ HttpResponse serve(const HttpRequest &req, Devices &devices) if (listen && !batch && !responses.empty()) { // subscriptions/listen always answers on an event stream. r.content_type = "text/event-stream"; - r.body = "event: message\ndata: " + responses[0] + "\n\n"; + if (!session.stream_head.empty()) r.body = "event: message\ndata: " + session.stream_head + "\n\n"; + r.body += "event: message\ndata: " + responses[0] + "\n\n"; return r; } if (batch) { @@ -2089,7 +2172,7 @@ HttpResponse serve_local(const std::string &body, Devices &devices, const Caller r.status = 202; return r; } - Session session{devices, tool_set(caller, devices.text_available && devices.text_available(), devices), caller}; + Session session{devices, tool_set(caller, devices.text_available && devices.text_available(), devices), caller, false, {}}; r.content_type = "application/json"; r.cache_control = "no-cache, no-transform"; r.body = handle_call(session, m); diff --git a/server-cpp/src/ai/mcp.hpp b/server-cpp/src/ai/mcp.hpp index a3c6b78a7..5662bfefa 100644 --- a/server-cpp/src/ai/mcp.hpp +++ b/server-cpp/src/ai/mcp.hpp @@ -10,6 +10,12 @@ // status codes, tool list, argument validation and results. A request that is not a JSON-RPC message, or whose // params have the wrong type, is refused with the same status and code but in this server's own words. // +// Version 2026-07-28 has no initialize: each call carries the version and the client's capabilities in +// params._meta, the version also in MCP-Protocol-Version, the method in Mcp-Method and a tool call's tool in +// Mcp-Name. Such calls get server/discover, tools/list, tools/call and subscriptions/listen (acknowledged with no +// notifications: this server sends none), results with resultType and the server in _meta, and the errors and +// HTTP statuses of that version (-32020 header mismatch, -32022 unsupported version, 404 for other methods). +// // This file is the protocol and the tools on top of Devices; mcp_routes.cpp connects them to the server. #include "ai/hid_sink.hpp" From 8b9ae59cff817f6935a7e5fc31832b5a2f3360e8 Mon Sep 17 00:00:00 2001 From: Gleb Pesin Date: Wed, 2 Dec 2026 20:14:17 +0200 Subject: [PATCH 2/2] fix(mcp): answer any unsupported version of the 2026-07-28 form with -32022 A call in the 2026-07-28 form (a version in params._meta) with an unsupported version dated before 2026-07-28, such as 1900-01-01 or 2026-01-01, got the plain-text 400 of the initialize era, which a client speaking both forms can take for a server of the older form. The form is now told after the body is read, by a _meta version or a header version of 2026-07-28 or later. Calls in that form get -32022 with the supported and requested versions whatever the date, and their Last-Event-ID is ignored. Calls in the initialize-era form keep the plain-text answers. The upstream watch now reads version_new (2026-07-28), the version server/discover reports. It no longer reads the initialize default (2025-11-25), so a newer specification is compared with the newest version spoken. Co-Authored-By: Claude Opus 5.5 --- .github/upstream-watch.json | 4 +-- docs/DEPENDENCY-UPDATES.md | 2 +- server-cpp/src/ai/mcp.cpp | 51 ++++++++++++++++++++++++++----------- 3 files changed, 39 insertions(+), 18 deletions(-) diff --git a/.github/upstream-watch.json b/.github/upstream-watch.json index 875cede0c..67c3854cd 100644 --- a/.github/upstream-watch.json +++ b/.github/upstream-watch.json @@ -576,9 +576,9 @@ "upstream_pattern": "^v([0-9]+\\.[0-9]+(?:\\.[0-9]+)?)$" }, { - "name": "MCP negotiated protocol", + "name": "MCP protocol", "path": "server-cpp/src/ai/mcp.cpp", - "pattern": "version_latest = \"([0-9-]+)\"", + "pattern": "version_new = \"([0-9-]+)\"", "kind": "github-tags", "repo": "modelcontextprotocol/modelcontextprotocol", "separator": "-", diff --git a/docs/DEPENDENCY-UPDATES.md b/docs/DEPENDENCY-UPDATES.md index 64449e9f6..0bbce2b53 100644 --- a/docs/DEPENDENCY-UPDATES.md +++ b/docs/DEPENDENCY-UPDATES.md @@ -37,7 +37,7 @@ The frontend and script CI suites remain mandatory. RustDesk has a host `cargo t - **RustDesk stable protocol reference**, paired with the hbb_common submodule commit from that release (never hbb_common/main). - The vendor kernel reference, the Sophgo conversion container and the supported .NET LTS build channel. Host tools installed from runner distribution repositories follow that distribution. - PawnIO, acme.sh, iPXE and netboot.xyz release channels. PawnIO is embedded at add-on build time. The other three are fetched when their features are used. -- The latest dated MCP specification tag against the version the native server negotiates. The original C++ port used Go SDK v1.8.0 as a reference. The retired Go branch pins v1.9.0. The C++ server has no SDK dependency. Its initialize response defaults to 2025-11-25. It handles some transport headers from 2026-07-28, but does not implement server/discover. +- The latest dated MCP specification tag against the newest version the native server speaks (`version_new` in `server-cpp/src/ai/mcp.cpp`, 2026-07-28: `server/discover` and per-request `_meta`). The original C++ port used Go SDK v1.8.0 as a reference. The retired Go branch pins v1.9.0. The C++ server has no SDK dependency. Its `initialize` answer for the older versions defaults to 2025-11-25. **musl:** the watch reads stable tags from the ifduyue mirror of upstream Git. The build verifies the pinned upstream archive. Alpine's patches in `platform/musl` (from aports `main/musl` of the Alpine branch) are followed diff --git a/server-cpp/src/ai/mcp.cpp b/server-cpp/src/ai/mcp.cpp index 080b39369..9ed83d7b9 100644 --- a/server-cpp/src/ai/mcp.cpp +++ b/server-cpp/src/ai/mcp.cpp @@ -46,8 +46,11 @@ constexpr const char *no_text_reader = // Protocol versions the Go SDK negotiates, newest first. const std::vector supported_versions = {"2026-07-28", "2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"}; +// The newest version this server speaks (the _meta request form): the one .github/upstream-watch.json compares with +// the latest dated MCP specification. constexpr const char *version_new = "2026-07-28"; constexpr const char *version_default = "2025-03-26"; +// The newest version of the initialize era: what initialize answers for an unknown or a newer request. constexpr const char *version_latest = "2025-11-25"; // --- Config --- @@ -585,8 +588,24 @@ std::string result_object(bool modern, const std::string &fields) return "{" + modern_head() + (fields.empty() ? "" : ",") + fields + "}"; } -// The versions the 2026-07-28 request form (a version in each request's _meta) is spoken in. -const std::vector modern_versions = {"2026-07-28"}; +// The versions the 2026-07-28 request form (a version in each request's _meta) is spoken in: version_new, the +// constant the upstream watch reads. +const std::vector modern_versions = {version_new}; + +// A message's params._meta object, or null. +const Value *message_meta(const Message &m) +{ + const Value *meta = m.params && m.params->is_object() ? m.params->get("_meta") : nullptr; + return meta && meta->is_object() ? meta : nullptr; +} + +// The protocol version in a message's _meta, "" when there is none. +std::string meta_protocol_version(const Message &m) +{ + if (const Value *meta = message_meta(m)) + if (auto v = meta->get("io.modelcontextprotocol/protocolVersion"); v && v->is_string()) return v->str; + return {}; +} // The 2026-07-28 methods a client may call here: the server advertises tools only, so the prompt, resource and // completion methods are not there, and the methods of the initialize era (initialize, ping, logging/setLevel, @@ -1992,12 +2011,6 @@ HttpResponse serve(const HttpRequest &req, Devices &devices) if (req.loopback && !loopback_host(req.host)) return text_error(403, "Forbidden: invalid Host header " + text::quote(req.host)); std::string version = req.header("Mcp-Protocol-Version"); - if (!version.empty() && std::find(supported_versions.begin(), supported_versions.end(), version) == supported_versions.end() && - version < version_new) { - std::string list; - for (const auto &v : supported_versions) list += (list.empty() ? "" : ",") + v; - return text_error(400, "Bad Request: Unsupported protocol version (supported versions: " + list + ")"); - } if (req.method != "POST") { auto r = text_error(405, "Method Not Allowed"); r.allow = "POST"; @@ -2021,8 +2034,6 @@ HttpResponse serve(const HttpRequest &req, Devices &devices) } if (!json_ok || !stream_ok) return text_error(400, "Accept must contain both 'application/json' and 'text/event-stream'"); if (req.body.size() > max_request_body) return text_error(413, "request body exceeds " + std::to_string(max_request_body) + " bytes"); - // 2026-07-28 has no stream resumption: a Last-Event-ID is ignored there. - if (version < version_new && !req.header_values("Last-Event-ID").empty()) return text_error(400, "can't send Last-Event-ID for POST request"); if (req.body.empty()) return text_error(400, "POST requires a non-empty body"); // An array of messages, else one message. The parsed request stays here: the messages point into it. @@ -2044,6 +2055,19 @@ HttpResponse serve(const HttpRequest &req, Devices &devices) messages.push_back(std::move(m)); } } + // The 2026-07-28 form is told by the header's version or by a version in a message's _meta, whatever its date: + // its version errors are JSON-RPC (-32022 below), and it has no stream resumption, so a Last-Event-ID is + // ignored. The initialize-era form keeps the plain-text answers. + bool modern_form = version >= version_new; + for (const auto &m : messages) modern_form = modern_form || !meta_protocol_version(m).empty(); + if (!modern_form) { + if (!version.empty() && std::find(supported_versions.begin(), supported_versions.end(), version) == supported_versions.end()) { + std::string list; + for (const auto &v : supported_versions) list += (list.empty() ? "" : ",") + v; + return text_error(400, "Bad Request: Unsupported protocol version (supported versions: " + list + ")"); + } + if (!req.header_values("Last-Event-ID").empty()) return text_error(400, "can't send Last-Event-ID for POST request"); + } std::string effective = version.empty() ? version_default : version; if (batch && effective >= "2025-06-18") return text_error(400, "JSON-RPC batching is not supported in 2025-06-18 and later (request version: " + effective + ")"); @@ -2052,11 +2076,8 @@ HttpResponse serve(const HttpRequest &req, Devices &devices) for (const auto &m : messages) { if (!m.request) continue; bool is_call = m.id.kind != Id::Kind::none; - const Value *meta = m.params && m.params->is_object() ? m.params->get("_meta") : nullptr; - if (meta && !meta->is_object()) meta = nullptr; - std::string meta_version; - if (meta) - if (auto v = meta->get("io.modelcontextprotocol/protocolVersion"); v && v->is_string()) meta_version = v->str; + const Value *meta = message_meta(m); + std::string meta_version = meta_protocol_version(m); // The 2026-07-28 protocol: each call carries the version in _meta and in the header, and the method (and // the tool) in headers too. Its errors are JSON-RPC errors with their own HTTP status. if (is_call && (effective >= version_new || !meta_version.empty())) {