// Peppa MCP server of an agent: gives sessions inside a project access to its epics, stories // (tasks in the tool names) and the PM. Served over stdio (index.ts) or, for agents in a runner // container, over the agent relay (PEP-17) — then locked to the session's project. import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { askPm, createTask, giteaForBot, getIncident, getAutonomy, getProject, getTaskDetails, incidentStatuses, listIncidents, listEpics, listTasks, blockedLabel, blockersMap, epicProgress, progressLabel, setDependencies, loadSharedRules, PeppaError, reportProgress, resolveTask, TASK_STATUSES, updateTask, getSession, listProjectSecrets, MEMORY_FILE, MEMORY_SECTIONS, memoryContext, rememberFact, replaceMemory, } from "@peppa/core"; import type { Db } from "@peppa/db"; import { requestReview, reviewGate, storyBranch } from "@peppa/runner"; import { z } from "zod"; import { formatIncident, formatTask } from "./format.ts"; export interface AgentServerOptions { /** The project of the agent's repo (.peppa/project.json) — default for bare story numbers. */ defaultKey?: string; /** Set for sessions Peppa started; absent for a manual `claude`. */ sessionId?: number; /** PEP-17: refuse stories and projects other than `defaultKey` (agents behind the relay). */ lockProject?: boolean; /** * PEP-30: the repo root of the agent's working copy (where .peppa/project.json lives) — the * project memory is there. null: not reachable from Peppa (a runner on a host, PEP-40). */ repoDir?: string | null; } export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpServer { const server = new McpServer({ name: "peppa", version: "0.1.0" }); const { defaultKey, sessionId } = opts; type Result = { content: Array<{ type: "text"; text: string }>; isError?: boolean }; function tool( name: string, description: string, inputSchema: S, run: (args: z.infer>) => Promise, ) { server.registerTool(name, { description, inputSchema }, (async (args: z.infer>): Promise => { 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"); const project = await getProject(db, k); if (opts.lockProject && project.key !== defaultKey) throw new PeppaError(`Access denied: this agent works only in project ${defaultKey}`); return project; } /** A story of this project (PEP-17: an agent behind the relay can't reach other projects). */ async function resolve(task: string) { const ref = await resolveTask(db, task, defaultKey); if (opts.lockProject && ref.project.key !== defaultKey) throw new PeppaError(`Access denied: ${ref.key} is not in project ${defaultKey}`); return ref; } 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 resolve(task))), ); 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 resolve(task); // 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 resolve(task); 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 resolve(task); 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 resolve(task); 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); }, ); tool( "open_pull_request", "Open a pull request in the project's Gitea repo from the story branch (default task/) to the default branch; returns the PR URL (pass it to update_task as pr_url). Use it when you have no Gitea token (e.g. in a runner container); an already open PR of the branch is returned as is.", { task: taskArg, title: z.string().min(3), body: z.string().optional(), head: z.string().optional().describe("Source branch; default task/") }, async ({ task, title, body, head }) => { const ref = await resolve(task); const branch = head ?? storyBranch(ref.key); const bot = giteaForBot(); const open = await bot.openPullForBranch(ref.project.giteaOwner, ref.project.giteaRepo, branch); const pr = open ?? (await bot.createPullRequest(ref.project.giteaOwner, ref.project.giteaRepo, { head: branch, base: ref.project.defaultBranch, title, body: body ?? `Story ${ref.key}` })); return `${open ? "Already open" : "Opened"}: ${pr.html_url}`; }, ); tool( "list_secrets", "List the names of this project's secrets (API keys and accesses the PM stored in Peppa). They are already in your environment as variables of the same name — use them as $NAME, never print, log or commit their values. Values are not available here. Missing a secret? ask_pm to add it in «⋯ Настройки проекта → Секреты» (the next session start gets it).", {}, async () => { // PEP-54: only the project of this session (or this repo), names only. const p = sessionId ? await getProject(db, (await getSession(db, sessionId)).projectKey) : await projectOrDefault(); const rows = await listProjectSecrets(db, p.id); if (!rows.length) return `${p.key} has no secrets.`; return [`Secrets of ${p.key} (in your env):`, ...rows.map((r) => `- ${r.name}`)].join("\n"); }, ); // ── PEP-30: project memory (.peppa/memory.md in the repo) ───────────────────── const memoryDir = () => { if (!opts.repoDir) { throw new PeppaError( opts.lockProject ? `Project memory is not reachable from Peppa for this runner: edit ${MEMORY_FILE} in your working copy directly and commit it in your story branch` : "No .peppa/project.json found — project memory lives next to it", ); } return opts.repoDir; }; tool( "get_memory", `Read the project memory (${MEMORY_FILE}: commands, conventions, pitfalls, decisions written by earlier agents) and a digest of the last finished stories. Runner sessions already get it in the system prompt.`, {}, async () => { const dir = memoryDir(); const project = await projectOrDefault(); return memoryContext(db, project.id, dir); }, ); tool( "remember", `Add one durable fact to the project memory (${MEMORY_FILE}) for the next agents: a build/test command, a convention, a pitfall you hit, a decision. One short line; duplicates are skipped. With replace: true, \`text\` becomes the whole memory (use it to compact when the size limit is near). Commit the file in your story branch.`, { section: z.string().optional().describe(`One of: ${MEMORY_SECTIONS.join(", ")} (or commands, conventions, pitfalls, decisions). Not needed with replace.`), text: z.string().describe("The fact (one line), or the whole memory with replace: true"), replace: z.boolean().optional(), }, async ({ section, text, replace }) => { const dir = memoryDir(); if (replace) { const st = replaceMemory(dir, text); return `Память переписана: ${st.chars} из ${st.max} символов. Закоммить ${MEMORY_FILE} в ветке стори.`; } const r = rememberFact(dir, section ?? "", text); if (r.result === "exists") return "Такой пункт уже есть — ничего не изменил."; return `Запомнил. Память: ${r.stats.chars} из ${r.stats.max} символов${r.stats.nearLimit ? " — почти предел, ужми (remember с replace: true)" : ""}. Закоммить ${MEMORY_FILE} в ветке стори.`; }, ); return server; }