convez.ai
MCP Server
ynishi

mlua-mcp-server

ynishi/mlua-mcp-server

Ver no GitHub
InicialPluginScore · de 0 a 100

RMCP Host for Lua: embed a Lua VM and expose dynamic Tool / Resource / Prompt surfaces

Instalação

$npx convez-ai ynishi/mlua-mcp-server

1 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

Estrelas
0
Forks
0
Acompanhando
0
Saúde
42%
Último commit
há 5 meses
Versão
—
Issues abertas
0
Contribuidores
1

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_eval Tool + lua://script/<name> Resource, dynamic Tool / Resource / Prompt registration with list_changed notifications, the symmetric unregister API, an AsyncIslePool for parallel dynamic dispatch, structured-error returns from Lua callbacks, the multi-message / Assistant-role rich Prompt form, lds recipe-pattern Tool dynamic injection, and the std.* stdlib from mlua-batteries (sandbox-aware via MLUA_MCP_SANDBOX_ROOT). See CHANGELOG.md for the full surface and docs/ROADMAP.md for the v0.2.x axes (http / llm / task / sql / kv extension 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):

  • rmcp latest version (currently 1.7)
  • mlua integrated, 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

CrateDescription
mlua-mcp-coreLua VM host primitive — LuaHost + eval() + lua() accessor + shared stringify_lua_value
mlua-mcp-serverrmcp 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_eval Tool. Stateful VM across calls. Stringified return, TAB-joined multi-return, syntax errors surfaced via McpError::internal_error.
  • Phase 1 (2026-06-13, done) — Resource (lua://script/<name>) exposes *.lua files under $MLUA_MCP_SCRIPT_DIR (default ./scripts/). Path-traversal guard rejects bad URIs at invalid_params.
  • Phase 2 (2026-06-13, done) — mcp.tool_register(name, description, schema, fn) Lua stdlib binding. Registered Tools are projected through manual ServerHandler::list_tools / call_tool. Introspection via mcp.tool_list().
  • Phase 3a (2026-06-13, done) — notifications/tools/list_changed pushed after each mcp.tool_register; clients refresh tool list mid-session. Peer captured in on_initialized.
  • Phase 3b (2026-06-13, done) — mcp.resource_expose(uri, name, description, mime_type, fn) and mcp.prompt_register(name, description, arguments, fn) Lua bindings. list_resources merges static (file-system) + dynamic; read_resource dispatches by prefix; list_prompts / get_prompt are wholly dynamic. notifications/resources/list_changed + notifications/prompts/list_changed accompany registration. lua://script/* is reserved and rejected for resource_expose.
  • Phase 4a (2026-06-13, done) — mlua-isle VM ownership migration. The single Arc<TokioMutex<LuaHost>> lock is replaced with AsyncIsle (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 through isle.exec(|lua| ...) so RegistryKey lookups stay on the originating VM. Public behaviour (multi-value TAB-join, nil → "nil") is preserved by stringifying inside isle.exec rather than calling AsyncIsle::eval directly. The notifications/<surface>/list_changed fanout is rewritten to enqueue intents on an unbounded mpsc channel and a dedicated worker task on the main runtime drains and awaits peer.notify_* — this is the architectural separation that lets later phases (Pool / Coroutine API) compose without dragging Lua-thread tokio::spawn calls into main-runtime I/O paths.
  • Phase 4b (2026-06-13, done) — mlua-batteries default stdlib integration. LuaHost::spawn's init closure calls mlua_batteries::register_all(lua, "std") before inject_mcp_bindings, exposing six default-feature modules (std.json / std.env / std.path / std.time / std.string / std.validate) on every Lua chunk. Policy is Config::default() = Unrestricted; sandboxing (cap-std, Sandboxed policy) is deferred to Phase 5. Per-module registration via module_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) — ServerHandler impl rewritten with async fn syntax; #[allow(clippy::manual_async_fn)] and the manual impl Future + Send + '_ returns are gone. Rust 1.75+ AFIT lowers async fn to the same RPITIT shape rmcp 1.7's ServerHandler expects (+ MaybeSendFuture + '_ is satisfied by the auto-generated future), so behaviour is unchanged.
    • #1 name-collision reject (done) — mcp.tool_register rejects the reserved lua_eval static name and duplicate dynamic names; mcp.resource_expose continues to reject the lua://script/ prefix and now also rejects duplicate dynamic URIs; mcp.prompt_register rejects duplicate dynamic names. All three surface mlua::Error::external callers can pcall on.
    • #2 unregister API (done) — mcp.tool_remove(name) / mcp.resource_revoke(uri) / mcp.prompt_remove(name) drop the entry, free the captured Lua closure via lua.remove_registry_value, and fire the matching notifications/<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 MCP isError: true with the message as content[0].text and (when the table carries fields beyond error) the full table as structuredContent. Plain string returns still surface as isError: false success; Lua-level error(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). Invalid role values (anything other than user / assistant) and missing text fields are rejected with invalid_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); declared params auto-derive the input_schema (all string + required) and are appended positionally to cmd. 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 over mcp.tool_register, suitable for wrapping just-style recipe runners (lds-style pattern) without growing the dispatch surface.
    • #d sandbox + #e extension modules (done) — mlua-batteries sandbox feature enabled with MLUA_MCP_SANDBOX_ROOT env var opt-in: when set to an existing directory, Config::builder().path_policy(Sandboxed::new([&root])) is wired through register_all_with, constraining std.fs / std.path access 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-isle 0.5.0 shipped AsyncIslePool, unblocking the previously deferred axis. The server now holds an AsyncIslePool of worker VMs (default 4, configurable via MLUA_MCP_POOL_SIZE) and routes every dynamic Tool / Resource / Prompt dispatch through pool.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::dump at 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 static lua_eval Tool 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 MCP session_id).
    • Remaining axes (priority order) — (1) http / llm extension modules (need explicit http_policy / llm_policy wiring + outbound-network security framing), (2) task / sql / kv extension modules (need host-owned rusqlite::Connection + TaskConfig wiring), (3) Coroutine-API surface decisions, (4) lua_eval per-session pool migration (introduce MCP-level session_id so 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).

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

RepoRole
agent-blockMCP client for Lua (symmetric counterpart)
persona-workrmcp Director-pattern Tool reference
mlua-probeWorkspace layout (-core Lib + -mcp CLI) reference
mlua-isleThread-isolated mlua VM + pool (Phase 4a integrated, IslePool is Phase 5)
mlua-batteriesStdlib bridge (Phase 4b target)
algoclineFull Lua-driven Orch (the complexity we deliberately do not carry here)

License

MIT OR Apache-2.0.

Ver o original no GitHub

Relacionados