mlua-mcp-server
ynishi/mlua-mcp-server
RMCP Host for Lua: embed a Lua VM and expose dynamic Tool / Resource / Prompt surfaces
Instalação
npx convez-ai ynishi/mlua-mcp-server1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.
Métricas
README
A tradução para o português deste README ainda está na fila.
mlua-mcp-server
RMCP Host for Lua. A thin MCP server that embeds an mlua VM (Lua 5.4) and exposes it as a Tool / Resource / Prompt surface. Composition belongs to the Lua side; the Rust layer is plumbing only.
Status: v0.1.0 — initial release. Static
lua_evalTool +lua://script/<name>Resource, dynamic Tool / Resource / Prompt registration withlist_changednotifications, the symmetric unregister API, anAsyncIslePoolfor parallel dynamic dispatch, structured-error returns from Lua callbacks, the multi-message / Assistant-role rich Prompt form, lds recipe-pattern Tool dynamic injection, and thestd.*stdlib frommlua-batteries(sandbox-aware viaMLUA_MCP_SANDBOX_ROOT). SeeCHANGELOG.mdfor the full surface anddocs/ROADMAP.mdfor the v0.2.x axes (http/llm/task/sql/kvextension modules, Coroutine API, per-session pool).
Why
Existing Lua-MCP options either bundle full Strategy / Swarm abstractions (algocline) or are MCP clients (agent-block). What was missing: a single-shot Lua eval host on the MCP server side — small enough that the Rust layer stays AI-maintainable, while Lua takes over all domain logic.
Design intent (literal):
rmcplatest version (currently 1.7)mluaintegrated, single VM per process- Lua source executes verbatim, no package abstraction
- No algocline-style internal Swarm complexity
- Lua eval is reachable through MCP Resource / Prompt / Tool primitives
- A wrap of algocline is acceptable, but a thin new implementation turned out cheaper
Crates
| Crate | Description |
|---|---|
mlua-mcp-core | Lua VM host primitive — LuaHost + eval() + lua() accessor + shared stringify_lua_value |
mlua-mcp-server | rmcp server binary (stdio transport) — static lua_eval + lua://script/<name> + dynamic Tool / Resource / Prompt registries via mcp.* Lua stdlib, with mid-session list_changed notifications |
Workspace layout is symmetric to mlua-probe (-core Lib + -mcp CLI), sharing [workspace.package] / [workspace.dependencies] for version bumping in one place.
Architecture
[MCP client (Claude Code / other)]
│ Tool: lua_eval { code } (static)
│ Tool: <name> { ... } (dynamic — Phase 2)
│ Resource: lua://script/<name> (list / read) (Phase 1)
│ Resource: <custom uri> (list / read) (Phase 3b)
│ Prompt: <name> (list / get) (Phase 3b)
▲ notifications/<surface>/list_changed (Phase 3a + 3b)
│
▼
[mlua-mcp-server (rmcp stdio)]
│ Manual ServerHandler::list_/call_/get_*
│ on_initialized captures Peer<RoleServer> (for notifications)
│ Three independent dynamic registries (Arc<StdMutex<HashMap>>, bytecode-backed)
│ Notification mpsc + main-runtime worker (Phase 4a fix)
│ AsyncIsle handle for lua_eval (sticky) (Phase 4a)
│ AsyncIslePool for dynamic dispatch (parallel) (Phase 5 IslePool)
▼
[Lua thread — dedicated, current_thread tokio runtime]
│ isle.exec(|lua| ...) dispatches every request
│ RegistryKey lookups stay on the originating VM
│ CancelToken hooks installed per request (mlua-isle)
▼
[mlua VM (Lua 5.4, vendored)]
▲
process-global, stateful across calls
mcp.tool_register / mcp.tool_list (Phase 2 / 3a)
mcp.recipe_tool_register (Phase 5 #6)
mcp.resource_expose / mcp.resource_list (Phase 3b)
mcp.prompt_register / mcp.prompt_list (Phase 3b)
Phase roadmap
- Phase 0 (2026-06-13, done) — single
lua_evalTool. Stateful VM across calls. Stringified return, TAB-joined multi-return, syntax errors surfaced viaMcpError::internal_error. - Phase 1 (2026-06-13, done) —
Resource(lua://script/<name>) exposes*.luafiles under$MLUA_MCP_SCRIPT_DIR(default./scripts/). Path-traversal guard rejects bad URIs atinvalid_params. - Phase 2 (2026-06-13, done) —
mcp.tool_register(name, description, schema, fn)Lua stdlib binding. Registered Tools are projected through manualServerHandler::list_tools/call_tool. Introspection viamcp.tool_list(). - Phase 3a (2026-06-13, done) —
notifications/tools/list_changedpushed after eachmcp.tool_register; clients refresh tool list mid-session. Peer captured inon_initialized. - Phase 3b (2026-06-13, done) —
mcp.resource_expose(uri, name, description, mime_type, fn)andmcp.prompt_register(name, description, arguments, fn)Lua bindings.list_resourcesmerges static (file-system) + dynamic;read_resourcedispatches by prefix;list_prompts/get_promptare wholly dynamic.notifications/resources/list_changed+notifications/prompts/list_changedaccompany registration.lua://script/*is reserved and rejected forresource_expose. - Phase 4a (2026-06-13, done) —
mlua-isleVM ownership migration. The singleArc<TokioMutex<LuaHost>>lock is replaced withAsyncIsle(Send + Sync handle, dedicated Lua thread, current_thread tokio runtime, cancellation hooks). Every dispatch (lua_eval,mcp.tool_register-driven Tools,mcp.resource_expose-driven Resources,mcp.prompt_register-driven Prompts) routes throughisle.exec(|lua| ...)soRegistryKeylookups stay on the originating VM. Public behaviour (multi-value TAB-join,nil → "nil") is preserved by stringifying insideisle.execrather than callingAsyncIsle::evaldirectly. Thenotifications/<surface>/list_changedfanout is rewritten to enqueue intents on an unbounded mpsc channel and a dedicated worker task on the main runtime drains and awaitspeer.notify_*— this is the architectural separation that lets later phases (Pool / Coroutine API) compose without dragging Lua-threadtokio::spawncalls into main-runtime I/O paths. - Phase 4b (2026-06-13, done) —
mlua-batteriesdefault stdlib integration.LuaHost::spawn's init closure callsmlua_batteries::register_all(lua, "std")beforeinject_mcp_bindings, exposing six default-feature modules (std.json/std.env/std.path/std.time/std.string/std.validate) on every Lua chunk. Policy isConfig::default()=Unrestricted; sandboxing (cap-std,Sandboxedpolicy) is deferred to Phase 5. Per-module registration viamodule_entries()is available but unused — the host registers the namespace in one shot. Extension modules (fs/sql/http/llm/hash/regex/base64/uuid/log/schema) stay behind explicit feature gating. - Phase 5 (in progress, basic-healthcheck triple done 2026-06-13) —
- #5 AFIT migration (done) —
ServerHandlerimpl rewritten withasync fnsyntax;#[allow(clippy::manual_async_fn)]and the manualimpl Future + Send + '_returns are gone. Rust 1.75+ AFIT lowersasync fnto the same RPITIT shape rmcp 1.7'sServerHandlerexpects (+ MaybeSendFuture + '_is satisfied by the auto-generated future), so behaviour is unchanged. - #1 name-collision reject (done) —
mcp.tool_registerrejects the reservedlua_evalstatic name and duplicate dynamic names;mcp.resource_exposecontinues to reject thelua://script/prefix and now also rejects duplicate dynamic URIs;mcp.prompt_registerrejects duplicate dynamic names. All three surfacemlua::Error::externalcallers canpcallon. - #2 unregister API (done) —
mcp.tool_remove(name)/mcp.resource_revoke(uri)/mcp.prompt_remove(name)drop the entry, free the captured Lua closure vialua.remove_registry_value, and fire the matchingnotifications/<surface>/list_changed. Static surfaces (lua_eval,lua://script/) are reserved; unknown name/uri returns a Lua error. - #3 structured error returns (done) — dynamic Tool callbacks can return
{ error = "<msg>", code = "...", data = {...} }instead of a plain string; the server maps that to MCPisError: truewith the message ascontent[0].textand (when the table carries fields beyonderror) the full table asstructuredContent. Plain string returns still surface asisError: falsesuccess; Lua-levelerror(msg)still propagates as a protocol-level internal error. - #4 rich Prompt form (done) — dynamic Prompt callbacks can return
{ messages = { {role = "user|assistant", text = "..."}, ... }, description = "<opt override>" }for multi-message conversations with mixed User / Assistant roles. Plain string returns still surface as a single User-role text message (Phase 0-4b backward compat). Invalidrolevalues (anything other thanuser/assistant) and missingtextfields are rejected withinvalid_params. Image / Resource / ResourceLink message content is deferred to a future extension axis. - #6 recipe-Tool dynamic-injection (done) —
mcp.recipe_tool_register(name, description, { cmd = {...}, params = {...}, env = {...} })registers a dynamic Tool whose callback shells out to the configured subprocess. The Rust side builds the Lua closure (no user-supplied function needed); declaredparamsauto-derive theinput_schema(all string + required) and are appended positionally tocmd. stdout becomes the text envelope on exit-zero; non-zero exit produces a P5 #3 structured-error envelope carrying{ error = stderr_first_line, code = "recipe_exit_<N>", data = { exit_code, stdout, stderr } }. Reuses the existing P5 #3 envelope path end-to-end — pure sugar overmcp.tool_register, suitable for wrappingjust-style recipe runners (lds-style pattern) without growing the dispatch surface. - #d sandbox + #e extension modules (done) —
mlua-batteriessandboxfeature enabled withMLUA_MCP_SANDBOX_ROOTenv var opt-in: when set to an existing directory,Config::builder().path_policy(Sandboxed::new([&root]))is wired throughregister_all_with, constrainingstd.fs/std.pathaccess to that tree via cap-std. Unset =Unrestricted(Phase 4b default, backward compat). Invalid root (non-existent or non-directory) fails server startup hard rather than silently degrading. The same cluster also enables seven default-on extension modules —std.fs(read / write / list / metadata / rename / symlink),std.regex(match / find / replace),std.log(info / warn / error),std.uuid(v4 / v7),std.base64(encode / decode),std.hash(sha2 family),std.schema(JSON Schema validate). Network-bound (http/llm) and host-Connection-bound (task/sql/kv) modules remain deferred — they need explicit policy / Connection wiring that warrants separate axes. - IslePool parallel dispatch (done) —
mlua-isle0.5.0 shippedAsyncIslePool, unblocking the previously deferred axis. The server now holds anAsyncIslePoolof worker VMs (default 4, configurable viaMLUA_MCP_POOL_SIZE) and routes every dynamic Tool / Resource / Prompt dispatch throughpool.checkout(), so concurrent MCP client requests run in parallel instead of serializing on a single VM (empirical: 4×200ms parallel calls land in ~210ms wall versus ~800ms serial). Callbacks survive cross-VM dispatch via portable Lua bytecode (Function::dumpat registration time,lua.load(&bytecode)at dispatch); upvalues do not survive — closures over local state silently lose it, so callbacks should be written as pure functions accessing globals. Recipe-backed Tools (Phase 5 #6) dispatch entirely in Rust without entering a VM, so they never block a pool worker. The staticlua_evalTool retains its dedicated AsyncIsle (separate from the pool) to preserve the "stateful across calls" contract — moving lua_eval onto the pool would partition variables across worker VMs and is a future axis (per-session lifecycle via MCPsession_id). - Remaining axes (priority order) — (1)
http/llmextension modules (need explicithttp_policy/llm_policywiring + outbound-network security framing), (2)task/sql/kvextension modules (need host-ownedrusqlite::Connection+TaskConfigwiring), (3) Coroutine-API surface decisions, (4)lua_evalper-session pool migration (introduce MCP-levelsession_idso the stateful contract scopes to a session rather than a global single VM — currently lua_eval bypasses the pool to keep "stateful across calls" backward compatible).
- #5 AFIT migration (done) —
Quick start
cargo install --path crates/mlua-mcp-server
Add to your MCP client config (e.g. project-local .mcp.json):
{
"mcpServers": {
"mlua-mcp-server": {
"command": "mlua-mcp-server",
"args": []
}
}
}
Static surface (Phase 0 + 1):
lua_eval { code: "return 1 + 1" } → "2"
lua_eval { code: "return 'hi', 42" } → "hi\t42"
lua_eval { code: "x = 10" } → ""
lua_eval { code: "return x * 2" } → "20" -- state persists
lua_eval { code: "return ((" } → MCP error (lua error: ...)
list_resources → [{ uri: "lua://script/hello", ... }]
read_resource(lua://script/hello) → "-- ..."
read_resource(lua://script/../etc/passwd) → invalid_params
Dynamic Tool (Phase 2 + 3a):
mcp.tool_register(
"wave",
"Wave hi to a name",
{ type = "object", properties = { name = { type = "string" } }, required = { "name" } },
function(args) return "wave to " .. (args.name or "someone") end
)
After registration the server pushes notifications/tools/list_changed; the client refreshes and the new Tool becomes callable:
wave { name: "world" } → "wave to world"
Dynamic Resource (Phase 3b):
mcp.resource_expose(
"data://greeting",
"greeting",
"Konnichiwa greeting from Lua",
"text/plain",
function() return "konnichiwa, world!" end
)
The new Resource appears in list_resources and read_resource(data://greeting) returns "konnichiwa, world!". Any URI is accepted except lua://script/*, which is reserved for the file-system layer.
Dynamic Prompt (Phase 3b):
mcp.prompt_register(
"greet_prompt",
"Generate a personalized greeting",
{ { name = "who", description = "Recipient name", required = true } },
function(args) return "Hello, " .. (args.who or "world") .. "!" end
)
list_prompts projects it as a standard MCP Prompt; get_prompt({name = "greet_prompt", arguments = {who = "world"}}) invokes the Lua callback and wraps the string return in a PromptMessage (role = user).
Introspection from inside Lua:
mcp.tool_list() -- → { "wave", ... }
mcp.resource_list() -- → { "data://greeting", ... }
mcp.prompt_list() -- → { "greet_prompt", ... }
Primitive stdlib (Phase 4b, std.* namespace):
local data = std.json.decode('{"k":"v"}') -- → { k = "v" }
local s = std.json.encode({ a = 1, b = "two" })-- → '{"a":1,"b":"two"}'
local p = std.path.join("/tmp", "a.txt") -- → "/tmp/a.txt"
local now = std.time.now() -- → 1740000000.123 (seconds since epoch)
local home = std.env.get("HOME") -- → "/Users/..."
Default-feature modules: std.json, std.env, std.path, std.time, std.string, std.validate. Extension modules (fs / http / llm / sql / hash / etc) require explicit feature flags on mlua-batteries and are not enabled by Phase 4b.
Design references (Frame Repo lineage)
docs/design/*.md and docs/adr/0001-host-lua-split.md capture an earlier framing of this repo as a persona-work v1 successor ("Context Compiler" / three-layer trinity / work_compile Tool). That framing is subsumed by the current Lua-Host primitive: any policy expressible in the old design can now be written as Lua functions registered through mcp.tool_register / mcp.resource_expose / mcp.prompt_register. The old docs are retained as reference, not as the current binding spec.
Related repos
| Repo | Role |
|---|---|
agent-block | MCP client for Lua (symmetric counterpart) |
persona-work | rmcp Director-pattern Tool reference |
mlua-probe | Workspace layout (-core Lib + -mcp CLI) reference |
mlua-isle | Thread-isolated mlua VM + pool (Phase 4a integrated, IslePool is Phase 5) |
mlua-batteries | Stdlib bridge (Phase 4b target) |
algocline | Full Lua-driven Orch (the complexity we deliberately do not carry here) |
License
MIT OR Apache-2.0.