peppa/packages/mcp/src/agent.ts
2026-11-16 13:30:26 +05:00

411 lines
24 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 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 { m as tr } from "@peppa/shared/i18n";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import {
askPm,
alertAdmins,
checkChoices,
reportBlocker,
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,
declareNeeds,
ensureProjectChat,
needsText,
productOnlySecret,
} from "@peppa/core";
import type { Db } from "@peppa/db";
import { requestReview, reviewGate, sayInDiscussion, storyBranch } from "@peppa/runner";
import { z } from "zod";
import { m } from "@peppa/shared/i18n";
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<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");
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",
"Only for projects where the PM approves every proposal (get_task says so). Elsewhere the PM is a product person, not an engineer, and approves nothing technical: decide yourself, record the decision in design.md, go on to apply — this call is refused there.",
{ 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);
// PEP-94: the PM doesn't approve technical decisions unless the project asks for it.
if ((await getAutonomy(db, ref.project.id)).proposal !== "pm") {
throw new PeppaError("Not sent: in this project the PM doesn't approve proposals or technical decisions. Decide yourself, write what you chose and why in design.md (and `remember` it), set status: in_progress and apply in this turn.");
}
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.`;
},
);
// PEP-149: four kinds of messages to the owner — question (here), done (Peppa sends it itself
// after green checks), progress (report_progress), blocker (report_blocker).
const optionsArg = z.array(z.string()).optional().describe("2–4 possible answers, shown to the owner as buttons");
const defaultArg = z.string().optional().describe("Your recommendation — exactly one of `options`; you go on with it while the owner has not answered");
tool(
"ask_pm",
"Ask the owner a PRODUCT question — the ONLY kind of message that reaches their «Ждут вашего ответа» and Telegram. What users see or get, business terms, a secret/account only they can provide — in plain words for a non-engineer. NEVER technical (stack, libraries, architecture, data model, CI, git, runners, tests, permissions): decide those yourself and record them in design.md. REQUIRED: `options` (2–4 answers as buttons) and `default` (your recommendation, one of the options) — without them the call is refused. Don't wait: keep working with your default in this turn; the owner's answer arrives later as a message, and you adjust if it differs.",
{
task: taskArg,
question: z.string().min(5).describe("One product question in plain words, 1–2 sentences of context, no jargon"),
options: optionsArg,
default: defaultArg,
},
async ({ task, question, options, default: def }) => {
const ref = await resolve(task);
const c = checkChoices(options, def);
const q = await askPm(db, ref, { kind: "question", msgType: "question", text: question, options: c.options, defaultOption: c.defaultOption, sessionId });
return `Question #${q.id} sent to the owner. Don't wait for the answer: continue with «${c.defaultOption}» now (note it in design.md); if the owner answers differently, the answer arrives as a message and you adjust.`;
},
);
tool(
"report_progress",
"Log a short progress note on a story. It is a `progress` message: it goes to the story thread in «События агентов» and never wakes the owner (not in «Ждут вашего ответа», not in Telegram). Don't use it to ask for anything.",
{ 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(
"report_blocker",
"Say that you cannot go on with the story: what stops you and what you already tried. Use it only after trying another approach or a mock. A PRODUCT blocker (only the owner can decide or give something: `product: true`) goes to the owner as a question — `options` (2–4) and `default` are required. Any other blocker (access, a broken service, CI, git, a limit) is recorded in the story thread and does NOT go to the owner: Peppa's administrators see it. After the call end your turn — Peppa wakes you when there is something to do.",
{
task: taskArg,
what: z.string().min(5).describe("What stops you, in plain words"),
tried: z.string().min(3).describe("What you already tried"),
product: z.boolean().optional().describe("true: only the owner can unblock it (a product decision, an account or a key only they have)"),
options: optionsArg,
default: defaultArg,
},
async ({ task, what, tried, product, options, default: def }) => {
const ref = await resolve(task);
if (product) {
const c = checkChoices(options, def);
const q = await askPm(db, ref, { kind: "question", msgType: "question", text: what, options: c.options, defaultOption: c.defaultOption, sessionId });
return `Blocker sent to the owner as question #${q.id}. End your turn — the answer arrives as a message.`;
}
const e = await reportBlocker(db, ref, { what, tried }, sessionId);
// Not the owner's business: the administrators of the factory hear about it.
await alertAdmins(db, `blocker:${e.id}`, `⛔ ${ref.key}: ${m("Агент не может продолжить: {what}", { what })}\n${m("Что уже пробовал: {tried}", { tried })}`, () => {}).catch(() => 0);
return `Blocker recorded on ${ref.key} (the owner is not asked about it). End your turn now; Peppa wakes you when there is something to do.`;
},
);
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/<key>) 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/<key in lower case>") },
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.`;
// PEP-112: ANTHROPIC_*/CLAUDE_*/OPENCODE_* go to the deployed product only.
return [`Secrets of ${p.key} (in your env; every one of them also reaches the deployed product as env of the same name):`, ...rows.map((r) => `- ${r.name}${productOnlySecret(r.name) ? " (deployed product only — not in your env)" : ""}`)].join("\n");
},
);
tool(
"declare_needs",
"Declare what the product's OWNER must give before the product works for real instead of on mocks/demo data: an API key, an account, credentials. Call it BEFORE moving the story to review whenever the story needs something only the owner has. The owner (a product manager, not a programmer) gets the list in plain words in the project chat and on the «Ваш продукт» card, with a field to paste each key; an item with `secret` closes itself once the owner stores that secret, and Peppa hands all project secrets to the deployed product as env vars of the same name and restarts it. Write title/why/how in the owner's language, no jargon. Items add up across stories (same secret or title = same item). Returns the whole list with states.",
{
task: taskArg.optional().describe("The story that needs it (for the record)"),
needs: z
.array(
z.object({
title: z.string().describe("What to give, in the owner's words: «Ключ Claude API»"),
why: z.string().optional().describe("What does not work without it, plainly: «без него ответы — вымышленные примеры»"),
how: z.string().optional().describe("Where to get it, step by step for a non-programmer"),
secret: z.string().optional().describe("Env name the product reads it from (A–Z, 0–9, _), e.g. ANTHROPIC_API_KEY. Omit for things that are not a key (the owner ticks them off)"),
}),
)
.min(1)
.max(10),
},
async ({ task, needs }) => {
const ref = task ? await resolve(task) : null;
const session = sessionId ? await getSession(db, sessionId) : null;
const p = ref?.project ?? (session ? await getProject(db, session.projectKey) : await projectOrDefault());
const { added, all } = await declareNeeds(db, p.id, needs, { source: "agent", story: ref?.key ?? null });
if (added.length) {
const chat = await ensureProjectChat(db, p.id);
const text = [tr("Чтобы продукт заработал по-настоящему, а не в демо-режиме, нужно от вас:"), "", needsText(added, process.env.PEPPA_WEB_URL ?? "", p.key)].join("\n");
await sayInDiscussion(db, p, chat.id, text, session?.agentName ? tr("Агент {name}", { name: session.agentName }) : tr("Агент"));
}
const line = (n: (typeof all)[number]) => `- ${n.open ? "⏳ ждёт владельца" : "✅ дано"}: ${n.title}${n.secret ? ` ($${n.secret})` : ""}`;
return [`Список «чтобы заработало по-настоящему» проекта ${p.key}:`, ...all.map(line), added.length ? `Владельцу отправлено сообщение о новых пунктах (${added.length}).` : "Новых пунктов нет — владельцу ничего не отправлено.", "Пока пункт открыт, продукт работает на моке: в резюме PR и в сообщении о готовности так и скажи. Служебных полей (токены, ключи) на экране пользователя быть не должно."].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;
}