Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 40 additions & 1 deletion .opencode/plugin/mcpx/daemon.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -69,6 +70,8 @@ type FakeOptions = {
config?: string;
version?: string;
servers?: number;
operationFingerprint?: string;
missingOperationFingerprint?: boolean;
};

const serveFake = (socket: string, opts: FakeOptions = {}): Fake => {
Expand All @@ -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,
Expand All @@ -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 });
},
});
Expand All @@ -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();
Expand Down
38 changes: 34 additions & 4 deletions .opencode/plugin/mcpx/daemon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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<void>;

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
Expand All @@ -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<Response> {
await this.assertOperationCompatibility();
return this.raw(path, init);
}

private assertOperationCompatibility(): Promise<void> {
this.operationCompatibility ??= this.verifyOperationCompatibility().catch((error: unknown) => {
this.operationCompatibility = undefined;
throw error;
});
return this.operationCompatibility;
}

private async verifyOperationCompatibility(): Promise<void> {
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.
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
Expand Down
2 changes: 2 additions & 0 deletions .opencode/plugin/mcpx/ops.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ type OpSpec = {
response: "json" | "response"
}

export const OPERATION_FINGERPRINT = "0ac07ddbbc06f9c28a106e4e26d701a31e6cfaa37b17646b7911f165acb0af2e"

/** Every /v1 operation, by name. */
export const OPS: Record<string, OpSpec> = {
adapters_add: {
Expand Down
8 changes: 7 additions & 1 deletion .opencode/plugin/mcpx/ops.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }

Expand All @@ -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,
Expand Down
13 changes: 13 additions & 0 deletions pkgs/mcpx/internal/api/ops_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package api_test

import (
"encoding/hex"
"encoding/json"
"strings"
"testing"
Expand All @@ -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
Expand Down
62 changes: 61 additions & 1 deletion pkgs/mcpx/internal/api/plugin_ts.go
Original file line number Diff line number Diff line change
@@ -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.
//
Expand Down Expand Up @@ -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<string, OpSpec> = {
`)
for _, op := range ops {
Expand Down
14 changes: 8 additions & 6 deletions pkgs/mcpx/internal/daemon/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
})
}

Expand All @@ -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.
Expand Down
41 changes: 40 additions & 1 deletion pkgs/mcpx/plugin/opencode/mcpx/daemon.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -69,6 +70,8 @@ type FakeOptions = {
config?: string;
version?: string;
servers?: number;
operationFingerprint?: string;
missingOperationFingerprint?: boolean;
};

const serveFake = (socket: string, opts: FakeOptions = {}): Fake => {
Expand All @@ -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,
Expand All @@ -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 });
},
});
Expand All @@ -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();
Expand Down
Loading