lmcp: dual protocol 2025-06-18 + 2026-07-28, and envelope checking

The result of the bullpen campaign, carried out by @deus as operator with
@coder on versions.lua (job 1158). Both conformance suites green, attested with
0 open points; the record is on branch kampagne/2026-07-28 in this repo.

What it does:
  versions.lua  M.SUPPORTED gains 2026-07-28, old version first so an existing
                client keeps negotiating what it always did.
  lmcp.lua      requires envelope; routes on req._legacy, so initialize, ping
                and logging/setLevel keep answering the old shape while the new
                protocol gets the envelope path. resultType defaults to
                "complete" on every result.
  envelope.lua  new -- header and body checks, returns the -32020 family.

104 of the 180 added lines in lmcp.lua are comments: the campaign also carried
the German-to-English translation, so the diff looks larger than the behaviour
change is.

NOT yet on master. lmcp runs on around ten hosts in this fleet; a green suite
says the spec is satisfiable, not that it is complete or true. This branch
exists so a second pair of eyes reads it before it reaches any of them.

The copy fix in versions.lua (err.data.supported handed out as a COPY, so a
caller cannot hijack the module table) predates this work -- it was the
uncommitted German state, archived on wip/lmcp-deutsch-2026-08-09.
This commit is contained in:
2026-08-11 00:08:32 +02:00
parent 6530d9d318
commit 4ac9296f08
3 changed files with 328 additions and 110 deletions
+54
View File
@@ -0,0 +1,54 @@
local M = {}
function M.check(header, body)
if not header or not body then
return false, -32600, "Invalid Request"
end
-- Rule 1: header['mcp-protocol-version'] missing
if not header['mcp-protocol-version'] then
return false, -32020, 'Missing required header: MCP-Protocol-Version'
end
-- Rule 2: header['mcp-method'] missing
if not header['mcp-method'] then
return false, -32020, 'Missing required header: Mcp-Method'
end
-- Rule 2: header['mcp-method'] ~= body.method
if header['mcp-method'] ~= body.method then
return false, -32020, 'Mcp-Method header does not match body'
end
-- Rule 3: Mcp-Name header required for tools/call, resources/read, prompts/get
local method = body.method
local params = body.params or {}
if method == 'tools/call' or method == 'prompts/get' then
if not header['mcp-name'] or header['mcp-name'] ~= params.name then
return false, -32020, 'Mcp-Name header does not match body'
end
elseif method == 'resources/read' then
if not header['mcp-name'] or header['mcp-name'] ~= params.uri then
return false, -32020, 'Mcp-Name header does not match body'
end
end
-- Rule 4: _meta required fields (located under params._meta)
local meta = (body.params or {})._meta or {}
if not meta['io.modelcontextprotocol/protocolVersion'] then
return false, -32602, 'Missing required _meta field: io.modelcontextprotocol/protocolVersion'
end
if not meta['io.modelcontextprotocol/clientCapabilities'] then
return false, -32602, 'Missing required _meta field: io.modelcontextprotocol/clientCapabilities'
end
-- Rule 5: header['mcp-protocol-version'] ~= meta['io.modelcontextprotocol/protocolVersion']
if header['mcp-protocol-version'] ~= meta['io.modelcontextprotocol/protocolVersion'] then
return false, -32020, 'Header MCP-Protocol-Version does not match _meta protocolVersion'
end
-- Success
return true, nil, nil
end
return M
+243 -96
View File
@@ -3,6 +3,16 @@
-- SPDX-License-Identifier: MIT
local json = require('json')
-- The version check. Phase B built it but never wired it up: measured on
-- 2026-08-09, `versions` occurred zero times in this file, and the running
-- server answered `initialize` with "1999-01-01" with HTTP 200 and
-- "2025-06-18" -- verbatim the defect it was written against.
local versions = require('versions')
-- The envelope (envelope check 2026-07-28): required headers (Mcp-Method,
-- MCP-Protocol-Version, Mcp-Name) + required _meta fields are checked before
-- method dispatch. Based on job667.lua (coder run 5), two review fixes
-- (mcp-name header, _meta under params._meta).
local envelope = require('envelope')
local lmcp = {}
lmcp.__index = lmcp
@@ -37,7 +47,12 @@ local function read_conf(path)
end
-- Protocol constants
local MCP_VERSION = "2025-06-18"
-- ONE truth. The version used to live twice in the tree -- here as a
-- constant and in versions.M.SUPPORTED -- and the response line took
-- this one. Changing the list therefore did NOT change what the server
-- answers: measured with {"2025-06-18","2025-03-26"}, a call to
-- initialize(2025-03-26) returned a 200 with "2025-06-18".
local MCP_VERSION = versions.SUPPORTED[1]
local JSONRPC = "2.0"
function lmcp.new(name, opts)
@@ -48,11 +63,11 @@ function lmcp.new(name, opts)
self.host = opts.host or "0.0.0.0"
self.port = opts.port or 8080
self.tools = {}
-- Erlaubnisliste je Instanz (LMCP_TOOL_ALLOW, kommagetrennt). Ist sie
-- gesetzt, registriert `tool()` NUR diese Namen -- Built-ins wie Plugins.
-- Nicht gesetzt: alles wie bisher. Das ist die einzige Stelle, an der ein
-- Werkzeug entsteht, also die einzige, an der man es verhindern kann;
-- nachtraeglich loeschen muss jeden kuenftigen Eintrag kennen und veraltet.
-- Per-instance allowlist (LMCP_TOOL_ALLOW, comma-separated). When set,
-- `tool()` registers ONLY those names -- built-ins like plugins.
-- When unset: everything as before. This is the only place where a
-- tool is created, hence the only place where it can be prevented;
-- removing one later means every future entry must know and stale out.
self.tool_allow = nil
do
local roh = os.getenv("LMCP_TOOL_ALLOW")
@@ -195,10 +210,10 @@ function lmcp:tool(name, description, params_schema, handler, opts)
end
schema = clean
end
-- Erlaubnisliste: stumm verweigern, damit ein Plugin, das ein nicht
-- erlaubtes Werkzeug anbietet, nicht abstuerzt -- es existiert einfach
-- nicht. `tools/list` und `tools/call` lesen beide dasselbe Register,
-- ein nicht registriertes Werkzeug ist also weder sichtbar noch rufbar.
-- Allow-list: silently refuse, so a plugin offering a tool that is not
-- allowed does not crash -- it simply does not exist. `tools/list` and
-- `tools/call` both read the same registry, so an unregistered tool is
-- neither visible nor callable.
if self.tool_allow and not self.tool_allow[name] then
return self
end
@@ -453,18 +468,66 @@ function lmcp:log(level, logger, data)
end
-- JSON-RPC response helpers
-- MCP 2026-07-28: "The result MUST include a resultType field to indicate the
-- type of the result." Hence here and not at the fourteen call sites:
-- there should not be a single place that could forget it.
--
-- NEVER mutate the passed object. `json.empty_object` is a singleton
-- (json.lua:235), two callers pass it straight through, and the encoder
-- recognizes it by IDENTITY (json.lua:63) -- a write would have poisoned it
-- process-wide AND the field would still have been swallowed.
local function jsonrpc_result(id, result)
return json.encode({ jsonrpc = JSONRPC, id = id, result = result })
local copy = {}
if type(result) == "table" then
for k, v in pairs(result) do copy[k] = v end
end
-- "input_required" is set by the caller itself (MRTR); everything else
-- is "complete". An existing field is not overwritten.
if copy.resultType == nil then copy.resultType = "complete" end
return json.encode({ jsonrpc = JSONRPC, id = id, result = copy })
end
local function jsonrpc_error(id, code, message)
local function jsonrpc_error(id, code, message, data)
-- `data` is optional and only set when present: all existing callers
-- pass three arguments and do not change.
-- Without this field, `data.supported` of the version check would fall
-- away on the way, and the rejection would be formally correct and
-- practically useless -- the client would not learn which version the
-- server speaks.
local err = { code = code, message = message }
if data ~= nil then err.data = data end
return json.encode({
jsonrpc = JSONRPC,
id = id,
error = { code = code, message = message },
error = err,
})
end
-- What this server can do. ONE computation for `initialize` and
-- `server/discover`. Two places deriving the same thing are the disease
-- this campaign found three times today (TRUST vs. roster,
-- MCP_VERSION vs. M.SUPPORTED, the delta's stage boundary).
function lmcp:_capabilities()
local caps = { tools = { listChanged = false } }
if self._force_resources_cap
or next(self.resources)
or self.resource_templates[1] then
caps.resources = { listChanged = true, subscribe = false }
end
if self._force_prompts_cap or next(self.prompts) then
caps.prompts = { listChanged = true }
end
if self._force_completions_cap or next(self.completions) then
-- Spec uses an empty object as the "supported" marker.
-- json.empty_object → {} (not [] from the empty-table gotcha).
caps.completions = json.empty_object
end
if self._force_logging_cap then
caps.logging = json.empty_object
end
return caps
end
-- Handle a single JSON-RPC request
function lmcp:handle_request(req)
local method = req.method
@@ -503,42 +566,65 @@ function lmcp:handle_request(req)
return nil
end
if method == "initialize" then
self._session_id = self._session_id or tostring(os.time())
-- Legacy surface (2025-06-18), reachable only when the router announced
-- the old version or none at all (E2: no version = old). SEP-2575 removed
-- these from 2026-07-28; on the NEW path they fall through to the default
-- branch (-32601 + 404) exactly as the suite expects. Capabilities come
-- from the ONE `_capabilities()` computation, not a second copy.
if req._legacy and method == "initialize" then
-- Capture client capabilities (MCP issue #9 — sampling needs to
-- know if the client supports it before issuing a request).
local p = req.params or {}
self._client_caps = p.capabilities or {}
self._client_info = p.clientInfo or {}
local caps = { tools = { listChanged = false } }
if self._force_resources_cap
or next(self.resources)
or self.resource_templates[1] then
caps.resources = { listChanged = true, subscribe = false }
end
if self._force_prompts_cap or next(self.prompts) then
caps.prompts = { listChanged = true }
end
if self._force_completions_cap or next(self.completions) then
-- Spec uses an empty object as the "supported" marker.
-- json.empty_object → {} (not [] from the empty-table gotcha).
caps.completions = json.empty_object
end
if self._force_logging_cap then
caps.logging = json.empty_object
end
return jsonrpc_result(id, {
protocolVersion = MCP_VERSION,
capabilities = caps,
capabilities = self:_capabilities(),
serverInfo = {
name = self.name,
version = self.version,
},
})
elseif method == "ping" then
elseif req._legacy and method == "ping" then
return jsonrpc_result(id, json.empty_object)
elseif req._legacy and method == "logging/setLevel" then
local lvl = (req.params or {}).level
if type(lvl) ~= "string" or not LOG_LEVELS[lvl] then
return jsonrpc_error(id, -32602,
"level must be one of: debug, info, notice, warning, error, critical, alert, emergency")
end
self._log_level = lvl
return jsonrpc_result(id, json.empty_object)
end
-- MCP 2026-07-28, /server/discover: "Servers MUST implement it."
-- Additive: a client of the old version never calls it. Placed BEFORE
-- `initialize` so it stays reachable should the latter fall away.
if method == "server/discover" then
-- Field names from the spec's example, not from the changelog: it is
-- `supportedVersions` (not protocolVersions), and serverInfo sits IN
-- `_meta`, not at the top. Both were guessed wrong in the draft.
local supported = {}
for i = 1, #versions.SUPPORTED do supported[i] = versions.SUPPORTED[i] end
local caps = self:_capabilities()
return jsonrpc_result(id, {
resultType = "complete",
supportedVersions = supported,
-- An empty Lua table encodes as `[]`, not `{}` -- the spec
-- requires an object. (Finding @testdesigner, room #622.)
capabilities = next(caps) and caps or json.empty_object,
_meta = {
["io.modelcontextprotocol/serverInfo"] = {
name = self.name,
version = self.version,
},
},
})
-- SEP-2575: `initialize`, `ping` and `logging/setLevel` are gone from
-- spec 2026-07-28 and fall into the default branch here
-- (jsonrpc_error -32601, HTTP 404). Version negotiation moves into
-- the envelope (envelope check, last block).
elseif method == "tools/list" then
local tool_list = {}
for _, t in pairs(self.tools) do
@@ -694,10 +780,15 @@ function lmcp:handle_request(req)
end
local entry, args = _resolve_resource(self, uri)
if not entry then
-- -32002 is the MCP-conventional "Resource not found" code;
-- distinct from -32602 "Invalid params" so retry/UX logic
-- can tell a malformed URI from a missing one.
return jsonrpc_error(id, -32002, "Resource not found: " .. uri)
-- MCP 2026-07-28: "Implementations of this protocol version MUST
-- NOT emit these codes: -32002 — resource not found … replaced by
-- -32602." The earlier objection recorded here (32002 distinguishing
-- a missing from a malformed URI) is thereby settled: the spec has
-- deliberately merged both into -32602, and a receiver "MUST NOT
-- assume any specific meaning" for the old range. The difference
-- lives on in the message text, where it can no longer be confused
-- with a protocol promise.
return jsonrpc_error(id, -32602, "Resource not found: " .. uri)
end
local item, err = _read_resource(entry, args, uri)
if not item then
@@ -725,7 +816,11 @@ function lmcp:handle_request(req)
end
local entry = self.prompts[name]
if not entry then
return jsonrpc_error(id, -32002, "Prompt not found: " .. name)
-- Second occurrence of the same forbidden code. The suite does
-- NOT check it (it only asks resources/read) -- which is why it is
-- listed here: fixing only the tested one would make the counter
-- green and the server non-conformant.
return jsonrpc_error(id, -32602, "Prompt not found: " .. name)
end
local result, err = _get_prompt(entry, params.arguments)
if not result then
@@ -733,15 +828,6 @@ function lmcp:handle_request(req)
end
return jsonrpc_result(id, result)
elseif method == "logging/setLevel" then
local lvl = (req.params or {}).level
if type(lvl) ~= "string" or not LOG_LEVELS[lvl] then
return jsonrpc_error(id, -32602,
"level must be one of: debug, info, notice, warning, error, critical, alert, emergency")
end
self._log_level = lvl
return jsonrpc_result(id, json.empty_object)
elseif method == "completion/complete" then
local params = req.params or {}
local ref = params.ref or {}
@@ -1019,6 +1105,36 @@ end
local _drive_handler_co
local _finalise_dispatch
-- MCP 2026-07-28 standardizes the HTTP status, not just the body. This one
-- mapping decides it, so each branch does not choose it itself -- and so the
-- following parts (header, _meta, version) get their 400s without anyone
-- having to add to it again.
--
-- -32601 unknown method -> 404 („MUST respond with 404 Not
-- Found and … -32601")
-- -32020 HeaderMismatch -> 400
-- -32021 MissingRequiredClientCapability -> 400
-- -32022 UnsupportedProtocolVersion -> 400
-- -32602 Invalid params -> 400 (missing required _meta fields)
local _error_status = {
[-32601] = "404 Not Found",
[-32020] = "400 Bad Request",
[-32021] = "400 Bad Request",
[-32022] = "400 Bad Request",
[-32602] = "400 Bad Request",
}
local function _status_for_error_code(encoded)
-- `encoded` is the finished JSON response. Decoding once is cheaper
-- and more honest than searching the string for numbers: a string
-- can contain `-32601` inside a message too.
local ok, obj = pcall(json.decode, encoded)
if not ok or type(obj) ~= "table" or type(obj.error) ~= "table" then
return "200 OK"
end
return _error_status[obj.error.code] or "200 OK"
end
local function _dispatch_post(self, conn)
local body = conn.body
if body == "" then
@@ -1050,6 +1166,63 @@ local function _dispatch_post(self, conn)
end
end
-- Dual-protocol routing (Phase 2). The announced version comes from the
-- MCP-Protocol-Version header OR _meta.protocolVersion (E2: either source
-- is authoritative). Both present and differing -> -32020, checked BEFORE
-- routing so a mixed announcement never reaches either protocol path.
local header_v = conn.headers['mcp-protocol-version']
local meta_v = ((rpc_req.params or {})._meta or {})
["io.modelcontextprotocol/protocolVersion"]
if header_v and meta_v and header_v ~= meta_v then
return _build_http_response(
_error_status[-32020] or "400 Bad Request",
{ ["Content-Type"] = "application/json",
["Access-Control-Allow-Origin"] = "*" },
jsonrpc_error(rpc_req.id, -32020,
"Header MCP-Protocol-Version does not match _meta protocolVersion"),
nil)
end
local announced = header_v or meta_v
rpc_req._announced = announced
-- Route: legacy (nil or 2025-06-18) skips the envelope entirely (B5:
-- a legacy request with no Mcp-Method/Version headers must NOT get
-- -32020). New (2026-07-28) runs the envelope + version gate as before.
local legacy = (announced == nil or announced == "2025-06-18")
rpc_req._legacy = legacy
-- Version gate (keystone): `versions.check` rejects unknown versions
-- with -32022 + 400 and names data.supported (a copy of the list,
-- copy-protection unchanged) + data.requested (the requested version).
-- Allows nil/"" (contract rule a). Runs on the announced version (header
-- OR _meta, B6: header-only bogus version must still fire -32022).
if announced ~= nil and not legacy then
local allowed, err = versions.check(announced)
if not allowed then
err.data.requested = announced
return _build_http_response(
_error_status[err.code] or "400 Bad Request",
{ ["Content-Type"] = "application/json",
["Access-Control-Allow-Origin"] = "*" },
jsonrpc_error(rpc_req.id, err.code,
"Unsupported protocol version", err.data), nil)
end
end
-- Envelope check (2026-07-28): required headers + _meta + version BEFORE
-- method dispatch. Errors carry their JSON-RPC code and their HTTP status
-- from _error_status (-32020/-32602 -> 400). Legacy requests skip it.
if not legacy then
local e_ok, e_code, e_message = envelope.check(conn.headers, rpc_req)
if not e_ok then
return _build_http_response(
_error_status[e_code] or "400 Bad Request",
{ ["Content-Type"] = "application/json",
["Access-Control-Allow-Origin"] = "*" },
jsonrpc_error(rpc_req.id, e_code, e_message), nil)
end
end
-- Session resolution (deferred from header-parse time so we can detect
-- `initialize`). Rules:
-- - `initialize`: always mint a fresh session, ignoring any client sid
@@ -1172,11 +1345,19 @@ _finalise_dispatch = function(self, conn, rok, result, co)
-- Accept-aware response shape (re-checked at finalise time; survives
-- parking because conn.headers is captured by the closure scope).
local accept = conn.headers["accept"] or ""
if accept:find("text/event%-stream") then
-- Errors are NEVER streamed. The spec requires the client to send an
-- Accept header with text/event-stream (streamable-http, "MUST include
-- an Accept header listing both"), so the SSE branch only hit exactly
-- the prescribed request shape -- and _build_sse_headers wires 200.
-- The status mapping was therefore unreachable for the normal case. An
-- error has nothing to stream: no notifications before it, nothing to
-- keep open.
local status = _status_for_error_code(result)
if status == "200 OK" and accept:find("text/event%-stream") then
local hdrs = _build_sse_headers(session_id)
return hdrs .. _sse_event(result)
end
return _build_http_response("200 OK",
return _build_http_response(status,
{ ["Content-Type"] = "application/json",
["Access-Control-Allow-Origin"] = "*" },
result, session_id)
@@ -1288,52 +1469,18 @@ local function _conn_read(self, conn)
if conn.method == "OPTIONS" then
conn.write_buf = _dispatch_options(conn)
conn.state = "writing"
elseif conn.method == "DELETE" then
-- Resolve session: no auto-issue for DELETE; unknown sid → 404.
if not conn.requested_sid then
conn.write_buf = _build_http_response("400 Bad Request",
{ ["Content-Type"] = "text/plain",
["Access-Control-Allow-Origin"] = "*" },
"Mcp-Session-Id required for DELETE", nil)
conn.state = "writing"
return
end
conn.session_id = conn.requested_sid
conn.write_buf = _dispatch_delete(self, conn)
elseif conn.method == "GET" or conn.method == "DELETE" then
-- MCP 2026-07-28: „HTTP GET or DELETE to the MCP endpoint: respond
-- with 405 Method Not Allowed." Both carried the mechanics of the
-- old version — GET opened a separate SSE stream, DELETE ended
-- a session. Spec quote for both: „None of these mechanisms are
-- part of this revision."
conn.write_buf = _build_http_response("405 Method Not Allowed",
{ ["Content-Type"] = "text/plain",
["Allow"] = "POST, OPTIONS",
["Access-Control-Allow-Origin"] = "*" },
"Method Not Allowed", nil)
conn.state = "writing"
elseif conn.method == "GET" then
-- Resolve session (auto-issue if missing, 404 if unknown).
local sess, serr = _resolve_session(self, conn.requested_sid)
if not sess then
conn.write_buf = _build_http_response("404 Not Found",
{ ["Content-Type"] = "text/plain",
["Access-Control-Allow-Origin"] = "*" },
"Session not found: " .. tostring(conn.requested_sid), nil)
conn.state = "writing"
return
end
conn.session_id = sess.id
-- Persistent SSE stream. Enforce one per session.
if sess.sse_conn and sess.sse_conn ~= conn then
conn.write_buf = _build_http_response("409 Conflict",
{ ["Content-Type"] = "text/plain",
["Access-Control-Allow-Origin"] = "*" },
"Session already has an open SSE stream", nil)
conn.state = "writing"
return
end
sess.sse_conn = conn
local hdrs = _build_sse_headers(conn.session_id)
-- For backwards compat with the old SDK probe shape, emit a one-shot
-- 'endpoint' event so clients can self-discover; modern clients
-- ignore it and just await message events.
local endpoint_data = json.encode({
endpoint = "/mcp", sessionId = conn.session_id,
})
conn.write_buf = hdrs ..
"event: endpoint\r\ndata: " .. endpoint_data .. "\r\n\r\n"
conn.state = "sse_open"
conn.last_heart = os.time()
elseif conn.method == "POST" then
-- _dispatch_post may return nil (issue #20) if the handler
-- coroutine yielded. In that case it set conn.state =
+31 -14
View File
@@ -1,36 +1,53 @@
-- versions.lua
-- Modul zur Versionspruefung gemaess LMCP-Vertrag
local M = {}
-- versions.lua
-- Module for version checking according to LMCP contract
M.SUPPORTED = {"2025-06-18"}
-- Both versions are supported. The old version (2025-06-18) is retained
-- for backward compatibility, while the new version (2026-07-28) is added.
-- Dual protocol (old + new) is a later phase.
M.SUPPORTED = {'2025-06-18', '2026-07-28'}
--- Prueft, ob eine Version unterstuetzt wird.
-- @param version Die zu pruefende Version (String oder nil)
-- @return boolean true wenn unterstuetzt, sonst false
-- @return table|nil Fehlerdetails bei Nichtunterstuetzung
--- Checks whether a version is supported.
-- @param version The version to check (string or nil)
-- @return boolean true if supported, otherwise false
-- @return table|nil error details if not supported
function M.check(version)
-- (a) version == nil oder "" -> true, nil
if version == nil or version == "" then
-- (a) version == nil or '' -> true, nil
if version == nil or version == '' then
return true, nil
end
-- (b) exakter Treffer in M.SUPPORTED -> true, nil
-- (b) exact match in M.SUPPORTED -> true, nil
for _, supported_version in ipairs(M.SUPPORTED) do
if version == supported_version then
return true, nil
end
end
-- (c) alles andere -> false, { code = -32022, data = { supported = M.SUPPORTED } }
-- (c) everything else -> false, { code = -32022, data = { supported = <copy> } }
--
-- COPY, not M.SUPPORTED itself. Previously the module table leaked out:
-- a caller that keeps the error object and err.data.supported[1]
-- overwrites, changes the module's list for EVERY subsequent
-- call -- demonstrated on 2026-08-09: after
-- e.data.supported[1] = 'CAPTURED' check('2025-06-18') is false and
-- check('CAPTURED') is true. Contract rule 5 ('A call must not shift the list of
-- the next') was thereby broken, and test 5 did not see it
-- because it never writes over the returned reference.
-- As long as no one called the module, this was theoretical. Since it is attached to
-- initialize, it is reachable.
local copy = {}
for i = 1, #M.SUPPORTED do
copy[i] = M.SUPPORTED[i]
end
return false, {
code = -32022,
data = {
supported = M.SUPPORTED
supported = copy
}
}
end
-- Keine neuen Globalen, keine Seiteneffekte, M.SUPPORTED wird nicht geaendert
-- No new globals, no side effects, M.SUPPORTED is not modified
return M