import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"; import { z } from "zod"; import docs from "../docs/workflows.md"; import { repoNames } from "./identity"; import { findPipeline, findRun } from "./notify"; import { getPipeline, getWorkflowDefinition, listWorkflowDefinitions, queryPipelines, } from "./pipelines"; import type { Store } from "./store"; import { rateLimit } from "./xrpc"; import { csi } from "./logs"; const sections = docs.split(/\n(?=## )/); function searchDocs(query: string): string { if (query.trim() === "") { return sections .map((section) => section.slice(section.indexOf(" ") + 1, section.indexOf("\n"))) .join("\n"); } const words = query.toLowerCase().split(/\s+/).filter(Boolean); const found = sections.filter((section) => words.some((word) => section.toLowerCase().includes(word)), ); return found.length > 0 ? found.join("\n") : `No section matches "${query}".`; } function text(value: Record) { return { content: [{ type: "text" as const, text: JSON.stringify(value) }], structuredContent: value, }; } async function listRepos( env: Env, store: DurableObjectStub, ): Promise<{ repos: { did: string; name?: string }[] }> { const [dids, names] = await Promise.all([ store.listRepos(), repoNames(env.OWNER_DID).catch((error: unknown) => { console.warn("no repo names", error); return new Map(); }), ]); return { repos: dids.map((did) => { const name = names.get(did); return name === undefined ? { did } : { did, name }; }), }; } const repo = z .string() .regex(/^did:/, "repo must be a DID") .describe("DID of the repo, from list_repos"); const pipeline = z.string().describe("pipeline id"); const annotations = { readOnlyHint: true }; const pipelineView = z.looseObject({ id: z.string(), repo: z.string(), commit: z.string(), createdAt: z.string(), trigger: z.looseObject({ $type: z.string(), ref: z.string().optional() }), workflows: z.array( z.looseObject({ name: z.string(), status: z.enum([ "pending", "blocked", "running", "failed", "timeout", "cancelled", "success", ]), startedAt: z.string().optional(), finishedAt: z.string().optional(), error: z.string().optional(), }), ), }); export async function mcp(request: Request, env: Env, ctx: ExecutionContext): Promise { const server = new McpServer( { name: "treadle", version: "0.1.0" }, { instructions: "treadle runs the CI pipelines of the Tangled repos of one owner. Call list_repos first to get the DID that the other tools take as repo.", }, ); const store = ctx.exports.Store.getByName("main"); server.registerTool( "list_repos", { description: "List the Tangled repos that have CI pipelines, with their DIDs and names.", outputSchema: { repos: z.array( z.object({ did: z.string(), name: z .string() .optional() .describe("owner handle/repo name, missing when unknown"), }), ), }, annotations, }, async () => { await rateLimit(request, env.LOG_LIMIT); return text(await listRepos(env, store)); }, ); server.registerTool( "list_pipelines", { description: "List the CI pipelines of a repo, newest first.", inputSchema: { repo, limit: z.number().int().min(1).max(250).optional().describe("default 50"), cursor: z .string() .optional() .describe("the cursor that the previous page returned"), commits: z.array(z.string()).optional().describe("full commit SHAs"), }, outputSchema: { cursor: z.string().optional().describe("missing on the last page"), total: z.number().describe("the number of pipelines that match"), pipelines: z.array(pipelineView), }, annotations, }, async (args) => text(await queryPipelines(args, store)), ); server.registerTool( "get_pipeline", { description: "Get one CI pipeline and the status of its workflows.", inputSchema: { repo, pipeline }, outputSchema: pipelineView, annotations, }, async (args) => text(await getPipeline(args, store)), ); server.registerTool( "list_workflows", { description: "List the CI workflow definitions of a repo at a ref (default HEAD).", inputSchema: { repo, ref: z.string().optional() }, annotations, }, async (args) => { await rateLimit(request, env.LOG_LIMIT); return text(await listWorkflowDefinitions(args, env)); }, ); server.registerTool( "get_workflow", { description: "Get one CI workflow definition of a repo at HEAD.", inputSchema: { repo, workflow: z.string().describe("workflow file name") }, annotations, }, async (args) => { await rateLimit(request, env.LOG_LIMIT); return text(await getWorkflowDefinition(args, env)); }, ); server.registerTool( "get_log", { description: "Read the log of one workflow run as lines. For engine: buildkite runs, returns the Buildkite build URL in place of log lines.", inputSchema: { repo, pipeline, workflow: z.string().describe("workflow file name"), step: z .number() .int() .min(0) .optional() .describe("only this step, from 0: 0 is the checkout, then the steps in order"), tail: z .number() .int() .min(1) .max(5000) .default(500) .describe( "number of last lines, of the selected step or else of the whole run", ), timestamps: z .boolean() .default(false) .describe( "start each line with its UTC time: the Buildkite timestamp in the line, or the time that treadle read it from the container, to about 5 s", ), }, outputSchema: { lines: z .array(z.string()) .optional() .describe("the log of an engine: cloudflare run"), url: z .string() .optional() .describe("the Buildkite build of an engine: buildkite run"), message: z.string().optional().describe("set when there are no lines"), }, annotations, }, async (args) => { await rateLimit(request, env.LOG_LIMIT); const run = findRun(await findPipeline(store, args.repo, args.pipeline), args.workflow); if (run.runner !== null) { const runner = ctx.exports.Runner.getByName(run.runner); const lines = await runner.readLog( args.pipeline, args.step, args.tail, args.timestamps, ); return text({ lines: lines.map((line) => line.replace(csi, "")) }); } return text( run.build_number === null ? { message: "The run has no Buildkite build." } : { url: `https://buildkite.com/${run.bk_org}/${run.bk_pipeline}/builds/${run.build_number}`, message: "The log of an engine: buildkite run is on Buildkite.", }, ); }, ); server.registerTool( "docs", { description: "Search the docs of the treadle CI workflow file format. Returns the matching sections, or the section titles for an empty query.", inputSchema: { query: z.string().default("") }, annotations, }, ({ query }) => ({ content: [{ type: "text", text: searchDocs(query) }] }), ); const transport = new WebStandardStreamableHTTPServerTransport({ enableJsonResponse: true }); await server.connect(transport); return await transport.handleRequest(request); }