- OAuth: RFC 8414/9728 metadata, RFC 7591 dynamic registration, authorization code + PKCE S256 with a consent screen after Gitea login, refresh token rotation; tokens and codes stored hashed; revoke in web - /mcp: stateless Streamable HTTP, Bearer → user; PM tools from @peppa/mcp/manager: projects, goals, tasks, create, move (board semantics, starts agents), inbox, answer/accept — owner-scoped - login keeps ?next= through Gitea OAuth; Settings page with MCP URL and connected apps - 5 new tests (53 e2e total, green); verified on prod as a client: DCR → consent → token → MCP over HTTPS → revoke → 401 - OpenSpec: pep-8 archived into spec remote-mcp Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
151 lines
7.7 KiB
TypeScript
151 lines
7.7 KiB
TypeScript
// 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 {
|
||
createTask,
|
||
getProject,
|
||
getQuestion,
|
||
getTaskDetails,
|
||
listGoals,
|
||
listTasks,
|
||
listUserProjects,
|
||
PeppaError,
|
||
projectForUser,
|
||
resolveTask,
|
||
type User,
|
||
} from "@peppa/core";
|
||
import { questions, projects, tasks, type Db } from "@peppa/db";
|
||
import { formatTaskKey } from "@peppa/shared";
|
||
import { acceptTask, answerAndDeliver, columnOf, isReviewQuestion, moveTask, type BoardColumn, type Provider } from "@peppa/runner";
|
||
import { and, asc, eq, isNull } from "drizzle-orm";
|
||
import { z } from "zod";
|
||
import { 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: "Готово" };
|
||
|
||
export function createManagerServer(db: Db, user: User, webUrl: string): McpServer {
|
||
const server = new McpServer({ name: "peppa", version: "0.2.0" });
|
||
|
||
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, 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} (${p.giteaOwner}/${p.giteaRepo}): ${counts}`);
|
||
}
|
||
return lines.join("\n");
|
||
});
|
||
|
||
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(
|
||
"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(
|
||
"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_inbox", "Open questions from agents waiting for the user (approvals, questions, permissions, ready-for-review), oldest first.", {}, true, async () => {
|
||
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(eq(projects.ownerId, user.id), 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' 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.";
|
||
},
|
||
);
|
||
|
||
return server;
|
||
}
|