mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 00:48:44 +01:00
Expand direct assistant MCP tools for work and configuration (#15380)
## 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>
This commit is contained in:
1 parent
892b0b3606
commit
2d0c138122
42 files changed
+2475
-164
No files matched your search
@@ -211,7 +211,7 @@ function makeReflectionCoachAgent(overrides: Record<string, unknown> = {}) {
|
||||
}
|
||||
|
||||
describe("agent instructions bundle routes", () => {
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
vi.resetModules();
|
||||
vi.doUnmock("../routes/agents.js");
|
||||
vi.doUnmock("../routes/authz.js");
|
||||
@@ -288,7 +288,13 @@ describe("agent instructions bundle routes", () => {
|
||||
instructionsFilePath: "/tmp/agent-1/AGENTS.md",
|
||||
},
|
||||
});
|
||||
});
|
||||
// Cold route compilation belongs to fixture setup. Timing it as a request
|
||||
// let a timed-out import resume under the next case's reset mocks.
|
||||
await Promise.all([
|
||||
vi.importActual("../routes/agents.js"),
|
||||
vi.importActual("../middleware/index.js"),
|
||||
]);
|
||||
}, 60_000);
|
||||
|
||||
it("returns bundle metadata", async () => {
|
||||
const res = await requestApp(
|
||||
|
||||
@@ -7679,6 +7679,8 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
).toBe(1);
|
||||
expect(deferred).toHaveLength(1);
|
||||
|
||||
// The production reorder window is 750 ms; allow the subsequent database
|
||||
// drain to finish on loaded CI instead of sharing the default one-second budget.
|
||||
deferred.shift()?.();
|
||||
await vi.waitFor(async () => {
|
||||
const rows = await db
|
||||
@@ -7686,7 +7688,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
.from(chatConversations)
|
||||
.where(eq(chatConversations.endpointId, endpoint.id));
|
||||
expect(rows).toHaveLength(1);
|
||||
});
|
||||
}, { timeout: 10_000 });
|
||||
const [conversation] = await db
|
||||
.select()
|
||||
.from(chatConversations)
|
||||
@@ -7702,7 +7704,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
"unmentioned follow-up delivered first",
|
||||
]);
|
||||
expect(wakeup).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
}, { timeout: 10_000 });
|
||||
await service.shutdown();
|
||||
});
|
||||
|
||||
|
||||
@@ -1,3 +1,12 @@
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { createPublicMcpTransfers } from "../services/public-mcp/file-transfers.js";
|
||||
import { projectRoutes } from "../routes/projects.js";
|
||||
import { agentRoutes } from "../routes/agents.js";
|
||||
import { companySkillRoutes } from "../routes/company-skills.js";
|
||||
import { MAX_ATTACHMENT_BYTES } from "../attachment-types.js";
|
||||
import { mcpAttachmentUploads, mcpFileTickets, principalPermissionGrants, heartbeatRuns } from "@paperclipai/db";
|
||||
import { createHmac, createHash, randomBytes, randomUUID } from "node:crypto";
|
||||
import express, { type Request } from "express";
|
||||
import request from "supertest";
|
||||
@@ -95,16 +104,16 @@ describe.skipIf(!support.supported)("public MCP OAuth and tool boundary", () =>
|
||||
}
|
||||
});
|
||||
|
||||
async function fixture(role = "member", write = true) {
|
||||
async function fixture(role = "member", write = true, configure = false) {
|
||||
const userId = randomUUID();
|
||||
await db.insert(authUsers).values({ id: userId, name: "Human", email: userId + "@example.com", createdAt: new Date(), updatedAt: new Date() });
|
||||
const [company] = await db.insert(companies).values({ name: "Team", issuePrefix: "M" + randomBytes(4).toString("hex") }).returning();
|
||||
const [membership] = await db.insert(companyMemberships).values({ companyId: company!.id, principalType: "user", principalId: userId, membershipRole: role, status: "active" }).returning();
|
||||
const actor: Request["actor"] = { type: "board", source: "session", userId };
|
||||
const client = await oauth.register({ client_name: "Test client", redirect_uris: [redirectUri] }, randomUUID());
|
||||
const url = await oauth.authorize({ client_id: client.client_id, redirect_uri: redirectUri, resource: config.resource, scope: "paperclip:read paperclip:write offline_access", state: "state", response_type: "code", code_challenge: challenge, code_challenge_method: "S256" });
|
||||
const url = await oauth.authorize({ client_id: client.client_id, redirect_uri: redirectUri, resource: config.resource, scope: "paperclip:read paperclip:write paperclip:configure offline_access", state: "state", response_type: "code", code_challenge: challenge, code_challenge_method: "S256" });
|
||||
const id = url.split("/").at(-1)!;
|
||||
const consent = await oauth.consent(id, actor, { decision: "approve", companyId: company!.id, allowWrites: write });
|
||||
const consent = await oauth.consent(id, actor, { decision: "approve", companyId: company!.id, allowWrites: write, allowConfiguration: configure });
|
||||
const code = new URL(consent.redirectUrl).searchParams.get("code")!;
|
||||
const exchange = { grant_type: "authorization_code", client_id: client.client_id, redirect_uri: redirectUri, resource: config.resource, code, code_verifier: verifier };
|
||||
const tokens = await oauth.token(exchange);
|
||||
@@ -585,6 +594,321 @@ describe.skipIf(!support.supported)("public MCP OAuth and tool boundary", () =>
|
||||
} finally { wake.mockRestore(); }
|
||||
});
|
||||
|
||||
it("requires fresh explicit configuration consent and never upscopes old grants", async () => {
|
||||
const old = await fixture();
|
||||
const f = await fixture("member", true, true);
|
||||
const dispatch = vi.fn().mockResolvedValue({ id: randomUUID(), name: "Updated" });
|
||||
const execute = createPublicMcpExecutor(db, oauth, dispatch);
|
||||
const args = { companyId: old.company.id, agentId: randomUUID(), requestId: randomUUID(), changes: { title: "Writer" } };
|
||||
await expect(execute(old.tokens.access_token, "paperclip_update_agent", args)).rejects.toThrow("paperclip:configure");
|
||||
expect(dispatch).not.toHaveBeenCalled();
|
||||
await execute(f.tokens.access_token, "paperclip_update_agent", { ...args, companyId: f.company.id });
|
||||
expect(dispatch).toHaveBeenCalledTimes(1);
|
||||
expect((await oauth.authenticate(f.tokens.access_token)).grant.scopes).toContain("paperclip:configure");
|
||||
await db.update(companyMemberships).set({ membershipRole: "viewer" }).where(eq(companyMemberships.id, f.membership.id));
|
||||
await expect(execute(f.tokens.access_token, "paperclip_update_agent", { ...args, companyId: f.company.id, requestId: randomUUID() })).rejects.toThrow("permission");
|
||||
const refreshed = await oauth.token({ grant_type: "refresh_token", client_id: old.client.client_id, resource: config.resource, refresh_token: old.tokens.refresh_token });
|
||||
expect(refreshed.scope).not.toContain("configure");
|
||||
});
|
||||
|
||||
it("shares named/API receipts and refuses unknown operations, fields and cross-company arguments", async () => {
|
||||
const f = await fixture();
|
||||
const dispatch = vi.fn().mockResolvedValue({ id: randomUUID(), title: "New title" });
|
||||
const execute = createPublicMcpExecutor(db, oauth, dispatch);
|
||||
const args = { companyId: f.company.id, taskId: randomUUID(), requestId: randomUUID(), changes: { title: "New title" } };
|
||||
const first = await execute(f.tokens.access_token, "paperclip_update_task", args);
|
||||
expect(await execute(f.tokens.access_token, "paperclip_call_api", { companyId: f.company.id, operationId: "paperclip_update_task", arguments: args })).toEqual(first);
|
||||
expect(dispatch).toHaveBeenCalledTimes(1);
|
||||
for (const field of ["onBehalfOfUserId", "reviewPolicy", "executionPolicy", "interrupt", "reviewInteractionId", "permissions"]) {
|
||||
await expect(execute(f.tokens.access_token, "paperclip_update_task", { ...args, changes: { [field]: "unauthorized" } })).rejects.toThrow();
|
||||
}
|
||||
for (const operationId of ["DELETE /companies/:id", "paperclip_call_api", "approve_approval", "https://evil.example"]) {
|
||||
await expect(execute(f.tokens.access_token, "paperclip_call_api", { companyId: f.company.id, operationId, arguments: args })).rejects.toThrow();
|
||||
}
|
||||
await expect(execute(f.tokens.access_token, "paperclip_call_api", { companyId: f.company.id, operationId: "paperclip_update_task", arguments: { ...args, companyId: randomUUID() } })).rejects.toThrow("Company");
|
||||
expect(dispatch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
async function expandedFixture(configure = false) {
|
||||
const f = await fixture(configure ? "owner" : "member", true, configure);
|
||||
if (configure) await db.insert(principalPermissionGrants).values(["agents:configure", "skills:create"].map(permissionKey => ({ companyId: f.company.id, principalType: "user", principalId: f.actor.userId!, permissionKey })));
|
||||
const storageDir = await mkdtemp(join(tmpdir(), "mcp-files-"));
|
||||
const storage = createStorageService(createLocalDiskStorageProvider(storageDir));
|
||||
const api = express.Router(); api.use(boardMutationGuard());
|
||||
api.use(issueRoutes(db, storage)); api.use(activityRoutes(db)); api.use(projectRoutes(db)); api.use(agentRoutes(db)); api.use(companySkillRoutes(db));
|
||||
const dispatch = createMcpApiDispatch(api);
|
||||
const transfers = createPublicMcpTransfers(db, oauth, dispatch, storage);
|
||||
const execute = createPublicMcpExecutor(db, oauth, dispatch, transfers);
|
||||
const [issue] = await db.insert(issues).values({ companyId: f.company.id, title: "Work", status: "backlog" }).returning();
|
||||
const call = (name: string, a: Record<string, unknown> = {}) => execute(f.tokens.access_token, name, { companyId: f.company.id, ...a });
|
||||
return { ...f, issue: issue!, call, dispatch, transfers, storage, cleanup: () => rm(storageDir, { recursive: true, force: true }) };
|
||||
}
|
||||
|
||||
it("edits, blocks and completes tasks through real routes and rejects review overrides", async () => {
|
||||
const f = await expandedFixture();
|
||||
try {
|
||||
expect(await f.call("paperclip_update_task", { taskId: f.issue.id, requestId: randomUUID(), changes: { title: "Edited", description: "Durable detail" } })).toHaveProperty("task.title", "Edited");
|
||||
expect(await f.call("paperclip_block_task", { taskId: f.issue.id, requestId: randomUUID(), unblockDescriptor: { owner: "board", action: "Supply the source file" } })).toHaveProperty("task.status", "blocked");
|
||||
expect(await f.call("paperclip_finish_task", { taskId: f.issue.id, requestId: randomUUID() })).toHaveProperty("task.status", "done");
|
||||
await db.update(issues).set({ status: "in_review" }).where(eq(issues.id, f.issue.id));
|
||||
const denied = await f.call("paperclip_finish_task", { taskId: f.issue.id, requestId: randomUUID() });
|
||||
expect(denied).toMatchObject({ outcome: "rejected", status: 403, code: "MCP_REVIEW_REQUIRED" });
|
||||
expect((await db.select().from(issues).where(eq(issues.id, f.issue.id)))[0]?.status).toBe("in_review");
|
||||
const logs = await db.select().from(activityLog).where(eq(activityLog.entityId, f.issue.id));
|
||||
expect(logs.some(v => v.actorType === "user" && v.actorId === f.actor.userId && v.action === "issue.updated")).toBe(true);
|
||||
} finally { await f.cleanup(); }
|
||||
});
|
||||
|
||||
it.each(["queued", "running", "scheduled_retry"])("preserves %s execution ownership and rejects dependency cycles", async status => {
|
||||
const f = await expandedFixture();
|
||||
try {
|
||||
const [agent] = await db.insert(agents).values({ companyId: f.company.id, name: "Worker" }).returning();
|
||||
const [run] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: agent!.id, status, runtimeMode: "native", nativeIssueId: f.issue.id }).returning();
|
||||
await db.update(issues).set({ assigneeAgentId: agent!.id, executionRunId: run!.id, status: "in_progress" }).where(eq(issues.id, f.issue.id));
|
||||
for (const changes of [{ status: "done" }, { status: "blocked", unblockDescriptor: { owner: "board", action: "Supply data" } }, { assigneeAgentId: null }, { status: "cancelled" }]) {
|
||||
expect(await f.call("paperclip_update_task", { taskId: f.issue.id, requestId: randomUUID(), changes })).toMatchObject({ outcome: "rejected", status: 409, code: "MCP_ACTIVE_EXECUTION" });
|
||||
}
|
||||
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run!.id)))[0]?.status).toBe(status);
|
||||
expect(await f.call("paperclip_update_task", { taskId: f.issue.id, requestId: randomUUID(), changes: { title: "Clarified title" } })).toHaveProperty("task.title", "Clarified title");
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, run!.id));
|
||||
await db.update(issues).set({ assigneeAgentId: null, executionRunId: null, status: "backlog" }).where(eq(issues.id, f.issue.id));
|
||||
const [second] = await db.insert(issues).values({ companyId: f.company.id, title: "Dependent", status: "backlog" }).returning();
|
||||
expect(await f.call("paperclip_update_task", { taskId: second!.id, requestId: randomUUID(), changes: { blockedByIssueIds: [f.issue.id] } })).toHaveProperty("task.id", second!.id);
|
||||
const cycle = await f.call("paperclip_update_task", { taskId: f.issue.id, requestId: randomUUID(), changes: { blockedByIssueIds: [second!.id] } });
|
||||
expect(cycle).toMatchObject({ outcome: "rejected" });
|
||||
expect([400, 409, 422]).toContain(cycle.status);
|
||||
} finally { await f.cleanup(); }
|
||||
});
|
||||
|
||||
it.each([
|
||||
["codex_local", "gpt-5.4", "modelReasoningEffort"],
|
||||
["claude_local", "claude-sonnet-4-6", "effort"],
|
||||
["paperclip_runner", "gpt-5.4", "modelReasoningEffort"],
|
||||
])("updates the effective %s reasoning setting and validates its model", async (adapterType, model, field) => {
|
||||
const f = await expandedFixture(true);
|
||||
try {
|
||||
const [agent] = await db.insert(agents).values({ companyId: f.company.id, name: "Reasoning", adapterType,
|
||||
adapterConfig: { model, [field]: "high", instructionsBundleMode: "managed" }, runtimeConfig: { heartbeat: { enabled: false } } }).returning();
|
||||
const edited = await f.call("paperclip_update_agent", { agentId: agent!.id, requestId: randomUUID(), changes: { adapterConfig: { reasoningEffort: "low" } } });
|
||||
expect(edited, JSON.stringify(edited)).toHaveProperty("agent.adapterConfig.reasoningEffort", "low");
|
||||
const stored = (await db.select().from(agents).where(eq(agents.id, agent!.id)))[0]!;
|
||||
expect(stored.adapterConfig[field]).toBe("low");
|
||||
expect(stored.adapterConfig.reasoningEffort).toBeUndefined();
|
||||
expect(await f.call("paperclip_get_agent", { agentId: agent!.id })).toHaveProperty("agent.adapterConfig.reasoningEffort", "low");
|
||||
for (const reasoningEffort of ["ultra"]) {
|
||||
expect(await f.call("paperclip_update_agent", { agentId: agent!.id, requestId: randomUUID(), changes: { adapterConfig: { reasoningEffort } } })).toMatchObject({ outcome: "rejected" });
|
||||
}
|
||||
if (adapterType === "claude_local") {
|
||||
expect(await f.call("paperclip_update_agent", { agentId: agent!.id, requestId: randomUUID(), changes: { adapterConfig: { model: "claude-haiku-4-5" } } })).toMatchObject({ outcome: "rejected", status: 422 });
|
||||
}
|
||||
} finally { await f.cleanup(); }
|
||||
});
|
||||
|
||||
it("writes durable documents and rejects stale revisions through both interfaces", async () => {
|
||||
const f = await expandedFixture();
|
||||
try {
|
||||
const a = { taskId: f.issue.id, requestId: randomUUID(), key: "report", document: { format: "markdown", body: "First revision", baseRevisionId: null } };
|
||||
const first = await f.call("paperclip_write_document", a);
|
||||
expect(first).toHaveProperty("document.body", "First revision");
|
||||
const revision = (first.document as { latestRevisionId: string }).latestRevisionId;
|
||||
expect(revision).toBeTruthy();
|
||||
const second = await f.call("paperclip_write_document", { ...a, requestId: randomUUID(), document: { ...a.document, body: "Second revision", baseRevisionId: revision } });
|
||||
expect(second).toHaveProperty("document.body", "Second revision");
|
||||
expect(await f.call("paperclip_write_document", { ...a, requestId: randomUUID() })).toMatchObject({ outcome: "rejected", status: 409 });
|
||||
expect(await f.call("paperclip_read_document", { taskId: f.issue.id, key: "report" })).toHaveProperty("document.body", "Second revision");
|
||||
expect(await f.call("paperclip_list_document_revisions", { taskId: f.issue.id, key: "report" })).toHaveProperty("revisions");
|
||||
} finally { await f.cleanup(); }
|
||||
});
|
||||
|
||||
it("creates and edits projects and agents while rejecting privileged configuration fields", async () => {
|
||||
const f = await expandedFixture(true);
|
||||
try {
|
||||
const created = await f.call("paperclip_create_project", { requestId: randomUUID(), project: { name: "Research", description: "Project context" } });
|
||||
expect(created).toHaveProperty("project.name", "Research");
|
||||
const id = (created.project as { id: string }).id;
|
||||
expect(await f.call("paperclip_update_project", { projectId: id, requestId: randomUUID(), changes: { name: "Updated project" } })).toHaveProperty("project.name", "Updated project");
|
||||
const [agent] = await db.insert(agents).values({ companyId: f.company.id, name: "Writer", adapterType: "codex_local", adapterConfig: { instructionsBundleMode: "managed", model: "gpt-5.4-mini", env: { SAFE_EXISTING: "retain" } }, runtimeConfig: { heartbeat: { enabled: false } } }).returning();
|
||||
const edited = await f.call("paperclip_update_agent", { agentId: agent!.id, requestId: randomUUID(), changes: { title: "Editor", budgetMonthlyCents: 1200, adapterConfig: { model: "gpt-5.4" } } });
|
||||
expect(edited, JSON.stringify(edited)).toHaveProperty("agent.title", "Editor");
|
||||
const stored = (await db.select().from(agents).where(eq(agents.id, agent!.id)))[0]!;
|
||||
expect(stored.adapterConfig.env).toEqual({ SAFE_EXISTING: { type: "plain", value: "retain" } });
|
||||
expect(stored.budgetMonthlyCents).toBe(1200);
|
||||
const read = await f.call("paperclip_get_agent", { agentId: agent!.id });
|
||||
expect(JSON.stringify(read)).not.toContain("SAFE_EXISTING");
|
||||
for (const changes of [{ permissions: {} }, { adapterConfig: { command: "evil" } }, { runtimeConfig: { debug: { providerTrace: "raw" } } }]) {
|
||||
await expect(f.call("paperclip_update_agent", { agentId: agent!.id, requestId: randomUUID(), changes })).rejects.toThrow();
|
||||
}
|
||||
} finally { await f.cleanup(); }
|
||||
});
|
||||
|
||||
it("rejects unchecked legacy prompt edits through named and generic operations", async () => {
|
||||
const f = await expandedFixture(true);
|
||||
try {
|
||||
const [agent] = await db.insert(agents).values({ companyId: f.company.id, name: "Legacy writer", adapterType: "codex_local", adapterConfig: { instructionsBundleMode: "managed", promptTemplate: "Newer human instructions" } }).returning();
|
||||
for (const base of [{ baseHash: null }, { baseHash: "0".repeat(64) }, { baseRevisionId: randomUUID() }]) {
|
||||
const args = { companyId: f.company.id, agentId: agent!.id, requestId: randomUUID(), file: { path: "promptTemplate.legacy.md", content: "Stale assistant overwrite", ...base } };
|
||||
expect(await f.call("paperclip_update_agent_instructions", args)).toMatchObject({ outcome: "rejected", status: 422, code: "MCP_LEGACY_INSTRUCTIONS_UNVERSIONED" });
|
||||
expect(await f.call("paperclip_call_api", { operationId: "paperclip_update_agent_instructions", arguments: { ...args, requestId: randomUUID() } })).toMatchObject({ outcome: "rejected", status: 422, code: "MCP_LEGACY_INSTRUCTIONS_UNVERSIONED" });
|
||||
}
|
||||
const stored = (await db.select().from(agents).where(eq(agents.id, agent!.id)))[0]!;
|
||||
expect(stored.adapterConfig.promptTemplate).toBe("Newer human instructions");
|
||||
} finally { await f.cleanup(); }
|
||||
});
|
||||
|
||||
it("version-checks agent instructions and skill files through the real domain services", async () => {
|
||||
const f = await expandedFixture(true);
|
||||
try {
|
||||
const [agent] = await db.insert(agents).values({ companyId: f.company.id, name: "Writer", adapterType: "codex_local", adapterConfig: { instructionsBundleMode: "managed" } }).returning();
|
||||
const input = { agentId: agent!.id, requestId: randomUUID(), file: { path: "AGENTS.md", content: "First instructions", baseRevisionId: null } };
|
||||
expect(await f.call("paperclip_update_agent_instructions", input)).toHaveProperty("instructions.content", "First instructions");
|
||||
const current = await f.call("paperclip_read_agent_instructions", { agentId: agent!.id });
|
||||
const instructions = current.instructions as { revision: { id: string } };
|
||||
expect(instructions.revision.id).toBeTruthy();
|
||||
expect(await f.call("paperclip_update_agent_instructions", { ...input, requestId: randomUUID(), file: { ...input.file, content: "New instructions", baseRevisionId: instructions.revision.id } })).toHaveProperty("instructions.content", "New instructions");
|
||||
expect(await f.call("paperclip_update_agent_instructions", { ...input, requestId: randomUUID() })).toMatchObject({ outcome: "rejected", status: 409 });
|
||||
expect(await f.call("paperclip_list_agent_instruction_revisions", { agentId: agent!.id })).toHaveProperty("revisions");
|
||||
const created = await f.call("paperclip_create_skill", { requestId: randomUUID(), skill: { name: "Source review", markdown: "# Source review\nReview citations carefully." } });
|
||||
expect(created).toHaveProperty("skill.id");
|
||||
const skill = created.skill as { id: string; currentVersionId: string };
|
||||
expect(skill.currentVersionId).toBeTruthy();
|
||||
const read = await f.call("paperclip_read_skill_file", { skillId: skill.id });
|
||||
const file = read.file as { content: string };
|
||||
const write = { skillId: skill.id, requestId: randomUUID(), file: { path: "SKILL.md", content: file.content + "\nPreserve source links.", expectedVersionId: skill.currentVersionId } };
|
||||
expect(await f.call("paperclip_write_skill_file", write)).toHaveProperty("file.versionId");
|
||||
expect(await f.call("paperclip_write_skill_file", { ...write, requestId: randomUUID() })).toMatchObject({ outcome: "rejected", status: 409 });
|
||||
expect(await f.call("paperclip_update_skill", { skillId: skill.id, requestId: randomUUID(), changes: { tagline: "Check sources" } })).toHaveProperty("skill.tagline", "Check sources");
|
||||
} finally { await f.cleanup(); }
|
||||
});
|
||||
|
||||
it("completes OAuth and concurrent upload retries with a one-connection pool", async () => {
|
||||
const originalDb = db, originalOauth = oauth;
|
||||
db = createDb(temp.connectionString, { maxConnections: 1 });
|
||||
oauth = createPublicMcpOAuth(db, config);
|
||||
let cleanup: (() => Promise<void>) | undefined;
|
||||
try {
|
||||
// Fixture approval and PKCE redemption must also stay on their transaction.
|
||||
const f = await expandedFixture(); cleanup = f.cleanup;
|
||||
await oauth.token({ grant_type: "refresh_token", client_id: f.client.client_id,
|
||||
resource: config.resource, refresh_token: f.tokens.refresh_token });
|
||||
const device = await deviceFixture();
|
||||
await oauth.consentDevice(device.codes.user_code, device.actor, { decision: "approve", companyId: device.company.id, allowWrites: true });
|
||||
await oauth.token(device.deviceExchange);
|
||||
const bytes = Buffer.from("one connection upload");
|
||||
const args = { taskId: f.issue.id, filename: "single.txt", contentType: "text/plain", byteSize: bytes.length,
|
||||
sha256: createHash("sha256").update(bytes).digest("hex") };
|
||||
const links = [];
|
||||
for (let i = 0; i < 3; i++) links.push(new URL((await f.call("paperclip_get_upload_url", { ...args, requestId: randomUUID() })).url as string));
|
||||
const app = express(); app.use(f.transfers.router);
|
||||
const results = await Promise.all(links.flatMap(url => Array.from({ length: 2 }, () =>
|
||||
request(app).put(url.pathname + url.search).set("Content-Type", args.contentType).send(bytes).timeout(5000))));
|
||||
expect(results.map(result => result.status)).toEqual(Array(6).fill(200));
|
||||
expect(new Set(results.map(result => result.body.attachment.id)).size).toBe(3);
|
||||
expect((await f.call("paperclip_list_deliverables", { taskId: f.issue.id })).attachments).toHaveLength(3);
|
||||
} finally { db = originalDb; oauth = originalOauth; await cleanup?.(); }
|
||||
}, 15000);
|
||||
|
||||
it("automatically finalizes binary uploads once, survives lost responses, and enforces live revocation", async () => {
|
||||
const f = await expandedFixture();
|
||||
try {
|
||||
const bytes = Buffer.from([0, 255, 18, 7, 64, 89, 33, 0]);
|
||||
const sha256 = createHash("sha256").update(bytes).digest("hex");
|
||||
const args = { taskId: f.issue.id, requestId: randomUUID(), filename: "demo.mp4", contentType: "video/mp4", byteSize: bytes.length, sha256 };
|
||||
const prepared = await f.call("paperclip_get_upload_url", args);
|
||||
const url = new URL(prepared.url as string);
|
||||
const app = express(); app.use(f.transfers.router);
|
||||
const put = (body = bytes) => request(app).put(url.pathname + url.search).set("Content-Type", args.contentType).send(body);
|
||||
const responses = await Promise.all([put(), put()]);
|
||||
expect(responses.map(v => v.status)).toEqual([200, 200]);
|
||||
const attachment = responses[0]!.body.attachment;
|
||||
expect(responses[1]!.body.attachment.id).toBe(attachment.id);
|
||||
expect(await f.call("paperclip_get_upload_url", args)).toMatchObject({ status: "completed", attachment: { id: attachment.id, sha256 } });
|
||||
const outputs = await f.call("paperclip_list_deliverables", { taskId: f.issue.id });
|
||||
expect(outputs.attachments).toHaveLength(1);
|
||||
expect((await put(Buffer.from("conflicting bytes"))).status).toBe(403);
|
||||
const download = await f.call("paperclip_get_download_url", { attachmentId: attachment.id });
|
||||
const downloadUrl = new URL(download.url as string);
|
||||
const content = await request(app).get(downloadUrl.pathname + downloadUrl.search).buffer(true);
|
||||
expect(content.status).toBe(200);
|
||||
expect(createHash("sha256").update(content.body as Buffer).digest("hex")).toBe(sha256);
|
||||
const tickets = await db.select().from(mcpFileTickets).where(eq(mcpFileTickets.grantId, (await oauth.authenticate(f.tokens.access_token)).grant.id));
|
||||
expect(JSON.stringify(tickets)).not.toContain(url.searchParams.get("ticket"));
|
||||
const receipts = await db.select().from(mcpMutationReceipts).where(eq(mcpMutationReceipts.companyId, f.company.id));
|
||||
expect(JSON.stringify(receipts)).not.toContain("ticket=");
|
||||
const other = await fixture();
|
||||
await expect(createPublicMcpExecutor(db, oauth, f.dispatch, f.transfers)(other.tokens.access_token, "paperclip_get_download_url", { companyId: other.company.id, attachmentId: attachment.id })).rejects.toThrow();
|
||||
await oauth.revokeConnection((await oauth.authenticate(f.tokens.access_token)).grant.id, f.actor.userId!);
|
||||
expect((await request(app).get(downloadUrl.pathname + downloadUrl.search)).status).not.toBe(200);
|
||||
expect((await put()).status).not.toBe(200);
|
||||
} finally { await f.cleanup(); }
|
||||
});
|
||||
|
||||
it("rejects expired, malformed and over-limit file tickets and respects the experimental gate", async () => {
|
||||
const f = await expandedFixture();
|
||||
try {
|
||||
const args = { taskId: f.issue.id, requestId: randomUUID(), filename: "data.json", contentType: "application/json", byteSize: 2, sha256: createHash("sha256").update("{}").digest("hex") };
|
||||
await expect(f.call("paperclip_get_upload_url", { ...args, byteSize: MAX_ATTACHMENT_BYTES + 1 })).rejects.toThrow();
|
||||
await expect(f.call("paperclip_get_upload_url", { ...args, filename: "../escape" })).rejects.toThrow();
|
||||
const prepared = await f.call("paperclip_get_upload_url", args);
|
||||
const url = new URL(prepared.url as string);
|
||||
const app = express(); app.use(f.transfers.router);
|
||||
const put = () => request(app).put(url.pathname + url.search).set("Content-Type", "application/json").send("{}");
|
||||
await instanceSettingsService(db).updateExperimental({ enablePublicMcp: false });
|
||||
try { expect((await put()).status).not.toBe(200); } finally { await instanceSettingsService(db).updateExperimental({ enablePublicMcp: true }); }
|
||||
await db.update(mcpFileTickets).set({ expiresAt: new Date(0) }).where(eq(mcpFileTickets.tokenHash, hashMcpSecret(url.searchParams.get("ticket")!)));
|
||||
expect((await put()).status).toBe(403);
|
||||
expect((await request(app).get("/mcp/files/download?ticket=bad")).status).toBe(403);
|
||||
} finally { await f.cleanup(); }
|
||||
});
|
||||
|
||||
it("rejects partial, oversized and mismatched uploads without creating attachments", async () => {
|
||||
const f = await expandedFixture();
|
||||
try {
|
||||
const bytes = Buffer.from("exact original content");
|
||||
const args = { taskId: f.issue.id, requestId: randomUUID(), filename: "data.txt", contentType: "text/plain", byteSize: bytes.length, sha256: createHash("sha256").update(bytes).digest("hex") };
|
||||
const url = new URL((await f.call("paperclip_get_upload_url", args)).url as string);
|
||||
const app = express(); app.use(f.transfers.router);
|
||||
const put = (body: Buffer, type = "text/plain") => request(app).put(url.pathname + url.search).set("Content-Type", type).send(body);
|
||||
expect((await put(bytes.subarray(0, 4))).status).toBe(403);
|
||||
expect((await put(Buffer.alloc(MAX_ATTACHMENT_BYTES + 1))).status).toBe(413);
|
||||
expect((await put(bytes, "video/mp4")).status).toBe(403);
|
||||
expect((await f.call("paperclip_list_deliverables", { taskId: f.issue.id })).attachments).toHaveLength(0);
|
||||
expect((await put(bytes)).status).toBe(200);
|
||||
expect((await f.call("paperclip_list_deliverables", { taskId: f.issue.id })).attachments).toHaveLength(1);
|
||||
} finally { await f.cleanup(); }
|
||||
});
|
||||
|
||||
it("rejects authority lost during storage and safely reclaims the orphaned object", async () => {
|
||||
const f = await expandedFixture();
|
||||
try {
|
||||
const bytes = Buffer.from("orphan test");
|
||||
const args = { taskId: f.issue.id, requestId: randomUUID(), filename: "data.txt", contentType: "text/plain", byteSize: bytes.length, sha256: createHash("sha256").update(bytes).digest("hex") };
|
||||
const prepared = await f.call("paperclip_get_upload_url", args);
|
||||
const principal = await oauth.authenticate(f.tokens.access_token);
|
||||
const originalPut = f.storage.putFile.bind(f.storage);
|
||||
const putSpy = vi.spyOn(f.storage, "putFile").mockImplementationOnce(async input => {
|
||||
const stored = await originalPut(input);
|
||||
await oauth.revokeConnection(principal.grant.id, f.actor.userId!);
|
||||
return stored;
|
||||
});
|
||||
const app = express(); app.use(f.transfers.router);
|
||||
const url = new URL(prepared.url as string);
|
||||
expect((await request(app).put(url.pathname + url.search).set("Content-Type", "text/plain").send(bytes)).status).not.toBe(200);
|
||||
putSpy.mockRestore();
|
||||
const [upload] = await db.select().from(mcpAttachmentUploads).where(eq(mcpAttachmentUploads.id, prepared.uploadId as string));
|
||||
expect(upload!.attachmentId).toBeNull();
|
||||
const orphan = await f.storage.getObject(upload!.companyId, upload!.objectKey);
|
||||
orphan.stream.destroy();
|
||||
await db.update(mcpAttachmentUploads).set({ expiresAt: new Date(0) }).where(eq(mcpAttachmentUploads.id, upload!.id));
|
||||
const fresh = await expandedFixture();
|
||||
try {
|
||||
const clean = createPublicMcpTransfers(db, oauth, fresh.dispatch, f.storage);
|
||||
await clean.getUploadUrl(await oauth.authenticate(fresh.tokens.access_token), { ...args, companyId: fresh.company.id, taskId: fresh.issue.id, requestId: randomUUID() });
|
||||
expect((await db.select().from(mcpAttachmentUploads).where(eq(mcpAttachmentUploads.id, upload!.id)))[0]!.cleanedAt).not.toBeNull();
|
||||
await expect(f.storage.getObject(upload!.companyId, upload!.objectKey)).rejects.toThrow();
|
||||
} finally { await fresh.cleanup(); }
|
||||
} finally { await f.cleanup(); }
|
||||
});
|
||||
|
||||
it("exposes discovery and individually named protocol tools, with CSRF-protected management", async () => {
|
||||
const f = await fixture();
|
||||
const dispatch = vi.fn().mockResolvedValue([{ id: randomUUID(), name: "Engineer", adapterConfig: { secret: "hidden" } }]);
|
||||
@@ -597,7 +921,7 @@ describe.skipIf(!support.supported)("public MCP OAuth and tool boundary", () =>
|
||||
const rpc = (method: string, params?: unknown) => request(app).post("/mcp/paperclip").timeout({ response: 5000, deadline: 7000 }).set("Authorization", `Bearer ${f.tokens.access_token}`).set("Accept", "application/json, text/event-stream").send({ jsonrpc: "2.0", id: 1, method, ...(params ? { params } : {}) });
|
||||
expect((await rpc("initialize", { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "test", version: "1" } })).body.result.serverInfo.name).toBe("paperclip");
|
||||
const catalog = await rpc("tools/list");
|
||||
expect(catalog.body.result.tools).toHaveLength(10);
|
||||
expect(catalog.body.result.tools).toHaveLength(publicMcpCapabilities.length);
|
||||
expect(catalog.body.result.tools.find((t: { name: string }) => t.name === "paperclip_create_task").annotations.readOnlyHint).toBe(false);
|
||||
const result = await rpc("tools/call", { name: "paperclip_list_agents", arguments: { companyId: f.company.id } });
|
||||
expect(JSON.stringify(result.body)).not.toContain("hidden");
|
||||
@@ -607,6 +931,11 @@ describe.skipIf(!support.supported)("public MCP OAuth and tool boundary", () =>
|
||||
expect(failed.body.result.isError).toBe(true);
|
||||
expect(JSON.stringify(failed.body)).not.toContain("tenant-secret");
|
||||
expect(failed.body.result.content[0].text).toContain("could not confirm");
|
||||
dispatch.mockClear();
|
||||
const invalid = await rpc("tools/call", { name: "paperclip_finish_task", arguments: { companyId: f.company.id, taskId: randomUUID(), requestId: "b2c3d4e5-f6a7-48b9-c0d1-e2f3a4b5c6d7" } });
|
||||
expect(invalid.body.result.structuredContent).toMatchObject({ outcome: "rejected", phase: "validation", issues: [{ path: "requestId", code: "invalid_format" }] });
|
||||
expect(invalid.body.result.structuredContent.issues[0].message).toContain("UUID");
|
||||
expect(dispatch).not.toHaveBeenCalled();
|
||||
const pending = await oauth.authorize({ client_id: f.client.client_id, redirect_uri: redirectUri, resource: config.resource, response_type: "code", code_challenge: challenge, code_challenge_method: "S256" });
|
||||
vi.stubEnv("PAPERCLIP_CLOUD_API_ORIGIN", "https://cloud.example.test");
|
||||
try {
|
||||
@@ -728,7 +1057,7 @@ describe.skipIf(!support.supported)("public MCP OAuth and tool boundary", () =>
|
||||
.send({ jsonrpc: "2.0", id: 1, method, params: { ...params, ...extra } });
|
||||
expect((await rpc("server/discover")).body.result).toMatchObject({ resultType: "complete", supportedVersions: ["2026-07-28"], capabilities: { tools: {}, events: {} } });
|
||||
expect((await rpc("events/list")).body.result.events.map((e: { name: string }) => e.name)).toEqual(publicMcpEventDefinitions.map(e => e.name));
|
||||
expect((await rpc("tools/list")).body.result.tools).toHaveLength(10);
|
||||
expect((await rpc("tools/list")).body.result.tools).toHaveLength(publicMcpCapabilities.length);
|
||||
expect((await rpc("tools/call", { name: "paperclip_connection", arguments: {} }, { "Mcp-Name": "=?base64?cGFwZXJjbGlwX2Nvbm5lY3Rpb24=?=" })).body.result.structuredContent.companyId).toBe(f.company.id);
|
||||
expect((await rpc("events/list", {}, { "Mcp-Method": "tools/list" })).body.error.code).toBe(-32020);
|
||||
expect((await rpc("events/list", { _meta: {} })).body.error.code).toBe(-32602);
|
||||
|
||||
Reference in new issue
Block a user