diff --git a/doc/public-mcp.md b/doc/public-mcp.md index 622f408e3c6..56c80968a16 100644 --- a/doc/public-mcp.md +++ b/doc/public-mcp.md @@ -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 diff --git a/server/src/__tests__/public-mcp.test.ts b/server/src/__tests__/public-mcp.test.ts index c5e406b360a..5c05e2cecbc 100644 --- a/server/src/__tests__/public-mcp.test.ts +++ b/server/src/__tests__/public-mcp.test.ts @@ -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 = 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 = 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 = 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 = 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); diff --git a/server/src/services/public-mcp/capabilities.ts b/server/src/services/public-mcp/capabilities.ts index a56683cff4e..442c40253f1 100644 --- a/server/src/services/public-mcp/capabilities.ts +++ b/server/src/services/public-mcp/capabilities.ts @@ -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." }; }, }, { diff --git a/tests/runner-e2e/public-mcp-grading.ts b/tests/runner-e2e/public-mcp-grading.ts index c474fd50805..0a3d340a8e3 100644 --- a/tests/runner-e2e/public-mcp-grading.ts +++ b/tests/runner-e2e/public-mcp-grading.ts @@ -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 }): 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