Something went wrong. Try again.
Tangled Spindle built on Cloudflare Workers
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331import { runInDurableObject } from "cloudflare:test";import { env, exports } from "cloudflare:workers";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { controlFrame, dataFrame } from "../src/logs";import { declarationsRoute, didDoc, freshRateWindow, pdsService, rateTestTimeout, repoDid as repo, routeFetch, seed,} from "./helpers";
const gone = "did:plc:gggggggggggggggggggggggg";const runner = `${repo}/main/deploy.yml`;const at = "2026-11-06T10:00:00.000Z";const anyString: unknown = expect.any(String);
function step(n: number) { return { step: n, name: `step ${n}`, command: undefined };}
async function call<T>(method: string, params: object, headers: object = {}): Promise<T> { const response = await exports.default.fetch("https://treadle.example.com/mcp", { method: "POST", headers: { Accept: "application/json, text/event-stream", "Content-Type": "application/json", ...headers, }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }), }); expect(response.status).toBe(200); const { result } = await response.json<{ result: T }>(); return result;}
function getPipelineCall(id: number): object { return { jsonrpc: "2.0", id, method: "tools/call", params: { name: "get_pipeline", arguments: { repo, pipeline: "3mcp" } }, };}
async function tool( name: string, args: object, headers: object = {},): Promise<{ text: string; isError?: boolean }> { const result = await call<{ content: [{ text: string }]; structuredContent?: unknown; isError?: boolean; }>("tools/call", { name, arguments: args }, headers); if (result.isError !== true && name !== "docs") { expect(result.structuredContent, name).toEqual(JSON.parse(result.content[0].text)); } return { text: result.content[0].text, ...(result.isError === true ? { isError: true } : {}) };}
beforeEach(async () => { await runInDurableObject(exports.Store.getByName("main"), async (_instance, state) => { seed(state.storage, [ { rkey: "3mcp", repo, trigger: { $type: "org.tangled.event.push", repo, ref: "refs/heads/main", oldSha: "0".repeat(40), newSha: "a".repeat(40), }, commit: "a".repeat(40), createdAt: at, runs: [ { workflow: "ci.yml", status: "running", buildUuid: "u", buildNumber: 7 }, { workflow: "deploy.yml", status: "success", startedAt: at, finishedAt: at }, { workflow: "lint.yml", status: "pending" }, ], }, ]); state.storage.sql.exec( "UPDATE workflow_runs SET engine = 'cloudflare', runner = ? WHERE workflow = 'deploy.yml'", runner, ); await state.storage.deleteAlarm(); }); await runInDurableObject(exports.Runner.getByName(runner), (_instance, state) => { state.storage.sql.exec("DELETE FROM frames"); for (const [pipeline, frame] of [ ["3mcp", controlFrame("deploy.yml", step(1), "start", at)], ["3mcp", dataFrame("deploy.yml", 1, "one\n", at)], ["3other", dataFrame("deploy.yml", 1, "other\n", at)], ["3mcp", controlFrame("deploy.yml", step(1), "end", at, "success")], ["3mcp", dataFrame("deploy.yml", 2, "two\n", at)], ["3mcp", dataFrame("deploy.yml", 2, "\u001b[1;31mthree\u001b[0m \u001b[2Kok\n", at)], ] as const) { state.storage.sql.exec( "INSERT INTO frames (pipeline, frame) VALUES (?, ?)", pipeline, frame, ); } });});
afterEach(async () => { await runInDurableObject(exports.Store.getByName("main"), (_instance, state) => state.storage.deleteAlarm(), );});
describe("mcp", () => { it("lists read-only tools and tells clients to start with list_repos", async () => { const { instructions } = await call<{ instructions: string }>("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "test", version: "1" }, }); expect(instructions).toContain("list_repos"); const { tools } = await call<{ tools: { name: string; annotations?: { readOnlyHint?: boolean }; outputSchema?: object; }[]; }>("tools/list", {}); expect(tools.map((t) => t.name)).toEqual([ "list_repos", "list_pipelines", "get_pipeline", "list_workflows", "get_workflow", "get_log", "docs", ]); expect(tools.filter((t) => t.outputSchema !== undefined).map((t) => t.name)).toEqual([ "list_repos", "list_pipelines", "get_pipeline", "get_log", ]); for (const t of tools) { expect(t.annotations?.readOnlyHint, t.name).toBe(true); } });
it("lists the repos with pipelines, named by the owner's declarations", async () => { const owner = env.OWNER_DID;
routeFetch({ [`GET https://plc.directory/${owner}`]: () => Response.json({ ...didDoc(owner, undefined, [pdsService]), alsoKnownAs: ["at://owner.example.com"], }), [declarationsRoute(owner)]: () => Response.json({ records: [ { uri: `at://${owner}/org.tangled.repo.declaration/treadle`, value: { repo, createdAt: at }, }, { uri: `at://${owner}/org.tangled.repo.declaration/idle`, value: { repo: "did:plc:iiiiiiiiiiiiiiiiiiiiiiii", createdAt: at }, }, ], }), }); await runInDurableObject(exports.Store.getByName("main"), (_instance, state) => { state.storage.sql.exec( `INSERT INTO pipelines (rkey, repo, trigger, commit_sha, branch, created_at) VALUES ('3gone', ?, '{}', ?, 'main', ?)`, gone, "b".repeat(40), at, ); }); const result = await tool("list_repos", {}); expect(result.isError).toBeUndefined(); expect(JSON.parse(result.text)).toEqual({ repos: [{ did: gone }, { did: repo, name: "owner.example.com/treadle" }], }); });
it("returns the docs sections that match a query, or the list of sections", async () => { const intro = await tool("docs", { query: ".tangled/workflows" }); expect(intro.text).toMatch(/^# treadle workflows\n/); const { text } = await tool("docs", { query: "snapshots" }); expect(text).toMatch(/^## Cache and snapshots\n/); expect(text).not.toContain("## Engines\n"); const list = await tool("docs", {}); expect(list.text.split("\n")).toEqual( expect.arrayContaining(["treadle workflows", "Engines", "Triggers"]), ); expect((await tool("docs", { query: "zzz" })).text).toContain("No section"); });
it("reads pipelines and logs", async () => { const list = await tool("list_pipelines", { repo, limit: 1, commits: ["a".repeat(40)], }); expect(JSON.parse(list.text)).toMatchObject({ pipelines: [ { workflows: [ { status: "running" }, { status: "success" }, { status: "pending" }, ], }, ], }); const log = async (args: object) => JSON.parse( (await tool("get_log", { repo, pipeline: "3mcp", ...args })).text, ) as unknown; expect(await log({ workflow: "deploy.yml" })).toEqual({ lines: ["--- step 1: step 1", "one", "--- step 1: step 1 (success)", "two", "three ok"], }); expect(await log({ workflow: "deploy.yml", step: 2, tail: 1 })).toEqual({ lines: ["three ok"], }); expect(await log({ workflow: "deploy.yml", step: 2, tail: 1, timestamps: true })).toEqual({ lines: [`${at} three ok`], }); expect(await log({ workflow: "ci.yml" })).toEqual({ url: "https://buildkite.com/gpanders/treadle/builds/7", message: anyString, }); expect(await log({ workflow: "lint.yml" })).toEqual({ message: anyString }); expect(await tool("get_log", { repo, pipeline: "3mcp", workflow: "x.yml" })).toEqual({ text: "x.yml is not a workflow of 3mcp", isError: true, }); const name = await tool("get_log", { repo: "owner.example.com/treadle", pipeline: "3mcp", workflow: "ci.yml", }); expect(name.isError).toBe(true); expect(name.text).toContain("DID"); expect(await tool("get_log", { repo, pipeline: "3nope", workflow: "ci.yml" })).toEqual({ text: `3nope is not a pipeline of ${repo}`, isError: true, }); });
it( "limits each client IP to 20 reads of logs and workflows a minute", { timeout: rateTestTimeout }, async () => { await freshRateWindow(); const args = { repo, pipeline: "3mcp", workflow: "ci.yml" }; const ip = { "CF-Connecting-IP": "203.0.113.9" }; const allowed = await Promise.all( Array.from({ length: 20 }, () => tool("get_log", args, ip)), ); expect(allowed.filter((result) => result.isError === true)).toEqual([]); const limited = { text: "too many requests", isError: true }; expect(await tool("get_log", args, ip)).toEqual(limited); expect(await tool("list_workflows", { repo }, ip)).toEqual(limited); expect(await tool("get_workflow", { repo, workflow: "ci.yml" }, ip)).toEqual(limited); expect( (await tool("get_log", args, { "CF-Connecting-IP": "203.0.113.10" })).isError, ).toBeUndefined(); }, );
it( "limits each client IP to 120 requests a minute, and counts a batch once", { timeout: rateTestTimeout }, async () => { await freshRateWindow(); const ip = { "CF-Connecting-IP": "203.0.113.42" }; const post = (body: unknown) => exports.default.fetch("https://treadle.example.com/mcp", { method: "POST", headers: { Accept: "application/json, text/event-stream", "Content-Type": "application/json", ...ip, }, body: JSON.stringify(body), }); const batch = await post(Array.from({ length: 100 }, (_, i) => getPipelineCall(i))); expect(batch.status).toBe(200); expect(await batch.json()).toHaveLength(100); const allowed = await Promise.all( Array.from({ length: 119 }, () => post(getPipelineCall(1))), ); expect(allowed.map((response) => response.status)).toEqual(Array(119).fill(200)); const limited = await post(getPipelineCall(1)); expect(limited.status).toBe(429); expect(await limited.json()).toMatchObject({ error: "RateLimitExceeded" }); }, );
it("lists repos without names when the owner's PDS fails", async () => { vi.spyOn(globalThis, "fetch").mockImplementation(() => Promise.resolve(new Response("down", { status: 500 })), ); expect(JSON.parse((await tool("list_repos", {})).text)).toEqual({ repos: [{ did: repo }] }); });
it("rejects non-POST requests with 405", async () => { const response = await exports.default.fetch("https://treadle.example.com/mcp", { headers: { Accept: "text/event-stream" }, }); expect(response.status).toBe(405); expect(response.headers.get("allow")).toBe("POST"); });
it("gets a pipeline, or a tool error for an unknown one", async () => { expect( JSON.parse((await tool("get_pipeline", { repo, pipeline: "3mcp" })).text), ).toMatchObject({ id: "3mcp" }); const result = await tool("get_pipeline", { repo, pipeline: "3nope" }); expect(result.isError).toBe(true); expect(result.text).toContain("3nope"); });});