peppa/packages/mcp/src/manager.ts
Асель 59c3b583de PEP-57: CD — deploy workflow, preview/staging/prod, health check and rollback, releases
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 14:49:24 +05:00

401 lines
22 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.

// PM-side MCP tools for remote clients (ChatGPT connectors etc.), scoped to one Peppa
// user's projects. Served over HTTP by the web app at /mcp; agents keep the stdio server.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import {
createGoal,
createTask,
getGoal,
giteaForUser,
updateGoal,
getProject,
getQuestion,
getTaskDetails,
listGoals,
listMembers,
listTasks,
listUserProjects,
PeppaError,
projectForUser,
repoAudience,
repoVisibilityLabel,
resolveTask,
updateTask,
userProjectIds,
getIncident,
getIncidentSettings,
incidentPolicies,
incidentStatuses,
listIncidents,
POLICY_RU,
updateIncidentSettings,
type User,
} from "@peppa/core";
import { questions, projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey, loadEnv } from "@peppa/shared";
import { currentReleases, deployProd, listReleases, decideIncident, resolveIncident, acceptTask, answerAndDeliver, columnOf, describeRepo, isReviewQuestion, moveTask, provisionProject, shareProject, unshareProject, type BoardColumn, type Provider } from "@peppa/runner";
import { and, asc, eq, inArray, isNull } from "drizzle-orm";
import { z } from "zod";
import { formatIncident, formatTask } from "./format.ts";
type Result = { content: Array<{ type: "text"; text: string }>; isError?: boolean };
const COLUMNS = ["backlog", "in_progress", "review", "done"] as const;
const COLUMN_NAME: Record<BoardColumn, string> = { backlog: "Бэклог", in_progress: "В работе", review: "Ревью", done: "Готово" };
/** Sent to clients on initialize: how Peppa is organised and how to use the tools. */
export const MANAGER_INSTRUCTIONS = `Peppa is a software factory: AI agents (Claude Code / Codex) implement tasks in Gitea repos, following OpenSpec.
Model: project (a Gitea repo, key like PEP) → goals (top-level objectives) → tasks (PEP-12, one deliverable each) → board columns Backlog / In progress / Review / Done.
- Moving a task to in_progress starts an agent on it; the agent writes an OpenSpec proposal, implements it, opens a PR and moves the task to review. backlog/done stop the agent.
- Agents only ask the user about architectural stoppers; those questions and "ready for review" messages are in the inbox (list_inbox → answer_question; answer "accept" to close a reviewed task).
Good habits:
- Before creating, look: list_projects, list_goals, list_tasks. Don't duplicate — fix with update_task / update_goal.
- Put tasks under a goal (goal_id). Write task descriptions with context and a "Definition of done" list; the agent works from them.
- Only move a task to in_progress when the user asks to start the work.
- Statuses: get_task for details, list_tasks for the board, list_inbox for what needs the user.
- Projects can be shared: add_member / remove_member (owner only); members can do everything else.
- CI/CD: every PR is checked (get_task shows the checks; red ones go back to the agent; "accept" merges the PR only when they are green). A merge deploys to staging; list_releases shows what runs where; deploy puts the healthy staging release into prod — only when the user asks.
- Production errors (Bugsink) arrive as incidents: list_incidents. What happens to a new one is the project's incident policy (get_incident_policy / set_incident_policy: notify, backlog — default, start, ask, triage with the user's mini-prompt). Pending ones wait for decide_incident (backlog / start / ignore); resolve_incident marks one fixed.`;
export function createManagerServer(db: Db, user: User, webUrl: string): McpServer {
const server = new McpServer({ name: "peppa", version: "0.3.0" }, { instructions: MANAGER_INSTRUCTIONS });
function tool<S extends z.ZodRawShape>(name: string, description: string, inputSchema: S, readOnly: boolean, run: (a: z.infer<z.ZodObject<S>>) => Promise<string>) {
server.registerTool(name, { description, inputSchema, annotations: { readOnlyHint: readOnly, openWorldHint: false } }, (async (a: z.infer<z.ZodObject<S>>): Promise<Result> => {
try {
return { content: [{ type: "text", text: await run(a) }] };
} catch (e) {
return { content: [{ type: "text", text: e instanceof PeppaError ? e.message : `Internal error: ${(e as Error).message}` }], isError: true };
}
}) as never);
}
const ownedProject = async (keyOrSlug: string) => projectForUser(db, user.id, (await getProject(db, keyOrSlug).catch(() => { throw new PeppaError("Не найдено"); })).id);
const ownedTask = async (key: string) => {
const ref = await resolveTask(db, key).catch(() => { throw new PeppaError("Не найдено"); });
await projectForUser(db, user.id, ref.project.id);
return ref;
};
const taskArg = z.string().describe("Task key, e.g. PEP-3");
const projectArg = z.string().describe("Project key (e.g. PEP) or slug");
tool("list_projects", "List the user's Peppa projects (key, name, Gitea repo URL, task counts by board column).", {}, true, async () => {
const ps = await listUserProjects(db, user.id);
if (!ps.length) return "No projects yet. Create one at " + webUrl + "/projects/new";
const lines = [];
for (const p of ps) {
const ts = await listTasks(db, { projectId: p.id });
const counts = COLUMNS.map((c) => `${COLUMN_NAME[c]} ${ts.filter((t) => columnOf(t.status) === c).length}`).join(", ");
lines.push(`- ${p.key} — ${p.name} (${loadEnv().GITEA_URL}/${p.giteaOwner}/${p.giteaRepo})${p.ownerId === user.id ? "" : " [shared with you]"}: ${counts}`);
}
return lines.join("\n");
});
tool("list_members", "Who works on a project: owner, members and pending invitations.", { project: projectArg }, true, async ({ project }) => {
const p = await ownedProject(project);
const m = await listMembers(db, p);
return [
`Owner: ${m.owner?.login ?? "—"}`,
`Members: ${m.members.map((u) => u.login).join(", ") || "—"}`,
`Invited (not logged in yet): ${m.invites.join(", ") || "—"}`,
].join("\n");
});
tool(
"add_member",
"Share a project with another person by Gitea login (owner only). They get the same access as the owner except managing members, plus write access to the repo. If they never logged into Peppa, an invitation is created and applied at their first login.",
{ project: projectArg, login: z.string().min(1).describe("Gitea login") },
false,
async ({ project, login }) => {
const p = await ownedProject(project);
const r = await shareProject(db, user, p, login);
return `${r.login}: ${r.status === "added" ? "added to" : "invited to"} ${p.key}${r.repoAccess ? " · repo collaborator (write)" : " · repo access NOT granted (no admin rights in Gitea) — add them in Gitea manually"}`;
},
);
tool(
"remove_member",
"Remove a member or cancel an invitation (owner), or leave a shared project yourself (pass your own login).",
{ project: projectArg, login: z.string().min(1) },
false,
async ({ project, login }) => {
const p = await ownedProject(project);
await unshareProject(db, user, p, login);
return `${login} removed from ${p.key}`;
},
);
tool("list_goals", "List open top-level goals of a project.", { project: projectArg }, true, async ({ project }) => {
const p = await ownedProject(project);
const gs = await listGoals(db, p.id);
return gs.length ? gs.map((g) => `- #${g.id} ${g.title}${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n") : "No open goals.";
});
tool(
"create_goal",
"Create a top-level goal in a project (an objective that groups tasks).",
{ project: projectArg, title: z.string().trim().min(3), description: z.string().optional() },
false,
async ({ project, title, description }) => {
const p = await ownedProject(project);
const g = await createGoal(db, p.id, title, description);
return `Created goal #${g.id} in ${p.key}: ${g.title}`;
},
);
tool(
"update_goal",
"Edit a goal: title, description and/or status (open, done = achieved, archived). Its tasks are not changed.",
{
project: projectArg,
goal_id: z.number().int(),
title: z.string().trim().min(3).optional(),
description: z.string().optional(),
status: z.enum(["open", "done", "archived"]).optional(),
},
false,
async ({ project, goal_id, title, description, status }) => {
if (title === undefined && description === undefined && status === undefined) throw new PeppaError("Nothing to update: pass title, description and/or status");
const p = await ownedProject(project);
await getGoal(db, p.id, goal_id).catch(() => { throw new PeppaError("Не найдено"); });
const g = await updateGoal(db, p.id, goal_id, { title, description, status });
return `Goal #${g.id} (${p.key}): ${g.title} [${g.status}]${g.description ? `\n${g.description}` : ""}`;
},
);
tool(
"create_project",
"Create a Peppa project: a new Gitea repo (private by default, or public) or connect an existing one you admin (its visibility is kept), in your namespace or an org you can create repos in, filled from the Peppa template with OpenSpec. Returns the repo URL, its visibility and who can see it. Takes ~15 s.",
{
name: z.string().trim().min(2).describe("Human name, e.g. Payments"),
slug: z.string().describe("Repo name: a-z, 0-9, dashes"),
key: z.string().describe("Task key prefix, 2–10 letters/digits, e.g. PAY"),
owner: z.string().optional().describe("Gitea namespace: your login (default) or an org"),
existing: z.boolean().optional().describe("Connect an existing repo owner/slug instead of creating one"),
visibility: z.enum(["private", "public"]).optional().describe("New repo visibility (default private: only the namespace owner/org members with access, peppa-bot and project members see it)"),
},
false,
async ({ name, slug, key, owner, existing, visibility }) => {
const ns = owner || user.login;
const p = await provisionProject(db, { gitea: await giteaForUser(db, user), owner: ns, ownerIsUser: ns === user.login, slug: slug.toLowerCase(), key, name, existing, visibility, ownerId: user.id });
const repo = await describeRepo(db, p, { fresh: true });
return [
`Created project ${p.key} — ${p.name}. ${webUrl}/p/${p.key}`,
`Repo: ${repo.url} (${repoVisibilityLabel(repo.private)}${repo.ownerKind ? `, ${repo.ownerKind === "org" ? "organization" : "personal"} namespace` : ""})`,
`Who can see it: ${repoAudience(repo)}`,
].join("\n");
},
);
tool(
"list_tasks",
"List tasks of a project as a board (Backlog / In progress / Review / Done), optionally one column.",
{ project: projectArg, column: z.enum(COLUMNS).optional() },
true,
async ({ project, column }) => {
const p = await ownedProject(project);
const ts = await listTasks(db, { projectId: p.id });
const out: string[] = [];
for (const c of column ? [column] : COLUMNS) {
const inCol = ts.filter((t) => columnOf(t.status) === c);
out.push(`## ${COLUMN_NAME[c]} (${inCol.length})`, ...inCol.map((t) => `- ${t.key} [${t.status}]${t.goalId ? ` (goal #${t.goalId})` : ""} ${t.title}`));
}
return out.join("\n");
},
);
tool("get_task", "Get a task: description, goal, status, OpenSpec change, PM questions, progress.", { task: taskArg }, true, async ({ task }) => {
const ref = await ownedTask(task);
return `${formatTask(await getTaskDetails(db, ref))}\n\nWeb: ${webUrl}/t/${ref.key}`;
});
tool(
"create_task",
"Create a task in a project (lands in Backlog). Link it to a goal when possible.",
{ project: projectArg, title: z.string().min(3), description: z.string().optional(), goal_id: z.number().int().optional() },
false,
async ({ project, title, description, goal_id }) => {
const p = await ownedProject(project);
const ref = await createTask(db, { projectId: p.id, title, description, goalId: goal_id });
return `Created ${ref.key}: ${title} (Backlog). ${webUrl}/t/${ref.key}`;
},
);
tool(
"update_task",
"Edit a task: title, description and/or goal (each optional, at least one). Status and everything else stay as they are; no agent is started or stopped. Returns the updated card.",
{
task: taskArg,
title: z.string().trim().min(3).optional().describe("New title"),
description: z.string().optional().describe("New description (replaces the old one; Markdown is fine)"),
goal_id: z.number().int().nullable().optional().describe("Move to this goal of the same project; null detaches the task from its goal"),
},
false,
async ({ task, title, description, goal_id }) => {
if (title === undefined && description === undefined && goal_id === undefined) throw new PeppaError("Nothing to update: pass title, description and/or goal_id");
const ref = await ownedTask(task);
await updateTask(db, ref, { title, description, goalId: goal_id });
const updated = await resolveTask(db, ref.key);
return `${formatTask(await getTaskDetails(db, updated))}\n\nWeb: ${webUrl}/t/${ref.key}`;
},
);
tool(
"move_task",
"Move a task card on the board. in_progress starts an AI agent session on it (if none is running); backlog and done stop the agent; done also accepts the work.",
{ task: taskArg, to: z.enum(COLUMNS), provider: z.enum(["claude", "codex"]).optional().describe("Agent for in_progress (default claude)") },
false,
async ({ task, to, provider }) => {
const ref = await ownedTask(task);
const r = await moveTask(db, ref, to, { provider: provider as Provider | undefined });
return `${ref.key} → ${COLUMN_NAME[to]}${r.started ? ` · agent session #${r.started} started` : ""}${r.stopped ? ` · ${r.stopped} session(s) stopped` : ""}`;
},
);
tool("list_releases", "Deployments of a project: what runs on staging and prod, and the latest releases (env, commit, status, tasks, who deployed).", { project: projectArg }, true, async ({ project }) => {
const p = await ownedProject(project);
const [cur, rows] = await Promise.all([currentReleases(db, p.id), listReleases(db, p.id, 15)]);
const head = (["staging", "prod"] as const).map((e) => `${e}: ${cur[e] ? `${cur[e]!.sha.slice(0, 7)}${cur[e]!.host ? ` https://${cur[e]!.host}` : ""}` : "—"}`).join(" · ");
if (!rows.length) return `${head}\nNo deployments yet (deploy is configured in .peppa/project.json → "deploy").`;
return [head, ...rows.map((r) => `- ${r.env}${r.prNumber ? ` #${r.prNumber}` : ""} ${r.sha.slice(0, 7)} ${r.status}${r.reason ? ` (${r.reason})` : ""}${r.tasks.length ? ` · ${r.tasks.join(", ")}` : ""} · ${r.deployedBy} · ${r.createdAt.toISOString().slice(0, 16)}`)].join("\n");
});
tool(
"deploy",
"Deploy the project's healthy staging release to prod (the same image). Only when the user asks; the result arrives as a release (list_releases) and a message.",
{ project: projectArg, env: z.enum(["prod"]).default("prod") },
false,
async ({ project }) => {
const p = await ownedProject(project);
const r = await deployProd(db, p, user.login);
return `${p.key}: ${r.sha.slice(0, 7)} is being deployed to prod${r.tasks.length ? ` (tasks ${r.tasks.join(", ")})` : ""}. Check list_releases in a minute or two.`;
},
);
tool("list_inbox", "Open questions from agents waiting for the user (approvals, questions, permissions, ready-for-review), oldest first.", {}, true, async () => {
const ids = await userProjectIds(db, user.id);
if (!ids.length) return "Inbox is empty — agents need nothing from you.";
const rows = await db
.select({ q: questions, key: projects.key, number: tasks.number, status: tasks.status })
.from(questions)
.innerJoin(projects, eq(questions.projectId, projects.id))
.leftJoin(tasks, eq(questions.taskId, tasks.id))
.where(and(inArray(projects.id, ids), isNull(questions.answeredAt)))
.orderBy(asc(questions.id));
if (!rows.length) return "Inbox is empty — agents need nothing from you.";
return rows
.map(({ q, key, number, status }) => {
const kind = q.kind === "attention" && status === "review" ? "ready for review (answer 'accept' or a comment)" : q.kind;
return `- #${q.id} ${number != null ? formatTaskKey(key, number) : key} · ${kind}\n ${q.text.replace(/\n/g, "\n ")}${q.options?.length ? `\n options: ${q.options.join(" | ")}` : ""}`;
})
.join("\n");
});
tool(
"answer_question",
"Answer an open inbox question; the answer is delivered into the agent's session. For approvals answer 'ok' to approve or a comment to send back. For permissions: allow | always | deny. For ready-for-review: 'accept' merges the task's PR (only with green CI checks and no conflicts, otherwise the reason is returned) and closes the task, any other text goes back to the agent.",
{ question_id: z.number().int(), answer: z.string().min(1) },
false,
async ({ question_id, answer }) => {
const q = await getQuestion(db, question_id).catch(() => { throw new PeppaError("Не найдено"); });
await projectForUser(db, user.id, q.projectId);
if (q.answeredAt) return `Already answered (${q.answeredVia}): ${q.answer}`;
if (answer.trim().toLowerCase() === "accept" && (await isReviewQuestion(db, q))) {
const ref = await acceptTask(db, q.id, "web");
return `${ref.key} accepted → Done`;
}
const { delivered } = await answerAndDeliver(db, q.id, answer, "web");
return delivered ? "Delivered to the agent session." : "Saved; the session is not running right now.";
},
);
// ── production errors (PEP-58) ──────────────────────────────────────────────────
const ownedIncident = async (id: number) => {
const i = await getIncident(db, id).catch(() => { throw new PeppaError("Не найдено"); });
await projectForUser(db, user.id, i.projectId);
return i;
};
tool(
"list_incidents",
"Production errors of a project (from Bugsink): id, status (pending = waits for the user's decision), title, where, environment, release, events, task.",
{ project: projectArg, status: z.enum(incidentStatuses).optional() },
true,
async ({ project, status }) => {
const p = await ownedProject(project);
const rows = await listIncidents(db, p.id, status ? [status] : undefined);
if (!rows.length) return (await getIncidentSettings(db, p.id)) ? "No incidents." : "Error tracking is not connected for this project (web: project page → «Подключить отслеживание ошибок»).";
const keys = new Map((await listTasks(db, { projectId: p.id })).map((t) => [t.id, t.key]));
return rows
.map((i) => `- #${i.id} [${i.status}] ${i.title}${i.culprit ? ` (${i.culprit})` : ""} · ${i.source}/${i.environment ?? "?"} · release ${i.lastRelease ?? "?"} · ${i.events} events${i.taskId ? ` · ${keys.get(i.taskId) ?? ""}` : ""}`)
.join("\n");
},
);
tool("get_incident", "Details of a production error: stack top, release, environment, frequency, decision, Bugsink link.", { id: z.number().int() }, true, async ({ id }) => formatIncident(await ownedIncident(id)));
tool(
"decide_incident",
"Decide what to do with a production error: backlog (bug task in the backlog), start (bug task + agent starts on it), ignore.",
{ id: z.number().int(), action: z.enum(["backlog", "start", "ignore"]) },
false,
async ({ id, action }) => {
await ownedIncident(id);
const r = await decideIncident(db, id, action, user.login);
return r.task ? `${r.task.key} created${action === "start" ? " and started" : " in the backlog"}.` : "Ignored.";
},
);
tool(
"resolve_incident",
"Mark a production error fixed (until CI/CD closes them by release). Also resolves it in Bugsink; if it comes back, the incident reopens and its task returns to the backlog.",
{ id: z.number().int(), release: z.string().optional().describe("Release (commit SHA) with the fix, if known") },
false,
async ({ id, release }) => {
await ownedIncident(id);
const r = await resolveIncident(db, id, { who: user.login, release });
return `Incident #${id} resolved${r.bugsinkResolved ? " (also in Bugsink)" : " (Bugsink not updated)"}.`;
},
);
tool("get_incident_policy", "A project's incident policy: what happens to a new production error, triage prompt, environments, daily task limit, ignore pattern.", { project: projectArg }, true, async ({ project }) => {
const p = await ownedProject(project);
const s = await getIncidentSettings(db, p.id);
if (!s) return "Error tracking is not connected for this project.";
return [
`Policy: ${s.policy} — ${POLICY_RU[s.policy]}`,
`Triage prompt: ${s.triagePrompt ?? "—"}`,
`Environments: ${s.environments.join(", ")}`,
`Daily task limit: ${s.dailyLimit}`,
`Ignore pattern: ${s.ignorePattern ?? "—"}`,
].join("\n");
});
tool(
"set_incident_policy",
"Change what happens to new production errors: notify (Telegram only), backlog (bug task, default), start (bug task + agent), ask (Telegram buttons), triage (a triage agent decides by triage_prompt — the user's own words on how to decide; falls back to ask when unsure).",
{
project: projectArg,
policy: z.enum(incidentPolicies).optional(),
triage_prompt: z.string().optional(),
environments: z.array(z.string()).optional(),
daily_limit: z.number().int().min(0).optional(),
ignore_pattern: z.string().optional().describe("Regex on the error title; empty string clears it"),
},
false,
async ({ project, policy, triage_prompt, environments, daily_limit, ignore_pattern }) => {
const p = await ownedProject(project);
const s = await updateIncidentSettings(db, p.id, {
policy,
triagePrompt: triage_prompt,
environments,
dailyLimit: daily_limit,
ignorePattern: ignore_pattern === undefined ? undefined : ignore_pattern || null,
});
return `Incident policy of ${p.key}: ${s.policy} — ${POLICY_RU[s.policy]}${s.policy === "triage" ? `; prompt: ${s.triagePrompt ?? "(empty — the triager will ask)"}` : ""}.`;
},
);
return server;
}