peppa/packages/testkit/test/mcp-code-mode.test.ts

225 lines
13 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.

// PEP-212, spec mcp-code-mode: the MCP servers in «code» mode — two tools instead of dozens,
// a sandbox without process/fs/network, the same rights as the tools, a journal event per script.
import assert from "node:assert/strict";
import { after, describe, test } from "node:test";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { events } from "@peppa/db";
import { and, eq } from "drizzle-orm";
import { core, db, project, setDefaultOwner, superadmin, teardown } from "./helpers.ts";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
process.env.PEPPA_WEB_URL = "http://peppa.test";
const { createAgentServer } = await import("@peppa/mcp/agent");
const { createManagerServer } = await import("@peppa/mcp/manager");
const { runSandbox, searchApi, signature, mcpMode } = await import("../../mcp/src/code-mode.ts");
after(teardown);
async function connect(make: () => { connect: (t: never) => Promise<void> }, mode: string) {
process.env.PEPPA_MCP_MODE = mode;
const server = make();
delete process.env.PEPPA_MCP_MODE;
const [a, b] = InMemoryTransport.createLinkedPair();
await server.connect(a as never);
const client = new Client({ name: "mock", version: "0" });
await client.connect(b);
const call = async (name: string, args: Record<string, unknown> = {}) => {
const r = await client.callTool({ name, arguments: args });
return { text: (r.content as Array<{ text: string }>)[0]!.text, isError: !!r.isError };
};
return { client, call, names: async () => (await client.listTools()).tools.map((t) => t.name).sort() };
}
let seq = 0;
/** A project owned by a fresh user; returns the project and its owner. */
async function owned() {
const u = await core.upsertUserFromGitea(db, { id: 881_000 + ++seq, login: `mock-code-owner-${seq}` }, { access_token: "x" });
setDefaultOwner(u.id);
const tp = await project({ turns: [[{ say: "ok" }]] });
setDefaultOwner(null);
return { tp, owner: u };
}
const manager = (u: Awaited<ReturnType<typeof owned>>["owner"]) => () => createManagerServer(db, u, "http://peppa.test");
describe("Режим «код» в MCP", () => {
test("Scenario: короткий список — в режиме code удалённый MCP видит только get_started, search_api, execute", async () => {
const { tp, owner } = await owned();
const c = await connect(manager(owner), "code");
assert.deepEqual(await c.names(), ["execute", "get_started", "search_api"]);
});
test("Scenario: старые имена — в режиме tools всё как раньше, в both ещё два новых", async () => {
const { tp, owner } = await owned();
const tools = await connect(manager(owner), "tools");
const both = await connect(manager(owner), "both");
const t = await tools.names();
assert.ok(t.includes("list_tasks") && !t.includes("execute"));
assert.deepEqual((await both.names()).filter((n) => !t.includes(n)), ["execute", "search_api"]);
assert.match((await both.call("list_tasks", { project: tp.key })).text, new RegExp(tp.taskKey));
assert.equal(mcpMode({}), "both");
assert.equal(mcpMode({ PEPPA_MCP_MODE: "code" }), "code");
assert.equal(mcpMode({ PEPPA_MCP_MODE: "nonsense" }), "both");
});
test("Scenario: описания короче хотя бы в 5 раз", async () => {
const { tp, owner } = await owned();
const size = async (mode: string) => JSON.stringify((await (await connect(manager(owner), mode)).client.listTools()).tools).length;
const [tools, code] = [await size("tools"), await size("code")];
console.log(`tools/list: tools ${tools} chars, code ${code} chars, ×${(tools / code).toFixed(1)}`);
assert.ok(tools / code >= 5, `${tools} vs ${code}`);
});
test("Scenario: поиск задач — сигнатура peppa.tasks.move есть, методов мониторингов нет", async () => {
const { tp, owner } = await owned();
const c = await connect(manager(owner), "code");
const r = await c.call("search_api", { query: "tasks move" });
assert.match(r.text, /peppa\.tasks\.move\(args: \{ task: string/);
assert.ok(!/monitors/.test(r.text));
assert.match((await c.call("search_api", { query: "*" })).text, /peppa\.tasks: .*list/);
assert.match((await c.call("search_api", { query: "zzzqqq" })).text, /No methods match/);
});
test("Scenario: один execute — найти задачи, создать и прочитать", async () => {
const { tp, owner } = await owned();
const c = await connect(manager(owner), "code");
const r = await c.call("execute", {
code: `const before = await peppa.tasks.list({ project: ${JSON.stringify(tp.key)} });
const made = await peppa.tasks.create({ project: ${JSON.stringify(tp.key)}, title: "Через код" });
console.log("created", made);
return { before, one: (await peppa.tasks.get({ task: ${JSON.stringify(tp.taskKey)} })).split("\\n")[0] };`,
});
assert.equal(r.isError, false, r.text);
assert.match(r.text, new RegExp(tp.taskKey));
assert.match(r.text, /created Created .*Через код/);
assert.match((await c.call("execute", { code: `return await peppa.tasks.list({ project: ${JSON.stringify(tp.key)} })` })).text, /Через код/);
});
test("Scenario: журнал — execute пишет mcp_execute, а смена статуса — своё событие", async () => {
const { tp, owner } = await owned();
const platform = await project({ turns: [[{ say: "ok" }]] });
process.env.PEPPA_PLATFORM_KEY = platform.key;
try {
const c = await connect(manager(owner), "code");
const r = await c.call("execute", { code: `return await peppa.tasks.list({ project: ${JSON.stringify(tp.key)} });` });
assert.equal(r.isError, false, r.text);
const proj = await core.getProject(db, platform.key);
const ev = await db.select().from(events).where(and(eq(events.projectId, proj.id), eq(events.type, "mcp_execute")));
assert.equal(ev.length, 1);
assert.deepEqual((ev[0]!.payload as { calls: string[] }).calls, ["list_tasks"]);
assert.equal((ev[0]!.payload as { ok: boolean }).ok, true);
} finally {
delete process.env.PEPPA_PLATFORM_KEY;
}
});
});
describe("Песочница", () => {
const run = (code: string, limits = {}) => runSandbox(code, { x: { ping: "ping" } }, async () => "pong", limits);
test("Scenario: попытка достучаться до процесса, файлов и сети — ошибка, секретов нет", async () => {
for (const code of [
"return process.env.PEPPA_SECRET",
'return require("fs").readFileSync("/etc/passwd","utf8")',
'return await fetch("http://127.0.0.1:1/")',
'return (function(){ return this })().process.env',
'return (0, eval)("process.env")',
'return [].constructor.constructor("return process")().env',
'return (await import("node:fs")).readFileSync("/etc/passwd","utf8")',
"return setTimeout(() => 1, 1)",
]) {
const r = await run(code);
assert.equal(r.ok, false, `${code} → ${r.text}`);
assert.ok(!r.text.includes("mock-secret-for-tests") && !r.text.includes("root:"), r.text);
}
const typeofs = await run("return [typeof process, typeof require, typeof fetch, typeof Buffer, typeof setTimeout].join()");
assert.equal(typeofs.text, "undefined,undefined,undefined,undefined,undefined");
});
test("Scenario: бесконечный цикл прерывается по времени, следующий скрипт работает", async () => {
const r = await run("while (true) {}", { timeoutMs: 300 });
assert.equal(r.ok, false);
assert.match(r.text, /Time limit exceeded/);
assert.equal((await run("return 1 + 1")).text, "2");
});
test("Scenario: ожидание зависшего вызова тоже ограничено временем", async () => {
const r = await runSandbox("return await peppa.x.ping()", { x: { ping: "ping" } }, () => new Promise(() => {}), { timeoutMs: 300 });
assert.equal(r.ok, false);
assert.match(r.text, /Time limit exceeded/);
assert.equal((await run("return 2")).text, "2");
});
test("Scenario: память и размер ответа ограничены", async () => {
const mem = await run('const a = []; while (true) a.push("x".repeat(1e6));', { memoryBytes: 8 * 1024 * 1024 });
assert.equal(mem.ok, false);
assert.match(mem.text, /Memory limit|memory/i);
const big = await run('return "a".repeat(200000)', { outputChars: 1000 });
assert.equal(big.ok, true);
assert.match(big.text, /truncated/);
assert.ok(big.text.length < 1200);
assert.equal((await run("return 3")).text, "3");
});
test("Scenario: ошибки метода — исключение внутри скрипта, число вызовов ограничено", async () => {
const r = await runSandbox('try { await peppa.x.ping() } catch (e) { return "caught: " + e.message }', { x: { ping: "ping" } }, async () => { throw new core.PeppaError("Не найдено"); });
assert.equal(r.text, "caught: Не найдено");
const many = await run("for (let i = 0; i < 100; i++) await peppa.x.ping(); return 1", { maxCalls: 5 });
assert.equal(many.ok, false);
assert.match(many.text, /Too many API calls/);
assert.equal((await run("syntax error here")).ok, false);
});
});
describe("Права внутри скрипта", () => {
test("Scenario: чужой проект — «Не найдено», мониторинги и статус платформы — не суперадмину", async () => {
const theirs = await project({ turns: [[{ say: "ok" }]] });
const stranger = await core.upsertUserFromGitea(db, { id: 880_212, login: "mock-code-stranger" }, { access_token: "x" });
const c = await connect(manager(stranger), "code");
const r = await c.call("execute", { code: `return await peppa.tasks.list({ project: ${JSON.stringify(theirs.key)} })` });
assert.equal(r.isError, true);
assert.match(r.text, /Не найдено/);
const m = await c.call("execute", { code: "return await peppa.monitors.list()" });
assert.equal(m.isError, true);
assert.match(m.text, /superadmin only/);
const s = await c.call("execute", { code: "return await peppa.platform.status()" });
assert.equal(s.isError, true);
assert.match(s.text, /superadmin only/);
});
test("Scenario: суперадмин — peppa.platform.status() и peppa.monitors.list()", async () => {
await superadmin();
const admins = await core.platformAdmins(db);
const admin = (await core.getUserByLogin(db, admins[admins.length - 1]!))!;
const c = await connect(manager(admin), "code");
const s = await c.call("execute", { code: "return await peppa.platform.status()" });
assert.equal(s.isError, false, s.text);
assert.match(s.text, /^Services:/);
assert.match(s.text, /Delays on our side/);
assert.equal((await c.call("execute", { code: "return await peppa.monitors.list()" })).isError, false);
});
test("Scenario: агент — прямыми остаются нужные фабрике инструменты, чужой проект закрыт lockProject", async () => {
const mine = await project({ turns: [[{ say: "ok" }]] });
const other = await project({ turns: [[{ say: "ok" }]] });
const c = await connect(() => createAgentServer(db, { defaultKey: mine.key, lockProject: true }), "code");
const names = await c.names();
for (const n of ["update_task", "ask_pm", "report_progress", "report_blocker", "get_task", "search_api", "execute"]) assert.ok(names.includes(n), n);
assert.ok(!names.includes("list_tasks") && !names.includes("remember"));
const ok = await c.call("execute", { code: "return await peppa.tasks.list()" });
assert.equal(ok.isError, false, ok.text);
assert.match(ok.text, new RegExp(mine.taskKey));
const no = await c.call("execute", { code: `return await peppa.tasks.list({ project: ${JSON.stringify(other.key)} })` });
assert.equal(no.isError, true);
assert.match(no.text, /Access denied/);
});
});
describe("Сигнатуры из zod", () => {
test("Scenario: сигнатура несёт типы, необязательность и перечисления", async () => {
const { z } = await import("../../mcp/node_modules/zod/index.js");
const d = { name: "list_tasks", description: "List stories.", shape: { project: z.string().describe("Key"), status: z.enum(["a", "b"]).optional() }, readOnly: true, run: async () => "" };
assert.equal(signature(d), 'peppa.tasks.list(args: { project: string /* Key */; status?: "a" | "b" }): Promise<string>');
assert.match(searchApi([d], "stories"), /peppa\.tasks\.list/);
});
});