Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
179 changes: 131 additions & 48 deletions server-cpp/src/ai/mcp.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::string> modern_versions = {"2026-07-28"};
Comment thread
dormancygrace marked this conversation as resolved.
Resolved

// 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<std::string> 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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -1706,6 +1743,8 @@ struct Session {
Devices &devices;
std::vector<Tool> 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.
Expand Down Expand Up @@ -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";
Expand All @@ -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));
}
Expand Down Expand Up @@ -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.
Expand All @@ -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()) {
Comment thread
dormancygrace marked this conversation as resolved.
Resolved
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<std::string> 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;
Expand All @@ -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<std::string> responses;
std::set<std::string> answered; // a batch's calls by id: a repeated id is answered once
bool listen = false;
Expand All @@ -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) {
Expand Down Expand Up @@ -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);
Expand Down
6 changes: 6 additions & 0 deletions server-cpp/src/ai/mcp.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down