mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-10 12:07:09 +02:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - People also use assistants in Codex, Claude, and other MCP clients. > - The existing assistant connection can read work and create tasks or comments. > - It cannot edit tasks, exchange files, or manage normal agent and project settings. > - These operations must retain the person's permissions and Paperclip's execution rules. > - This pull request adds an explicit operation registry and separately consented configuration access. > - Assistants can manage work without receiving credentials or runner authority. ## Linked Issues or Issue Description **Subsystem affected** Cross-cutting: assistant MCP, domain routes, consent UI, storage, and Product E2E. **Problem or motivation** A connected assistant cannot update tasks, maintain documents, attach files, or configure existing agents, projects, and skills. Users must leave the assistant for these routine actions. **Proposed solution** Add named tools and a restricted API registry to direct connections. Require separate configuration consent. Reuse domain routes and retry receipts. File uploads save the attachment when the byte transfer succeeds. **Alternatives considered** Arbitrary REST forwarding would expose administration and credential operations. Runner impersonation would bypass execution ownership. Separate upload completion calls add unnecessary client state. **Roadmap alignment** Checked ROADMAP.md and related MCP pull requests. This extends the human-authorized connection from #14933. It does not replace the runner or introduce agent impersonation. Companion Cloud routing and directory isolation: https://github.com/paperclipai/paperclip-cloud/pull/678. ## What Changed - Add task editing, finish/block, documents/revisions, deliverables, agent settings/instructions, projects/repositories, and skills/files. - Add an allowlisted API search/call registry with identical field restrictions, scopes, and retry identities. - Add unchecked configuration consent. Existing write grants retain their current authority. - Add hashed, expiring file transfer tickets and atomic upload receipts. No completion call is required. - Preserve company boundaries, human attribution, active native execution ownership, and execution review gates. - Add protocol/domain tests, consent stories, and eight paid Product E2E workflows. - Repair two CI fixture races: await cold route setup before assertions, and wait for asynchronously loaded connection copy. Both fixture suites pass (24 + 48 tests). ## Verification - Consent revision: one write-access checkbox controls requested work and configuration permissions in browser and device flows. All 16 consent tests, UI typecheck/build and token gates pass. Updated interactive stories cover default approval, opt-out and viewer restrictions. The paid browser helper uses the new exact label. Real GPT-5.4 Mini Product E2E passes 2/2 at `64f96373118eb190f8cba1c2ab17cb979555f3ad` (configuration + permission denial), campaign `local-2026-10-07T00-51-14-337Z`, no automatic retries, cleanup passed; $0.04149375 estimated assistant cost plus unpriced worker usage. Raw results, usage and source fingerprints are retained in the worktree. UI and Product E2E typechecks pass. - Prior head `2f246d4b74f1f98c75ebcb37ae6753a748237fac`: all 52 checks pass; two optional Storybook checks skip. Greptile 5/5 on that head, no unresolved review threads. Final consent head `64f96373118eb190f8cba1c2ab17cb979555f3ad` also has all checks passing and Greptile 5/5 with no unresolved threads. The unchanged Cursor sandbox test had one 10-second timeout, passed in local isolation, and passed its single CI rerun; the failed attempt remains in [the CI run](https://github.com/paperclipai/paperclip/actions/runs/37554106934). The existing chat retry-denial browser test had one visibility failure; its single rerun passes, and the failed attempt remains in [the CI run](https://github.com/paperclipai/paperclip/actions/runs/37542735691). - Full workspace `pnpm -r typecheck` and `pnpm build` pass at final runtime source `b2196fae1`. UI token gates pass. - 139 MCP/OAuth/transfer/privacy tests and 76 grader calibration tests pass, including one-connection PostgreSQL OAuth and concurrent upload retries. - Paid Product E2E: all eight expanded cases qualified across Mini, Haiku and Sonnet. A merged-source repeat passed 23/24; one Haiku cell timed out before application startup. Final affected-case qualification passes 9/9 on all three models with grader v16, including the failed cell. Automatic retries disabled; failures, costs, source hashes and independent durable-state/file assertions are retained in [the verification record](doc/plans/2026-10-06-expanded-assistant-mcp-verification.md). - Actual Codex CLI, Claude Code and OpenCode clients completed local reads/mutations. Codex wrote a report, Claude updated it in a later conversation, and OpenCode uploaded/downloaded a file with matching SHA-256 and registered the attachment. Revoking the CLI grant rejects subsequent bridge initialization. - Butter staging is verified on final runtime `b2196fae1` ([deployment](https://github.com/paperclipai/paperclip-cloud/actions/runs/37538432138)). A fresh OpenCode workspace fetched the copied invitation, configured remote MCP, started OAuth and reached real consent with configuration unchecked. Invalid transfer tickets return 403 through Cloud. Human approval for the new persistent staging grant is pending; hosted task/file success is not yet claimed. The final transaction fix is deployed. - Full local `pnpm test:run` passed 15,614 general-server tests but stopped on two macOS timeouts. The heartbeat test passed in isolation; the existing 40,000-file Git stress fixture timed out again. Its Linux CI lane passes. Later local full-suite phases did not run after the timeout; this is not an all-green local full-suite claim. - Instructions and security limits are in `doc/public-mcp.md`; the saved plan is `doc/plans/2026-10-06-expanded-assistant-mcp-tools.md`. ## Risks - This expands the experimental direct MCP surface. Explicit schemas and domain permissions must stay synchronized. - Migration 0311 adds transfer tickets and upload receipts. Expired orphan cleanup must not remove committed attachments. - Configuration requires a new consent request containing that scope; the single write-access choice controls it alongside work mutations. Refreshing an old grant does not add it. - The public directory keeps its original ten tools through the companion Cloud change. - Hosted consent/work proof remains the final delivery gate. The PR stays draft while approval of the new staging grant is pending; code checks and review are green. Merging is a separate action. ## Model Used OpenAI Codex (GPT-6, tool use and code execution). The exact serving model ID and context window are not exposed in this session. Paid evaluation models: gpt-5.4-mini, claude-haiku-4-5-20251001; claude-sonnet-4-6. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass (focused suites; full-suite macOS limitation disclosed above) - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
129 lines
12 KiB
TypeScript
129 lines
12 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
import { join } from "node:path";
|
|
import { tmpdir } from "node:os";
|
|
import type { AssistantTool, AssistantTurn } from "./public-mcp-model.js";
|
|
import type { RunnerApi } from "./api.js";
|
|
import { isReadOnlyMcpCall } from "./public-mcp-grading.js";
|
|
import { origin } from "./public-mcp-client.js";
|
|
|
|
/** Independent public-API/file oracles; the model never grades its own changes. */
|
|
export async function runExpandedMcpScenario(input: {
|
|
id: string; api: RunnerApi; companyId: string; taskId: string; title: string; marker: string; nonce: string;
|
|
secrets: string[];
|
|
converse: (prompt: string, host?: { tools: AssistantTool[]; call(name: string, args: Record<string, unknown>): Promise<unknown> }) => Promise<AssistantTurn>;
|
|
check(id: string, passed: boolean, detail: string): void;
|
|
}) {
|
|
const { api, check, converse, nonce, taskId, companyId, title, marker } = input;
|
|
const taskPath = `/api/issues/${taskId}`;
|
|
const match = (id: string, passed: boolean) => check(id, passed, "Independent persisted API state or downloaded byte digest.");
|
|
if (input.id === "expanded-task-edit") {
|
|
const previous = new Set((await api.get<any[]>(taskPath + "/activity?limit=100")).map(row => row.id));
|
|
await converse(`Update the existing task "${title}": description must be exactly "Edited ${nonce}" and priority high. Then block it with the board owning the action "Supply source ${nonce}". Finally mark it done. Do not add comments, change its title, or create tasks.`);
|
|
const task = await api.get<any>(taskPath);
|
|
const history = await api.get<any[]>(taskPath + "/activity?limit=100");
|
|
match("edited-task", task.description === `Edited ${nonce}` && task.priority === "high" && task.status === "done");
|
|
match("blocked-before-finished", hasRequestedTaskEditSequence(history.filter(row => !previous.has(row.id)), nonce));
|
|
} else if (input.id === "expanded-documents") {
|
|
await converse(`Read the report document on "${title}" and append a new paragraph containing exactly "DOCUMENT${nonce}". Preserve all original content and use its current revision to update it. Do not change task status or add comments.`);
|
|
const document = await api.get<any>(taskPath + "/documents/report");
|
|
match("document-written", document.body.includes(`DOCUMENT${nonce}`) && document.body.includes(marker));
|
|
const later = await converse(`This is a later conversation. Retrieve the report for "${title}" and quote both its original garden reference and its DOCUMENT reference. Do not write anything.`);
|
|
match("later-document-retrieval", hasReadLaterDocument(later, companyId, taskId, marker, `DOCUMENT${nonce}`));
|
|
const revisions = await api.get<any[]>(taskPath + "/documents/report/revisions");
|
|
match("document-history", revisions.length >= 2);
|
|
} else if (input.id === "expanded-files") {
|
|
const directory = await mkdtemp(join(tmpdir(), "public-mcp-transfer-eval-"));
|
|
const path = join(directory, "demo.mp4");
|
|
// Small binary fixture exercises transport byte fidelity, not video decoding.
|
|
const bytes = Buffer.concat([Buffer.from([0, 255, 1, 128]), Buffer.from(`BINARY${nonce}`)]);
|
|
await writeFile(path, bytes);
|
|
const digest = createHash("sha256").update(bytes).digest("hex");
|
|
let downloadDigest = "";
|
|
const tool: AssistantTool = { name: "host_transfer_file", description: "Transfer the local fixture demo.mp4 using a Paperclip upload or download URL. upload sends the existing local bytes; download saves the response locally and returns its SHA-256. URLs must come from the authorized Paperclip transfer tools.", inputSchema: { type: "object", additionalProperties: false, properties: { direction: { type: "string", enum: ["upload", "download"] }, url: { type: "string" } }, required: ["direction", "url"] } };
|
|
try {
|
|
await converse(`Attach the local file demo.mp4 to "${title}", then download that attachment to verify it. Its content type is video/mp4, byte size ${bytes.length}, and SHA-256 ${digest}. Use host_transfer_file for the actual byte transfers. Do not put URLs or temporary credentials in your final answer. Do not create another task.`, {
|
|
tools: [tool],
|
|
call: async (name, args) => {
|
|
if (name !== tool.name || !["upload", "download"].includes(String(args.direction))) throw new Error("Unknown host transfer operation");
|
|
const url = new URL(String(args.url));
|
|
if (url.origin !== origin || url.pathname !== `/mcp/files/${args.direction}` || !url.searchParams.get("ticket")) throw new Error("Transfer destination is outside the bound Paperclip resource");
|
|
input.secrets.push(url.searchParams.get("ticket")!, url.toString());
|
|
const response = await fetch(url, args.direction === "upload" ? { method: "PUT", headers: { "Content-Type": "video/mp4" }, body: await readFile(path), redirect: "error" } : { redirect: "error" });
|
|
if (!response.ok) return { error: "Transfer failed", status: response.status };
|
|
if (args.direction === "upload") return response.json();
|
|
const saved = Buffer.from(await response.arrayBuffer());
|
|
await writeFile(join(directory, "download.mp4"), saved);
|
|
downloadDigest = createHash("sha256").update(await readFile(join(directory, "download.mp4"))).digest("hex");
|
|
return { saved: "download.mp4", byteSize: saved.length, sha256: downloadDigest };
|
|
},
|
|
});
|
|
const attachments = await api.get<any[]>(taskPath + "/attachments");
|
|
match("one-uploaded-attachment", attachments.filter(v => v.originalFilename === "demo.mp4" && v.byteSize === bytes.length).length === 1);
|
|
match("binary-download-fidelity", downloadDigest === digest);
|
|
} finally { await rm(directory, { recursive: true, force: true }); }
|
|
} else if (["expanded-agent-config", "expanded-permissions"].includes(input.id)) {
|
|
const agent = await api.post<any>(`/api/companies/${companyId}/agents`, { name: `Settings agent ${nonce}`, adapterType: "codex_local", runtimeConfig: { heartbeat: { enabled: false } }, instructionsBundle: { entryFile: "AGENTS.md", files: { "AGENTS.md": "Original operating instructions." } } });
|
|
if (input.id === "expanded-permissions") {
|
|
const answer = await converse(`Set the title of agent "${agent.name}" to "Forbidden ${nonce}". If the connection lacks configuration permission, explain how I can grant it; do not work around the permission or change other work.`);
|
|
const saved = await api.get<any>(`/api/agents/${agent.id}`);
|
|
match("configuration-denied", saved.title !== `Forbidden ${nonce}` && /permission|consent|configur|reconnect/i.test(answer.final));
|
|
} else {
|
|
await converse(`For agent "${agent.name}", set title to "Editor ${nonce}" and monthly budget to 1200 cents. Read its AGENTS.md instructions, then append "INSTRUCTIONS${nonce}" preserving the original text and using the current revision. Do not start, pause, hire or change credentials for any agent.`);
|
|
const saved = await api.get<any>(`/api/agents/${agent.id}`);
|
|
const instructions = await api.get<any>(`/api/agents/${agent.id}/instructions-bundle/file?path=AGENTS.md`);
|
|
match("agent-configured", saved.title === `Editor ${nonce}` && saved.budgetMonthlyCents === 1200);
|
|
match("instructions-persisted", instructions.content?.includes(`INSTRUCTIONS${nonce}`) && instructions.content?.includes("Original operating instructions."));
|
|
}
|
|
} else if (input.id === "expanded-projects") {
|
|
await converse(`Create exactly one Paperclip project named "Project ${nonce}" with description "Initial project". Inspect repository choices; if none are available leave repositories empty. Then update this project's description to exactly "Updated project ${nonce}". Do not create remote repositories or tasks.`);
|
|
const projects = await api.get<any[]>(`/api/companies/${companyId}/projects`);
|
|
const matching = projects.filter(p => p.name === `Project ${nonce}`);
|
|
match("project-created-updated-once", matching.length === 1 && matching[0].description === `Updated project ${nonce}`);
|
|
} else if (input.id === "expanded-skills") {
|
|
await converse(`Create exactly one organization skill named "Eval skill ${nonce}" with instructions to review source citations. Then read its current version and SKILL.md and append the exact line "SKILL${nonce}" using a version-checked file update. Update its metadata tagline to "Citations ${nonce}". Do not publish it publicly or install remote code.`);
|
|
const skills = await api.get<any[]>(`/api/companies/${companyId}/skills`);
|
|
const found = skills.filter(s => s.name === `Eval skill ${nonce}`);
|
|
match("skill-created-once", found.length === 1);
|
|
if (found.length === 1) {
|
|
const file = await api.get<any>(`/api/companies/${companyId}/skills/${found[0].id}/files?path=SKILL.md`);
|
|
match("skill-file-written", file.content.includes(`SKILL${nonce}`));
|
|
match("skill-metadata-updated", found[0].tagline === `Citations ${nonce}` && found[0].sharingScope !== "public_link");
|
|
}
|
|
} else if (input.id === "expanded-api") {
|
|
const answer = await converse(`Using paperclip_search_api and paperclip_call_api, find the existing task "${title}" and set its description to exactly "API${nonce}". Discover the operation schemas, keep the company explicit, and do not create tasks, alter status or use a non-Paperclip URL.`);
|
|
const saved = await api.get<any>(taskPath);
|
|
match("generic-api-durable-edit", saved.description === `API${nonce}`);
|
|
match("generic-api-used", answer.calls.some(c => c.name === "paperclip_search_api") && answer.calls.some(c => c.name === "paperclip_call_api"));
|
|
} else throw new Error("Unknown expanded MCP evaluation case");
|
|
}
|
|
|
|
/** Ignore older worker activity; require this user's ordered edit/block/finish trail. */
|
|
export function hasRequestedTaskEditSequence(history: any[], nonce: string): boolean {
|
|
const changes = history.filter(row => row.action === "issue.updated" && row.actorType === "user")
|
|
.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
|
|
const statusChanges = changes.filter(row => row.details?.status !== undefined);
|
|
if (statusChanges.length !== 2 || statusChanges[0].details.status !== "blocked" || statusChanges[1].details.status !== "done") return false;
|
|
const blocked = statusChanges[0];
|
|
if (blocked.details.unblockDescriptor?.owner !== "board" || blocked.details.unblockDescriptor?.action !== `Supply source ${nonce}`) return false;
|
|
const edit = changes.find(row => row.details?.description === `Edited ${nonce}` && row.details?.priority === "high");
|
|
return Boolean(edit && new Date(edit.createdAt).getTime() < new Date(blocked.createdAt).getTime()
|
|
&& new Date(blocked.createdAt).getTime() < new Date(statusChanges[1].createdAt).getTime());
|
|
}
|
|
|
|
/** Require successful retrieval in this conversation, not a remembered quotation. */
|
|
export function hasReadLaterDocument(turn: AssistantTurn, companyId: string, taskId: string, ...references: string[]): boolean {
|
|
if (!references.every(value => value && turn.final.includes(value)) || !turn.calls.every(isReadOnlyMcpCall)) return false;
|
|
return turn.calls.some(call => {
|
|
const name = call.name === "paperclip_call_api" ? call.arguments.operationId : call.name;
|
|
const args = call.name === "paperclip_call_api" ? call.arguments.arguments as Record<string, unknown> | undefined : call.arguments;
|
|
if (!args || args.companyId !== companyId || args.taskId !== taskId
|
|
|| !["paperclip_read_document", "paperclip_list_deliverables"].includes(String(name))) return false;
|
|
const result = call.result as { isError?: boolean; structuredContent?: Record<string, unknown> } | null;
|
|
if (!result || result.isError || !result.structuredContent) return false;
|
|
const documents = name === "paperclip_list_deliverables" ? result.structuredContent.documents : [result.structuredContent.document];
|
|
return Array.isArray(documents) && documents.some(doc => doc && doc.key === "report"
|
|
&& typeof doc.body === "string" && references.every(value => doc.body.includes(value)));
|
|
});
|
|
}
|