peppa/packages/mcp/src/index.ts
2026-11-14 06:28:53 +05:00

235 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Peppa MCP server: gives Claude sessions inside a project access to its epics, stories
// (tasks in the tool names) and the PM. Runs over stdio; the project defaults to the repo's .peppa/project.json.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
askPm,
createTask,
findProjectFile,
getIncident,
getAutonomy,
getProject,
getTaskDetails,
incidentStatuses,
listIncidents,
listEpics,
listTasks,
blockedLabel,
blockersMap,
epicProgress,
progressLabel,
setDependencies,
loadSharedRules,
PeppaError,
reportProgress,
resolveTask,
TASK_STATUSES,
updateTask,
} from "@peppa/core";
import { createDb } from "@peppa/db";
import { requestReview, reviewGate } from "@peppa/runner";
import { z } from "zod";
import { formatIncident, formatTask } from "./format.ts";
const db = createDb();
const projectFile = findProjectFile(process.env.PEPPA_PROJECT_DIR ?? process.cwd());
const defaultKey = projectFile?.data.key;
// Set by the runner for sessions it starts; absent for a manual `claude`.
const sessionId = process.env.PEPPA_SESSION_ID ? Number(process.env.PEPPA_SESSION_ID) : undefined;
const server = new McpServer({ name: "peppa", version: "0.1.0" });
type Result = { content: Array<{ type: "text"; text: string }>; isError?: boolean };
function tool<S extends z.ZodRawShape>(
name: string,
description: string,
inputSchema: S,
run: (args: z.infer<z.ZodObject<S>>) => Promise<string>,
) {
server.registerTool(name, { description, inputSchema }, (async (args: z.infer<z.ZodObject<S>>): Promise<Result> => {
try {
return { content: [{ type: "text", text: await run(args) }] };
} catch (e) {
const msg = e instanceof PeppaError ? e.message : `Internal error: ${(e as Error).message}`;
return { content: [{ type: "text", text: msg }], isError: true };
}
}) as never);
}
const taskArg = z
.string()
.describe(`Story key like ${defaultKey ?? "PEP"}-42, or just the number for the current project`);
const projectArg = z
.string()
.optional()
.describe(`Project key or slug; defaults to the current repo's project${defaultKey ? ` (${defaultKey})` : ""}`);
async function projectOrDefault(p?: string) {
const k = p ?? defaultKey;
if (!k) throw new PeppaError("No project given and no .peppa/project.json found in this repo");
return getProject(db, k);
}
tool(
"get_rules",
"Get Peppa's shared agent rules (story workflow on OpenSpec, PM approval, when to ask the PM). Sessions started by Peppa already have them in the system prompt; call this in a manually started session.",
{},
async () => (await loadSharedRules()).text,
);
tool("get_task", "Get a Peppa story (one business story = one OpenSpec change): description, epic, status, OpenSpec change, PM Q&A and the next step to take. Call this first when the user names a story number.", { task: taskArg }, async ({ task }) =>
formatTask(await getTaskDetails(db, await resolveTask(db, task, defaultKey))),
);
tool(
"list_tasks",
"List stories in a project in board order (top = highest priority), optionally filtered by status or epic; \"waits for\" marks stories blocked by unfinished predecessors.",
{ project: projectArg, status: z.enum(TASK_STATUSES).optional(), epic_id: z.number().int().optional(), goal_id: z.number().int().optional().describe("Alias of epic_id") },
async ({ project, status, epic_id, goal_id }) => {
const p = await projectOrDefault(project);
const rows = await listTasks(db, { projectId: p.id, goalId: epic_id ?? goal_id, statuses: status ? [status] : undefined });
if (!rows.length) return "No stories.";
const deps = await blockersMap(db, p.id);
return rows.map((t) => {
const b = blockedLabel(deps.get(t.id))?.replace("ждёт", "waits for");
return `- ${t.key} [${t.status}]${t.goalId ? ` (epic #${t.goalId})` : ""} ${t.title}${b ? ` — ${b}` : ""}`;
}).join("\n");
},
);
const listEpicsText = async ({ project }: { project?: string }) => {
const p = await projectOrDefault(project);
const rows = await listEpics(db, p.id);
if (!rows.length) return "No open epics.";
const progress = await epicProgress(db, p.id);
return rows.map((g) => `- #${g.id} ${g.title} (done ${progressLabel(progress.get(g.id))})${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n");
};
tool("list_epics", "List the open epics of a project (labels that group stories).", { project: projectArg }, listEpicsText);
tool("list_goals", "Alias of list_epics (goals were renamed to epics).", { project: projectArg }, listEpicsText);
tool(
"create_task",
"Create a new story (e.g. follow-up work discovered outside the current change's scope). Label it with an epic when one fits.",
{
title: z.string().min(3),
description: z.string().optional(),
epic_id: z.number().int().optional(),
goal_id: z.number().int().optional().describe("Alias of epic_id"),
blocked_by: z.array(z.string()).optional().describe("Stories this one waits for (keys); it won't be started automatically until they are in review/done"),
project: projectArg,
},
async ({ title, description, epic_id, goal_id, blocked_by, project }) => {
const p = await projectOrDefault(project);
const ref = await createTask(db, { projectId: p.id, goalId: epic_id ?? goal_id, title, description });
const deps = blocked_by?.length ? await setDependencies(db, ref, blocked_by).catch((e: Error) => { throw new PeppaError(`Created ${ref.key}, but dependencies were not set: ${e.message}`); }) : [];
return `Created ${ref.key}: ${title}${deps.length ? ` (waits for ${deps.map((d) => d.key).join(", ")})` : ""}`;
},
);
tool(
"update_task",
"Update a story's status, OpenSpec change name, PR URL, title or description.",
{
task: taskArg,
status: z.enum(TASK_STATUSES).optional(),
openspec_change: z.string().optional().describe("Change id under openspec/changes/, e.g. pep-42-add-auth"),
pr_url: z.string().url().optional(),
title: z.string().optional(),
description: z.string().optional(),
},
async ({ task, status, openspec_change, pr_url, title, description }) => {
const ref = await resolveTask(db, task, defaultKey);
// Acceptance stays with the PM: agents can't mark work done or approve themselves.
if (status === "done") throw new PeppaError("Only the PM marks a story done. Open a PR and set status: review.");
if (status === "in_progress" && ref.task.status === "awaiting_approval") {
throw new PeppaError("The proposal is awaiting the PM's approval; only the PM can move it to in_progress.");
}
// PEP-23: a project where the PM approves every proposal — Apply only after the approval
// (the PM's answer moves the story to in_progress itself).
if (status === "in_progress" && (ref.task.status === "backlog" || ref.task.status === "proposing") && (await getAutonomy(db, ref.project.id)).proposal === "pm") {
throw new PeppaError("In this project the PM approves every proposal: call request_approval with the proposal summary and end your turn.");
}
if (status === "review" && ref.task.status !== "review") {
// PEP-57: review only with green checks of the PR head (the PR given now counts).
const reason = await reviewGate({ ...ref, task: { ...ref.task, prUrl: pr_url ?? ref.task.prUrl } });
if (reason) {
throw new PeppaError(`Not moved to review: ${reason}. Wait for the CI checks of the PR's last commit to pass (red ones come back to you with the log), then set status: review again.`);
}
}
if (status === "review" && ref.task.status !== "review") {
// PEP-26: the project's reviewer agent reads the diff before the PM (when turned on).
const withPr = { ...ref, task: { ...ref.task, prUrl: pr_url ?? ref.task.prUrl } };
const r = await requestReview(db, withPr).catch(() => ({ action: "review" as const }));
if (r.action === "queued") {
await updateTask(db, ref, { openspecChange: openspec_change, prUrl: pr_url, title, description }, sessionId);
return `${ref.key}: the reviewer agent is checking PR commit ${r.review.sha.slice(0, 7)} (review #${r.review.id}); the story stays in_progress. End your turn now — findings come back to you as a message; if the review is fine the story goes to the PM's review by itself.`;
}
}
const t = await updateTask(db, ref, { status, openspecChange: openspec_change, prUrl: pr_url, title, description }, sessionId);
return `${ref.key} updated: status=${t.status}${t.openspecChange ? `, change=${t.openspecChange}` : ""}${t.prUrl ? `, pr=${t.prUrl}` : ""}`;
},
);
tool(
"request_approval",
"Ask the PM to approve an ARCHITECTURAL decision in a story's proposal (new service/dependency, data model, security/access, money, irreversible actions, scope change). Routine proposals need no approval — go straight to apply. Sets awaiting_approval and notifies the PM; end your turn afterwards.",
{ task: taskArg, summary: z.string().min(10).describe("What, why, risks, open questions — readable on a phone") },
async ({ task, summary }) => {
const ref = await resolveTask(db, task, defaultKey);
const q = await askPm(db, ref, { kind: "approval", text: summary, sessionId });
return `Approval requested (#${q.id}); ${ref.key} is awaiting_approval. End your turn now and wait for the PM's reply.`;
},
);
tool(
"ask_pm",
"Ask the PM about a STOPPER only (scope, architecture, data, money, access/secrets, or a costly-to-undo fork). Decide everything else yourself and record it in design.md. Delivered to Telegram; end your turn afterwards — the answer arrives as the next user message.",
{
task: taskArg,
question: z.string().min(5).describe("One question, 1–2 sentences of context"),
options: z.array(z.string()).max(6).optional().describe("Suggested answers, shown as buttons"),
},
async ({ task, question, options }) => {
const ref = await resolveTask(db, task, defaultKey);
const q = await askPm(db, ref, { kind: "question", text: question, options, sessionId });
return `Question #${q.id} sent to the PM. End your turn now and wait for the answer.`;
},
);
tool(
"report_progress",
"Log a short progress note on a story (visible to the PM in the web UI / Telegram digest).",
{ task: taskArg, text: z.string().min(3) },
async ({ task, text }) => {
const ref = await resolveTask(db, task, defaultKey);
await reportProgress(db, ref, text, sessionId);
return `Progress noted on ${ref.key}.`;
},
);
tool(
"list_incidents",
"List production errors (Bugsink incidents) of a project: id, status, title, where, release, event count, linked story.",
{ project: projectArg, status: z.enum(incidentStatuses).optional() },
async ({ project, status }) => {
const p = await projectOrDefault(project);
const rows = await listIncidents(db, p.id, status ? [status] : undefined);
if (!rows.length) return "No incidents.";
return rows.map((i) => `- #${i.id} [${i.status}] ${i.title}${i.culprit ? ` (${i.culprit})` : ""} · ${i.environment ?? "?"} · release ${i.lastRelease ?? "?"} · ${i.events} events${i.taskId ? ` · story #${i.taskId}` : ""}`).join("\n");
},
);
tool(
"get_incident",
"Get a production error (Bugsink incident): stack top, where, release, environment, frequency, Bugsink link. Use it when fixing a bug story made from an incident: first write a test reproducing this stack.",
{ id: z.number().int() },
async ({ id }) => {
const i = await getIncident(db, id);
if (defaultKey && i.projectId !== (await getProject(db, defaultKey)).id) throw new PeppaError(`Incident #${id} is not in this project`);
return formatIncident(i);
},
);
await server.connect(new StdioServerTransport());