Compare commits

...

31 Commits

Author SHA1 Message Date
marfrit 3409a41d85 versions.lua: MCP protocol-version gate, built by the bullpen society
Phase B, third attempt. The contract is the head of tests/phase_b_acceptance.lua;
this is the module that satisfies it.

M.SUPPORTED = {"2025-06-18"} -- and that list is not a guess. The acceptance test
anchors it against a LIVE server: it calls initialize and compares M.SUPPORTED to
the protocolVersion the server actually reports. The first attempt shipped
{"2025-06-18","2025-11-25"} and passed 14/14, because the test then only compared
the list against itself; lmcp does not speak 2025-11-25. Answering HTTP 200 to a
version header proves nothing -- the same endpoint answers 200 to 1999-01-01.

Provenance, all of it in marfrit/bullpen room.jsonl:
  #218/#234  @coder wrote the module (qwen3.6-coding), two passes rejected first:
             pass 1 implemented M.is_supported instead of the contract's M.check
             and embedded its own self-test; pass 2 arrived without a certificate.
  #246       @testdesigner refused to materialise the file in the clone root --
             writing the subject and then greening it yourself collapses the
             implementer/tester split. The refusal was correct.
  #256       two certificates, both from container `testdesign`, same test
             (sha256 78a4758d706a2539, commit e8c18f1e3b):
               empty state -> ROT rc 2 (subject absent)
               these bytes -> GRUEN rc 0, 17/17, live anchor included
  #283       @deus lifted it out through the room; sha256 byte-identical.

sha256 of this file: e5bb0739b84a2354422842cc1be28d2d8ad407307b84e3f05e79faa30e68e5da
2026-08-09 00:06:46 +02:00
Markus Fritsche e8c18f1e3b tests: Phase B an der Wirklichkeit verankern
Der Test prueft M.SUPPORTED bisher nur gegen sich selbst: erster Eintrag
wird angenommen, Unbekanntes abgelehnt, data.supported entspricht
M.SUPPORTED. Ein Modul mit {"2025-06-18","2025-11-25"} besteht ihn mit
14/14 -- obwohl lmcp 2025-11-25 nicht spricht. Genau das ist am
2026-08-08 passiert: die Gesellschaft hat sauber gearbeitet, der Test gab
Rueckgabe 0, und abgenommen wurde der falsche Vertrag.

Drei Instanzen liessen es durch, und keine war nachlaessig: @coder riet
eine echte MCP-Fassung, @foreman konnte es aus dem Vertragstext nicht
widerlegen und bestaetigte es zweimal ausdruecklich, und der Test hatte
die Luecke geerbt. Die Wurzel war der Vertrag: er verlangt "die
Fassungen, die DIESER Server spricht" und nennt sie nicht. Damit war die
Liste eine freie Variable statt einer Tatsache.

DER NAHELIEGENDE FIX WAERE FALSCH GEWESEN. Die Liste im Vertrag zu
NENNEN ersetzt eine ungebundene Variable durch eine zweite Kopie der
Tatsache -- die veraltet, sobald lmcp eine Fassung dazulernt, und dann
schreibt der Vertrag wieder etwas fest, das der Server nicht spricht,
nur andersherum. (Dank an Fable fuer den Widerspruch.)

Stattdessen misst der Test jetzt: er schickt dem laufenden lmcp ein
`initialize` und haelt M.SUPPORTED gegen die gemeldete protocolVersion.
Die Bindung sitzt damit an der Quelle, und keiner der Beteiligten kann
mehr raten.

Ohne erreichbaren Server FAELLT der Test, er ueberspringt nicht. Eine
Abnahme, die ihre zentrale Eigenschaft nicht pruefen kann, ist keine
Abnahme -- und ein stiller Uebersprung ist genau die Art Gruen, gegen die
diese Phase antritt. Gemessen: ohne LMCP_PROBE_URL Rueckgabe 1.

Damit hat die Regel drei Richtungen statt zwei:
  rot gegen eine kaputte Fassung,
  gruen gegen eine korrekte,
  und gruen gegen die WIRKLICHKEIT.

Nachgemessen gegen hertz-tools:8080:
  SUPPORTED = {"2025-06-18"}                 -> 0 Fehlschlaege, Rueckgabe 0
  SUPPORTED = {"2025-06-18","2025-11-25"}    -> 1 Fehlschlag,  Rueckgabe 1
Das zweite ist das Modul, das heute Vormittag als GRUEN abgenommen
wurde. Die Abnahme ist damit rueckwirkend rot -- und das ist das
Ergebnis, nicht der Fehler.

Aufruf: LMCP_PROBE_URL=http://<host>:8080/mcp LMCP_PROBE_TOKEN=<token> \
        lua5.4 tests/phase_b_acceptance.lua <impl.lua>
2026-08-08 13:41:16 +02:00
Markus Fritsche 611a047bef lmcp: LMCP_TOOL_ALLOW — Erlaubnisliste je Instanz
Eine lmcp-Instanz konnte ihren Werkzeugsatz bisher nur ERWEITERN.
tools.d-Dateien fuegen hinzu; der Grundstock aus server.lua bringt
shell, shell_bg, write_file, edit_file, read_file, fetch und web_search
mit, und eine Plugin-Datei kann nichts wegnehmen.

Gemessen am 2026-08-08 im bullpen: jeder Agent-Container haelt den
Raum-Token, also hatte JEDER von ihnen eine Wurzelschale im
Raum-Container. Nachgewiesen aus dem foreman-Container -> uid=0(root),
hostname room, Schreibzugriff auf room.jsonl. Das ist keine
Einbruchsluecke (alle Container sind eine Sicherheitsdomaene), aber es
macht jede Aussage ueber Rollentrennung unbelegbar: der Orchestrator,
der laut Entwurf KEINE Schale haben darf ("Raumtext ist nicht
vertrauenswuerdig"), hat eine — und hat sie im ersten Durchlauf
unaufgefordert benutzt, um die Abnahme seiner eigenen Koordination
auszufuehren.

GEPRUEFT WIRD BEI DER REGISTRIERUNG, nicht nachtraeglich loeschend.
Die Alternative waere eine Plugin-Datei, die nach dem Laden aus
server.tools entfernt — die muss jeden kuenftigen Grundstock-Eintrag
kennen und ist damit wieder eine Liste, die jemand pflegen muss. Genau
solche Listen laufen auseinander (siehe PRIVILEGED, zwei Kopien in zwei
Dateien). An der Registrierung ist die Regel EINE Aussage: was nicht auf
der Liste steht, entsteht nicht — Built-ins wie Plugins, heute wie fuer
alles, was morgen dazukommt.

Rueckwaertsvertraeglich: ohne LMCP_TOOL_ALLOW aendert sich nichts.
Verweigern ist stumm und wirft nicht, damit ein Plugin, das ein
gesperrtes Werkzeug anbietet, weiterlaeuft statt abzustuerzen; tool()
bleibt verkettbar.

tests/test_tool_allow.lua weist es in beide Richtungen nach: Rueckgabe 0
gegen diese Fassung, Rueckgabe 1 mit sieben Fehlschlaegen gegen die
vorige. Der Test prueft ausdruecklich, dass ein verweigertes Werkzeug
auch nicht AUFRUFBAR ist — tools/list und tools/call lesen dasselbe
Register, ein reiner Anzeigefilter waere wertlos gewesen.

Zwei Fallen im Test selbst, als Kommentar festgehalten, weil sie mich
zwei Runden gekostet haben: package.path muss VORNE ergaenzt werden,
sonst gewinnt die installierte /usr/share/lua/5.4/lmcp.lua und der Test
misst den falschen Baum; und die Rueckwaerts-Pruefung darf nur im
Elternlauf laufen, im Kind ist die Liste gesetzt.
2026-08-08 13:26:05 +02:00
Markus Fritsche e44b35b0e0 tests: Abnahmetest fuer Phase B — Fassungen durchsetzen
Phase A stellte fest, welche Fassungen verlangt werden. Phase B lehnt
ab, was der Server nicht spricht. Gemessen am 2026-08-08 an
hertz-tools:8080 antwortet lmcp mit HTTP 200 auf JEDE Fassungsangabe,
auch auf 1999-01-01 - eine Fassung, die es nie gab. Es liest den Kopf
nicht; `Mcp-Protocol-Version` kommt im Quelltext genau einmal vor, in
einer CORS-Erlaubnisliste.

Vertrag im Kopf der Datei. Vier Punkte, die Handfassungen regelmaessig
verfehlen und die deshalb einzeln geprueft werden:

  * Der FEHLENDE Kopf ist zulaessig. Die sitzungslose Abkuerzung
    schickt ihn oft nicht, und sie traegt den meisten Verkehr - eine
    Ablehnung dort legt mehr lahm als sie schuetzt.
  * Die Ablehnung muss die unterstuetzten Fassungen NENNEN. Ohne die
    Liste kann die Gegenstelle nicht nachverhandeln, nur aufgeben.
  * Sie wirft nie. Zahl, Tabelle, Funktion - alles ergibt false. Ein
    Server, der an einem fremden Kopf stirbt, ist schlechter als einer,
    der ihn ignoriert.
  * 2026-07-28 wird abgelehnt, SOLANGE sie nicht in SUPPORTED steht.
    Wer die Zielfassung durchwinkt, bevor er sie spricht, hat den
    Fehler nur verschoben.

Unterscheidungsfaehig nachgewiesen, in beide Richtungen: Rueckgabe 0
gegen eine korrekte Fassung, Rueckgabe 1 mit fuenf Fehlschlaegen gegen
eine absichtlich kaputte.

Aufruf: lua5.4 tests/phase_b_acceptance.lua <impl.lua>
2026-08-08 08:23:08 +02:00
Markus Fritsche 8196f6fb8e tools.d: nash entfernt — mneme ist der Nachfolger
nash-mem0 gibt es nicht mehr. Der Dienst dahinter antwortet nicht
(192.168.88.143:8000, HTTP 000), der Zielcontainer `nash` existiert
auf hertz nicht mehr, und die Deploy-Automatisierung ist heute
ausser Dienst gestellt. Geblieben war das Werkzeug-Modul: das Paket
lieferte weiterhin nash_add/nash_search/nash_list/nash_delete auf
JEDEN Wirt aus, der lmcp installiert.

Aktiv war es nirgends - auf hertz als nash.lua.disabled abgehaengt,
auf boltzmann und dcw2 gar nicht vorhanden, kein lmcp im Netz bietet
ein nash_*-Werkzeug an. Also kein Ausfall, sondern Ballast: vier
Werkzeuge, die ein Modell waehlen KANN und die dann ins Leere laufen.
Ein angebotenes Werkzeug ist ein Versprechen.

Die Nachfolge steht schon: hertz-tools bietet `apropos` und `recall`
gegen mneme, gemessen 26 Werkzeuge, keines davon nash.

Damit faellt es beim naechsten Release von selbst aus dem Paket.
Installierte Kopien bleiben liegen, bis der jeweilige Wirt aktualisiert
- das ist unschaedlich, weil sie ohne Symlink in tools.d nicht geladen
werden.
2026-08-08 08:08:23 +02:00
Markus Fritsche 08e0075d14 tests: Abnahmetest fuer Phase A der Fassungs-Meldung
Phase A des Umstiegs auf MCP 2026-07-28 ist "observe-only": erst
feststellen, welche Protokollfassungen die Gegenstellen ueberhaupt
verlangen, bevor irgendetwas durchgesetzt wird. Der Vertrag dafuer
steht im Kopf der Datei; dies ist der getrennte Test dazu.

GETRENNT ist hier die Bedingung, nicht die Beschreibung. An derselben
Aufgabe war der Defekt an vier aufeinanderfolgenden Laeufen der
SELBSTTEST, nie der Code - wer implementiert, schreibt den Test nicht.
Deshalb ist er hier im Repo und nicht in der Werkstatt der Erzeuger.

Nachgewiesen unterscheidungsfaehig, in beide Richtungen:
  * Rueckgabe 1 und zwei Fehlschlaege gegen eine absichtlich kaputte
    Fassung,
  * Rueckgabe 0 gegen eine korrekte.
Ein Test, der nur besteht, misst nichts.

Zehn Pruefungen, darunter die zwei, die in Handfassungen zuerst
fallen: der Deckel bei 50 darf nicht zu frueh zuschlagen, und das
Modul darf keine neue globale Variable hinterlassen.

Aufruf: lua5.4 tests/phase_a_acceptance.lua <impl.lua>
2026-08-08 08:02:21 +02:00
Markus Fritsche 250f3d38f0 hub: probe ssh-only backends with a TCP connect instead of leaving them unknown
The design note says the probe is lmcp-only because checking ssh "is expensive (3-6s per
offline host) and the hub exists specifically to absorb lots of offline hosts". That holds
for an ssh SESSION. A bare TCP connect to port 22 answers the only question a host card
asks — is the box there — with no handshake and no auth.

Measured on the room host: a dead target costs 1.05s, a live one milliseconds, and riding
the existing parallel fan-out keeps wall clock at one budget window — 3.07s for 14 lmcp
plus 9 ssh probes together, against 3.10s for the 14 lmcp probes alone. The cost objection
is answered rather than ignored.

Eight reachable hosts had been reported as "no probe result": dcw2, deus, escher, hermes,
nash, noether, orca, pipi. They now report UP via=ssh, and a host whose port 22 refuses
gets a real reason ("ssh port unreachable") instead of silence.

Deliberately unchanged: a backend with BOTH paths whose lmcp is down still reads DOWN, per
the existing note that remote_* falls through to ssh regardless. Only ssh-ONLY backends
get the new probe. Without nc the probe reports nothing rather than guessing DOWN — an
unprobed host is honest, a wrongly-asserted one is not.

Two detours worth recording, since both were self-inflicted and cost a restart each:

  * The first attempt edited /opt/lmcp/hub.lua and restarted the service, which loads
    /usr/share/lua/5.4/hub.lua — a separate copy. Nothing keeps the two in step; the log
    line still showed the old format string, which is the only reason it was noticed.
  * The second attempt compared this repository against the deployed file and concluded
    that 120 lines of MCP tool annotations had never been committed. They had. The working
    copy was 17 commits stale, so the "drift" was entirely an artefact of the comparison.
    Against the current tree the real change is 36 lines, and the patched file now hashes
    identical to the running one.
2026-08-02 21:35:15 +02:00
noether (claude) 2bb7b94a66 tools.d: add boltzmann stash tool (fleet-memory CLI wrapper)
Wraps incus exec memory -- docker exec stash-stash-1 /stash <command> behind one
MCP tool so pi-agents call stash command:="recall ... -n /infra/hosts" instead of
hand-typing the incus/docker chain. Loaded via LMCP_TOOLS_DIR=/opt/lmcp/tools.d.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EWpfhDgYNA21tETDP9ueBE
2026-07-18 13:23:29 +02:00
noether (claude) 80fb60c60f hub: serve apropos + wake_fleet (fleet-central tools) alongside remote_*
Consolidate the two fleet-central local tools (stash recall + pve WoL) onto
the hub broker so :8090 is a complete fleet-management endpoint. They run
locally on hertz via a new run_local() helper (no ssh backend hop). Still
also served by hertz-tools (:8080) for now; the hertz-side removal is the
follow-up once every client (pi-agents) has a @hub session.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EWpfhDgYNA21tETDP9ueBE
2026-07-18 08:51:16 +02:00
noether (claude) 6fa98dd655 shell: kill process group on timeout/cancel (no orphans) + shell_bg job registry + kill_job/list_jobs
Root cause of the shell->shell_bg thrash: run() backgrounded POSIX commands
with a bare & and never captured the pid, so on timeout it returned an error
while the children kept running. Now: setsid (own process group), capture the
leader pid, SIGTERM+SIGKILL the whole group on timeout/cancel, and a message
telling the model it was killed + to use shell_bg. Plus shell_bg registers jobs
to /tmp/lmcp-bg-jobs.tsv and new kill_job/list_jobs let a runaway job be reaped
without a reboot.
2026-07-12 14:28:52 +02:00
noether (claude) a7b3c44f1c reconcile: sync repo to live deployment (wake_fleet + apropos tools, stash_recall helper) 2026-07-12 14:25:30 +02:00
marfrit 840341d2dd fix: replace LXC/LXD with Incus
Replace all /snap/bin/lxc references with incus in the
hertz-specific tool definitions. Tool names changed from
lxc_exec/lxc_list to incus_exec/incus_list.

Context: LXC snap was removed from hertz; the system
now uses incus (Debian package) for container management.
2026-06-12 23:18:58 +02:00
marfrit 8748fe53bc Merge pull request 'Add nash memory tools as lmcp plugin' (#26) from williams/lmcp:master into master
Reviewed-on: marfrit/lmcp#26
2026-06-05 15:54:26 +00:00
williams 8d8d8fac65 Add nash memory tools (nash_add/search/list/delete) 2026-06-05 15:51:51 +00:00
marfrit 3dd01e5313 Merge pull request 'fix: case-insensitive Bearer token parsing in auth header' (#25) from williams/lmcp:fix/case-insensitive-bearer-auth into master
Reviewed-on: marfrit/lmcp#25
2026-05-30 14:43:37 +00:00
williams d2c2962ad1 fix: case-insensitive Bearer token parsing in auth header 2026-05-30 12:55:02 +00:00
Markus Fritsche c5375b8a77 v1.2.1/#22: LMCP_HOST + LMCP_CONF env support
Adds two env vars to the packaged server.lua so hosts can switch
fully to the packaged entrypoint (combined with v1.2.0's tools.d/
plugin scan):

  LMCP_HOST — interface to bind on (default 0.0.0.0). Hosts that
              need .18-only binding (hertz) or similar single-NIC
              constraints set this. Threaded into lmcp.new opts.host.
  LMCP_CONF — path to a conf file with bearer-token entries (e.g.
              /opt/herding/etc/hertz-tools.conf). Read by lmcp.lua's
              read_conf; the `.godparticle` entry becomes the bearer
              token. Threaded into lmcp.new opts.conf.

Both unset → unchanged behavior (binds 0.0.0.0, no conf file).

Together with v1.2.0's tools.d/ scan, this lets a host like hertz
ship NO override server.lua — just an /opt/lmcp/tools.d/hertz.lua
plugin file and a systemd unit that points at the packaged
server.lua with LMCP_HOST=192.168.88.18 + LMCP_CONF=/opt/herding/
etc/hertz-tools.conf. apt upgrade then delivers all packaged
improvements automatically.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 23:33:30 +00:00
Markus Fritsche e05438f0e3 v1.2.0/#22: tools.d/ plugin scan — host-local tool extensions
Adds a directory-scan plugin mechanism to the packaged server.lua
so hosts can drop their own tools alongside the packaged generics
without forking server.lua.

Mechanism:
- After all packaged tool registrations + before transport selection,
  the server scans LMCP_TOOLS_DIR (default /opt/lmcp/tools.d on POSIX,
  %ProgramData%\lmcp\tools.d on Windows) for *.lua files.
- Each plugin file is invoked as a function receiving (server, run):
    local server, run = ...
    server:tool("my_local_tool", "...", {...}, function(a) return ... end)
- Load errors and runtime errors are reported on stderr and skipped;
  the server continues with the tools it successfully loaded.

Why:
Hosts like hertz and ampere have always carried local /opt/lmcp/server.lua
overrides containing both packaged-overlap tools (shell, read_file, …)
AND host-specific tools (fritz, ha_api, mqtt_*, lxc_exec, …). When the
override drifts, the host either loses packaged improvements (the v1.1.1
fetch/web_search regression on hertz/ampere) or accumulates hand-merged
patches that vanish on shutdown (the original symptom in issue #22).
With tools.d/, hosts drop ONLY their custom tools as plugin files; the
packaged server.lua stays canonical. apt upgrade picks up new packaged
tools automatically.

Smoke-tested:
  $ mkdir -p /tmp/probe && cat > /tmp/probe/p.lua <<E
  local server, run = ...
  server:tool("plugin_probe", "test", {type="object"},
              function() return "ok" end)
  E
  $ LMCP_TOOLS_DIR=/tmp/probe lua server.lua
  lmcp: loaded plugin /tmp/probe/p.lua
  $ curl POST tools/list → plugin_probe present in the 10 tools listed

Existing single-file server deployments (no /opt/lmcp/tools.d/) keep
working unchanged — io.popen on a non-existent directory returns nil
and the plugin loop no-ops. Backwards compatible.

Closes the structural side of #22 (the ad-hoc-override pattern); ampere
+ hertz migration to use tools.d/ for their custom tools is the operator
follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 23:32:12 +00:00
Markus Fritsche 9707f7ae93 v1.1.1: omit empty inputSchema.properties at registration
Same json.lua empty-table → [] gotcha that bit `ping` in v1.0.0-rc1
(project_json_empty_table_gotcha memory) bit again — this time on
tool inputSchemas with `properties = {}`. Symptom: spec-strict MCP
clients (Zod et al.) reject tools/list with:

  expected: record, code: invalid_type,
  path: [tools, N, inputSchema, properties],
  message: "Invalid input: expected record, received array"

Fix: in `lmcp:tool()`, normalise the registered inputSchema —
when `properties` is an empty Lua table, drop the key entirely.
JSON Schema permits omitting `properties` on `type: "object"`
(means "any object, no constraints" — exactly what a no-arg tool
wants).

Clone-before-mutate so the caller's table isn't trampled (matters
when a server author shares one schema across multiple
registrations).

Smoke tested locally with 3 tools (empty, default-nil, populated):
- `properties = {}` → emitted as `{"type":"object"}`
- nil schema → same default, same output
- populated properties → emitted intact with full shape

Discovered against hertz-tools live (lxc_list, network_status had
`properties = {}` — hertz hotfixed by hand before this commit;
this protects every future tool author from the same trap).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 22:39:56 +00:00
Markus Fritsche 9e53b23b11 windows/build-msi.sh: cross-build the MSI on Linux via wixl + mingw-w64
Discovered building v1.1.0 that the MSI can be produced entirely on
Linux — no Windows VM, no manual WiX install, no GUI babysitting:

  apt install wixl unzip gcc-mingw-w64-x86-64 binutils-mingw-w64-x86-64 \
              mingw-w64-x86-64-dev curl

The new build-msi.sh script:
  1. Runs sync.sh to refresh pkg/{lmcp,server,json}.lua from root.
  2. Downloads Lua 5.4.2 Win64 binaries from LuaBinaries (Tools +
     Library zips — interpreter + headers + import lib).
  3. Cross-compiles LuaSocket 3.1.0 via x86_64-w64-mingw32-gcc
     (produces socket-3.0.0.dll + mime-1.0.3.dll for Win64).
  4. Stages pkg/lua/{lua.exe, lua54.dll, socket/, mime/, *.lua} per
     the WiX manifest layout.
  5. Invokes wixl on the lmcp.wxs manifest (with sed for the
     Windows backslash path separators → forward slashes).

Output: lmcp-<version>.msi. Version is read from lmcp.wxs
Version="…", so bump that before each release.

Cold build: ~30s. Warm cache: ~5s. The artifact contains all 17
files the WiX manifest expects, ProductVersion matches lmcp.wxs.

README updated to point at build-msi.sh as the recommended path;
the Windows-side candle/light recipe kept as an alternative.

Reproducibility note (deferred): the MSI is not yet bit-reproducible
across builds — file mtimes in the Lua binaries' zip propagate to
the cab inside the MSI. The debian/lmcp/build-deb.sh in marfrit-
packages uses SOURCE_DATE_EPOCH to fix this; same pattern would
apply here. Out of scope for the first cut.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 20:27:32 +00:00
Markus Fritsche 7e62f71931 v1.1.0/#18: windows MSI build — sync.sh + tracked manifest
windows/ was previously an untracked working tree with manually-
copied .lua files that drifted ~6 months out of date (missed every
feature added since April 2026). #18 introduces Option 1 from the
issue body: build-time sync.

New tracked files:
  - windows/sync.sh — copies root {lmcp,server,json}.lua to pkg/.
    Idempotent; run before WiX. Catches missing source files; logs
    each sync.
  - windows/README.md — workflow doc + tracked-vs-generated map.
  - windows/lmcp.wxs — MSI manifest (Version bumped 0.1.0 → 1.1.0).
  - windows/pkg/{install_service,start}.bat — Windows service
    installer + launcher (now tracked; they were already in pkg/).

New .gitignore at repo root:
  - windows/pkg/{lmcp,server,json}.lua — regenerated by sync.sh
  - windows/pkg/lua/ — bundled Lua + LuaSocket runtime (downloaded
    separately, not in git)
  - editor noise (*.swp, *.swo, .DS_Store)

Verification (Phase 7):
  $ ./windows/sync.sh
    synced lmcp.lua
    synced server.lua
    synced json.lua
  $ diff lmcp.lua windows/pkg/lmcp.lua  → empty
  $ git ls-files -o --exclude-standard windows/
    windows/README.md
    windows/lmcp.wxs
    windows/pkg/install_service.bat
    windows/pkg/start.bat
    windows/sync.sh
  $ git check-ignore windows/pkg/{lmcp,server,json}.lua  → all 3 ignored

The "missed every feature since April" failure mode this fixes:
running sync.sh before each MSI build now guarantees pkg/ matches
master. Forgetting to run it is failure-loud (the MSI ships the
last sync's snapshot, easy to spot in QA), not silent (the manifest
points at fresh files that mismatch root).

Closes v1.1.0 milestone with #11, #20.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 19:43:27 +00:00
Markus Fritsche 55ead8041f v1.1.0/#11: progress + cancellation notifications
ctx augmentation:
- ctx.progress(p, total?, message?) emits notifications/progress on
  the session's notify_q. No-op when the original request omitted
  _meta.progressToken (per spec: only emit when client opted in).
  Type-checks numeric args; passes progressToken through unchanged
  (spec allows number OR string keys).
- ctx.cancelled() returns true once the client has sent a
  notifications/cancelled for this request's id.

handle_request:
- New side-effect in the id==nil branch: notifications/cancelled
  scans the module-level _ctx_by_co for an in-flight ctx whose
  request_id matches; flips self._cancelled_ids[rid_str] only when
  found. Unknown rids drop silently (no map growth).
- Pre-handler short-circuit: if cancel arrived before dispatch
  reached tools/call, skip the handler entirely.

Cross-module ctx lookup:
- Module-level weak _ctx_by_co table in lmcp.lua keyed by
  coroutine. lmcp.current_ctx() returns the ctx of the running
  coroutine. server.lua's run() lazy-requires lmcp and uses it
  to opt into auto-cancellation without depending on lmcp internals.

server.lua:run():
- After each sleep_ms cycle, check ctx.cancelled(); exit poll loop
  with cancelled=true if set.
- Poll interval capped at 500ms when a ctx is present so worst-case
  cancel latency stays ≤500ms (vs. 2s default growth).
- Returns "(cancelled)" sentinel; handler propagates normally.

_finalise_dispatch:
- Single cleanup site for both _cancelled_ids and _ctx_by_co (per
  Phase 5 review).
- When was_cancelled: emit JSON-RPC -32800 "Request cancelled"
  (deviation from Phase 4 plan; documented).

Phase 4 deviation explained: plan was silent TCP close (per spec
"SHOULD NOT respond"). Empirically: os.execute's fork+exec
inherits the parent's TCP socket FD into the spawned shell, so
sock:close() doesn't actually deliver FIN until the subshell exits
(i.e. the long-running command completes anyway). Verified
luasocket close() works on bare sockets (curl exits with RST in
511ms). The fix would be FD_CLOEXEC on accepted sockets, which
luasocket doesn't expose — needs a C shim or luaposix. Deferred.
Captured in memory project_fd_inheritance_in_run.

Practical UX with the deviation: client receives a structured
-32800 error within ~420ms of POSTing the cancel notification.

Measurements (Phase 7):
  cancel timing (3 runs, sleep 10 with cancel at 0.4s):
    run 1: t=0.42s code=-32800
    run 2: t=0.42s code=-32800
    run 3: t=0.42s code=-32800
  progress: 3/3 events arrived on SSE; spec-shaped payload
  concurrent fast+slow (#20 regression): unchanged (fast 0.01s)
  all previously-closed issues regression-test green

Zero handler source-code changes. Existing tools (shell, fetch,
web_search, hub remote_*) get cancellation for free via run().

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 19:29:00 +00:00
Markus Fritsche 2ac502e50f v1.1.0/#20: concurrent handler dispatch
Replaces the synchronous tools/call path with a coroutine-wrapped
dispatch. The select()-based event loop from v1.0.0-rc1 already
multiplexes I/O; this change extends the same single-thread
cooperative scheduling to tool handler execution.

How:
- server.lua:sleep_ms detects coroutine context and yields with
  { wake_at = gettime() + ms/1000 } instead of blocking. Falls back
  to today's busy-blocking sleep when on the main thread (stdio
  dispatch, init code).
- server.lua:run() now uses gettime() deltas for timeout accounting
  (Phase 5 review fix — the prior interval-accumulator diverged
  from wall-clock when scheduler delayed resumes).
- lmcp.lua wraps the handle_request call inside _dispatch_post in a
  coroutine. Synchronous completion (no yield) takes the inline-
  response path; if the handler yields, the coroutine parks in
  self._pending_handlers and the conn enters dispatching_async.
- New _scheduler_tick services pending coroutines whose wake_at has
  passed; on completion calls the shared _finalise_dispatch helper
  to build the deferred HTTP response (Accept-aware: SSE or JSON).
- select() timeout tightens to the next pending wake_at so short
  yields don't pay the full 100ms tick.

Measurement (Phase 7):
  before: fast ping during slow shell sleep 3 = 4.28s
  after:  fast ping during slow shell sleep 3 = 0.01s   (~400×)
  3 parallel slow shells: 3.77s total wall (was ~9s).

Zero handler source-code changes. Every existing tool that goes
through run() (shell, shell_bg, fetch, web_search, list_dir,
search_files, systeminfo, hub remote_*) gets concurrency for free.
Pure-Lua handlers (ping, read_file, write_file, edit_file) continue
to complete inline. stdio transport stays serialised by design
(single-client per stdio process).

Known limits documented in memory project_handler_coroutines:
- socket.gettime() is wall-clock not monotonic; large NTP steps may
  bunch resumes. Acceptable on chrony-slewed fleet.
- Cancellation (#11) is now tractable since the scheduler can flip a
  flag between resumes — implementation pending.
- Server-initiated request await (sampling/roots from inside a
  handler) still requires a future yield-on-pending helper.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 19:03:06 +00:00
Markus Fritsche deb73d129e v1.0.0-rc1: full MCP 2025-06-18 surface
Closes 14 issues; lmcp now implements the complete client-facing
surface of MCP spec 2025-06-18.

New primitives:
  - fetch (#3)              HTTP GET/HEAD with bounded body + render chain
  - web_search (#4)         pluggable backend (SearXNG/DDG/Tavily/Brave)
  - Resources (#5)          resources/list, /read, /templates/list + list_changed
  - Prompts (#6)            prompts/list, /get + list_changed
  - Completion (#7)         completion/complete for prompt/template args
  - Logging (#8)            logging/setLevel + notifications/message
  - Sampling (#9)           server-initiated sampling/createMessage
  - Roots (#10)             roots/list + cache + path_in_roots helper

Protocol / wire:
  - Pagination (#12)        cursor on tools|resources|prompts/list
  - Structured tool output (#13)  structuredContent + _meta + protoV bump to 2025-06-18
  - Tool annotations (#14)  readOnlyHint/destructive/idempotent/openWorld on all tools
  - stdio transport (#15)   LMCP_TRANSPORT=stdio for Claude Desktop / IDE clients
  - Streamable HTTP (#16)   select()-based event loop, sessions, persistent SSE,
                            DELETE, heartbeat, server-initiated request helper
  - ping (#19)              now emits result:{} not result:[] via json.empty_object

Cross-cutting fixes:
  - json.lua: UTF-16 surrogate pair combination (emoji/non-BMP CJK round-trip)
  - json.lua: json.empty_object sentinel for spec-correct {} emission
  - handle_request: generic notification suppression (id==nil → return nil)
    eliminates malformed -32601 with id:null on stdio and HTTP transports

Tool annotations backfilled across all registrations:
  - server.lua: 10 tools (shell, shell_bg, read_file, write_file, edit_file,
    list_dir, search_files, fetch, web_search, systeminfo)
  - hub.lua:   8 remote_* tools
  - example_server.lua: 4 demo tools + 3 sample resources + 1 sample prompt
                        + 1 sample completer

Honest limits, filed as follow-up issues:
  - #11 progress + cancellation — gated on #20 (handler concurrency)
  - #18 windows/pkg sync         — stale April-2026 snapshot, packaging decision
  - #20 concurrent handler dispatch — select() loop concurrencies I/O, not
                                      handler execution; synchronous tool
                                      handlers still serialise (shell sleep 3
                                      blocks a parallel ping)

Backwards compatible: every previously-deployed lmcp client (sessionless
POST, HTTP-only, no Mcp-Session-Id awareness) keeps working unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 17:15:54 +00:00
Markus Fritsche b81b021b5b v0.5.4: ship examples/lmcp.service template
Companion to lmcp-hub.service. Gives a copy-and-edit starting point for
per-host lmcp instances (foo-tools style). Handles the Arch-vs-Debian
/usr/bin/lua vs /usr/bin/lua5.4 split via a comment pointing users to
override ExecStart.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 20:12:43 +00:00
Markus Fritsche 17af91a99b v0.5.3: hub hardening — hard ssh timeout, parallel probes, sticky DOWN cache
Three fixes addressing the recurring "hub wedges on offline backends" class
of failures (2 incidents in 24h, root-caused to single-threaded Lua + an
uninterruptible os.execute ssh call):

1. Hard wall-clock cap on ssh fallback via GNU `timeout --kill-after=2 30`.
   ConnectTimeout alone only bounds TCP connect; a half-dead sshd (auth
   stall, remote bash-s hang) used to freeze the whole event loop
   indefinitely. Configurable via LMCP_HUB_SSH_HARD_TIMEOUT. Also adds
   ServerAliveInterval=5/Count=2 so an established-but-dead tunnel dies.

2. Parallel lmcp probes for remote_list_hosts. Shells out a single bash
   fan-out of curl -m 3 calls, bounded by PROBE_BUDGET. Wall clock for a
   full 12-backend probe went from ~28 s (sum of per-host ssh connect
   timeouts) to ~3 s.

3. Probe is lmcp-only — ssh is no longer used as health check. The hub
   exists to absorb lots of offline hosts, so an expensive ssh per probe
   was the exact wrong tradeoff. Actual remote_* tool calls still fall
   through to ssh fallback when lmcp is down.

4. Sticky DOWN cache with exponential backoff: 60 → 120 → 240 → 480 →
   900 s. Prevents a sleeping fleet from burning probe budget on every
   health check. UP hosts still use 30 s TTL. Tunable via
   LMCP_HUB_PROBE_TTL_{UP,DOWN_MIN,DOWN_MAX}.

5. Per-request logging to stderr (tool, host, via, elapsed) — invisible
   before, now captured in journal for the next hang's RCA.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 11:58:44 +00:00
Markus Fritsche b29a2716d1 v0.5.2: shell_bg / remote_shell_bg — background launch tools
server.lua gains a shell_bg tool that launches a detached command via
setsid + nohup + stdio-redirect + &, returns immediately with PID and
log path. Linux-only for MVP (Windows Start-Process equivalent TBD).

hub.lua gains remote_shell_bg, forwarding to backend shell_bg. lmcp-only,
no ssh fallback — fallback for fire-and-forget is semantically murky.

Addresses the 'how do I launch a daemon over lmcp without the sentinel-
file wrapper blocking forever' question. Existing remote_shell keeps
its current synchronous-with-timeout behaviour.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 09:34:24 +00:00
Markus Fritsche 555beb9fd9 v0.5.1: search_files uses find -L for macOS symlink start paths
BSD find on macOS silently emits nothing when the starting path is
itself a symlink (no trailing slash, no -L). On riemann with Homebrew,
/usr/local/share/lua is a symlink to /usr/local/Cellar/luarocks/.../share/lua
which tripped this — search_files returned empty for clearly-matching
patterns. GNU find on Linux follows the starting arg by default, so the
bug was invisible on every other host.

Add -L explicitly. Both BSD and GNU find accept it, both detect cycles,
and behavior becomes consistent.

Fixes marfrit-tracker task #16 (opened 2026-04-18 while stress-testing
riemann-tools MCP).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 12:48:05 +00:00
Markus Fritsche 490e688cc1 v0.5.0: add hub — fleet-wide MCP broker
One lmcp server on a central host (typically hertz) that proxies
remote_* tools to every backend in a registry, with a clean SSH
fallback for hosts whose lmcp is temporarily down or not installed.

Tools: remote_list_hosts, remote_{shell,read_file,write_file,edit_file,
list_dir,search_files}. Each takes a `host` argument naming the target
in /opt/herding/etc/hub-backends.conf (or $LMCP_HUB_BACKENDS).

Lazy 30s health cache; `remote_list_hosts force=true` bypasses it.
Bearer auth on inbound (standard lmcp opts.conf / LMCP_TOKEN machinery);
backend Bearer tokens kept in the registry and forwarded per-call.

SSH fallback uses `ssh host 'bash -s' < local_script` — stdin-piped
script body is the canonical shell-escape-free technique. Covers
shell/read_file/write_file/list_dir/search_files. edit_file is lmcp-only
because the literal-match + uniqueness check is nontrivial to replicate
safely in shell.

Ships an example systemd unit and a commented backends.conf template
in examples/. No migration required for existing lmcp deployments —
hub.lua is additive alongside the existing server.lua.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 12:29:13 +00:00
Markus Fritsche c5884d6a97 scripts/lmcp-install-macos.sh: fix for real-world Homebrew
Original draft assumed `brew install lua luasocket` works. It doesn't:
luasocket isn't a brew formula (install via luarocks), and default `lua`
is 5.5 while the rest of the fleet is on 5.4. Fix tested on riemann
(Intel Mac, macOS 14.8.3):

- Pin to lua@5.4 (keg-only brew formula) — matches fleet library paths.
- Install luasocket via luarocks into the user-local rocks tree.
- Source brew shellenv ourselves so non-login bash shells can find brew.
- Bake LUA_PATH / LUA_CPATH into the LaunchAgent plist so the service
  resolves `require 'socket'` from ~/.luarocks/.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 12:37:05 +00:00
Markus Fritsche 2f2c1f3036 Add scripts/lmcp-install-macos.sh + LMCP_TOKEN env fallback
lmcp.lua: if opts.auth_token and opts.conf are both unset, fall back to
the LMCP_TOKEN environment variable. Empty string treated as unset.
This is the primitive launchd/systemd drop-ins need — no conf file
bookkeeping on hosts that don't already use one.

scripts/lmcp-install-macos.sh: macOS installer via Homebrew. Drops the
Lua library files into $(brew --prefix)/share/lua/5.4/, mints (or
reuses) a Bearer token stored at $(brew --prefix)/etc/lmcp/token,
installs a ~/Library/LaunchAgents/ plist with LMCP_TOKEN baked in,
launchctl-loads it, and smoke-tests. Prints the Claude Code ~/.claude.json
snippet at the end.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 10:45:54 +00:00
23 changed files with 4721 additions and 189 deletions
+13
View File
@@ -0,0 +1,13 @@
# Generated by windows/sync.sh — see windows/README.md
windows/pkg/lmcp.lua
windows/pkg/server.lua
windows/pkg/json.lua
# Bundled Lua + LuaSocket runtime for the Windows MSI; downloaded
# separately, not in git.
windows/pkg/lua/
# Editor / OS noise
*.swp
*.swo
.DS_Store
+111 -5
View File
@@ -11,6 +11,10 @@ local server = lmcp.new("example-tools", {
port = tonumber(arg[1]) or 8080,
})
-- The optional 5th `opts` arg to server:tool carries MCP annotations.
-- Omit it and clients assume the worst (destructive, openWorld) — fine
-- for prototypes; declare annotations once you know each tool's stance.
server:tool("shell", "Execute a shell command", {
type = "object",
properties = {
@@ -24,7 +28,15 @@ server:tool("shell", "Execute a shell command", {
local result = handle:read('*a')
handle:close()
return result ~= '' and result or '(no output)'
end)
end, {
annotations = {
title = "Run shell",
readOnlyHint = false,
destructiveHint = true,
idempotentHint = false,
openWorldHint = true,
},
})
server:tool("read_file", "Read a file", {
type = "object",
@@ -38,7 +50,15 @@ server:tool("read_file", "Read a file", {
local content = f:read('*a')
f:close()
return content
end)
end, {
annotations = {
title = "Read file",
readOnlyHint = true,
destructiveHint = false,
idempotentHint = true,
openWorldHint = false,
},
})
server:tool("write_file", "Write content to a file", {
type = "object",
@@ -53,7 +73,15 @@ server:tool("write_file", "Write content to a file", {
f:write(args.content)
f:close()
return string.format("Written %d bytes to %s", #args.content, args.path)
end)
end, {
annotations = {
title = "Write file",
readOnlyHint = false,
destructiveHint = true,
idempotentHint = true,
openWorldHint = false,
},
})
server:tool("list_dir", "List directory contents", {
type = "object",
@@ -67,7 +95,85 @@ server:tool("list_dir", "List directory contents", {
local result = handle:read('*a')
handle:close()
return result
end, {
annotations = {
title = "List directory",
readOnlyHint = true,
destructiveHint = false,
idempotentHint = true,
openWorldHint = false,
},
})
-- ---- Resources (MCP primitive — see issue #5) ----
-- Tools-only servers force the client to spend a tools/call round-trip
-- for every read. Resources let the client list and read by URI, with a
-- stable identity it can cache and reference in prompts.
server:resource("text://greeting", {
name = "Greeting",
mimeType = "text/plain",
}, function() return "Hello from lmcp!" end)
-- Tiny binary resource: 8-byte PNG signature, demonstrates blob handling.
server:resource("data://lmcp.png", {
name = "PNG signature",
mimeType = "image/png",
}, function()
return { blob_bytes = "\x89PNG\r\n\x1a\n", mimeType = "image/png" }
end)
io.stderr:write("Starting lmcp example server...\n")
server:run()
-- Template: any local file. `args.path` is captured greedily (no leading
-- slash because the template literal already includes ///).
server:resource_template("file:///{path}", {
name = "Local file",
mimeType = "text/plain",
}, function(args)
local f = io.open("/" .. args.path, "r")
if not f then error("file not found: /" .. args.path) end
local content = f:read("*a"); f:close()
return content
end)
-- ---- Prompts (MCP primitive — see issue #6) ----
-- Parameterised prompt templates the client surfaces as a menu
-- (slash-commands, snippets). Handler returns either a plain string (one
-- user-role text message) or a full { description?, messages = {...} }
-- shape for finer control.
server:prompt("release_note", {
description = "Draft a release note for a given version",
arguments = {
{ name = "version", description = "Tag, e.g. v0.7.1", required = true },
{ name = "since", description = "Previous tag", required = false },
},
}, function(args)
return "Write concise release notes for version " .. (args.version or "?")
.. " since " .. (args.since or "the previous tag")
.. ". Group by category (features / fixes / docs)."
end)
-- Completion for the release_note prompt's `version` argument. Returned
-- list is filtered against `value` (prefix match) by the server's spec
-- contract is "candidates"; clients may further filter.
server:complete("ref/prompt", "release_note", "version", function(value, ctx)
local all = { "v0.5.0", "v0.5.1", "v0.5.2", "v0.5.3", "v0.5.4",
"v0.6.0", "v0.7.0", "v0.7.1", "v1.0.0-rc1" }
if value == "" then return all end
local out = {}
for _, v in ipairs(all) do
if v:sub(1, #value) == value then out[#out + 1] = v end
end
return out
end)
local transport = os.getenv("LMCP_TRANSPORT") or "http"
if transport == "stdio" then
if os.getenv("LMCP_PORT") then
io.stderr:write("lmcp: LMCP_PORT ignored in stdio mode\n")
end
server:run_stdio()
else
io.stderr:write("Starting lmcp example server...\n")
server:run()
end
+22
View File
@@ -0,0 +1,22 @@
# lmcp hub backend registry.
#
# Format: whitespace-separated "name ssh_host lmcp_url token"
# Use "-" for not-applicable fields.
# - Missing ssh_host (col 2 = -): no ssh fallback available for this backend
# - Missing lmcp_url (col 3 = -): this backend is ssh-only
# - Missing token (col 4 = -): backend accepts unauth lmcp (LAN-only hosts)
#
# Lines starting with # are comments. Blank lines ignored.
#
# LXD-container caveat: if your hub lives on the LXD host and the backend is
# a sibling LXD container, Fritz DNS often caches a stale DHCP lease for the
# container's hostname. Hardcode the container IP here and update when it
# rotates, or wire the .lxd stub zone into systemd-resolved.
# name ssh_host lmcp_url token
# --- --- --- ---
# boltzmann boltzmann.fritz.box http://boltzmann.fritz.box:8080/mcp <64hex>
# tesla 192.168.88.67 http://192.168.88.67:8080/mcp -
# nc nc.reauktion.de http://nc.reauktion.de:8080/mcp <opaque>
# pve1 pve1.fritz.box http://pve1.fritz.box:8080/mcp <opaque>
# hertz - http://hertz.fritz.box:8080/mcp <opaque>
+25
View File
@@ -0,0 +1,25 @@
[Unit]
Description=lmcp hub — fleet MCP broker
After=network.target
Wants=network.target
[Service]
Type=simple
User=mfritsche
Group=mfritsche
# When deploying, copy hub.lua to /opt/lmcp/ or adjust the path below.
ExecStart=/usr/bin/lua5.4 /usr/share/lua/5.4/hub.lua
Environment=LMCP_NAME=hub-tools
Environment=LMCP_PORT=8090
# Backend registry: space-separated "name ssh_host lmcp_url token" per line.
# See hub-backends.conf.example in this examples/ dir.
Environment=LMCP_HUB_BACKENDS=/opt/herding/etc/hub-backends.conf
# Bearer token file (key `.godparticle=<hex>`).
Environment=LMCP_HUB_CONF=/opt/herding/etc/lmcp-hub.conf
Restart=on-failure
RestartSec=5
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
+22
View File
@@ -0,0 +1,22 @@
[Unit]
Description=lmcp MCP Server
After=network.target
[Service]
Type=simple
User=root
# Arch ships the Lua 5.4 binary as /usr/bin/lua; Debian ships /usr/bin/lua5.4.
# Override ExecStart if your distro differs.
ExecStart=/usr/bin/lua /usr/share/lua/5.4/server.lua
# Distinct name per host: foo-tools appears in /mcp listings and logs.
Environment=LMCP_NAME=CHANGEME-tools
Environment=LMCP_PORT=8080
# Bearer token. Generate with: openssl rand -hex 24
# For untrusted networks, bind to LAN-only via firewall; the server itself
# listens on 0.0.0.0 by default.
Environment=LMCP_TOKEN=CHANGEME
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
+29
View File
@@ -0,0 +1,29 @@
import urllib.request, json, threading, queue, sys
BASE="http://192.168.88.184:8080"
q=queue.Queue()
def sse():
try:
r=urllib.request.urlopen(BASE+"/sse", timeout=30)
for raw in r:
s=raw.decode(errors="replace").strip()
if s.startswith("data:"): q.put(s[5:].strip())
except Exception as e: q.put("ERR:"+str(e))
threading.Thread(target=sse,daemon=True).start()
try:
ep=q.get(timeout=10)
if ep.startswith("ERR:"): print("stash unreachable:",ep); sys.exit(1)
purl=BASE+ep if ep.startswith("/") else ep
def post(o):
urllib.request.urlopen(urllib.request.Request(purl,data=json.dumps(o).encode(),headers={"Content-Type":"application/json"}),timeout=15).read()
post({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"apropos","version":"1"}}})
q.get(timeout=10)
post({"jsonrpc":"2.0","method":"notifications/initialized"})
query=sys.argv[1] if len(sys.argv)>1 else ""
limit=int(sys.argv[2]) if len(sys.argv)>2 else 3
post({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"recall","arguments":{"query":query,"limit":limit}}})
d=json.loads(q.get(timeout=25))
txt=d.get("result",{}).get("content",[{}])[0].get("text","[]")
facts=json.loads(txt)
if not facts: print("(no memory found for: %s)"%query); sys.exit(0)
for f in facts: print("- %s (score %.2f)" % (f.get("content","").strip(), f.get("score",0)))
except Exception as e: print("recall error:",e); sys.exit(1)
+721
View File
@@ -0,0 +1,721 @@
#!/usr/bin/env lua
-- lmcp hub — fleet-wide MCP broker.
--
-- One MCP endpoint that fans out to every lmcp-backed host, with an SSH
-- fallback for hosts whose lmcp is temporarily down (or not installed).
-- Exposes a small set of "remote_*" tools that all take a `host` arg
-- naming the target in the backend registry.
--
-- Registry file (default /opt/herding/etc/hub-backends.conf):
-- # name ssh_host lmcp_url token
-- boltzmann boltzmann.fritz.box http://boltzmann.fritz.box:8080/mcp <bearer>
-- tesla tesla http://tesla.fritz.box:8080/mcp -
-- broglie - http://broglie.fritz.box:8080/mcp -
-- Use `-` for "not applicable". Lines starting with # are comments.
-- Missing `ssh_host`: no ssh fallback available. Missing `lmcp_url`: ssh-only.
--
-- SPDX-License-Identifier: MIT
local dir = arg[0]:match('(.*/)') or './'
package.path = package.path .. ';' .. dir .. '?.lua'
local lmcp = require('lmcp')
local json = require('json')
local socket = require('socket')
-- ---- Backend registry ---------------------------------------------------
local CONF_PATH = os.getenv("LMCP_HUB_BACKENDS") or "/opt/herding/etc/hub-backends.conf"
local PROBE_TTL_UP = tonumber(os.getenv("LMCP_HUB_PROBE_TTL_UP") or "30")
local PROBE_TTL_DOWN_MIN = tonumber(os.getenv("LMCP_HUB_PROBE_TTL_DOWN_MIN") or "60")
local PROBE_TTL_DOWN_MAX = tonumber(os.getenv("LMCP_HUB_PROBE_TTL_DOWN_MAX") or "900")
local PROBE_BUDGET = tonumber(os.getenv("LMCP_HUB_PROBE_BUDGET") or "3")
-- TCP port that answers "is this host there" for ssh-only backends.
local SSH_PROBE_PORT = os.getenv("LMCP_HUB_SSH_PORT") or "22"
local LMCP_TIMEOUT = tonumber(os.getenv("LMCP_HUB_LMCP_TIMEOUT") or "6")
local SSH_TIMEOUT = tonumber(os.getenv("LMCP_HUB_SSH_TIMEOUT") or "10")
local SSH_HARD_TIMEOUT = tonumber(os.getenv("LMCP_HUB_SSH_HARD_TIMEOUT") or "30")
local LOG_REQUESTS = (os.getenv("LMCP_HUB_LOG") or "1") ~= "0"
local function logreq(fmt, ...)
if not LOG_REQUESTS then return end
io.stderr:write(string.format("[hub %s] " .. fmt .. "\n",
os.date("%H:%M:%S"), ...))
io.stderr:flush()
end
local function monotonic()
local ok, s = pcall(socket.gettime)
return ok and s or os.time()
end
local backends = {} -- name -> { name, ssh_host, lmcp_url, token }
local status = {} -- name -> { up=bool, via="lmcp"|"ssh"|nil, checked=t, err=... }
local function load_registry()
local f = io.open(CONF_PATH, "r")
if not f then
io.stderr:write("hub: no backend registry at " .. CONF_PATH .. "\n")
return
end
backends = {}
for line in f:lines() do
line = line:gsub("^%s+", ""):gsub("%s+$", "")
if line ~= "" and not line:match("^#") then
local parts = {}
for p in line:gmatch("%S+") do parts[#parts+1] = p end
if #parts >= 2 then
local name = parts[1]
local ssh_host = (parts[2] ~= "-" and parts[2]) or nil
local lmcp_url = (parts[3] ~= "-" and parts[3]) or nil
local token = (parts[4] ~= "-" and parts[4]) or nil
backends[name] = {
name = name,
ssh_host = ssh_host,
lmcp_url = lmcp_url,
token = token,
}
end
end
end
f:close()
end
-- ---- Outbound HTTP client (plain, no TLS) ------------------------------
local function parse_url(url)
local scheme, host, port, path = url:match("^(%w+)://([^:/]+):?(%d*)(/?.*)$")
if not scheme then return nil, "bad url" end
port = tonumber(port) or (scheme == "https" and 443 or 80)
if path == "" then path = "/" end
return { scheme = scheme, host = host, port = port, path = path }
end
local function http_post_json(url, body, token, timeout)
local u, err = parse_url(url)
if not u then return nil, err end
if u.scheme ~= "http" then return nil, "hub only speaks http to backends" end
local sock = socket.tcp()
sock:settimeout(timeout or 6)
local ok, e = sock:connect(u.host, u.port)
if not ok then sock:close(); return nil, "connect: " .. e end
local headers = {
"POST " .. u.path .. " HTTP/1.1",
"Host: " .. u.host .. ":" .. u.port,
"Content-Type: application/json",
"Content-Length: " .. tostring(#body),
"Connection: close",
}
if token then
headers[#headers+1] = "Authorization: Bearer " .. token
end
local req = table.concat(headers, "\r\n") .. "\r\n\r\n" .. body
local _, se = sock:send(req)
if se then sock:close(); return nil, "send: " .. se end
local chunks = {}
while true do
local data, rerr, partial = sock:receive(4096)
if data then chunks[#chunks+1] = data
elseif partial and #partial > 0 then chunks[#chunks+1] = partial
end
if not data then
if rerr == "timeout" then sock:close(); return nil, "timeout" end
break
end
end
sock:close()
local resp = table.concat(chunks)
local hend = resp:find("\r\n\r\n", 1, true)
if not hend then return nil, "no body separator" end
local status_line = resp:sub(1, resp:find("\r\n", 1, true) - 1)
local status_code = tonumber(status_line:match("HTTP/[%d%.]+%s+(%d+)"))
local body_str = resp:sub(hend + 4)
if status_code ~= 200 then
return nil, "http " .. tostring(status_code) .. ": " .. body_str:sub(1, 200)
end
local ok2, parsed = pcall(json.decode, body_str)
if not ok2 then return nil, "bad json: " .. body_str:sub(1, 200) end
return parsed
end
local function jsonrpc_call(url, token, method, params)
local body = json.encode({
jsonrpc = "2.0",
id = os.time() * 1000 + math.random(1000, 9999),
method = method,
params = params or {},
})
local resp, err = http_post_json(url, body, token, LMCP_TIMEOUT)
if not resp then return nil, err end
if resp.error then
return nil, "rpc: " .. (resp.error.message or "unknown")
end
return resp.result
end
-- ---- SSH exec (shell-escape-free via bash -s on stdin) -----------------
local function shell_quote(s)
-- Single-quote wrap, replace embedded single quotes with '\''
return "'" .. tostring(s):gsub("'", "'\\''") .. "'"
end
local function tmpwrite(content)
local path = os.tmpname()
local f = io.open(path, "w")
if not f then return nil, "tmpfile create failed" end
f:write(content)
f:close()
return path
end
local function ssh_run_script(ssh_host, script)
-- Write the script body locally, then ssh with stdin redirected from it.
-- bash -s reads the script from stdin. Nothing inside `script` is subject
-- to another shell round of expansion — this is the escape-free path.
local spath, perr = tmpwrite(script)
if not spath then return nil, perr, -1 end
local outpath = spath .. ".out"
-- Hard-cap wall time with GNU `timeout` — ssh's ConnectTimeout only
-- bounds TCP connect, not the session. Without this, a half-dead sshd
-- (auth stall, remote bash-s hang) locks the hub event loop indefinitely.
local cmd = string.format(
"timeout --kill-after=2 %d ssh -o ConnectTimeout=%d -o ServerAliveInterval=5 -o ServerAliveCountMax=2 -o BatchMode=yes -o StrictHostKeyChecking=accept-new %s 'bash -s' < %s > %s 2>&1; echo $? > %s.rc",
SSH_HARD_TIMEOUT, SSH_TIMEOUT, shell_quote(ssh_host), shell_quote(spath),
shell_quote(outpath), shell_quote(spath)
)
local t0 = monotonic()
os.execute(cmd)
local dt = monotonic() - t0
local rc_f = io.open(spath .. ".rc", "r")
local rc = -1
if rc_f then
local s = rc_f:read("*a") or ""
s = s:match("^(%S+)") or ""
rc = tonumber(s) or -1
rc_f:close()
end
local out_f = io.open(outpath, "r")
local output = out_f and out_f:read("*a") or ""
if out_f then out_f:close() end
os.remove(spath); os.remove(outpath); os.remove(spath .. ".rc")
-- timeout(1) exits 124 on wall-clock expiry, 137 on SIGKILL. Surface it.
if rc == 124 or rc == 137 then
logreq("ssh HARD-TIMEOUT host=%s after=%.2fs rc=%d", ssh_host, dt, rc)
return nil, string.format("ssh hard-timeout after %ds", SSH_HARD_TIMEOUT), rc
end
logreq("ssh host=%s elapsed=%.2fs rc=%d bytes=%d", ssh_host, dt, rc, #output)
return output, nil, rc
end
-- ---- Health probe ------------------------------------------------------
--
-- Design notes:
-- - Probe is lmcp-only. SSH is NOT checked here: it's expensive (3-6s per
-- offline host) and the hub exists specifically to absorb lots of
-- offline hosts. Hosts with lmcp down but ssh up show as DOWN in the
-- health list, but actual remote_* calls still fall through to ssh
-- fallback correctly.
-- - Sticky DOWN cache with exponential backoff: a DOWN host is re-probed
-- at intervals that grow from PROBE_TTL_DOWN_MIN (default 60s) up to
-- PROBE_TTL_DOWN_MAX (default 900s). Prevents a sleeping fleet from
-- burning probe budget every health check.
-- - `remote_list_hosts` uses a parallel curl fan-out for all hosts at
-- once so wall-clock is bounded by PROBE_BUDGET (default 3s), not the
-- sum of per-host timeouts.
local function cache_fresh(s, now)
if not s then return false end
local ttl
if s.up then
ttl = PROBE_TTL_UP
else
ttl = math.min(PROBE_TTL_DOWN_MAX, PROBE_TTL_DOWN_MIN * (2 ^ (s.down_streak or 0)))
end
return (now - s.checked) < ttl
end
local function apply_probe_result(name, up, err, via, tool_count)
local prev = status[name]
local new_s = {
checked = os.time(),
up = up,
via = up and (via or "lmcp") or nil,
err = err,
tool_count = tool_count,
down_streak = up and 0 or ((prev and prev.down_streak or 0) + 1),
}
status[name] = new_s
return new_s
end
-- Fallback single-host probe used only when a caller explicitly needs a
-- status refresh outside the parallel path (currently only
-- remote_list_hosts when a single host is looked up). lmcp-only.
local function probe(name, force)
local b = backends[name]
if not b then return { up = false, err = "unknown host" } end
local s = status[name]
if not force and cache_fresh(s, os.time()) then return s end
if not b.lmcp_url then
return apply_probe_result(name, false, "no lmcp url", nil, nil)
end
local result, err = jsonrpc_call(b.lmcp_url, b.token, "tools/list", {})
if result and result.tools then
return apply_probe_result(name, true, nil, "lmcp", #result.tools)
end
return apply_probe_result(name, false, "lmcp: " .. tostring(err), nil, nil)
end
-- Parallel lmcp probe for every backend with an lmcp_url, via a single
-- bash fan-out of curl calls. Total wall clock ≈ PROBE_BUDGET.
local function probe_all_parallel(force)
local now = os.time()
local need, need_ssh = {}, {}
for name, b in pairs(backends) do
if force or not cache_fresh(status[name], now) then
if b.lmcp_url then
need[#need+1] = b
elseif b.ssh_host then
-- ssh-only: no lmcp endpoint to ask, but "is the box there" is still
-- answerable cheaply. See the SSH probe note below.
need_ssh[#need_ssh+1] = b
end
end
end
if #need == 0 and #need_ssh == 0 then return end
local script_parts = {}
for _, b in ipairs(need) do
local auth = b.token and (" -H 'Authorization: Bearer " .. b.token .. "'") or ""
local url = b.lmcp_url:gsub("'", "'\\''")
script_parts[#script_parts+1] = string.format(
"(curl --max-time %d -s -o /dev/null -w '%s %%{http_code} %%{time_total}\\n' -X POST%s -H 'Content-Type: application/json' -d '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\",\"params\":{}}' '%s' || echo '%s ERR 0') &",
PROBE_BUDGET, b.name, auth, url, b.name
)
end
-- SSH probe. The design note above rejects checking ssh because a session costs
-- 3-6s per offline host — true for a SESSION. A bare TCP connect to 22 answers the
-- only question a host card asks ("is it there") with no handshake and no auth:
-- measured on this host, a dead target costs 1.05s and a live one milliseconds, and
-- it rides the same parallel fan-out, so wall clock stays one budget window.
-- Without nc we report nothing rather than guessing DOWN — a wrong claim is worse
-- than the "no probe result" the dashboard already renders as unknown.
for _, b in ipairs(need_ssh) do
local host = b.ssh_host:gsub("'", "'\\''")
script_parts[#script_parts+1] = string.format(
"(if command -v nc >/dev/null 2>&1; then " ..
"nc -z -w%d '%s' %s >/dev/null 2>&1 && echo '%s SSHUP 0' || echo '%s SSHDOWN 0'; " ..
"else echo '%s SSHSKIP 0'; fi) &",
PROBE_BUDGET, host, SSH_PROBE_PORT, b.name, b.name, b.name)
end
script_parts[#script_parts+1] = "wait"
local t0 = monotonic()
local p = io.popen(table.concat(script_parts, "\n"))
local out = p and p:read("*a") or ""
if p then p:close() end
local dt = monotonic() - t0
local seen = {}
for line in out:gmatch("[^\n]+") do
local name, code, t = line:match("^(%S+)%s+(%S+)%s+([%d%.]+)")
if name then
seen[name] = true
if code == "SSHUP" then
apply_probe_result(name, true, nil, "ssh", nil)
elseif code == "SSHDOWN" then
apply_probe_result(name, false, "ssh port unreachable", nil, nil)
elseif code == "SSHSKIP" then
-- nc missing: leave it unprobed rather than assert a state.
seen[name] = nil
elseif code == "200" then
apply_probe_result(name, true, nil, "lmcp", nil)
else
apply_probe_result(name, false, "lmcp code=" .. code, nil, nil)
end
end
end
-- Hosts with no output (fan-out error): mark DOWN
for _, b in ipairs(need) do
if not seen[b.name] then
apply_probe_result(b.name, false, "probe fan-out missing", nil, nil)
end
end
logreq("probe_all_parallel lmcp=%d ssh=%d elapsed=%.2fs", #need, #need_ssh, dt)
end
-- ---- Call-tool dispatcher ----------------------------------------------
-- `allow_ssh`: whether the tool has an SSH fallback path
-- `ssh_impl`: function(backend, args) -> output string, or nil + error
local function call_remote(tool, args, allow_ssh, ssh_impl)
local t_start = monotonic()
local host = args.host
if type(host) ~= "string" or host == "" then
logreq("tool=%s ERR missing-host", tool)
return "Error: missing `host` parameter"
end
local b = backends[host]
if not b then
logreq("tool=%s host=%s ERR unknown-host", tool, host)
return string.format("Error: unknown host %q (registry: %s)", host, CONF_PATH)
end
local errs = {}
local via = nil
-- Try lmcp first
if b.lmcp_url then
local args_pass = {}
for k, v in pairs(args) do if k ~= "host" then args_pass[k] = v end end
local result, err = jsonrpc_call(b.lmcp_url, b.token, "tools/call",
{ name = tool, arguments = args_pass })
if result then
via = "lmcp"
logreq("tool=%s host=%s via=lmcp elapsed=%.2fs", tool, host, monotonic() - t_start)
-- Propagate backend's content, extract first text block
if type(result.content) == "table" and result.content[1] and result.content[1].text then
local prefix = result.isError and "[lmcp isError] " or ""
return prefix .. result.content[1].text
end
return json.encode(result)
end
errs[#errs+1] = "lmcp: " .. tostring(err)
else
errs[#errs+1] = "lmcp: no url configured"
end
-- Fallback to ssh
if allow_ssh and ssh_impl and b.ssh_host then
local out, serr = ssh_impl(b, args)
if out ~= nil then
logreq("tool=%s host=%s via=ssh elapsed=%.2fs", tool, host, monotonic() - t_start)
return "[via ssh fallback]\n" .. out
end
errs[#errs+1] = "ssh: " .. tostring(serr)
elseif allow_ssh and not b.ssh_host then
errs[#errs+1] = "ssh: no host configured"
end
logreq("tool=%s host=%s FAIL elapsed=%.2fs err=%s", tool, host, monotonic() - t_start, table.concat(errs, " | "):sub(1, 200))
return "Error: " .. table.concat(errs, " | ")
end
-- ---- SSH implementations for each fallback-capable tool ----------------
local function ssh_shell(b, a)
if type(a.command) ~= "string" then return nil, "command required" end
local cwd_prefix = ""
if a.cwd and a.cwd ~= "" then
cwd_prefix = "cd " .. shell_quote(a.cwd) .. " && "
end
local script = cwd_prefix .. a.command .. "\n"
local out, err, rc = ssh_run_script(b.ssh_host, script)
if err then return nil, err end
-- ssh exits 255 when it couldn't connect/authenticate. Treat that as
-- fallback-failed so the caller sees the combined lmcp+ssh errors.
if rc == 255 then
local line1 = (out:match("^([^\n]+)") or ""):gsub("%s+$", "")
return nil, "ssh connect failed: " .. line1
end
return string.format("[rc=%d]\n%s", rc, out)
end
local function ssh_read_file(b, a)
if type(a.path) ~= "string" then return nil, "path required" end
local script = "cat -- " .. shell_quote(a.path) .. "\n"
local out, err, rc = ssh_run_script(b.ssh_host, script)
if err then return nil, err end
if rc ~= 0 then return nil, "cat exit " .. rc .. ": " .. out:sub(1, 200) end
return out
end
local function ssh_write_file(b, a)
if type(a.path) ~= "string" or type(a.content) ~= "string" then
return nil, "path and content required"
end
-- Emit a script that decodes content from base64, so no shell
-- interpretation of the payload is possible. Lua stdlib has no base64;
-- implement a minimal encoder inline.
local b64_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
local function b64enc(data)
local out = {}
local pad = (3 - (#data % 3)) % 3
local padded = data .. ("\0"):rep(pad)
for i = 1, #padded, 3 do
local a1, a2, a3 = padded:byte(i), padded:byte(i+1), padded:byte(i+2)
local n = a1 * 65536 + a2 * 256 + a3
out[#out+1] = b64_alphabet:sub(((n >> 18) & 63) + 1, ((n >> 18) & 63) + 1)
out[#out+1] = b64_alphabet:sub(((n >> 12) & 63) + 1, ((n >> 12) & 63) + 1)
out[#out+1] = b64_alphabet:sub(((n >> 6) & 63) + 1, ((n >> 6) & 63) + 1)
out[#out+1] = b64_alphabet:sub(((n ) & 63) + 1, ((n ) & 63) + 1)
end
local s = table.concat(out)
if pad > 0 then s = s:sub(1, -pad - 1) .. ("="):rep(pad) end
return s
end
local payload = b64enc(a.content)
local script = string.format(
"base64 -d > %s <<'EOF_B64_PAYLOAD'\n%s\nEOF_B64_PAYLOAD\n",
shell_quote(a.path), payload
)
local out, err, rc = ssh_run_script(b.ssh_host, script)
if err then return nil, err end
if rc ~= 0 then return nil, "write exit " .. rc .. ": " .. out:sub(1, 200) end
return string.format("Written %d bytes to %s (via ssh)", #a.content, a.path)
end
local function ssh_list_dir(b, a)
local path = (a and type(a.path) == "string" and a.path) or "."
local script = "ls -1 -- " .. shell_quote(path) .. "\n"
local out, err, rc = ssh_run_script(b.ssh_host, script)
if err then return nil, err end
if rc ~= 0 then return nil, "ls exit " .. rc .. ": " .. out:sub(1, 200) end
return out
end
local function ssh_search_files(b, a)
if type(a.pattern) ~= "string" then return nil, "pattern required" end
local path = (a.path and a.path ~= "") and a.path or "/"
local script = string.format(
"find %s -name %s 2>/dev/null | head -200\n",
shell_quote(path), shell_quote(a.pattern)
)
local out, err, rc = ssh_run_script(b.ssh_host, script)
if err then return nil, err end
return out
end
-- ---- Server setup ------------------------------------------------------
load_registry()
math.randomseed(os.time())
local server = lmcp.new(os.getenv("LMCP_NAME") or "hub-tools", {
port = tonumber(os.getenv("LMCP_PORT") or arg[1]) or 8090,
version = "0.5.4",
conf = os.getenv("LMCP_HUB_CONF") or "/opt/herding/etc/lmcp-hub.conf",
})
local HOST_ARG = {
type = "string",
description = "Name of the backend host (see remote_list_hosts)",
}
server:tool("remote_list_hosts",
"List all registered fleet hosts and their live status (lmcp vs ssh vs down).",
{ type = "object", properties = {
force = { type = "boolean", description = "Force re-probe (bypass cache)", default = false },
} },
function(a)
local force = a and a.force or false
probe_all_parallel(force)
local lines = {}
local names = {}
for n in pairs(backends) do names[#names+1] = n end
table.sort(names)
for _, n in ipairs(names) do
local b = backends[n]
local s = status[n] or { up = false, err = "no probe result" }
local paths = {}
if b.lmcp_url then paths[#paths+1] = "lmcp" end
if b.ssh_host then paths[#paths+1] = "ssh" end
lines[#lines+1] = string.format(
"%-14s %-6s via=%-4s paths=%s %s",
n,
s.up and "UP" or "DOWN",
tostring(s.via or "-"),
table.concat(paths, ","),
s.err and ("[" .. s.err .. "]") or ""
)
end
return table.concat(lines, "\n")
end,
{ annotations = {
title = "List fleet hosts",
readOnlyHint = true,
destructiveHint = false,
idempotentHint = true,
openWorldHint = true,
} }
)
server:tool("remote_shell", "Run a shell command on a fleet host. lmcp-primary with ssh fallback.",
{ type = "object", properties = {
host = HOST_ARG,
command = { type = "string", description = "Shell command" },
cwd = { type = "string", description = "Working directory" },
timeout = { type = "integer", description = "Timeout (seconds)", default = 120 },
}, required = { "host", "command" } },
function(a) return call_remote("shell", a, true, ssh_shell) end,
{ annotations = {
title = "Remote shell",
readOnlyHint = false,
destructiveHint = true,
idempotentHint = false,
openWorldHint = true,
} }
)
server:tool("remote_read_file", "Read a file from a fleet host.",
{ type = "object", properties = {
host = HOST_ARG,
path = { type = "string", description = "File path" },
}, required = { "host", "path" } },
function(a) return call_remote("read_file", a, true, ssh_read_file) end,
{ annotations = {
title = "Remote read file",
readOnlyHint = true,
destructiveHint = false,
idempotentHint = true,
openWorldHint = true,
} }
)
server:tool("remote_write_file", "Write content to a file on a fleet host.",
{ type = "object", properties = {
host = HOST_ARG,
path = { type = "string" },
content = { type = "string" },
}, required = { "host", "path", "content" } },
function(a) return call_remote("write_file", a, true, ssh_write_file) end,
{ annotations = {
title = "Remote write file",
readOnlyHint = false,
destructiveHint = true,
idempotentHint = true,
openWorldHint = true,
} }
)
server:tool("remote_edit_file",
"Literal-match edit on a fleet host. **Requires backend lmcp up** — no ssh fallback.",
{ type = "object", properties = {
host = HOST_ARG,
path = { type = "string" },
old_string = { type = "string" },
new_string = { type = "string" },
replace_all = { type = "boolean", default = false },
}, required = { "host", "path", "old_string", "new_string" } },
function(a) return call_remote("edit_file", a, false, nil) end,
{ annotations = {
title = "Remote edit file",
readOnlyHint = false,
destructiveHint = true,
idempotentHint = false,
openWorldHint = true,
} }
)
server:tool("remote_shell_bg",
"Launch a detached background command on a fleet host (Linux). Returns PID + log path immediately. Requires backend lmcp v0.5.2+.",
{ type = "object", properties = {
host = HOST_ARG,
command = { type = "string", description = "Shell command" },
cwd = { type = "string" },
log = { type = "string", description = "Log file path" },
}, required = { "host", "command" } },
function(a) return call_remote("shell_bg", a, false, nil) end,
{ annotations = {
title = "Remote shell (background)",
readOnlyHint = false,
destructiveHint = true,
idempotentHint = false,
openWorldHint = true,
} }
)
server:tool("remote_list_dir", "List directory entries on a fleet host.",
{ type = "object", properties = {
host = HOST_ARG,
path = { type = "string", default = "." },
}, required = { "host" } },
function(a) return call_remote("list_dir", a, true, ssh_list_dir) end,
{ annotations = {
title = "Remote list directory",
readOnlyHint = true,
destructiveHint = false,
idempotentHint = true,
openWorldHint = true,
} }
)
server:tool("remote_search_files", "find-by-pattern on a fleet host.",
{ type = "object", properties = {
host = HOST_ARG,
pattern = { type = "string" },
path = { type = "string", default = "/" },
}, required = { "host", "pattern" } },
function(a) return call_remote("search_files", a, true, ssh_search_files) end,
{ annotations = {
title = "Remote find files",
readOnlyHint = true,
destructiveHint = false,
idempotentHint = true,
openWorldHint = true,
} }
)
-- ---- Fleet-central local tools (migrated from tools.d/hertz.lua, 2026-07-18) ----
-- These run LOCALLY on hertz (where the hub process also lives), so no ssh
-- backend hop. Consolidated here so the hub is the single fleet-management
-- endpoint. Still also served by hertz-tools (:8080) for now — remove there
-- once every client (pi-agents etc.) has a @hub session.
local function run_local(cmd, timeout)
local full = timeout and ("timeout " .. tostring(timeout) .. " " .. cmd) or cmd
local p = io.popen(full .. " 2>&1")
if not p then return "Error: popen failed" end
local out = p:read("*a")
p:close()
return out or ""
end
server:tool("apropos",
"Search shared fleet memory (stash) for facts about the fleet, projects, decisions, and preferences. query = 2-6 words on the topic; limit = max results (default 3). Read-only.",
{ type = "object", properties = {
query = { type = "string", description = "2-6 words describing what to recall" },
limit = { type = "integer", description = "max results, default 3" },
}, required = { "query" } },
function(a)
local q = tostring(a.query or ""):gsub("[^%w%s%-%.]", " "):gsub("%s+", " ")
if q:gsub("%s", "") == "" then return "Error: query required" end
local lim = tonumber(a.limit) or 3
return run_local("python3 /opt/lmcp/helpers/stash_recall.py '" .. q .. "' " .. lim, 30)
end,
{ annotations = {
title = "Apropos (fleet memory)",
readOnlyHint = true,
destructiveHint = false,
idempotentHint = true,
openWorldHint = true,
} }
)
server:tool("wake_fleet",
"Wake a fleet NUC (pve1..pve4) via Fritz!Box Wake-on-LAN. Powers a node ON only; it cannot power anything off. Node boots in ~30-60s.",
{ type = "object", properties = {
node = { type = "string", description = "Node to wake: '1'..'4' or 'pve1'..'pve4'" },
}, required = { "node" } },
function(a)
local node = tostring(a.node or ""):gsub("[^%w]", "")
if not node:match("^p?v?e?[1-4]$") then
return "Error: node must be 1-4 or pve1-pve4 (got: " .. tostring(a.node) .. ")"
end
return run_local("sudo /root/.local/bin/wake-pve " .. node, 15)
end,
{ annotations = {
title = "Wake fleet NUC",
readOnlyHint = false,
destructiveHint = false,
idempotentHint = true,
openWorldHint = true,
} }
)
io.stderr:write(string.format("lmcp-hub starting on port %d with %d backends from %s\n",
server.port, (function() local n = 0; for _ in pairs(backends) do n = n + 1 end; return n end)(), CONF_PATH))
server:run()
+26 -2
View File
@@ -60,6 +60,13 @@ encode_value = function(v)
local t = type(v)
if v == nil or v == json.null then
return 'null'
elseif v == json.empty_object then
-- Sentinel for forcing {} (object) instead of [] (array) when
-- the field semantically requires an object but is empty.
-- Without this, every empty Lua table goes through is_array()
-- and emits as [], breaking spec-strict JSON-RPC consumers
-- (e.g. ping result, MUST be {}).
return '{}'
elseif t == 'boolean' then
return v and 'true' or 'false'
elseif t == 'number' then
@@ -110,9 +117,20 @@ local function decode_string(s, pos)
pos = pos + 1
c = s:sub(pos, pos)
if c == 'u' then
local hex = s:sub(pos + 1, pos + 4)
parts[#parts + 1] = utf8.char(tonumber(hex, 16))
local cp = tonumber(s:sub(pos + 1, pos + 4), 16)
pos = pos + 5
-- Combine UTF-16 surrogate pair so non-BMP chars (emoji,
-- supplementary CJK) decode correctly instead of as two
-- lone surrogates → invalid UTF-8.
if cp and cp >= 0xD800 and cp <= 0xDBFF
and s:sub(pos, pos + 1) == "\\u" then
local lo = tonumber(s:sub(pos + 2, pos + 5), 16)
if lo and lo >= 0xDC00 and lo <= 0xDFFF then
cp = (cp - 0xD800) * 0x400 + (lo - 0xDC00) + 0x10000
pos = pos + 6
end
end
parts[#parts + 1] = utf8.char(cp)
else
local esc = { n = '\n', r = '\r', t = '\t', b = '\b', f = '\f' }
parts[#parts + 1] = esc[c] or c
@@ -210,6 +228,12 @@ end
-- Sentinel for JSON null
json.null = setmetatable({}, { __tostring = function() return 'null' end })
-- Sentinel for an empty JSON object ({}). Use when a field semantically
-- requires an object but is empty — e.g. `ping` result, MCP _meta = {}.
-- Without this, an empty Lua table goes through is_array() → '[]'.
-- See memory project_json_empty_table_gotcha.md.
json.empty_object = setmetatable({}, { __tostring = function() return '{}' end })
-- Helper: encode a table as a JSON array even if empty
function json.array(t)
return setmetatable(t or {}, { __is_array = true })
+1539 -148
View File
File diff suppressed because it is too large Load Diff
+157
View File
@@ -0,0 +1,157 @@
#!/bin/bash
# Install lmcp on macOS via Homebrew.
#
# Pins to lua@5.4 (keg-only brew formula) to keep library paths aligned
# with the rest of the fleet (Arch/ALARM, Debian). Installs luasocket via
# luarocks into the user-local rocks tree (~/.luarocks/) and bakes the
# required LUA_PATH / LUA_CPATH into the LaunchAgent plist so the service
# can `require 'socket'`.
#
# Usage (from lmcp repo root):
# ./scripts/lmcp-install-macos.sh
#
# Uninstall:
# launchctl unload ~/Library/LaunchAgents/de.reauktion.marfrit.lmcp.plist
# rm ~/Library/LaunchAgents/de.reauktion.marfrit.lmcp.plist
# rm $(brew --prefix)/etc/lmcp/token
set -euo pipefail
# brew is only on PATH in login shells by default; source its env explicitly
# so this works under a plain non-login bash too.
if ! command -v brew >/dev/null 2>&1; then
for candidate in /opt/homebrew/bin/brew /usr/local/bin/brew; do
if [ -x "$candidate" ]; then
eval "$("$candidate" shellenv)"
break
fi
done
fi
command -v brew >/dev/null 2>&1 || { echo "error: Homebrew not found"; exit 1; }
REPO=${REPO:-$(cd "$(dirname "$0")/.." && pwd)}
for f in lmcp.lua json.lua server.lua example_server.lua; do
[ -f "$REPO/$f" ] || { echo "error: $REPO/$f not found — run from lmcp repo root or set REPO="; exit 1; }
done
echo "==> brew install lua@5.4 luarocks"
brew install --quiet lua@5.4 luarocks
LUA54_PREFIX=$(brew --prefix lua@5.4)
LUA54=$LUA54_PREFIX/bin/lua5.4
BREW_PREFIX=$(brew --prefix)
[ -x "$LUA54" ] || { echo "error: $LUA54 missing after brew install"; exit 1; }
echo "==> luarocks install luasocket (user-local, pinned to lua@5.4)"
luarocks --lua-version 5.4 --lua-dir "$LUA54_PREFIX" install --local luasocket
LR_PATH=$(luarocks --lua-version 5.4 --lua-dir "$LUA54_PREFIX" path --lr-path)
LR_CPATH=$(luarocks --lua-version 5.4 --lua-dir "$LUA54_PREFIX" path --lr-cpath)
DEFAULT_LUA_P="$BREW_PREFIX/share/lua/5.4/?.lua;$BREW_PREFIX/share/lua/5.4/?/init.lua;$BREW_PREFIX/lib/lua/5.4/?.lua;$BREW_PREFIX/lib/lua/5.4/?/init.lua;./?.lua;./?/init.lua"
DEFAULT_LUA_CP="$BREW_PREFIX/lib/lua/5.4/?.so;./?.so"
FULL_LUA_P="$DEFAULT_LUA_P;$LR_PATH"
FULL_LUA_CP="$DEFAULT_LUA_CP;$LR_CPATH"
echo "==> install library files into $BREW_PREFIX/share/lua/5.4/"
install -d "$BREW_PREFIX/share/lua/5.4"
install -m 644 "$REPO/lmcp.lua" "$BREW_PREFIX/share/lua/5.4/lmcp.lua"
install -m 644 "$REPO/json.lua" "$BREW_PREFIX/share/lua/5.4/json.lua"
install -m 644 "$REPO/server.lua" "$BREW_PREFIX/share/lua/5.4/server.lua"
install -m 755 "$REPO/example_server.lua" "$BREW_PREFIX/bin/lmcp-example"
# Token: retain existing, mint new otherwise
TOKEN_FILE="$BREW_PREFIX/etc/lmcp/token"
install -d -m 755 "$BREW_PREFIX/etc/lmcp"
if [ -r "$TOKEN_FILE" ]; then
TOKEN=$(cat "$TOKEN_FILE")
echo "==> reusing token from $TOKEN_FILE"
else
TOKEN=$(openssl rand -hex 32)
umask 077
printf '%s\n' "$TOKEN" > "$TOKEN_FILE"
chmod 600 "$TOKEN_FILE"
echo "==> minted new token, stored at $TOKEN_FILE (0600)"
fi
LABEL="de.reauktion.marfrit.lmcp"
PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
PORT="${LMCP_PORT:-8080}"
NAME="${LMCP_NAME:-$(hostname -s)-tools}"
echo "==> write LaunchAgent $PLIST"
mkdir -p "$HOME/Library/LaunchAgents"
cat > "$PLIST" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>$LABEL</string>
<key>ProgramArguments</key>
<array>
<string>$LUA54</string>
<string>$BREW_PREFIX/share/lua/5.4/server.lua</string>
</array>
<key>EnvironmentVariables</key>
<dict>
<key>LMCP_PORT</key>
<string>$PORT</string>
<key>LMCP_NAME</key>
<string>$NAME</string>
<key>LMCP_TOKEN</key>
<string>$TOKEN</string>
<key>LUA_PATH</key>
<string>$FULL_LUA_P</string>
<key>LUA_CPATH</key>
<string>$FULL_LUA_CP</string>
</dict>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>/tmp/lmcp.log</string>
<key>StandardErrorPath</key>
<string>/tmp/lmcp.err</string>
</dict>
</plist>
PLIST
chmod 600 "$PLIST" # plist contains token
echo "==> (re)load LaunchAgent"
launchctl unload "$PLIST" 2>/dev/null || true
launchctl load "$PLIST"
sleep 2
echo "==> smoke test (unauth expected 401, Bearer expected 200)"
unauth=$(curl -s -o /dev/null -w '%{http_code}' --max-time 3 -X POST "http://127.0.0.1:$PORT/mcp" \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' || echo "000")
auth=$(curl -s --max-time 3 -X POST "http://127.0.0.1:$PORT/mcp" \
-H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' || true)
if [ "$unauth" = "401" ] && echo "$auth" | grep -q '"tools"'; then
echo "OK — lmcp listening on :$PORT as $NAME, Bearer-gated"
else
echo "smoke test failed (unauth=$unauth, auth body below)"
echo "$auth" | head -c 500; echo
tail -20 /tmp/lmcp.err 2>/dev/null || true
exit 1
fi
cat <<INFO
Token: $TOKEN
Add to Claude Code ~/.claude.json on the client machine:
"$NAME": {
"type": "http",
"url": "http://$(hostname -s).fritz.box:$PORT/mcp",
"headers": { "Authorization": "Bearer $TOKEN" }
}
(Use .fritz.box, .local, or the LAN IP depending on where the client lives.)
INFO
+934 -34
View File
File diff suppressed because it is too large Load Diff
+113
View File
@@ -0,0 +1,113 @@
-- Abnahmetest fuer lmcp Phase A (nur beobachten, nie ablehnen).
--
-- Vom Vertrag geschrieben, NICHT von der Implementierung: der Autor dieses
-- Tests hat den zu pruefenden Code nicht gesehen. Genau daran sind die
-- letzten vier Runden gescheitert - der Implementierer hat seine eigenen
-- Hausaufgaben korrigiert, und der Test prueft dann verlaesslich das, was
-- der Code ohnehin tut.
--
-- VERTRAG
-- Eine einzelne, in sich geschlossene Lua-5.4-Datei stellt eine Tabelle M
-- bereit mit:
-- M.report(version, peer, ua) -- Produktionseinstieg
-- M.sink(version, peer, ua) -- ueberschreibbar, wird beim ERSTEN
-- -- Auftreten eines Tripels gerufen
-- * jedes verschiedene Tripel (version, peer, ua) genau EINMAL
-- * version nil oder "" -> nichts
-- * der Entprellungszustand ist ein privates Upvalue: KEINE globale
-- Variable, KEIN Parameter, den der Aufrufer mitgeben muss
-- * gedeckelt bei 50 verschiedenen Tripeln; danach nichts mehr
-- * M.report lehnt NIE etwas ab und liefert immer nil
--
-- Aufruf: lua5.4 phase_a_acceptance.lua <zu-pruefende-datei.lua>
local pfad = arg and arg[1]
if not pfad then
io.stderr:write("usage: lua5.4 phase_a_acceptance.lua <impl.lua>\n")
os.exit(2)
end
local vorher_global = {}
for k in pairs(_G) do vorher_global[k] = true end
local lade = assert(loadfile(pfad))
local M = lade()
if type(M) ~= "table" then
io.stderr:write("FAIL: die Datei liefert keine Tabelle zurueck\n")
os.exit(1)
end
local fehler = 0
local function pruefe(name, bedingung, zusatz)
if bedingung then
print((" [ok ] %s"):format(name))
else
fehler = fehler + 1
print((" [FAIL ] %s%s"):format(name, zusatz and ("" .. zusatz) or ""))
end
end
-- Faenger einhaengen
local gesehen = {}
M.sink = function(v, p, u)
gesehen[#gesehen + 1] = { v = v, p = p, u = u }
end
local function zuruecksetzen() gesehen = {} end
pruefe("M.report existiert und ist aufrufbar", type(M.report) == "function")
if type(M.report) ~= "function" then os.exit(1) end
-- 1. nil und Leerstring melden nichts
zuruecksetzen()
M.report(nil, "peerA", "uaA")
M.report("", "peerA", "uaA")
pruefe("nil und \"\" melden nichts", #gesehen == 0,
("es kamen %d Meldungen"):format(#gesehen))
-- 2. erstes Tripel meldet genau einmal
zuruecksetzen()
M.report("2025-06-18", "peerA", "uaA")
pruefe("erstes Tripel meldet einmal", #gesehen == 1)
-- 3. DER FALL, DER DREI RUNDEN LANG DURCHRUTSCHTE:
-- Entprellung am ECHTEN Einstieg, ohne dass der Aufrufer Zustand mitgibt.
zuruecksetzen()
for _ = 1, 5 do M.report("2025-06-18", "peerA", "uaA") end
pruefe("fuenf gleiche Tripel -> keine weitere Meldung", #gesehen == 0,
("es kamen %d Meldungen; Zustand ueberlebt den Aufruf nicht")
:format(#gesehen))
-- 4. gleiche Fassung, andere Gegenstelle -> meldet wieder
zuruecksetzen()
M.report("2025-06-18", "peerB", "uaA")
pruefe("gleiche Fassung, andere Gegenstelle -> Meldung", #gesehen == 1,
"Entprellung nur auf die Fassung wuerde andere Klienten maskieren")
-- 5. gleiche Fassung und Gegenstelle, anderer User-Agent -> meldet wieder
zuruecksetzen()
M.report("2025-06-18", "peerB", "uaZ")
pruefe("anderer User-Agent -> Meldung", #gesehen == 1)
-- 6. liefert immer nil, lehnt nie ab
local r1 = M.report("2026-07-28", "peerC", "uaC")
local r2 = M.report("2026-07-28", "peerC", "uaC")
pruefe("M.report liefert nil (lehnt nie ab)", r1 == nil and r2 == nil)
-- 7. Deckel bei 50
zuruecksetzen()
for i = 1, 80 do M.report("v" .. i, "peerD", "uaD") end
pruefe("Deckel greift bei 50", #gesehen <= 50,
("es kamen %d Meldungen"):format(#gesehen))
pruefe("Deckel wirft nicht zu frueh", #gesehen >= 40,
("nur %d Meldungen vor dem Deckel"):format(#gesehen))
-- 8. kein globaler Zustand
local neue = {}
for k in pairs(_G) do
if not vorher_global[k] then neue[#neue + 1] = k end
end
pruefe("keine neuen globalen Variablen", #neue == 0,
"hinzugekommen: " .. table.concat(neue, ", "))
print((" %d Pruefungen fehlgeschlagen"):format(fehler))
os.exit(fehler == 0 and 0 or 1)
+195
View File
@@ -0,0 +1,195 @@
-- Abnahmetest fuer Phase B der Angleichung an MCP 2026-07-28.
--
-- Phase A war beobachtend: feststellen, welche Fassungen ueberhaupt verlangt
-- werden. Phase B setzt durch. Gemessen am 2026-08-08 an hertz-tools:8080
-- antwortet lmcp mit HTTP 200 auf JEDE Fassungsangabe - auch auf 1999-01-01,
-- eine Fassung, die es nie gab. Es liest den Kopf schlicht nicht.
--
-- VERTRAG. Eine in sich geschlossene Lua-5.4-Datei, Tabelle M:
--
-- M.SUPPORTED Liste der Fassungen, die dieser Server spricht.
-- M.check(version) -> true, nil wenn zulaessig
-- -> false, <fehlertabelle> sonst
--
-- 1. version == nil oder "" -> zulaessig. Ein fehlender Kopf ist erlaubt;
-- der Server nimmt dann seine Grundfassung an. Das ist kein Sonderfall
-- aus Bequemlichkeit: die sitzungslose Abkuerzung schickt ihn oft nicht,
-- und sie traegt den meisten Verkehr.
-- 2. Genaue Uebereinstimmung mit einem Eintrag in M.SUPPORTED -> zulaessig.
-- 3. Alles andere -> false plus Fehlertabelle mit code == -32022 und einer
-- data.supported-Liste, die GENAU M.SUPPORTED entspricht. Ohne die Liste
-- kann die Gegenstelle nicht nachverhandeln, sie kann nur aufgeben.
-- 4. Wirft nie. Zahl, Tabelle, Wahrheitswert, Funktion - alles beantwortet
-- sie mit false, nicht mit einem Laufzeitfehler. Ein Server, der an
-- einem fremden Kopf stirbt, ist schlechter als einer, der ihn ignoriert.
-- 5. Aendert M.SUPPORTED nicht. Ein Aufruf darf die Liste des naechsten
-- nicht verschieben.
-- 6. Keine neue globale Variable.
--
-- Aufruf: lua5.4 phase_b_acceptance.lua <impl.lua>
local impl_path = arg and arg[1]
if not impl_path then
io.stderr:write("usage: lua5.4 phase_b_acceptance.lua <impl.lua>\n")
os.exit(2)
end
-- Globale Variablen VOR dem Laden festhalten, damit Regel 6 pruefbar ist.
local vorher = {}
for k in pairs(_G) do vorher[k] = true end
local chunk, lerr = loadfile(impl_path)
if not chunk then
io.stderr:write("kann " .. impl_path .. " nicht laden: " .. tostring(lerr) .. "\n")
os.exit(2)
end
local ok_load, M = pcall(chunk)
if not ok_load then
io.stderr:write("Laden warf: " .. tostring(M) .. "\n")
os.exit(2)
end
local fehler = 0
local function pruefe(name, bedingung, detail)
if bedingung then
print(string.format("[ok ] %s", name))
else
fehler = fehler + 1
print(string.format("[FEHLER] %s%s", name, detail and (" -> " .. tostring(detail)) or ""))
end
end
-- 0. Form
pruefe("M ist eine Tabelle", type(M) == "table", type(M))
if type(M) ~= "table" then print(fehler .. " Pruefungen fehlgeschlagen"); os.exit(1) end
pruefe("M.check ist aufrufbar", type(M.check) == "function", type(M.check))
pruefe("M.SUPPORTED ist eine nicht-leere Liste",
type(M.SUPPORTED) == "table" and #M.SUPPORTED >= 1, type(M.SUPPORTED))
if type(M.check) ~= "function" or type(M.SUPPORTED) ~= "table" then
print(fehler .. " Pruefungen fehlgeschlagen"); os.exit(1)
end
local function ruf(v)
local ok, a, b = pcall(M.check, v)
return ok, a, b
end
-- 1. fehlender Kopf
local ok, zulaessig = ruf(nil)
pruefe("nil ist zulaessig", ok and zulaessig == true, ok and tostring(zulaessig) or "warf")
ok, zulaessig = ruf("")
pruefe("leerer String ist zulaessig", ok and zulaessig == true, ok and tostring(zulaessig) or "warf")
-- 2. bekannte Fassung
local bekannt = M.SUPPORTED[1]
ok, zulaessig = ruf(bekannt)
pruefe("bekannte Fassung " .. tostring(bekannt) .. " ist zulaessig",
ok and zulaessig == true, ok and tostring(zulaessig) or "warf")
-- 3. unbekannte Fassung -> -32022 samt Liste
local ok3, zul3, err3 = ruf("1999-01-01")
pruefe("unbekannte Fassung wird abgelehnt", ok3 and zul3 == false,
ok3 and tostring(zul3) or "warf")
pruefe("Ablehnung traegt code -32022",
ok3 and type(err3) == "table" and err3.code == -32022,
ok3 and type(err3) == "table" and tostring(err3.code) or type(err3))
local liste_ok = false
if ok3 and type(err3) == "table" and type(err3.data) == "table"
and type(err3.data.supported) == "table" then
liste_ok = (#err3.data.supported == #M.SUPPORTED)
for i = 1, #M.SUPPORTED do
if err3.data.supported[i] ~= M.SUPPORTED[i] then liste_ok = false end
end
end
pruefe("Ablehnung nennt genau M.SUPPORTED", liste_ok)
-- 3b. die Fassung, auf die wir zuwandern, ist noch NICHT zulaessig.
-- Wer 2026-07-28 durchwinkt, bevor er sie spricht, hat den Fehler nur verschoben.
local ok3b, zul3b, err3b = ruf("2026-07-28")
local spricht_neu = false
for i = 1, #M.SUPPORTED do if M.SUPPORTED[i] == "2026-07-28" then spricht_neu = true end end
if spricht_neu then
pruefe("2026-07-28 steht in SUPPORTED und wird angenommen", ok3b and zul3b == true)
else
pruefe("2026-07-28 wird abgelehnt, solange sie nicht in SUPPORTED steht",
ok3b and zul3b == false and type(err3b) == "table" and err3b.code == -32022,
ok3b and tostring(zul3b) or "warf")
end
-- 3c. VERANKERUNG: M.SUPPORTED gegen den LAUFENDEN Server.
--
-- Ohne diese Pruefung misst der Test die Liste nur an sich selbst -- und ein
-- Modul, das eine Fassung beansprucht, die der Server nicht spricht, besteht
-- ihn glatt. Genau das ist am 2026-08-08 passiert: {"2025-06-18","2025-11-25"}
-- ergab 14/14, obwohl lmcp nur 2025-06-18 meldet.
--
-- Gefragt wird per `initialize`; die Antwort nennt genau EINE protocolVersion,
-- naemlich die, die dieser Server spricht. M.SUPPORTED muss exakt daraus
-- bestehen.
--
-- Kein Uebersprung, wenn der Server fehlt: eine Abnahme, die ihre zentrale
-- Eigenschaft nicht pruefen kann, ist keine Abnahme.
local probe_url = os.getenv("LMCP_PROBE_URL")
local probe_token = os.getenv("LMCP_PROBE_TOKEN")
pruefe("LMCP_PROBE_URL ist gesetzt (ohne Server keine Verankerung)",
probe_url ~= nil and probe_url ~= "", tostring(probe_url))
if probe_url and probe_url ~= "" then
local rumpf = '{"jsonrpc":"2.0","id":1,"method":"initialize","params":' ..
'{"protocolVersion":"2025-06-18","capabilities":{},' ..
'"clientInfo":{"name":"phase-b-acceptance","version":"1"}}}'
local befehl = "curl -s -m 15 -X POST"
.. " -H 'Content-Type: application/json'"
.. " -H 'Accept: application/json, text/event-stream'"
if probe_token and probe_token ~= "" then
befehl = befehl .. " -H 'Authorization: Bearer " .. probe_token .. "'"
end
befehl = befehl .. " -d '" .. rumpf .. "' '" .. probe_url .. "' 2>/dev/null"
local p = io.popen(befehl)
local antwort = p and p:read("*a") or ""
if p then p:close() end
local gemessen = antwort:match('"protocolVersion"%s*:%s*"([^"]+)"')
pruefe("Server nennt eine protocolVersion", gemessen ~= nil,
(#antwort > 0) and antwort:sub(1, 70) or "keine Antwort")
if gemessen then
local passt = (#M.SUPPORTED == 1) and (M.SUPPORTED[1] == gemessen)
pruefe("M.SUPPORTED entspricht GENAU dem, was der Server spricht ("
.. gemessen .. ")", passt, table.concat(M.SUPPORTED, ","))
end
end
-- 4. wirft nie
local fremde = { 42, true, false, {}, print, 0/0 }
local alle_still, welcher = true, nil
for _, v in ipairs({42, true, {}, print}) do
local okx, zulx = pcall(M.check, v)
if not okx or zulx ~= false then alle_still = false; welcher = tostring(v) end
end
pruefe("fremde Typen ergeben false statt Laufzeitfehler", alle_still, welcher)
-- 5. SUPPORTED bleibt unangetastet
local kopie = {}
for i, v in ipairs(M.SUPPORTED) do kopie[i] = v end
ruf("1999-01-01"); ruf(bekannt); ruf(nil)
local unveraendert = (#kopie == #M.SUPPORTED)
for i = 1, #kopie do if kopie[i] ~= M.SUPPORTED[i] then unveraendert = false end end
pruefe("M.SUPPORTED wird durch Aufrufe nicht veraendert", unveraendert)
-- 5b. wiederholte Ablehnung bleibt gleich (kein verbrauchbarer Zustand)
local _, _, e1 = ruf("1999-01-01")
local _, _, e2 = ruf("1999-01-01")
pruefe("zweite Ablehnung ist so vollstaendig wie die erste",
type(e1) == "table" and type(e2) == "table"
and e1.code == e2.code
and type(e2.data) == "table" and type(e2.data.supported) == "table")
-- 6. keine neuen Globalen
local neu = {}
for k in pairs(_G) do if not vorher[k] then neu[#neu + 1] = tostring(k) end end
pruefe("keine neuen globalen Variablen", #neu == 0, table.concat(neu, ","))
print(fehler .. " Pruefungen fehlgeschlagen")
os.exit(fehler == 0 and 0 or 1)
+124
View File
@@ -0,0 +1,124 @@
-- Ausfuehrbare Zusicherung fuer LMCP_TOOL_ALLOW.
--
-- Hintergrund: eine lmcp-Instanz konnte ihren Werkzeugsatz nur ERWEITERN.
-- tools.d-Dateien fuegen hinzu; der Grundstock aus server.lua bringt shell,
-- write_file und Verwandte mit, und eine Plugin-Datei kann nichts wegnehmen.
-- Am 2026-08-08 hatte damit jeder Agent mit dem Raum-Token eine Wurzelschale
-- im Raum-Container -- nachgewiesen: uid=0(root), Schreibzugriff auf
-- room.jsonl. Das ist keine Einbruchsluecke (eine Sicherheitsdomaene), aber
-- es macht jede Aussage ueber Rollentrennung unbelegbar.
--
-- Geprueft wird an der REGISTRIERUNG, nicht nachtraeglich loeschend: was nicht
-- auf der Liste steht, entsteht gar nicht -- fuer Built-ins wie fuer Plugins,
-- heute wie fuer alles, was spaeter dazukommt.
--
-- Aufruf: lua5.4 tests/test_tool_allow.lua
local hier = arg[0]:match('(.*/)') or './'
-- VORNE anhaengen, nicht hinten. Sonst gewinnt die INSTALLIERTE Fassung unter
-- /usr/share/lua/5.4/lmcp.lua, und der Test prueft nicht den Baum, in dem er
-- liegt -- gemessen am 2026-08-08: der Test gab rot, obwohl der Code stimmte.
package.path = hier .. '../?.lua;' .. package.path
local fehler = 0
local function pruefe(name, bedingung, detail)
if bedingung then
print(string.format("[ok ] %s", name))
else
fehler = fehler + 1
print(string.format("[FEHLER] %s%s", name, detail and (" -> " .. tostring(detail)) or ""))
end
end
local function namen(server)
local t = {}
for n in pairs(server.tools) do t[#t + 1] = n end
table.sort(t)
return t
end
local function enthaelt(liste, wert)
for _, v in ipairs(liste) do if v == wert then return true end end
return false
end
-- lmcp frisch laden, damit die Umgebungsvariable beim Anlegen gilt.
local function frisch()
package.loaded['lmcp'] = nil
return require('lmcp')
end
local leer = { type = "object" }
local function nichts() return "x" end
-- 1. Ohne die Variable aendert sich nichts (Rueckwaertsvertraeglichkeit).
-- Nur im ELTERNLAUF: im Kind ist die Liste gesetzt, dort waere die Aussage
-- falsch und der Test wuerde sich selbst widerlegen.
if os.getenv("LMCP_TOOL_ALLOW") == nil then
local lmcp = frisch()
local s = lmcp.new("probe-offen", { port = 0 })
s:tool("room_say", "d", leer, nichts)
s:tool("shell", "d", leer, nichts)
local n = namen(s)
pruefe("ohne LMCP_TOOL_ALLOW bleibt alles registriert",
enthaelt(n, "room_say") and enthaelt(n, "shell"), table.concat(n, ","))
end
-- Ab hier mit Liste. lmcp liest sie beim Anlegen der Instanz, also muss sie
-- VOR lmcp.new() in der Umgebung stehen -- in Lua nur ueber einen Kindprozess
-- setzbar, deshalb startet der Test sich selbst neu.
if os.getenv("LMCP_TOOL_ALLOW") == nil then
local eigen = arg[0]
local rc = os.execute(
'LMCP_TOOL_ALLOW="room_say,room_read,lease_acquire" lua5.4 "' .. eigen .. '" --kind')
local ok = (rc == true or rc == 0)
pruefe("Teillauf mit gesetzter Liste besteht", ok, tostring(rc))
print(fehler .. " Pruefungen fehlgeschlagen")
os.exit(fehler == 0 and 0 or 1)
end
-- --- Kindlauf: LMCP_TOOL_ALLOW ist gesetzt -----------------------------------
do
local lmcp = frisch()
local s = lmcp.new("probe-eng", { port = 0 })
-- erlaubt
s:tool("room_say", "d", leer, nichts)
s:tool("room_read", "d", leer, nichts)
s:tool("lease_acquire", "d", leer, nichts)
-- nicht erlaubt: genau die, die die Wurzelschale ausmachten
s:tool("shell", "d", leer, nichts)
s:tool("shell_bg", "d", leer, nichts)
s:tool("write_file", "d", leer, nichts)
s:tool("edit_file", "d", leer, nichts)
s:tool("read_file", "d", leer, nichts)
local n = namen(s)
pruefe("erlaubte Werkzeuge sind da",
enthaelt(n, "room_say") and enthaelt(n, "room_read") and enthaelt(n, "lease_acquire"),
table.concat(n, ","))
pruefe("shell ist NICHT registriert", not enthaelt(n, "shell"))
pruefe("shell_bg ist NICHT registriert", not enthaelt(n, "shell_bg"))
pruefe("write_file ist NICHT registriert", not enthaelt(n, "write_file"))
pruefe("edit_file ist NICHT registriert", not enthaelt(n, "edit_file"))
pruefe("read_file ist NICHT registriert", not enthaelt(n, "read_file"))
pruefe("genau drei Werkzeuge uebrig", #n == 3, table.concat(n, ","))
-- Der Kern: `tools/list` und `tools/call` lesen DASSELBE Register. Ein
-- nicht registriertes Werkzeug ist also nicht bloss unsichtbar, es ist
-- nicht rufbar. Waere es nur aus der Liste gefiltert, bliebe es erreichbar.
pruefe("verweigertes Werkzeug ist auch nicht aufrufbar",
s.tools["shell"] == nil)
-- Die Registrierung darf nicht werfen: ein Plugin, das ein gesperrtes
-- Werkzeug anbietet, soll weiterlaufen, nicht abstuerzen.
local ok = pcall(function() s:tool("shell", "d", leer, nichts) end)
pruefe("Registrierung eines gesperrten Werkzeugs wirft nicht", ok)
-- Verkettung muss erhalten bleiben (tool() gibt self zurueck).
local zurueck = s:tool("shell", "d", leer, nichts)
pruefe("tool() liefert weiterhin self (verkettbar)", zurueck == s)
end
print(fehler .. " Pruefungen fehlgeschlagen")
os.exit(fehler == 0 and 0 or 1)
+30
View File
@@ -0,0 +1,30 @@
-- boltzmann-tools plugin: `stash` — fleet persistent-memory CLI wrapper.
-- Receives (server, run). Runs the stash CLI inside the memory Incus container's
-- stash-stash-1 docker container (which has NO shell — /stash is invoked directly
-- as argv; docker exec handles that, no `sh -c` inside the container).
local server, run = ...
server:tool("stash",
"Fleet persistent memory (stash knowledge graph on the memory container). "
.. "`command` = a stash subcommand + its args as ONE string. "
.. "Examples: command:=\"recall escher plug AIN\" | command:=\"facts\" | "
.. "command:=\"remember 'the NAS is at 192.168.88.10'\" | command:=\"namespace list\". "
.. "Wrap multi-word text in single quotes. Read subcommands: recall, facts, namespace list, "
.. "goal list, context show. Write: remember, forget, consolidate run.",
{ type = "object", properties = {
command = { type = "string",
description = "stash subcommand + args, e.g. \"recall <query>\" or \"remember '<text>'\"" },
}, required = { "command" } },
function(a)
local c = tostring(a.command or ""):gsub("^%s+", ""):gsub("%s+$", "")
if c == "" then return "Error: command required (e.g. command:=\"recall <query>\")" end
return run("incus exec memory -- docker exec stash-stash-1 /stash " .. c, 60)
end,
{ annotations = {
title = "Stash fleet memory",
readOnlyHint = false,
destructiveHint = false,
idempotentHint = false,
openWorldHint = true,
} }
)
+292
View File
@@ -0,0 +1,292 @@
-- /opt/lmcp/tools.d/hertz.lua — hertz-specific tool registrations.
--
-- Invoked by the packaged server.lua's tools.d scan (lmcp ≥ v1.2.0, issue #22).
-- Receives (server, run) — the configured lmcp instance and the
-- coroutine-aware run() helper. We add hertz-only tools on top of the
-- packaged generics (shell, read_file, write_file, edit_file, list_dir,
-- search_files, fetch, web_search, shell_bg).
--
-- Previously these all lived in /opt/lmcp/server.lua (a copy-paste fork of
-- the packaged server.lua). That pattern drifted on every release; now the
-- packaged file stays canonical and only the genuine hertz-specifics live
-- here.
local server, run = ...
-- Local helpers — single-host scoped, not worth lifting into the packaged lib.
local function read_file_raw(path)
local f = io.open(path, 'r')
if not f then return nil end
local c = f:read('*a'); f:close(); return c
end
local function farad(cmd, timeout)
return run("incus exec farad -- sh -c " .. string.format("%q", cmd),
timeout or 15)
end
-- ---- LXD tools ----
server:tool("incus_exec", "Execute a command inside an Incus container on hertz.", {
type = "object",
properties = {
container = { type = "string", description = "Container name" },
command = { type = "string", description = "Command to execute" },
timeout = { type = "integer", default = 30 },
},
required = { "container", "command" },
}, function(a)
return run(string.format("incus exec %s -- sh -c %q",
a.container:gsub("[^%w%-]", ""), a.command), a.timeout or 30)
end)
server:tool("incus_list", "List all Incus containers on hertz.",
{ type = "object" },
function() return run("incus list -c ns4 -f csv", 10) end)
-- ---- Fritz!Box tools ----
server:tool("fritz", "Execute Fritz!Box TR-064 command (info, hosts, wan, "
.. "wol <mac>, reconnect, reboot, reboot-repeater <ip>, routes, route-add, "
.. "route-del, services, actions, call).",
{
type = "object",
properties = {
command = { type = "string", description = "fritz subcommand and args" },
},
required = { "command" },
},
function(a) return run("sudo /root/.local/bin/fritz " .. a.command, 15) end)
-- ---- Network tools ----
server:tool("ping_host", "Check if a host is reachable (1 ICMP ping, 2s timeout).", {
type = "object",
properties = { host = { type = "string" } },
required = { "host" },
}, function(a)
local host = a.host:gsub("[^%w%.%-:]", "")
return run("ping -c1 -W2 " .. host, 5)
end)
server:tool("network_status",
"Check reachability of all infrastructure hosts and MCP endpoints.",
{ type = "object" },
function()
local script = [[
hosts="hertz:localhost boltzmann:boltzmann tesla:tesla data:192.168.88.30 broglie:192.168.88.160 higgs:10.170.16.10"
for entry in $hosts; do
name="${entry%%:*}"
ip="${entry#*:}"
if ping -c1 -W2 "$ip" >/dev/null 2>&1; then
status="UP"
if [ "$name" != "data" ]; then
if timeout 3 bash -c "echo >/dev/tcp/${ip}/8080" 2>/dev/null; then
status="UP (MCP ok)"
else
status="UP (no MCP)"
fi
fi
else
status="DOWN"
fi
printf "%-12s %-20s %s\n" "$name" "$ip" "$status"
done
]]
return run(script, 30)
end)
server:tool("wol_and_wait",
"Wake the data server via Fritz!Box WoL and wait until it (or broglie MCP) is reachable.",
{
type = "object",
properties = {
mac = { type = "string", default = "", description = "MAC address (auto-detected if empty)" },
wait_for_mcp = { type = "boolean", default = true, description = "Wait for broglie MCP instead of just ping" },
timeout = { type = "integer", default = 120 },
},
},
function(a)
local mac = a.mac
if not mac or mac == "" then
local hosts_out = run("sudo /root/.local/bin/fritz hosts 2>/dev/null | grep -i 'data\\|192.168.88.30'", 10)
mac = hosts_out and hosts_out:match("(%x%x:%x%x:%x%x:%x%x:%x%x:%x%x)") or ""
if mac == "" then return "Error: could not detect MAC for data. Provide it manually." end
end
run("sudo /root/.local/bin/fritz wol " .. mac:gsub("[^%x:]", ""), 10)
local timeout = a.timeout or 120
local check
if a.wait_for_mcp == false then
check = "ping -c1 -W2 192.168.88.30"
else
check = "timeout 3 bash -c 'echo >/dev/tcp/192.168.88.160/8080'"
end
local target = (a.wait_for_mcp == false) and "data" or "broglie:8080"
local elapsed = 0
while elapsed < timeout do
os.execute("sleep 5")
elapsed = elapsed + 5
local rc = os.execute(check)
if rc == true or rc == 0 then
return string.format("WoL sent to %s. %s reachable after %ds.",
mac, target, elapsed)
end
end
return string.format("WoL sent to %s but %s not reachable after %ds.",
mac, target, timeout)
end)
-- ---- Proxmox fallback ----
server:tool("pct_exec",
"Execute a command in a Proxmox CT on data (SSH fallback when broglie is down).",
{
type = "object",
properties = {
ctid = { type = "string", description = "Container ID (e.g. 108, 165)" },
command = { type = "string" },
timeout = { type = "integer", default = 30 },
},
required = { "ctid", "command" },
},
function(a)
local ctid = a.ctid:gsub("[^%d]", "")
return run(string.format("ssh -o ConnectTimeout=5 root@data 'pct exec %s -- sh -c %q'",
ctid, a.command), a.timeout or 30)
end)
-- ---- Home Assistant ----
server:tool("ha_cli",
"Run Home Assistant CLI command inside farad (e.g. 'core restart', 'backups list', 'info').",
{
type = "object",
properties = {
command = { type = "string", description = "ha subcommand, e.g. 'core restart', 'supervisor info', 'backups list'" },
raw_json = { type = "boolean", default = false, description = "Return raw JSON output" },
},
required = { "command" },
},
function(a)
local flags = a.raw_json and " --raw-json" or ""
return farad("ha " .. a.command .. flags)
end)
server:tool("ha_api",
"Call Home Assistant Core REST API. Requires token in /opt/lmcp/ha_token on hertz.",
{
type = "object",
properties = {
method = { type = "string", default = "GET" },
endpoint = { type = "string", description = "/api/states, /api/services/climate/set_temperature, etc." },
body = { type = "string", description = "JSON body for POST" },
},
required = { "endpoint" },
},
function(a)
local token = read_file_raw("/opt/lmcp/ha_token")
if not token or token == "" then
return "Error: no HA token. Create a long-lived token in HA UI → Profile → "
.. "Long-Lived Access Tokens, then: echo '<token>' | sudo tee /opt/lmcp/ha_token"
end
token = token:gsub("%s+", "")
local method = (a.method or "GET"):upper()
local cmd = string.format(
"curl -sf -X %s -H 'Authorization: Bearer %s' -H 'Content-Type: application/json'",
method, token)
if a.body and a.body ~= "" then
cmd = cmd .. " -d " .. string.format("'%s'", a.body:gsub("'", "'\\''"))
end
cmd = cmd .. " http://localhost:8123" .. a.endpoint
return farad(cmd, 15)
end)
-- ---- MQTT (Eurotronic thermostats + general) ----
server:tool("mqtt_pub", "Publish an MQTT message (via Mosquitto in farad).", {
type = "object",
properties = {
topic = { type = "string" },
message = { type = "string" },
retain = { type = "boolean", default = false },
},
required = { "topic", "message" },
}, function(a)
local retain = a.retain and "-r " or ""
return farad(string.format("mosquitto_pub %s-t '%s' -m '%s'",
retain, a.topic:gsub("'", "'\\''"), a.message:gsub("'", "'\\''")))
end)
server:tool("mqtt_sub",
"Subscribe to MQTT topics and collect messages (via Mosquitto in farad).",
{
type = "object",
properties = {
topic = { type = "string", description = "Topic pattern, e.g. 'eurotronic/#' or '#'" },
count = { type = "integer", default = 10, description = "Number of messages to collect" },
timeout = { type = "integer", default = 5, description = "Seconds to wait" },
verbose = { type = "boolean", default = true, description = "Show topics with messages" },
},
required = { "topic" },
},
function(a)
local v = a.verbose ~= false and "-v " or ""
return farad(string.format("mosquitto_sub %s-t '%s' -C %d -W %d",
v, a.topic:gsub("'", "'\\''"), a.count or 10, a.timeout or 5),
(a.timeout or 5) + 5)
end)
-- ---- Mediagrab (kids show downloader) ----
server:tool("mediagrab",
"Manage kids show downloads in doppler container. Commands: list, weekly, "
.. "archive, test <url>, add '<json>'",
{
type = "object",
properties = {
command = { type = "string", description = "Command: list, weekly, archive, 'test <url>', 'add <json>'" },
},
required = { "command" },
},
function(a)
return run("incus exec doppler -- python3 /opt/mediagrab/mediagrab.py "
.. a.command, 120)
end)
-- ---- Fleet wake (pipi: wake-only, no power-off) ----
server:tool("wake_fleet",
"Wake a fleet NUC (pve1..pve4) via Fritz!Box Wake-on-LAN. Powers a node ON only; it cannot power anything off. Node boots in ~30-60s.",
{
type = "object",
properties = {
node = { type = "string", description = "Node to wake: '1'..'4' or 'pve1'..'pve4'" },
},
required = { "node" },
},
function(a)
local node = tostring(a.node or ""):gsub("[^%w]", "")
if not node:match("^p?v?e?[1-4]$") then
return "Error: node must be 1-4 or pve1-pve4 (got: " .. tostring(a.node) .. ")"
end
return run("sudo /root/.local/bin/wake-pve " .. node .. " 2>&1", 15)
end)
-- ---- apropos: lean facade for stash recall (read-only memory) ----
server:tool("apropos",
"Search shared fleet memory (stash) for facts about the fleet, projects, decisions, and preferences. query = 2-6 words on the topic; limit = max results (default 3). Read-only.",
{
type = "object",
properties = {
query = { type = "string", description = "2-6 words describing what to recall" },
limit = { type = "integer", description = "max results, default 3" },
},
required = { "query" },
},
function(a)
local q = tostring(a.query or ""):gsub("[^%w%s%-%.]", " "):gsub("%s+", " ")
if q:gsub("%s","") == "" then return "Error: query required" end
local lim = tonumber(a.limit) or 3
return run("python3 /opt/lmcp/helpers/stash_recall.py '" .. q .. "' " .. lim, 30)
end)
+36
View File
@@ -0,0 +1,36 @@
-- versions.lua
-- Modul zur Versionspruefung gemaess LMCP-Vertrag
local M = {}
M.SUPPORTED = {"2025-06-18"}
--- 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
function M.check(version)
-- (a) version == nil oder "" -> true, nil
if version == nil or version == "" then
return true, nil
end
-- (b) exakter Treffer 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 } }
return false, {
code = -32022,
data = {
supported = M.SUPPORTED
}
}
end
-- Keine neuen Globalen, keine Seiteneffekte, M.SUPPORTED wird nicht geaendert
return M
+57
View File
@@ -0,0 +1,57 @@
# lmcp Windows MSI build
This directory contains the WiX manifest and packaging files for the
Windows MSI build of lmcp.
## Recommended: cross-build on Linux (one command)
```sh
./build-msi.sh /path/to/output/dir
```
Downloads Lua 5.4 Win64 binaries from LuaBinaries, cross-compiles
LuaSocket via `mingw-w64`, stages `pkg/lua/`, and runs `wixl` to
produce `lmcp-<version>.msi`. No Windows VM required.
Prereqs on a Debian/Ubuntu builder:
```sh
sudo apt install wixl unzip gcc-mingw-w64-x86-64 \
binutils-mingw-w64-x86-64 mingw-w64-x86-64-dev curl
```
Version comes from `lmcp.wxs` `Version="…"`. Bump that before
building a release.
## Alternative: build on Windows via WiX toolset
```cmd
sync.sh REM see "tracked vs. generated"
REM ensure pkg/lua/ has the runtime — see below
candle.exe lmcp.wxs
light.exe lmcp.wixobj -o lmcp-1.x.y.msi
```
## What's tracked vs. generated
- **Tracked** (edit in git):
- `lmcp.wxs` — WiX MSI manifest
- `sync.sh` — copies root .lua sources → `pkg/`
- `README.md` — this file
- `pkg/install_service.bat` — Windows service installer
- `pkg/start.bat` — manual launcher
- **Generated / external** (gitignored):
- `pkg/lmcp.lua`, `pkg/server.lua`, `pkg/json.lua` — produced by
`sync.sh`. Never edit directly; edit the root files and re-sync.
- `pkg/lua/` — the Lua + LuaSocket runtime drop-in. Download
separately and place here. Suggested source: the lua-binaries
project (https://github.com/rjpcomputing/luaforwindows) or a
similar pre-built bundle. The MSI expects `pkg/lua/lua.exe`,
`pkg/lua/lua54.dll`, and the `pkg/lua/socket/` + `pkg/lua/mime/`
subdirectories per the manifest.
## Issue history
Issue #18 (closed in v1.1.0) introduced this workflow after the
`pkg/` lua sources had silently drifted ~6 months out of date,
missing every feature added since April 2026.
+100
View File
@@ -0,0 +1,100 @@
#!/bin/sh
# windows/build-msi.sh — produce lmcp-<ver>.msi on Linux via wixl.
#
# This is the first-time-discovered cross-build path: download Lua 5.4
# Win64 binaries from LuaBinaries, cross-compile LuaSocket with mingw-w64,
# stage windows/pkg/lua/, then invoke wixl on the WiX manifest.
#
# Avoids the VM106-clone + WiX-on-Windows path entirely. ~1 minute on a
# warm cache; ~3-5 minutes cold (downloads ~700 KB + cross-compiles).
#
# Prereqs (apt install on Debian aarch64):
# apt-get install -y wixl unzip gcc-mingw-w64-x86-64 binutils-mingw-w64-x86-64 \
# mingw-w64-x86-64-dev
#
# Usage: ./build-msi.sh [output_dir]
# Output: $output_dir/lmcp-<ver>.msi (default: $PWD)
#
# Version comes from windows/lmcp.wxs Version="…" attribute.
set -eu
here=$(dirname "$(readlink -f "$0")")
root=$(cd "$here/.." && pwd)
out_dir=${1:-$PWD}
work=$(mktemp -d /tmp/lmcp-msi-XXXXXX)
trap "rm -rf $work" EXIT
# Versions — bump as upstream releases.
LUA_VER=5.4.2
LUASOCKET_VER=3.1.0
# Pull current lmcp version from the WiX manifest.
lmcp_ver=$(sed -n 's/.*Version="\([^"]*\)".*/\1/p' "$here/lmcp.wxs" | head -1)
[ -n "$lmcp_ver" ] || { echo "build-msi.sh: cannot parse Version from lmcp.wxs" >&2; exit 1; }
echo "build-msi.sh: lmcp $lmcp_ver, lua $LUA_VER, luasocket $LUASOCKET_VER"
echo "==> 1/5 sync lmcp .lua sources into pkg/"
"$here/sync.sh"
echo "==> 2/5 fetch lua $LUA_VER win64 binaries + dev library"
cd "$work"
curl -sSLf -o lua-bin.zip \
"https://downloads.sourceforge.net/project/luabinaries/${LUA_VER}/Tools%20Executables/lua-${LUA_VER}_Win64_bin.zip"
curl -sSLf -o lua-lib.zip \
"https://downloads.sourceforge.net/project/luabinaries/${LUA_VER}/Windows%20Libraries/Dynamic/lua-${LUA_VER}_Win64_dllw6_lib.zip"
mkdir -p luabin lualib include/lua/54 include/lua54 bin/lua/54 bin/lua54 lib/lua/54 lib/lua54
unzip -q -o lua-bin.zip -d luabin
unzip -q -o lua-lib.zip -d lualib
cp lualib/include/*.h include/lua/54/
cp lualib/include/*.h include/lua54/
cp lualib/liblua54.a lib/lua/54/
cp lualib/liblua54.a lib/lua54/
cp lualib/lua54.dll bin/lua/54/
cp lualib/lua54.dll bin/lua54/
echo "==> 3/5 cross-compile LuaSocket $LUASOCKET_VER for win64"
curl -sSLf -o luasocket.tar.gz \
"https://github.com/lunarmodules/luasocket/archive/refs/tags/v${LUASOCKET_VER}.tar.gz"
tar xzf luasocket.tar.gz
cd "luasocket-${LUASOCKET_VER}"
make -s PLAT=mingw \
CC=x86_64-w64-mingw32-gcc \
LD=x86_64-w64-mingw32-gcc \
LUAV=54 \
LUAINC_mingw_base="$work/include" \
LUALIB_mingw_base="$work/bin" \
> /dev/null
echo "==> 4/5 stage pkg/lua/"
pkg_lua="$here/pkg/lua"
rm -rf "$pkg_lua"
mkdir -p "$pkg_lua/socket" "$pkg_lua/mime"
# WiX manifest expects "lua.exe" (not "lua54.exe").
cp "$work/luabin/lua54.exe" "$pkg_lua/lua.exe"
cp "$work/luabin/lua54.dll" "$pkg_lua/lua54.dll"
cp src/socket.lua "$pkg_lua/"
cp src/mime.lua "$pkg_lua/"
cp src/ltn12.lua "$pkg_lua/"
cp src/socket-3.0.0.dll "$pkg_lua/socket/core.dll"
cp src/ftp.lua "$pkg_lua/socket/"
cp src/headers.lua "$pkg_lua/socket/"
cp src/http.lua "$pkg_lua/socket/"
cp src/smtp.lua "$pkg_lua/socket/"
cp src/tp.lua "$pkg_lua/socket/"
cp src/url.lua "$pkg_lua/socket/"
cp src/mime-1.0.3.dll "$pkg_lua/mime/core.dll"
echo "==> 5/5 wixl: produce MSI"
# wixl wants forward slashes; rewrite Windows-style backslashes in Source=.
wxs_tmp="$work/lmcp.wxs"
sed 's|Source="pkg\\|Source="pkg/|g; s|\\\([a-zA-Z]\)|/\1|g' "$here/lmcp.wxs" > "$wxs_tmp"
mkdir -p "$out_dir"
out_msi="$out_dir/lmcp-${lmcp_ver}.msi"
(cd "$here" && wixl -v "$wxs_tmp" -o "$out_msi")
echo ""
echo "==> done: $out_msi"
ls -la "$out_msi"
sha256sum "$out_msi"
+119
View File
@@ -0,0 +1,119 @@
<?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
<!-- Bump Version on every release. See windows/README.md. -->
<Product Id="*"
Name="lmcp — Lua MCP Server"
Language="1033"
Version="1.1.0"
Manufacturer="QAP'LA Project"
UpgradeCode="A7F3E2D1-4B5C-6D7E-8F9A-0B1C2D3E4F5A">
<Package InstallerVersion="200"
Compressed="yes"
InstallScope="perMachine"
Description="Lightweight MCP server in Lua. 2MB RSS."
Comments="Zero-dependency MCP server." />
<MediaTemplate EmbedCab="yes" />
<MajorUpgrade DowngradeErrorMessage="A newer version is already installed." />
<Directory Id="TARGETDIR" Name="SourceDir">
<Directory Id="ProgramFiles64Folder">
<Directory Id="INSTALLFOLDER" Name="lmcp">
<Directory Id="LUA_DIR" Name="lua">
<Directory Id="SOCKET_DIR" Name="socket" />
<Directory Id="MIME_DIR" Name="mime" />
</Directory>
</Directory>
</Directory>
</Directory>
<!-- lmcp application files -->
<DirectoryRef Id="INSTALLFOLDER">
<Component Id="JsonLua" Guid="B1A2C3D4-E5F6-7890-ABCD-EF1234567890">
<File Id="json.lua" Source="pkg\json.lua" KeyPath="yes" />
</Component>
<Component Id="LmcpLua" Guid="B1A2C3D4-E5F6-7890-ABCD-EF1234567891">
<File Id="lmcp.lua" Source="pkg\lmcp.lua" KeyPath="yes" />
</Component>
<Component Id="ServerLua" Guid="B1A2C3D4-E5F6-7890-ABCD-EF1234567892">
<File Id="server.lua" Source="pkg\server.lua" KeyPath="yes" />
</Component>
<Component Id="StartBat" Guid="B1A2C3D4-E5F6-7890-ABCD-EF1234567893">
<File Id="start.bat" Source="pkg\start.bat" KeyPath="yes" />
</Component>
<Component Id="InstallService" Guid="B1A2C3D4-E5F6-7890-ABCD-EF1234567894">
<File Id="install_service.bat" Source="pkg\install_service.bat" KeyPath="yes" />
</Component>
</DirectoryRef>
<!-- Lua runtime -->
<DirectoryRef Id="LUA_DIR">
<Component Id="LuaExe" Guid="C2B3D4E5-F6A7-8901-BCDE-F12345678900">
<File Id="lua.exe" Source="pkg\lua\lua.exe" KeyPath="yes" />
</Component>
<Component Id="LuaDll" Guid="C2B3D4E5-F6A7-8901-BCDE-F12345678901">
<File Id="lua54.dll" Source="pkg\lua\lua54.dll" KeyPath="yes" />
</Component>
<Component Id="SocketLua" Guid="C2B3D4E5-F6A7-8901-BCDE-F12345678902">
<File Id="socket.lua" Source="pkg\lua\socket.lua" KeyPath="yes" />
</Component>
<Component Id="MimeLua" Guid="C2B3D4E5-F6A7-8901-BCDE-F12345678903">
<File Id="mime.lua" Source="pkg\lua\mime.lua" KeyPath="yes" />
</Component>
<Component Id="Ltn12Lua" Guid="C2B3D4E5-F6A7-8901-BCDE-F12345678904">
<File Id="ltn12.lua" Source="pkg\lua\ltn12.lua" KeyPath="yes" />
</Component>
</DirectoryRef>
<!-- LuaSocket native DLLs -->
<DirectoryRef Id="SOCKET_DIR">
<Component Id="SocketCoreDll" Guid="D3C4E5F6-A7B8-9012-CDEF-123456789010">
<File Id="socket_core.dll" Name="core.dll" Source="pkg\lua\socket\core.dll" KeyPath="yes" />
</Component>
<Component Id="SocketFtp" Guid="D3C4E5F6-A7B8-9012-CDEF-123456789011">
<File Id="ftp.lua" Source="pkg\lua\socket\ftp.lua" KeyPath="yes" />
</Component>
<Component Id="SocketHeaders" Guid="D3C4E5F6-A7B8-9012-CDEF-123456789012">
<File Id="headers.lua" Source="pkg\lua\socket\headers.lua" KeyPath="yes" />
</Component>
<Component Id="SocketHttp" Guid="D3C4E5F6-A7B8-9012-CDEF-123456789013">
<File Id="http.lua" Source="pkg\lua\socket\http.lua" KeyPath="yes" />
</Component>
<Component Id="SocketTp" Guid="D3C4E5F6-A7B8-9012-CDEF-123456789014">
<File Id="tp.lua" Source="pkg\lua\socket\tp.lua" KeyPath="yes" />
</Component>
<Component Id="SocketUrl" Guid="D3C4E5F6-A7B8-9012-CDEF-123456789015">
<File Id="url.lua" Source="pkg\lua\socket\url.lua" KeyPath="yes" />
</Component>
</DirectoryRef>
<DirectoryRef Id="MIME_DIR">
<Component Id="MimeCoreDll" Guid="E4D5F6A7-B8C9-0123-DEFA-234567890120">
<File Id="mime_core.dll" Name="core.dll" Source="pkg\lua\mime\core.dll" KeyPath="yes" />
</Component>
</DirectoryRef>
<Feature Id="MainFeature" Title="lmcp Server" Level="1">
<ComponentRef Id="JsonLua" />
<ComponentRef Id="LmcpLua" />
<ComponentRef Id="ServerLua" />
<ComponentRef Id="StartBat" />
<ComponentRef Id="InstallService" />
<ComponentRef Id="LuaExe" />
<ComponentRef Id="LuaDll" />
<ComponentRef Id="SocketLua" />
<ComponentRef Id="MimeLua" />
<ComponentRef Id="Ltn12Lua" />
<ComponentRef Id="SocketCoreDll" />
<ComponentRef Id="SocketFtp" />
<ComponentRef Id="SocketHeaders" />
<ComponentRef Id="SocketHttp" />
<ComponentRef Id="SocketTp" />
<ComponentRef Id="SocketUrl" />
<ComponentRef Id="MimeCoreDll" />
</Feature>
</Product>
</Wix>
+24
View File
@@ -0,0 +1,24 @@
@echo off
REM Install lmcp as a Windows service using NSSM (Non-Sucking Service Manager)
REM Download nssm from https://nssm.cc if not present
if not exist "%~dp0nssm.exe" (
echo ERROR: nssm.exe not found in %~dp0
echo Download from https://nssm.cc and place nssm.exe here.
exit /b 1
)
set INSTALL_DIR=%~dp0
set SERVICE_NAME=lmcp
echo Installing lmcp as Windows service...
%INSTALL_DIR%nssm.exe install %SERVICE_NAME% "%INSTALL_DIR%lua\lua.exe" "%INSTALL_DIR%server.lua"
%INSTALL_DIR%nssm.exe set %SERVICE_NAME% AppDirectory "%INSTALL_DIR%"
%INSTALL_DIR%nssm.exe set %SERVICE_NAME% AppEnvironmentExtra "LMCP_PORT=8080"
%INSTALL_DIR%nssm.exe set %SERVICE_NAME% DisplayName "lmcp MCP Server"
%INSTALL_DIR%nssm.exe set %SERVICE_NAME% Description "Lightweight MCP server in Lua"
%INSTALL_DIR%nssm.exe set %SERVICE_NAME% Start SERVICE_AUTO_START
%INSTALL_DIR%nssm.exe start %SERVICE_NAME%
echo Done. Service '%SERVICE_NAME%' installed and started.
echo Check: sc query %SERVICE_NAME%
+7
View File
@@ -0,0 +1,7 @@
@echo off
REM lmcp — Lua MCP Server
REM Start the server on port 8080 (or LMCP_PORT if set)
cd /d "%~dp0"
if not defined LMCP_PORT set LMCP_PORT=8080
echo Starting lmcp on port %LMCP_PORT%...
lua\lua.exe server.lua
+25
View File
@@ -0,0 +1,25 @@
#!/bin/sh
# windows/sync.sh — refresh windows/pkg/ from root .lua sources (issue #18).
#
# Run BEFORE invoking the WiX build so the MSI bundles whatever is in
# master. The .lua files in windows/pkg/ are regenerated on every run
# and are gitignored — never edit them directly.
#
# Idempotent: re-running just re-copies. Safe to call from a Makefile,
# a CI step, or by hand before `candle.exe + light.exe`.
set -eu
here=$(dirname "$(readlink -f "$0")")
root=$(cd "$here/.." && pwd)
for f in lmcp.lua server.lua json.lua; do
if [ ! -f "$root/$f" ]; then
echo "windows/sync.sh: missing source $root/$f" >&2
exit 1
fi
cp "$root/$f" "$here/pkg/$f"
echo " synced $f"
done
echo "windows/sync.sh: done — pkg/ matches root .lua at $(date +%Y-%m-%dT%H:%M:%S)"