Skip to content
amurruPublic

About

execute lua scripts on remote devices using mcp and grpc

Topics

Resources

Security policy

Stars

3 stars

Watchers

0 watching

Forks

Repository files navigation

Moonbunny

Go License

Moonbunny

Moonbunny is an intelligence security spearhead tool built in Go that combines an embedded Lua scripting engine with a gRPC API and an MCP (Model Context Protocol) interface. Load and run Lua scripts over gRPC, or let an AI agent drive them over MCP. Configuration is embedded directly into the binary so a single artifact deploys to a remote host.

Features

  • Lua script engine - embedded gopher-lua VM with system, io, and network modules (full system access by design)
  • gRPC API - script management, execution (sync, batch, streaming), and status/stats
  • MCP interface - Streamable HTTP server exposing tools/list and tools/call for AI agents (optional mTLS)
  • mTLS transport - optional mutual TLS with cert generation built in
  • Remote UDP logging - fire-and-forget telemetry to an admin endpoint
  • Embedded configuration - MBXC binary format packed at the end of the binary
  • xiaotu - companion CLI to edit, validate, and pack configuration

Status

Implemented and tested (race-clean):

Area Implemented
ScriptService List, Load, Unload, Reload, GetInfo, Validate, StreamScriptUpdates
ExecutionService Execute, ExecuteBatch, ExecuteStream (real-time), GetExecutionStatus, ListExecutions, CancelExecution, Timeout
StatusService GetHealth, GetVersion, GetStats, GetVMStats, GetExecutionStats
ToolRegistryService ListTools, GetToolDetails, RegisterTool, UnregisterTool, UpdateTool, CallTool (named-arg Lua tools with input schema validation; registered tools also surface in MCP tools/list)
MCP initialize, tools/list (built-in execute_lua + registered tools), tools/call (by name or inline source, with timeout), tools/cancel
Config MBXC pack/unpack, JSON file persistence, dotted-key get/set
xiaotu configure, set, get, show, validate, pack, unpack
Security mTLS transport, -gen-cert CA + server cert generation

Not yet implemented (defined in proto, return Unimplemented or are deferred): PolicyService, and all services in proto/lua/ (VM pool, sandbox, debugger, events).

Quick start

Prerequisites

  • Go 1.25.4+
  • protoc + protoc-gen-go + protoc-gen-go-grpc (only needed to regenerate proto code; generated files are committed)

Build

go mod download
make build          # bin/moonbunny
make build-xiaotu   # bin/xiaotu

Configure

Configuration lives in moonbunny.json (override the path with the MOONBUNNY_CONFIG environment variable). xiaotu edits it:

./bin/xiaotu set grpc.port 50051
./bin/xiaotu set mcp.port 50052
./bin/xiaotu set logging.remote_enabled true
./bin/xiaotu set logging.remote_endpoint udp://admin.example.com:5140
./bin/xiaotu show
./bin/xiaotu validate

Then pack the config into the binary (the server reads it from itself at startup):

./bin/xiaotu pack ./bin/moonbunny
./bin/moonbunny          # reads embedded config, serves gRPC :50051 + MCP :50052

Without a packed config the binary exits with code 1 and prints the fix steps.

Optional mTLS

./bin/moonbunny -gen-cert                 # writes certs/{ca,server}.{crt,key}
./bin/xiaotu set auth.mtls.enabled true
./bin/xiaotu set auth.mtls.cert_file certs/server.crt
./bin/xiaotu set auth.mtls.key_file certs/server.key
./bin/xiaotu set auth.mtls.ca_cert_file certs/ca.crt
./bin/xiaotu validate && ./bin/xiaotu pack ./bin/moonbunny

The generated server certificate is valid for localhost / 127.0.0.1 (regenerate with production SANs for real deployments). Clients must present a certificate signed by the CA.

Configuration reference

{
  "grpc": { "port": 50051, "host": "0.0.0.0", "timeout_seconds": 30 },
  "mcp": { "port": 50052, "host": "0.0.0.0" },
  "lua": { "max_memory_mb": 512, "timeout_seconds": 300 },
  "auth": {
    "mtls": {
      "enabled": false,
      "cert_file": "certs/server.crt",
      "key_file": "certs/server.key",
      "ca_cert_file": "certs/ca.crt"
    }
  },
  "logging": {
    "remote_enabled": false,
    "remote_endpoint": "udp://admin.example.com:5140",
    "level": "info"
  }
}

MBXC binary format

Config is appended to the binary in the MBXC format and read back at startup:

MBXC_START  (10 bytes)   start marker
version     (2 bytes)    0x0001
length      (4 bytes)    big-endian JSON payload length
payload     (variable)   JSON config
crc32       (4 bytes)    IEEE CRC32 over payload
MBXC_END    (8 bytes)    end marker

Startup error codes: 1 no embedded config, 2 invalid, 3 corrupt checksum.

Using the gRPC API

package main

import (
	"context"
	"log"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"

	pb "shodow/moonbunny/proto"
)

func main() {
	conn, err := grpc.NewClient("localhost:50051",
		grpc.WithTransportCredentials(insecure.NewCredentials())) // use TLS creds in production
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	ctx := context.Background()
	exec := pb.NewExecutionServiceClient(conn)

	// Run inline Lua.
	res, err := exec.Execute(ctx, &pb.ExecuteRequest{Source: `print("hello")`})
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("status=%v output=%q", res.Result.Status, res.Result.Output)

	// Or load a named script, then call a function by name.
	sc := pb.NewScriptServiceClient(conn)
	sc.LoadScript(ctx, &pb.LoadScriptRequest{
		Name:   "greet",
		Source: `function greet(n) return "hi " .. n end`,
	})
	res2, _ := exec.Execute(ctx, &pb.ExecuteRequest{
		ScriptName:   "greet",
		FunctionName: "greet",
		Args:         []string{"world"},
	})
	log.Printf("greet=%q", res2.Result.Output)
}

Using the MCP interface

The MCP server listens on :50052 and speaks the Streamable HTTP transport at /mcp (the current MCP standard; the older HTTP+SSE /sse transport is deprecated). Multi-request flows need a session, so prefer an MCP client:

# One-shot initialize (returns server info + a Mcp-Session-Id header)
curl -s -X POST http://localhost:50052/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -H "MCP-Protocol-Version: 2025-11-25" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"curl","version":"1"}}}'

For tools/list and tools/call (including the built-in execute_lua), use an MCP client library and point it at http://localhost:50052/mcp. Optional mutual TLS is available -- see the MCP interface guide.

Architecture

cmd/moonbunny  ── reads embedded config ── starts ──┬── pkg/grpc  (gRPC :50051, mTLS)
                                                    └── pkg/mcp   (Streamable HTTP :50052, mTLS)
pkg/grpc, pkg/mcp ── embed ── pkg/lua   (gopher-lua VM + system/io/network modules)
                   ── log ──── pkg/remote (async UDP logger)
cmd/xiaotu ──────────────── pkg/config (MBXC pack/unpack + JSON file + SetKey/GetKey)
pkg/certs ───────────────── CA + server certificate generation (-gen-cert)
proto/   ────────────────── generated gRPC stubs (moonbunny.proto)

Packages

Package Responsibility
cmd/moonbunny Server entrypoint; config read/validate, start gRPC + MCP + logger
cmd/xiaotu Configuration CLI
pkg/grpc gRPC services over a shared Lua engine
pkg/mcp MCP Streamable HTTP server (tools/list, tools/call); optional mTLS
pkg/lua gopher-lua wrapper: output capture, streaming sink, Validate
pkg/config MBXC format + JSON file persistence + dotted-key access
pkg/remote Async UDP logger (100-entry buffer, fire-and-forget)
pkg/certs mTLS certificate generation
proto/ Protobuf definitions + generated Go stubs

Development

make build          # build moonbunny
make build-xiaotu   # build xiaotu
make test           # go test ./...
make test-race      # race detector
make protogen       # regenerate proto/moonbunny.* (run after editing .proto)
make protogen-lua   # regenerate proto/lua/lua.* (deferred services)
make vet            # go vet
make fmt            # gofmt + goimports

End-to-end tests

The E2E suite brings up the server, a UDP telemetry collector, and a Go test driver in Docker Compose and exercises the real deployment topology (embedded config, mTLS, MCP, UDP telemetry, full-access Lua):

make e2e          # build images, run all E2E tests, tear down
make e2e-host     # run the Go tests on the host against published ports

Requires Docker. Each run regenerates certificate fixtures under e2e/certs/ (gitignored).

Security note

Moonbunny intentionally gives Lua scripts full system access (shell execution, unrestricted file I/O, network, environment). Only load and run trusted scripts. Network-level access control (mTLS with certificate whitelisting) is the primary boundary.

License

MIT - see LICENSE.

About

execute lua scripts on remote devices using mcp and grpc

Topics

Resources

Security policy

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages