mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-19 07:42:38 +01:00
feat(public-mcp): let paperclip_create_task assign a person or no one (#22011)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The public MCP endpoint (`/mcp/paperclip`) lets an outside assistant, or another Paperclip instance, act in a company as a person. > - The `paperclip_create_task` tool requires `assigneeAgentId`. > - So every task that an outside caller files starts an agent run on the receiving instance and spends its budget. > - A colleague on another instance must be able to file work for a person, or for nobody, without that cost. > - This pull request makes the agent assignee optional and accepts `assigneeUserId`, the same field the REST issues API uses. > - The benefit is that instance-to-instance task filing does not spend the receiving company's budget unless the caller picks an agent. ## Linked Issues or Issue Description **Subsystem affected** Public MCP endpoint (`/mcp/paperclip`), tool `paperclip_create_task`. **Problem or motivation** `paperclip_create_task` requires `assigneeAgentId`. A caller cannot create a task for a person or an unassigned task. One Paperclip instance can connect to another through the generic remote MCP connector, and people use this to file tasks on a colleague's instance. Every such task wakes an agent on the receiving instance and can spend its budget. **Proposed solution** Make `assigneeAgentId` optional and accept `assigneeUserId`, the same field the REST issues API uses. Reject both at once. Only an agent assignee starts a run. Add a read-only `paperclip_list_people` tool so the caller can find a person's user ID. **Alternatives considered** A new MCP-only assignee field. We did not use it, because the REST API already has `assigneeUserId` and its checks. **Roadmap alignment** This supports instance-to-instance communication through the public MCP endpoint. It does not duplicate planned core work in ROADMAP.md. ## What Changed - `paperclip_create_task`: `assigneeAgentId` is optional. The tool accepts `assigneeUserId`, with the same shape as the REST issues API. - `paperclip_create_task`: a schema refinement rejects a call that has both assignees. The rejection occurs before the server writes an idempotency receipt or a task. - `paperclip_create_task`: the tool description says that an agent assignee may start work and spend budget, and that a person or no assignee does not start a run. The `scheduling` result text now matches the assignee type. - New read-only tool `paperclip_list_people`. It uses the existing `GET /companies/:companyId/user-directory` route, which only needs company access. It returns user ID, name and role. It does not return email. - The task goes through the same REST create route as before. Company scope, the `tasks:assign` decision (which also checks that a person is an active member), activity logging and the service checks all still apply. - `doc/public-mcp.md`: documents the three assignee shapes and the new tool. - `tests/runner-e2e/public-mcp-grading.ts`: adds `paperclip_list_people` to the read-only tool list. - The stdio server (`packages/mcp-server`) already uses `createIssueInputSchema`, which accepts both fields. It does not change. ## Verification - New test in `server/src/__tests__/public-mcp.test.ts`. It uses the real issue and access routes. It proves: - a task for a person and an unassigned task are created as `todo`, and their `requestId` replays return the same result; - neither shape wakes an agent, and the company has no heartbeat runs; - a task for an agent still wakes that agent one time; - both assignees at once are rejected with a clear message, and no receipt is written; - a member of another company is rejected (HTTP 403 from the REST assignment check), with a result identical to a user ID that does not exist; - `paperclip_list_people` returns members without email and without other companies' users. - Red first: the test failed with "Unknown Paperclip operation" before the change. Green after the change. - `cd server && npx vitest run src/__tests__/public-mcp.test.ts`: 85 passed (also after the rebase on `origin/master`). - `npx vitest run --config tests/runner-e2e/vitest.config.ts tests/runner-e2e/public-mcp-grading.test.ts tests/runner-e2e/public-mcp-expanded-flow.test.ts tests/runner-e2e/public-mcp-invitation-grading.test.ts`: 81 passed. - `cd server && npx tsc --noEmit -p .`: passed. - `pnpm verify` exits 2 because a doc changed (a global CI input). CI supplies the broad coverage. ## Risks - Low risk. The change only adds optional input. Existing calls with `assigneeAgentId` behave the same. - An unassigned task is created as `todo`, the same status as before. No code path wakes an agent for a task without an agent assignee. - `paperclip_list_people` shows member names and roles to any connection with read scope. The same data is already available to any company member in the UI assignee picker through the same route. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), through Claude Code, with tool use and code execution. ## 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 - [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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b1efe32c60
commit
78cf5aa81a
4 files changed
+98
-6
No files matched your search
+11
-1
@@ -241,15 +241,25 @@ OAuth credential bodies and redirect locations are redacted from HTTP logs.
|
||||
| --- | --- |
|
||||
| `paperclip_connection` | Person, company, scopes, connection management link |
|
||||
| `paperclip_list_agents` | Safe agent summary and availability |
|
||||
| `paperclip_list_people` | Active human members: user ID, name and role (no email) |
|
||||
| `paperclip_list_projects` | Safe project summary |
|
||||
| `paperclip_search_tasks` | Bounded task search with offset pagination |
|
||||
| `paperclip_read_task` | Current task plus recent comments/history |
|
||||
| `paperclip_create_task` | Assigned task, submitted to existing scheduling |
|
||||
| `paperclip_create_task` | Task for an agent, a person or no one; only an agent assignee is scheduled |
|
||||
| `paperclip_add_comment` | Human feedback; may wake or queue work |
|
||||
| `paperclip_list_deliverables` | Documents, attachments and work-product references |
|
||||
| `paperclip_read_document` | Durable document body and current revision |
|
||||
| `paperclip_pending_approvals` | Pending approvals and existing decision links |
|
||||
|
||||
`paperclip_create_task` takes at most one of `assigneeAgentId` and
|
||||
`assigneeUserId`, the same fields as the REST issues API; passing both is a
|
||||
validation error. An agent assignee is submitted to normal scheduling and may
|
||||
start a run that spends the company's budget. A person (a `userId` from
|
||||
`paperclip_list_people`) or no assignee creates a `todo` task without waking any
|
||||
agent, so a connection from another Paperclip instance can file work without
|
||||
spending the receiving company's budget. A person outside the company is
|
||||
rejected by the normal REST assignment check, identically to an unknown user ID.
|
||||
|
||||
Every company-scoped call requires its explicit authorized company ID. The
|
||||
server emits bounded projections without upstream credentials. Direct connections
|
||||
can read the allowed operating configuration through the expanded tools below. URLs include the company's prefix so unrelated browser company
|
||||
|
||||
@@ -22,6 +22,7 @@ import { publicMcpIngressRoutes, publicMcpManagementRoutes } from "../routes/pub
|
||||
import { authorizationService } from "../services/authorization.js";
|
||||
import { issueRoutes } from "../routes/issues.js";
|
||||
import { activityRoutes } from "../routes/activity.js";
|
||||
import { accessRoutes } from "../routes/access.js";
|
||||
import { documentService } from "../services/documents.js";
|
||||
import { createStorageService } from "../storage/service.js";
|
||||
import { createLocalDiskStorageProvider } from "../storage/local-disk-provider.js";
|
||||
@@ -625,6 +626,72 @@ describe.skipIf(!support.supported)("public MCP OAuth and tool boundary", () =>
|
||||
} finally { wake.mockRestore(); }
|
||||
});
|
||||
|
||||
it("creates tasks for a person or no one without starting an agent run, and keeps agent assignment", async () => {
|
||||
const f = await fixture();
|
||||
// Keep the real wakeup guard; replace only the heartbeat it would call.
|
||||
const realQueue = assignmentWakeups.queueIssueAssignmentWakeup;
|
||||
const heartbeatWakeup = vi.fn().mockResolvedValue(null);
|
||||
const wake = vi.spyOn(assignmentWakeups, "queueIssueAssignmentWakeup").mockImplementation((input) => realQueue({ ...input, heartbeat: { wakeup: heartbeatWakeup } }));
|
||||
try {
|
||||
const [agent] = await db.insert(agents).values({ companyId: f.company.id, name: "Researcher", role: "researcher", adapterType: "process", status: "idle" }).returning();
|
||||
const colleagueId = randomUUID();
|
||||
await db.insert(authUsers).values({ id: colleagueId, name: "Colleague", email: colleagueId + "@example.com", createdAt: new Date(), updatedAt: new Date() });
|
||||
await db.insert(companyMemberships).values({ companyId: f.company.id, principalType: "user", principalId: colleagueId, membershipRole: "member", status: "active" });
|
||||
const outsider = await fixture();
|
||||
const api = express.Router(); api.use(boardMutationGuard());
|
||||
api.use(issueRoutes(db, createStorageService(createLocalDiskStorageProvider("/tmp/paperclip-public-mcp-unused-storage"))));
|
||||
api.use(accessRoutes(db, { deploymentMode: "authenticated", deploymentExposure: "private", bindHost: "127.0.0.1", allowedHostnames: [] }));
|
||||
const execute = createPublicMcpExecutor(db, oauth, createMcpApiDispatch(api));
|
||||
const base = { companyId: f.company.id, description: "Filed from a colleague's instance" };
|
||||
|
||||
const people: Record<string, unknown> = await execute(f.tokens.access_token, "paperclip_list_people", { companyId: f.company.id });
|
||||
expect(people.people).toEqual(expect.arrayContaining([{ userId: colleagueId, name: "Colleague", role: "member" }]));
|
||||
expect(JSON.stringify(people)).not.toContain("@example.com");
|
||||
expect(JSON.stringify(people)).not.toContain(outsider.actor.userId!);
|
||||
|
||||
const toPerson = { ...base, requestId: randomUUID(), title: "Review the contract", assigneeUserId: colleagueId };
|
||||
const personResult: Record<string, unknown> = await execute(f.tokens.access_token, "paperclip_create_task", toPerson);
|
||||
expect(personResult).toMatchObject({ task: { status: "todo", assigneeUserId: colleagueId, assigneeAgentId: null } });
|
||||
expect(personResult.scheduling).toContain("No agent run was started");
|
||||
expect(await execute(f.tokens.access_token, "paperclip_create_task", toPerson)).toEqual(personResult);
|
||||
|
||||
const unassigned = { ...base, requestId: randomUUID(), title: "Triage this request" };
|
||||
const unassignedResult: Record<string, unknown> = await execute(f.tokens.access_token, "paperclip_create_task", unassigned);
|
||||
expect(unassignedResult).toMatchObject({ task: { status: "todo", assigneeUserId: null, assigneeAgentId: null } });
|
||||
expect(unassignedResult.scheduling).toContain("No agent run was started");
|
||||
expect(await execute(f.tokens.access_token, "paperclip_create_task", unassigned)).toEqual(unassignedResult);
|
||||
|
||||
// Neither shape may wake an agent or create a run.
|
||||
expect(heartbeatWakeup).not.toHaveBeenCalled();
|
||||
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.company.id))).toHaveLength(0);
|
||||
|
||||
const toAgent = { ...base, requestId: randomUUID(), title: "Write the report", assigneeAgentId: agent!.id };
|
||||
const agentResult: Record<string, unknown> = await execute(f.tokens.access_token, "paperclip_create_task", toAgent);
|
||||
expect(agentResult).toMatchObject({ task: { status: "todo", assigneeAgentId: agent!.id, assigneeUserId: null } });
|
||||
expect(agentResult.scheduling).toContain("Submitted to normal Paperclip scheduling");
|
||||
expect(await execute(f.tokens.access_token, "paperclip_create_task", toAgent)).toEqual(agentResult);
|
||||
expect(heartbeatWakeup).toHaveBeenCalledTimes(1);
|
||||
expect(heartbeatWakeup.mock.calls[0]?.[0]).toBe(agent!.id);
|
||||
|
||||
// Both assignees at once is rejected before any receipt or task is written.
|
||||
const both = { ...base, requestId: randomUUID(), title: "Ambiguous owner", assigneeAgentId: agent!.id, assigneeUserId: colleagueId };
|
||||
await expect(execute(f.tokens.access_token, "paperclip_create_task", both)).rejects.toThrow("either assigneeAgentId or assigneeUserId");
|
||||
expect(await db.select().from(mcpMutationReceipts).where(eq(mcpMutationReceipts.requestId, both.requestId))).toHaveLength(0);
|
||||
|
||||
// Another company's member is rejected by the REST assignment check, indistinguishable from a user id that does not exist.
|
||||
const reject = async (assigneeUserId: string) => {
|
||||
const { requestId: _requestId, ...result } = await execute(f.tokens.access_token, "paperclip_create_task", { ...base, requestId: randomUUID(), title: "Outside", assigneeUserId });
|
||||
return result;
|
||||
};
|
||||
const nonMember = await reject(outsider.actor.userId!);
|
||||
expect(nonMember).toMatchObject({ outcome: "rejected", status: 403 });
|
||||
expect(await reject(randomUUID())).toEqual(nonMember);
|
||||
|
||||
const created = await db.select().from(issues).where(eq(issues.companyId, f.company.id));
|
||||
expect(created.map((issue) => issue.title).sort()).toEqual(["Review the contract", "Triage this request", "Write the report"]);
|
||||
} 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);
|
||||
|
||||
@@ -75,6 +75,14 @@ export const publicMcpCapabilities: Capability[] = [
|
||||
schema: z.object(company).strict(),
|
||||
run: async (p, a, api) => ({ agents: rows(await api(p, "GET", `/companies/${a.companyId}/agents`)).map((v) => pick(v, ["id", "name", "role", "title", "status", "capabilities"])) }),
|
||||
},
|
||||
{
|
||||
name: "paperclip_list_people", description: "List the people (active human members) of the authorized company. Use a returned userId as assigneeUserId to give a task to a person instead of an agent.",
|
||||
schema: z.object(company).strict(),
|
||||
run: async (p, a, api) => ({ people: rows(object(await api(p, "GET", `/companies/${a.companyId}/user-directory`)).users).map((v) => {
|
||||
const member = object(v);
|
||||
return { userId: member.principalId, name: object(member.user).name ?? null, role: member.membershipRole ?? null };
|
||||
}) }),
|
||||
},
|
||||
{
|
||||
name: "paperclip_list_projects", description: "List projects in the authorized company.",
|
||||
schema: z.object(company).strict(),
|
||||
@@ -106,16 +114,23 @@ export const publicMcpCapabilities: Capability[] = [
|
||||
},
|
||||
{
|
||||
name: "paperclip_create_task", write: true,
|
||||
description: "Delegate work by creating one durable task assigned to a Paperclip agent. This may schedule autonomous execution and consume the company's configured model budget. Normal permissions, approval gates and agent availability apply. Returns immediately; retrieve progress later. Never retry with a new requestId after an uncertain result.",
|
||||
schema: z.object({ ...company, requestId, title: z.string().trim().min(1).max(200), description: z.string().max(50000), assigneeAgentId: z.uuid(), projectId: z.uuid().optional() }).strict(),
|
||||
description: "Create one durable task. Assign it to a Paperclip agent (assigneeAgentId from paperclip_list_agents), to a person (assigneeUserId from paperclip_list_people), or to no one by omitting both. An agent assignee may start work and consume the company's configured model budget; a person or no assignee does not start an agent run. Normal permissions, approval gates and agent availability apply. Returns immediately; retrieve progress later. Never retry with a new requestId after an uncertain result.",
|
||||
schema: z.object({ ...company, requestId, title: z.string().trim().min(1).max(200), description: z.string().max(50000),
|
||||
assigneeAgentId: z.uuid().optional().describe("Agent to assign. May start an agent run that consumes budget. Omit when assigning a person or no one."),
|
||||
assigneeUserId: z.string().trim().min(1).max(200).optional().describe("Person to assign, as the userId from paperclip_list_people. Does not start an agent run. Omit when assigning an agent or no one."),
|
||||
projectId: z.uuid().optional() }).strict()
|
||||
.refine((a) => !(a.assigneeAgentId && a.assigneeUserId), { message: "Assign either assigneeAgentId or assigneeUserId, not both. Omit both to leave the task unassigned.", path: ["assigneeUserId"] }),
|
||||
run: async (p, a, api, origin) => {
|
||||
const result = await api(p, "POST", `/companies/${a.companyId}/issues`, {
|
||||
title: a.title, description: a.description, assigneeAgentId: a.assigneeAgentId,
|
||||
title: a.title, description: a.description,
|
||||
...(a.assigneeAgentId ? { assigneeAgentId: a.assigneeAgentId } : {}),
|
||||
...(a.assigneeUserId ? { assigneeUserId: a.assigneeUserId } : {}),
|
||||
...(a.projectId ? { projectId: a.projectId } : {}), status: "todo",
|
||||
idempotencyKey: `mcp:${hashMcpSecret(p.grant.companyId + ":" + p.grant.userId)}:${a.requestId}`,
|
||||
});
|
||||
return { task: pick(result, taskFields), url: origin + "/" + pathId(p.company.issuePrefix) + "/issues/" + pathId(object(result).identifier ?? object(result).id),
|
||||
scheduling: "Submitted to normal Paperclip scheduling. Creation does not guarantee execution has started." };
|
||||
scheduling: a.assigneeAgentId ? "Submitted to normal Paperclip scheduling. Creation does not guarantee execution has started."
|
||||
: a.assigneeUserId ? "Assigned to a person. No agent run was started." : "Left unassigned. No agent run was started." };
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -33,7 +33,7 @@ export function gradeInvitation(value: InvitationEvidence | null) {
|
||||
/** Fail closed when the catalog grows: only known read operations count as read-only. */
|
||||
export function isReadOnlyMcpCall(call: { name: string; arguments: Record<string, unknown> }): boolean {
|
||||
if (call.name === "paperclip_call_api") return isReadOnlyMcpCall({ name: String(call.arguments.operationId), arguments: {} });
|
||||
return ["paperclip_connection", "paperclip_list_agents", "paperclip_list_projects", "paperclip_search_tasks", "paperclip_read_task", "paperclip_read_document", "paperclip_list_deliverables", "paperclip_pending_approvals", "paperclip_list_document_revisions", "paperclip_get_download_url", "paperclip_get_agent", "paperclip_read_agent_instructions", "paperclip_list_agent_instruction_revisions", "paperclip_get_project", "paperclip_list_project_repositories", "paperclip_list_skills", "paperclip_get_skill", "paperclip_read_skill_file", "paperclip_search_api"].includes(call.name);
|
||||
return ["paperclip_connection", "paperclip_list_agents", "paperclip_list_people", "paperclip_list_projects", "paperclip_search_tasks", "paperclip_read_task", "paperclip_read_document", "paperclip_list_deliverables", "paperclip_pending_approvals", "paperclip_list_document_revisions", "paperclip_get_download_url", "paperclip_get_agent", "paperclip_read_agent_instructions", "paperclip_list_agent_instruction_revisions", "paperclip_get_project", "paperclip_list_project_repositories", "paperclip_list_skills", "paperclip_get_skill", "paperclip_read_skill_file", "paperclip_search_api"].includes(call.name);
|
||||
}
|
||||
|
||||
/** Both public retrieval operations return document bodies. Grade the returned
|
||||
|
||||
Reference in new issue
Block a user