diff --git a/.opencode/plugin/mcpx/daemon.test.ts b/.opencode/plugin/mcpx/daemon.test.ts index 0c192a7f84..d3b8dc3c13 100644 --- a/.opencode/plugin/mcpx/daemon.test.ts +++ b/.opencode/plugin/mcpx/daemon.test.ts @@ -30,6 +30,7 @@ import { type Candidate, type DaemonInfo, } from "./daemon.ts"; +import { OPERATION_FINGERPRINT } from "./ops.gen.ts"; // Short by design. A unix socket path is capped at 104 bytes on macOS, and // the daemon itself moves its socket elsewhere when the state path would @@ -69,6 +70,8 @@ type FakeOptions = { config?: string; version?: string; servers?: number; + operationFingerprint?: string; + missingOperationFingerprint?: boolean; }; const serveFake = (socket: string, opts: FakeOptions = {}): Fake => { @@ -79,11 +82,17 @@ const serveFake = (socket: string, opts: FakeOptions = {}): Fake => { const url = new URL(req.url); seen.push(url.pathname); if (url.pathname === "/v1/health") { - return Response.json({ status: "ok", version: opts.version ?? "test", pid: 1 }); + return Response.json({ + status: "ok", + version: opts.version ?? "test", + pid: 1, + ...(opts.missingOperationFingerprint ? {} : { operationFingerprint: opts.operationFingerprint ?? OPERATION_FINGERPRINT }), + }); } if (url.pathname === "/v1/status") { return Response.json({ version: opts.version ?? "test", + ...(opts.missingOperationFingerprint ? {} : { operationFingerprint: opts.operationFingerprint ?? OPERATION_FINGERPRINT }), pid: 1, socket, config: opts.config, @@ -98,6 +107,7 @@ const serveFake = (socket: string, opts: FakeOptions = {}): Fake => { if (!opts.resolve) return new Response("not found", { status: 404 }); return Response.json(opts.resolve(url.searchParams.get("dir") ?? "")); } + if (url.pathname === "/v1/namespaces") return Response.json([]); return new Response("not found", { status: 404 }); }, }); @@ -122,6 +132,35 @@ afterEach(() => { while (scratch.length) rmSync(scratch.pop()!, { recursive: true, force: true }); }); +describe("generated operation compatibility", () => { + test("allows operations when the daemon table fingerprint matches", async () => { + const socket = join(tempRoot(), "matching.sock"); + const server = fake(socket); + const client = new DaemonClient({ kind: "socket", path: socket }); + + await expect(client.ops.namespaces()).resolves.toEqual([]); + expect(server.seen).toEqual(["/v1/health", "/v1/namespaces"]); + }); + + test("refuses generated operations when the daemon table fingerprint differs", async () => { + const socket = join(tempRoot(), "mismatch.sock"); + const server = fake(socket, { operationFingerprint: "stale-table" }); + const client = new DaemonClient({ kind: "socket", path: socket }); + + await expect(client.ops.namespaces()).rejects.toThrow("operation table mismatch"); + expect(server.seen).toEqual(["/v1/health"]); + }); + + test("fails closed when an older daemon has no operation fingerprint", async () => { + const socket = join(tempRoot(), "missing-fingerprint.sock"); + const server = fake(socket, { missingOperationFingerprint: true }); + const client = new DaemonClient({ kind: "socket", path: socket }); + + await expect(client.ops.namespaces()).rejects.toThrow("does not publish an operation fingerprint"); + expect(server.seen).toEqual(["/v1/health"]); + }); +}); + describe("rung 2: the info files", () => { test("no binary and one daemon: everything works", async () => { const state = tempRoot(); diff --git a/.opencode/plugin/mcpx/daemon.ts b/.opencode/plugin/mcpx/daemon.ts index a6f5d3c91c..10d1128275 100644 --- a/.opencode/plugin/mcpx/daemon.ts +++ b/.opencode/plugin/mcpx/daemon.ts @@ -43,7 +43,7 @@ import { readdirSync, readFileSync, statSync } from "node:fs"; import { homedir, tmpdir } from "node:os"; import { join } from "node:path"; -import { DaemonOps, OpError } from "./ops.gen.ts"; +import { DaemonOps, OPERATION_FINGERPRINT, OpError } from "./ops.gen.ts"; /** * Every tunable in one place. @@ -394,7 +394,12 @@ export const withDaemonAuth = (init: RequestInit): RequestInit => { * path for both transports and no hand-rolled HTTP. */ export class DaemonClient { - constructor(readonly target: Target) {} + readonly ops: DaemonOps; + private operationCompatibility?: Promise; + + constructor(readonly target: Target) { + this.ops = new DaemonOps((path, init) => this.operationFetch(path, init)); + } /** * Every /v1 operation as a typed method, generated from the table the @@ -403,7 +408,31 @@ export class DaemonClient { * surface, so nothing the daemon serves is reachable only through a * hand-built URL. */ - readonly ops: DaemonOps = new DaemonOps((path, init) => this.raw(path, init)); + private async operationFetch(path: string, init: RequestInit): Promise { + await this.assertOperationCompatibility(); + return this.raw(path, init); + } + + private assertOperationCompatibility(): Promise { + this.operationCompatibility ??= this.verifyOperationCompatibility().catch((error: unknown) => { + this.operationCompatibility = undefined; + throw error; + }); + return this.operationCompatibility; + } + + private async verifyOperationCompatibility(): Promise { + const health = await this.health(); + if (!health) { + throw new Error("mcpx: cannot verify /v1 operation compatibility because the daemon health endpoint did not answer; update or restart the mcpx daemon and plugin"); + } + if (typeof health.operationFingerprint !== "string" || health.operationFingerprint.length === 0) { + throw new Error("mcpx: cannot verify /v1 operation compatibility because the daemon does not publish an operation fingerprint; update and restart the mcpx daemon before using generated plugin operations"); + } + if (health.operationFingerprint !== OPERATION_FINGERPRINT) { + throw new Error(`mcpx: /v1 operation table mismatch (plugin ${OPERATION_FINGERPRINT}, daemon ${health.operationFingerprint}); update the mcpx plugin and daemon from matching versions`); + } + } private url(path: string): string { // Any host works over a socket; the dispatcher ignores it. @@ -470,7 +499,7 @@ export class DaemonClient { */ async health( timeoutMs = TUNING.healthTimeoutMs, - ): Promise<{ status: string; version?: string; pid?: number; uptime?: string; endpoint?: string } | undefined> { + ): Promise<{ status: string; version?: string; pid?: number; uptime?: string; endpoint?: string; operationFingerprint?: string } | undefined> { try { return await this.get("/v1/health", timeoutMs); } catch { @@ -747,6 +776,7 @@ export class DaemonClient { /** What /v1/status answers, as much of it as discovery cares about. */ export type DaemonStatus = { version?: string; + operationFingerprint?: string; pid?: number; uptime?: string; endpoint?: string; diff --git a/.opencode/plugin/mcpx/ops.gen.ts b/.opencode/plugin/mcpx/ops.gen.ts index cb852e92a2..204d47c8ff 100644 --- a/.opencode/plugin/mcpx/ops.gen.ts +++ b/.opencode/plugin/mcpx/ops.gen.ts @@ -20,6 +20,8 @@ type OpSpec = { response: "json" | "response" } +export const OPERATION_FINGERPRINT = "0ac07ddbbc06f9c28a106e4e26d701a31e6cfaa37b17646b7911f165acb0af2e" + /** Every /v1 operation, by name. */ export const OPS: Record = { adapters_add: { diff --git a/.opencode/plugin/mcpx/ops.test.ts b/.opencode/plugin/mcpx/ops.test.ts index a4c0099ee4..6f4dc360f1 100644 --- a/.opencode/plugin/mcpx/ops.test.ts +++ b/.opencode/plugin/mcpx/ops.test.ts @@ -18,7 +18,7 @@ import { tmpdir } from "node:os" import { join } from "node:path" import { DaemonClient, renderExec } from "./daemon.ts" -import { buildRequest, OpError, OPS } from "./ops.gen.ts" +import { buildRequest, OPERATION_FINGERPRINT, OpError, OPS } from "./ops.gen.ts" type Seen = { method: string; path: string; type: string | null; body: Uint8Array } @@ -36,6 +36,12 @@ const fake = (reply: (s: Seen) => Response = () => Response.json({ ok: true })) unix: socket, async fetch(req) { const url = new URL(req.url) + // Every generated operation first verifies the daemon's operation-table + // fingerprint. Answer that handshake without recording it, so `seen` + // stays the list of operations the test is asserting about. + if (url.pathname === "/v1/health") { + return Response.json({ status: "ok", operationFingerprint: OPERATION_FINGERPRINT }) + } const s: Seen = { method: req.method, path: url.pathname + url.search, diff --git a/pkgs/mcpx/internal/api/ops_test.go b/pkgs/mcpx/internal/api/ops_test.go index 0a5b3cdaf0..986637db75 100644 --- a/pkgs/mcpx/internal/api/ops_test.go +++ b/pkgs/mcpx/internal/api/ops_test.go @@ -1,6 +1,7 @@ package api_test import ( + "encoding/hex" "encoding/json" "strings" "testing" @@ -17,6 +18,18 @@ func op(t *testing.T, name string) api.Op { return o } +func TestOperationFingerprintIsStableSHA256(t *testing.T) { + want := api.OperationFingerprint() + if decoded, err := hex.DecodeString(want); err != nil || len(decoded) != 32 { + t.Fatalf("OperationFingerprint() = %q, want a 32-byte hex digest (err %v)", want, err) + } + for i := 0; i < 3; i++ { + if got := api.OperationFingerprint(); got != want { + t.Fatalf("OperationFingerprint() changed: first %q, then %q", want, got) + } + } +} + func TestArgumentsLandWhereTheRouteExpectsThem(t *testing.T) { // The whole proxy is this function. A caller filling in a tool call // should not have to know which of its arguments the daemon reads from diff --git a/pkgs/mcpx/internal/api/plugin_ts.go b/pkgs/mcpx/internal/api/plugin_ts.go index d30d886763..13866dd878 100644 --- a/pkgs/mcpx/internal/api/plugin_ts.go +++ b/pkgs/mcpx/internal/api/plugin_ts.go @@ -1,11 +1,69 @@ package api import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" "fmt" "sort" "strings" ) +type fingerprintParam struct { + Name string `json:"name"` + In In `json:"in"` + Type string `json:"type"` + Required bool `json:"required"` + Enum []string `json:"enum"` + Schema string `json:"schema"` + Raw bool `json:"raw"` +} + +type fingerprintOperation struct { + Name string `json:"name"` + Method string `json:"method"` + Path string `json:"path"` + Params []fingerprintParam `json:"params"` + Wrap string `json:"wrap"` + Response string `json:"response"` +} + +// OperationFingerprint identifies the request and response contract used by +// generated plugin operations. Its input is a canonical projection of Ops, +// not the generated TypeScript file (which embeds this value). +func OperationFingerprint() string { + ops := Ops() + sort.Slice(ops, func(i, j int) bool { return ops[i].Name < ops[j].Name }) + contract := make([]fingerprintOperation, 0, len(ops)) + for _, op := range ops { + params := append([]Param(nil), op.Params...) + sort.Slice(params, func(i, j int) bool { return params[i].Name < params[j].Name }) + projected := make([]fingerprintParam, 0, len(params)) + for _, param := range params { + enum := append([]string{}, param.Enum...) + projected = append(projected, fingerprintParam{ + Name: param.Name, In: param.In, Type: param.Type, + Required: param.Required, Enum: enum, Schema: param.Schema, Raw: param.Raw, + }) + } + wrap, _ := op.bodyIsOneObject() + response := "json" + if op.Text || op.Streams { + response = "response" + } + contract = append(contract, fingerprintOperation{ + Name: op.Name, Method: op.Method, Path: op.Path, + Params: projected, Wrap: wrap, Response: response, + }) + } + encoded, err := json.Marshal(contract) + if err != nil { + panic(fmt.Sprintf("marshal operation fingerprint contract: %v", err)) + } + digest := sha256.Sum256(encoded) + return hex.EncodeToString(digest[:]) +} + // PluginTS renders plugin/opencode/mcpx/ops.gen.ts: one typed method per // /v1 operation, for the opencode plugin's DaemonClient. // @@ -43,7 +101,9 @@ type OpSpec = { response: "json" | "response" } -/** Every /v1 operation, by name. */ +`) + fmt.Fprintf(&b, "export const OPERATION_FINGERPRINT = %q\n\n", OperationFingerprint()) + b.WriteString(`/** Every /v1 operation, by name. */ export const OPS: Record = { `) for _, op := range ops { diff --git a/pkgs/mcpx/internal/daemon/server.go b/pkgs/mcpx/internal/daemon/server.go index 6dc41861d1..3e102f59a5 100644 --- a/pkgs/mcpx/internal/daemon/server.go +++ b/pkgs/mcpx/internal/daemon/server.go @@ -902,11 +902,12 @@ func writeText(w http.ResponseWriter, code int, s string) { func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) { writeJSON(w, 200, map[string]any{ - "status": "ok", - "version": s.version, - "pid": os.Getpid(), - "uptime": time.Since(s.started).Truncate(time.Second).String(), - "endpoint": s.endpoint, + "status": "ok", + "version": s.version, + "pid": os.Getpid(), + "uptime": time.Since(s.started).Truncate(time.Second).String(), + "endpoint": s.endpoint, + "operationFingerprint": api.OperationFingerprint(), }) } @@ -916,7 +917,8 @@ func (s *Server) handleStatus(w http.ResponseWriter, _ *http.Request) { cfgPath = cfg.Path } writeJSON(w, 200, map[string]any{ - "version": s.version, + "version": s.version, + "operationFingerprint": api.OperationFingerprint(), // #1877: this daemon's instance identity, so an `mcpx serve` // shim backed by this daemon can report the DAEMON's identity // (not the shim process's) to its host. diff --git a/pkgs/mcpx/plugin/opencode/mcpx/daemon.test.ts b/pkgs/mcpx/plugin/opencode/mcpx/daemon.test.ts index 0c192a7f84..d3b8dc3c13 100644 --- a/pkgs/mcpx/plugin/opencode/mcpx/daemon.test.ts +++ b/pkgs/mcpx/plugin/opencode/mcpx/daemon.test.ts @@ -30,6 +30,7 @@ import { type Candidate, type DaemonInfo, } from "./daemon.ts"; +import { OPERATION_FINGERPRINT } from "./ops.gen.ts"; // Short by design. A unix socket path is capped at 104 bytes on macOS, and // the daemon itself moves its socket elsewhere when the state path would @@ -69,6 +70,8 @@ type FakeOptions = { config?: string; version?: string; servers?: number; + operationFingerprint?: string; + missingOperationFingerprint?: boolean; }; const serveFake = (socket: string, opts: FakeOptions = {}): Fake => { @@ -79,11 +82,17 @@ const serveFake = (socket: string, opts: FakeOptions = {}): Fake => { const url = new URL(req.url); seen.push(url.pathname); if (url.pathname === "/v1/health") { - return Response.json({ status: "ok", version: opts.version ?? "test", pid: 1 }); + return Response.json({ + status: "ok", + version: opts.version ?? "test", + pid: 1, + ...(opts.missingOperationFingerprint ? {} : { operationFingerprint: opts.operationFingerprint ?? OPERATION_FINGERPRINT }), + }); } if (url.pathname === "/v1/status") { return Response.json({ version: opts.version ?? "test", + ...(opts.missingOperationFingerprint ? {} : { operationFingerprint: opts.operationFingerprint ?? OPERATION_FINGERPRINT }), pid: 1, socket, config: opts.config, @@ -98,6 +107,7 @@ const serveFake = (socket: string, opts: FakeOptions = {}): Fake => { if (!opts.resolve) return new Response("not found", { status: 404 }); return Response.json(opts.resolve(url.searchParams.get("dir") ?? "")); } + if (url.pathname === "/v1/namespaces") return Response.json([]); return new Response("not found", { status: 404 }); }, }); @@ -122,6 +132,35 @@ afterEach(() => { while (scratch.length) rmSync(scratch.pop()!, { recursive: true, force: true }); }); +describe("generated operation compatibility", () => { + test("allows operations when the daemon table fingerprint matches", async () => { + const socket = join(tempRoot(), "matching.sock"); + const server = fake(socket); + const client = new DaemonClient({ kind: "socket", path: socket }); + + await expect(client.ops.namespaces()).resolves.toEqual([]); + expect(server.seen).toEqual(["/v1/health", "/v1/namespaces"]); + }); + + test("refuses generated operations when the daemon table fingerprint differs", async () => { + const socket = join(tempRoot(), "mismatch.sock"); + const server = fake(socket, { operationFingerprint: "stale-table" }); + const client = new DaemonClient({ kind: "socket", path: socket }); + + await expect(client.ops.namespaces()).rejects.toThrow("operation table mismatch"); + expect(server.seen).toEqual(["/v1/health"]); + }); + + test("fails closed when an older daemon has no operation fingerprint", async () => { + const socket = join(tempRoot(), "missing-fingerprint.sock"); + const server = fake(socket, { missingOperationFingerprint: true }); + const client = new DaemonClient({ kind: "socket", path: socket }); + + await expect(client.ops.namespaces()).rejects.toThrow("does not publish an operation fingerprint"); + expect(server.seen).toEqual(["/v1/health"]); + }); +}); + describe("rung 2: the info files", () => { test("no binary and one daemon: everything works", async () => { const state = tempRoot(); diff --git a/pkgs/mcpx/plugin/opencode/mcpx/daemon.ts b/pkgs/mcpx/plugin/opencode/mcpx/daemon.ts index a6f5d3c91c..10d1128275 100644 --- a/pkgs/mcpx/plugin/opencode/mcpx/daemon.ts +++ b/pkgs/mcpx/plugin/opencode/mcpx/daemon.ts @@ -43,7 +43,7 @@ import { readdirSync, readFileSync, statSync } from "node:fs"; import { homedir, tmpdir } from "node:os"; import { join } from "node:path"; -import { DaemonOps, OpError } from "./ops.gen.ts"; +import { DaemonOps, OPERATION_FINGERPRINT, OpError } from "./ops.gen.ts"; /** * Every tunable in one place. @@ -394,7 +394,12 @@ export const withDaemonAuth = (init: RequestInit): RequestInit => { * path for both transports and no hand-rolled HTTP. */ export class DaemonClient { - constructor(readonly target: Target) {} + readonly ops: DaemonOps; + private operationCompatibility?: Promise; + + constructor(readonly target: Target) { + this.ops = new DaemonOps((path, init) => this.operationFetch(path, init)); + } /** * Every /v1 operation as a typed method, generated from the table the @@ -403,7 +408,31 @@ export class DaemonClient { * surface, so nothing the daemon serves is reachable only through a * hand-built URL. */ - readonly ops: DaemonOps = new DaemonOps((path, init) => this.raw(path, init)); + private async operationFetch(path: string, init: RequestInit): Promise { + await this.assertOperationCompatibility(); + return this.raw(path, init); + } + + private assertOperationCompatibility(): Promise { + this.operationCompatibility ??= this.verifyOperationCompatibility().catch((error: unknown) => { + this.operationCompatibility = undefined; + throw error; + }); + return this.operationCompatibility; + } + + private async verifyOperationCompatibility(): Promise { + const health = await this.health(); + if (!health) { + throw new Error("mcpx: cannot verify /v1 operation compatibility because the daemon health endpoint did not answer; update or restart the mcpx daemon and plugin"); + } + if (typeof health.operationFingerprint !== "string" || health.operationFingerprint.length === 0) { + throw new Error("mcpx: cannot verify /v1 operation compatibility because the daemon does not publish an operation fingerprint; update and restart the mcpx daemon before using generated plugin operations"); + } + if (health.operationFingerprint !== OPERATION_FINGERPRINT) { + throw new Error(`mcpx: /v1 operation table mismatch (plugin ${OPERATION_FINGERPRINT}, daemon ${health.operationFingerprint}); update the mcpx plugin and daemon from matching versions`); + } + } private url(path: string): string { // Any host works over a socket; the dispatcher ignores it. @@ -470,7 +499,7 @@ export class DaemonClient { */ async health( timeoutMs = TUNING.healthTimeoutMs, - ): Promise<{ status: string; version?: string; pid?: number; uptime?: string; endpoint?: string } | undefined> { + ): Promise<{ status: string; version?: string; pid?: number; uptime?: string; endpoint?: string; operationFingerprint?: string } | undefined> { try { return await this.get("/v1/health", timeoutMs); } catch { @@ -747,6 +776,7 @@ export class DaemonClient { /** What /v1/status answers, as much of it as discovery cares about. */ export type DaemonStatus = { version?: string; + operationFingerprint?: string; pid?: number; uptime?: string; endpoint?: string; diff --git a/pkgs/mcpx/plugin/opencode/mcpx/ops.gen.ts b/pkgs/mcpx/plugin/opencode/mcpx/ops.gen.ts index cb852e92a2..204d47c8ff 100644 --- a/pkgs/mcpx/plugin/opencode/mcpx/ops.gen.ts +++ b/pkgs/mcpx/plugin/opencode/mcpx/ops.gen.ts @@ -20,6 +20,8 @@ type OpSpec = { response: "json" | "response" } +export const OPERATION_FINGERPRINT = "0ac07ddbbc06f9c28a106e4e26d701a31e6cfaa37b17646b7911f165acb0af2e" + /** Every /v1 operation, by name. */ export const OPS: Record = { adapters_add: { diff --git a/pkgs/mcpx/plugin/opencode/mcpx/ops.test.ts b/pkgs/mcpx/plugin/opencode/mcpx/ops.test.ts index a4c0099ee4..6f4dc360f1 100644 --- a/pkgs/mcpx/plugin/opencode/mcpx/ops.test.ts +++ b/pkgs/mcpx/plugin/opencode/mcpx/ops.test.ts @@ -18,7 +18,7 @@ import { tmpdir } from "node:os" import { join } from "node:path" import { DaemonClient, renderExec } from "./daemon.ts" -import { buildRequest, OpError, OPS } from "./ops.gen.ts" +import { buildRequest, OPERATION_FINGERPRINT, OpError, OPS } from "./ops.gen.ts" type Seen = { method: string; path: string; type: string | null; body: Uint8Array } @@ -36,6 +36,12 @@ const fake = (reply: (s: Seen) => Response = () => Response.json({ ok: true })) unix: socket, async fetch(req) { const url = new URL(req.url) + // Every generated operation first verifies the daemon's operation-table + // fingerprint. Answer that handshake without recording it, so `seen` + // stays the list of operations the test is asserting about. + if (url.pathname === "/v1/health") { + return Response.json({ status: "ok", operationFingerprint: OPERATION_FINGERPRINT }) + } const s: Seen = { method: req.method, path: url.pathname + url.search,