mcp: JSON-RPC client + ffi/curl status_code; PHASE0 §4 amended

First commit of Phase 2 per docs/PHASE2.md §12. Three changes bundled:

mcp.lua (new, 153 lines):
  - M.connect(url, opts) returns a Session.
  - Session:initialize() round-trips initialize + notifications/initialized
    + tools/list. Caches tools for session lifetime (lmcp announces
    capabilities.tools.listChanged = false; no refetch).
  - Session:list_tools() returns the cached tool list.
  - Session:call_tool(name, args) returns (result_table, kind) where
    kind ∈ {"ok", "handler_error", "rpc_error", "transport_error"} per
    the §4 error split. Folded HTTP-level failure into transport_error.
  - Per-server Bearer auth via opts.auth_token or opts.auth_env env-var
    indirection.
  - Captures protocolVersion mismatch as a warning string rather than
    aborting (lmcp doesn't negotiate — N3 in review).

ffi/curl.lua extension:
  - Add curl_easy_getinfo to ffi.cdef.
  - Pre-cast as getinfo_long; helper get_response_code() fetches
    CURLINFO_RESPONSE_CODE (decimal 2097154 = CURLINFOTYPE_LONG | 2).
  - M.post now returns (body, status_code) on transport success;
    (nil, errmsg) on libcurl failure stays unchanged. Phase 1 callers
    reading only the first slot are unaffected.

docs/PHASE0.md §4:
  - Insert `mcp.lua` between broker.lua and router.lua per PHASE2.md §9.
  - Module-stability invariant clarified: rename prohibition is what
    matters; adding new files is additive.

Smoke-test passes for all four kinds against boltzmann lmcp v0.5.4:
  - initialize: ok (7 tools cached)
  - list_dir /tmp: ok (1.2KB content)
  - read_file /nonexistent: ok (boltzmann's baseline §3 quirk —
    isError:false even on failure; content is authoritative)
  - nope_tool: rpc_error (code=-32601)
  - wrong auth: transport_error (HTTP 401)
  - unreachable host: transport_error (DNS failure)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-12 13:06:39 +00:00
parent f5daa6afc0
commit 6c194deea0
3 changed files with 184 additions and 5 deletions
+2 -1
View File
@@ -59,6 +59,7 @@ aish/
├── main.lua # Entry point: arg parsing, config load, REPL start ├── main.lua # Entry point: arg parsing, config load, REPL start
├── repl.lua # Readline loop, input dispatch, prompt rendering ├── repl.lua # Readline loop, input dispatch, prompt rendering
├── broker.lua # llama.cpp HTTP client; Phase 0: blocking POST ├── broker.lua # llama.cpp HTTP client; Phase 0: blocking POST
├── mcp.lua # MCP JSON-RPC 2.0 client (Phase 2; added 2026-05-12)
├── router.lua # Task classifier: shell / AI / meta ├── router.lua # Task classifier: shell / AI / meta
├── executor.lua # Command execution; Phase 0: io.popen ├── executor.lua # Command execution; Phase 0: io.popen
├── context.lua # In-memory conversation history, token budget ├── context.lua # In-memory conversation history, token budget
@@ -73,7 +74,7 @@ aish/
└── libc.lua # Shared: errno, signal, write, read, misc └── libc.lua # Shared: errno, signal, write, read, misc
``` ```
All modules are required explicitly from `main.lua`. No module autoloading. File names are stable across phases — later phases fill in bodies, not rename files. All modules are required explicitly from `main.lua`. No module autoloading. File names are stable across phases — later phases fill in bodies, not rename files. Adding new files is permitted and additive (e.g. `mcp.lua` was inserted at Phase 2 per docs/PHASE2.md §9); the rename prohibition is what keeps cross-phase wiring stable.
--- ---
+29 -4
View File
@@ -25,6 +25,7 @@ struct curl_slist *curl_slist_append(struct curl_slist *list, const char *string
void curl_slist_free_all(struct curl_slist *list); void curl_slist_free_all(struct curl_slist *list);
int curl_easy_setopt(CURL *handle, int option, ...); int curl_easy_setopt(CURL *handle, int option, ...);
int curl_easy_getinfo(CURL *handle, int info, ...);
]] ]]
-- libcurl-dev's unversioned `libcurl.so` symlink isn't assumed; fall back to -- libcurl-dev's unversioned `libcurl.so` symlink isn't assumed; fall back to
@@ -64,13 +65,36 @@ local setopt_str = ffi.cast("int(*)(void*, int, const char*)", C.curl_easy_seto
local setopt_long = ffi.cast("int(*)(void*, int, long)", C.curl_easy_setopt) local setopt_long = ffi.cast("int(*)(void*, int, long)", C.curl_easy_setopt)
local setopt_ptr = ffi.cast("int(*)(void*, int, void*)", C.curl_easy_setopt) local setopt_ptr = ffi.cast("int(*)(void*, int, void*)", C.curl_easy_setopt)
-- curl_easy_getinfo is variadic too. The Phase 2 caller only needs the
-- CURLINFO_LONG family (HTTP response code); pre-cast to that signature.
-- CURLINFO_RESPONSE_CODE = CURLINFO_LONG (0x200000) + 2 = 2097154.
local getinfo_long = ffi.cast("int(*)(void*, int, long*)", C.curl_easy_getinfo)
local INFO_RESPONSE_CODE = 2097154
local function get_response_code(handle)
local out = ffi.new("long[1]")
if getinfo_long(handle, INFO_RESPONSE_CODE, out) == 0 then
return tonumber(out[0])
end
return 0 -- 0 = no response (e.g. couldn't connect)
end
local M = {} local M = {}
-- POST `body` to `url` with `headers` (list of "Name: value" strings) and an -- POST `body` to `url` with `headers` (list of "Name: value" strings) and an
-- optional `timeout_ms`. -- optional `timeout_ms`.
-- Returns: -- Returns:
-- string response body on success -- body, status_code on transport success — body is the raw response
-- nil, errmsg on libcurl failure (non-zero CURLcode) -- string (may be empty); status_code is the HTTP
-- response code (2xx success, 4xx/5xx surface as
-- transport-level failure for callers that care,
-- e.g. mcp.lua treating 401 as auth failure).
-- FAILONERROR is intentionally NOT set so the body
-- is observable on non-2xx (lmcp's 401 returns a
-- non-JSON-RPC body that callers need to recognise).
-- nil, errmsg on libcurl-level failure (non-zero CURLcode)
-- Phase 1 callers reading only the first slot stay correct: success
-- returns truthy body, failure returns nil — same disjunction as before.
function M.post(url, body, headers, timeout_ms) function M.post(url, body, headers, timeout_ms)
local handle = C.curl_easy_init() local handle = C.curl_easy_init()
if handle == nil then return nil, "curl_easy_init returned NULL" end if handle == nil then return nil, "curl_easy_init returned NULL" end
@@ -101,9 +125,10 @@ function M.post(url, body, headers, timeout_ms)
end end
local rc = C.curl_easy_perform(handle) local rc = C.curl_easy_perform(handle)
local result, err local result, status, err
if rc == 0 then if rc == 0 then
result = table.concat(chunks) result = table.concat(chunks)
status = get_response_code(handle)
else else
err = ffi.string(C.curl_easy_strerror(rc)) err = ffi.string(C.curl_easy_strerror(rc))
end end
@@ -112,7 +137,7 @@ function M.post(url, body, headers, timeout_ms)
if slist ~= nil then C.curl_slist_free_all(slist) end if slist ~= nil then C.curl_slist_free_all(slist) end
write_cb:free() write_cb:free()
if rc == 0 then return result end if rc == 0 then return result, status end
return nil, err return nil, err
end end
+153
View File
@@ -0,0 +1,153 @@
-- mcp.lua — MCP (Model Context Protocol) JSON-RPC 2.0 client.
-- Phase 2 v1: HTTP POST per RPC against lmcp servers; no long-lived SSE
-- channel (lmcp doesn't push — capabilities.tools.listChanged = false).
-- See docs/PHASE2.md §3 (module changes) and §4 (transport).
local curl = require("ffi.curl")
local json = require("dkjson")
local M = {}
local Session = {}
Session.__index = Session
local MCP_PROTOCOL_VERSION = "2025-03-26"
-- ---------------------------------------------------------------- M.connect
-- Open a session. No network traffic yet — call session:initialize()
-- to actually round-trip initialize + tools/list.
-- opts:
-- alias short name for this server (defaults to URL hostname)
-- auth_token literal Bearer token
-- auth_env env-var name to read the token from (used if auth_token nil)
function M.connect(url, opts)
opts = opts or {}
local auth = opts.auth_token
if (not auth or auth == "") and opts.auth_env then
local env = os.getenv(opts.auth_env)
if env and env ~= "" then auth = env end
end
return setmetatable({
url = url,
alias = opts.alias or url:match("https?://([^:/]+)") or url,
auth = auth,
next_id = 1,
tools = nil, -- populated by initialize()
server_info = nil,
server_caps = nil,
version_warning = nil, -- non-nil string if server returned different protocolVersion
}, Session)
end
-- ---------------------------------------------------------------- headers
function Session:_headers()
local h = { "Content-Type: application/json", "Accept: application/json" }
if self.auth and self.auth ~= "" then
h[#h + 1] = "Authorization: Bearer " .. self.auth
end
return h
end
-- ---------------------------------------------------------------- _rpc
-- One round-trip. Returns:
-- result_table, "ok" — JSON-RPC success
-- nil, "rpc_error", error_obj — JSON-RPC envelope error
-- nil, "transport_error", msg — HTTP >=400 / libcurl / parse
-- If has_id == false this is a notification: lmcp returns HTTP 202 empty
-- body and we synthesize (true, "ok") on transport success.
function Session:_rpc(method, params, has_id)
local req = { jsonrpc = "2.0", method = method, params = params or {} }
if has_id ~= false then
req.id = self.next_id
self.next_id = self.next_id + 1
end
local body, status = curl.post(self.url, json.encode(req), self:_headers())
if not body then
return nil, "transport_error", tostring(status) -- 2nd slot is errmsg
end
if status >= 400 then
return nil, "transport_error",
("HTTP %d: %s"):format(status, body:sub(1, 200))
end
if has_id == false then
return true, "ok"
end
local doc, _, derr = json.decode(body)
if not doc then
return nil, "transport_error", "malformed JSON: " .. tostring(derr)
end
if doc.error then
return nil, "rpc_error", doc.error
end
return doc.result or {}, "ok"
end
-- ---------------------------------------------------------------- initialize
-- Round-trips initialize + sends notifications/initialized + caches tools/list.
-- Returns:
-- true, "ok" — session ready
-- false, kind, err — first failing RPC (caller logs)
function Session:initialize()
local r, kind, err = self:_rpc("initialize", {
protocolVersion = MCP_PROTOCOL_VERSION,
capabilities = {},
clientInfo = { name = "aish", version = "phase2" },
})
if not r then return false, kind, err end
self.server_info = r.serverInfo
self.server_caps = r.capabilities
local sv = r.protocolVersion
if sv and sv ~= MCP_PROTOCOL_VERSION then
self.version_warning =
("protocol version mismatch (sent %s, got %s); proceeding")
:format(MCP_PROTOCOL_VERSION, tostring(sv))
end
-- notifications/initialized — fire-and-forget; failure non-fatal.
self:_rpc("notifications/initialized", nil, false)
-- Eagerly fetch tools (cache for session lifetime per
-- capabilities.tools.listChanged = false).
local tr, tkind, terr = self:_rpc("tools/list", {})
if not tr then return false, tkind, terr end
self.tools = tr.tools or {}
return true, "ok"
end
-- ---------------------------------------------------------------- list_tools
-- Cached. Returns the tool list captured at initialize() time;
-- empty table if not initialized.
function Session:list_tools()
return self.tools or {}
end
-- ---------------------------------------------------------------- call_tool
-- Returns:
-- result_table, "ok" — tool succeeded (content[])
-- result_table, "handler_error" — tool ran but result.isError = true
-- (caller passes content through
-- to the model regardless;
-- PHASE2-baseline.md §3 also
-- notes isError may be false on
-- actual failure — content is
-- authoritative)
-- nil, "rpc_error", error_obj — JSON-RPC envelope error
-- nil, "transport_error", msg — HTTP/libcurl/parse failure
function Session:call_tool(name, args)
local r, kind, err = self:_rpc("tools/call",
{ name = name, arguments = args or {} })
if not r then return nil, kind, err end
if r.isError then return r, "handler_error" end
return r, "ok"
end
-- ---------------------------------------------------------------- close
-- Drops cached state. lmcp has no session teardown — every RPC was
-- already Connection: close.
function Session:close()
self.tools = nil
self.server_info = nil
self.server_caps = nil
self.version_warning = nil
end
return M