|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | +// |
| 3 | +// [#30891] The MCP `delete_records` tool, end to end on a booted stack: the |
| 4 | +// live `/api/v1/mcp` transport, the runtime's real data bridge, the real |
| 5 | +// engine and a package's real locking rule, for an ADMINISTRATOR caller. |
| 6 | +// |
| 7 | +// ## What this file pins that the package's own pins cannot |
| 8 | +// |
| 9 | +// `packages/mcp/src/mcp-delete-records.test.ts` drives the tool on an engine |
| 10 | +// double. Here the rule that refuses a row is a real `beforeDelete` hook, |
| 11 | +// written the way a package writes one: HotCRM's |
| 12 | +// `opportunity_line_item_freeze` refuses a USER's change of a closed deal's |
| 13 | +// line with `RECORD_LOCKED` / 409 and lets a write with no acting user (a |
| 14 | +// seed, a migration) through. So the lock refuses whoever calls as a user, |
| 15 | +// administrators included, and only a delete that stopped running as the |
| 16 | +// caller could get past it. The maintainer's ruling on the card is that no |
| 17 | +// caller bypasses such a rule (「不绕过」); the admin pin below is that ruling's |
| 18 | +// executable form. |
| 19 | +// |
| 20 | +// • preview: an unconfirmed call answers the count and a sample, and the |
| 21 | +// records are all still readable over REST afterwards; |
| 22 | +// • confirmed: the unlocked rows are deleted, the locked rows are answered |
| 23 | +// as one group (code, status, the hook's own sentence, their ids) and stay; |
| 24 | +// • control: REST `DELETE /data/:object/:id` refuses the same admin on a |
| 25 | +// locked row, so the tool answers what the platform's other door answers; |
| 26 | +// • the cap: 203 matching rows, one call deletes 200 and says 3 remain, the |
| 27 | +// next call deletes the 3 (the count is the runtime's real aggregate). |
| 28 | + |
| 29 | +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; |
| 30 | +import { bootStack, type VerifyStack } from '@objectstack/verify'; |
| 31 | +import { defineStack } from '@objectstack/spec'; |
| 32 | +import { ObjectSchema, Field } from '@objectstack/spec/data'; |
| 33 | +import { MCPServerPlugin } from '@objectstack/mcp'; |
| 34 | +import { AI_ACTION_CONFIRMATION_MEMBER } from '@objectstack/spec/contracts'; |
| 35 | + |
| 36 | +const LOCKED = 'dlr_close_task'; |
| 37 | +const BULK = 'dlr_bulk_row'; |
| 38 | +const LOCK_SENTENCE = 'This task belongs to a closed period, so it can no longer be deleted.'; |
| 39 | + |
| 40 | +const CloseTask = ObjectSchema.create({ |
| 41 | + name: LOCKED, |
| 42 | + label: 'Close task', |
| 43 | + fields: { |
| 44 | + name: Field.text({ label: 'Name', required: true }), |
| 45 | + batch: Field.text({ label: 'Batch' }), |
| 46 | + period_closed: Field.boolean({ label: 'Period closed' }), |
| 47 | + }, |
| 48 | +}); |
| 49 | + |
| 50 | +const BulkRow = ObjectSchema.create({ |
| 51 | + name: BULK, |
| 52 | + label: 'Bulk row', |
| 53 | + fields: { |
| 54 | + name: Field.text({ label: 'Name', required: true }), |
| 55 | + batch: Field.text({ label: 'Batch' }), |
| 56 | + }, |
| 57 | +}); |
| 58 | + |
| 59 | +const fixture = defineStack({ |
| 60 | + manifest: { |
| 61 | + id: 'com.dogfood.mcp-delete-records', |
| 62 | + namespace: 'dlr', |
| 63 | + version: '0.0.0', |
| 64 | + type: 'app', |
| 65 | + name: 'MCP delete_records fixture', |
| 66 | + description: 'A package locking rule that refuses a user delete of a closed-period row, for #30891.', |
| 67 | + }, |
| 68 | + objects: [CloseTask, BulkRow], |
| 69 | + hooks: [ |
| 70 | + { |
| 71 | + // A package's locking rule, in HotCRM's shape: a USER's delete of a |
| 72 | + // closed-period row is refused; a write with no acting user passes. |
| 73 | + name: 'dlr_close_period_lock', |
| 74 | + object: LOCKED, |
| 75 | + events: ['beforeDelete'], |
| 76 | + handler: async (ctx: any) => { |
| 77 | + if (!ctx.user?.id) return; |
| 78 | + if (ctx.previous?.period_closed !== true) return; |
| 79 | + throw Object.assign(new Error(LOCK_SENTENCE), { code: 'RECORD_LOCKED', status: 409 }); |
| 80 | + }, |
| 81 | + }, |
| 82 | + ], |
| 83 | +}); |
| 84 | + |
| 85 | +const idOf = (b: any) => b?.id ?? b?.record?.id ?? b?.data?.id; |
| 86 | + |
| 87 | +describe('MCP delete_records on a real stack: preview, grouped refusals, an admin under a locking rule, the cap (#30891)', () => { |
| 88 | + let stack: VerifyStack; |
| 89 | + let admin: string; |
| 90 | + |
| 91 | + /** One `tools/call` over the live MCP transport; the tool's text content, parsed. */ |
| 92 | + const tool = async (name: string, args: Record<string, unknown>) => { |
| 93 | + const res = await stack.api('/mcp', { |
| 94 | + method: 'POST', |
| 95 | + headers: { |
| 96 | + 'Content-Type': 'application/json', |
| 97 | + Accept: 'application/json, text/event-stream', |
| 98 | + Authorization: `Bearer ${admin}`, |
| 99 | + }, |
| 100 | + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }), |
| 101 | + }); |
| 102 | + expect(res.status).toBe(200); |
| 103 | + const rpc: any = await res.json(); |
| 104 | + expect(rpc.error, JSON.stringify(rpc.error)).toBeUndefined(); |
| 105 | + const text = String(rpc.result?.content?.[0]?.text ?? ''); |
| 106 | + let payload: any; |
| 107 | + try { |
| 108 | + payload = JSON.parse(text); |
| 109 | + } catch { |
| 110 | + payload = { message: text }; |
| 111 | + } |
| 112 | + return { isError: rpc.result?.isError === true, payload, text }; |
| 113 | + }; |
| 114 | + |
| 115 | + const create = async (object: string, data: Record<string, unknown>): Promise<string> => { |
| 116 | + const res = await stack.apiAs(admin, 'POST', `/data/${object}`, data); |
| 117 | + expect(res.status, await res.clone().text()).toBeLessThan(300); |
| 118 | + const id = idOf(await res.json()); |
| 119 | + expect(id, 'created record id').toBeTruthy(); |
| 120 | + return String(id); |
| 121 | + }; |
| 122 | + const readStatus = async (object: string, id: string) => (await stack.apiAs(admin, 'GET', `/data/${object}/${id}`)).status; |
| 123 | + |
| 124 | + beforeAll(async () => { |
| 125 | + stack = await bootStack(fixture, { extraPlugins: [new MCPServerPlugin()] }); |
| 126 | + admin = await stack.signIn(); |
| 127 | + }, 300_000); |
| 128 | + |
| 129 | + afterAll(async () => { |
| 130 | + await stack?.stop?.(); |
| 131 | + }); |
| 132 | + |
| 133 | + describe('a selection with locked rows', () => { |
| 134 | + let open: string[]; |
| 135 | + let closed: string[]; |
| 136 | + let other: string; |
| 137 | + |
| 138 | + beforeAll(async () => { |
| 139 | + open = [await create(LOCKED, { name: 'open 1', batch: 'q4' }), await create(LOCKED, { name: 'open 2', batch: 'q4' })]; |
| 140 | + closed = [ |
| 141 | + await create(LOCKED, { name: 'closed 1', batch: 'q4', period_closed: true }), |
| 142 | + await create(LOCKED, { name: 'closed 2', batch: 'q4', period_closed: true }), |
| 143 | + ]; |
| 144 | + other = await create(LOCKED, { name: 'another batch', batch: 'q1' }); |
| 145 | + }, 60_000); |
| 146 | + |
| 147 | + it('preview: an unconfirmed call answers the count and a sample, and deletes nothing', async () => { |
| 148 | + const refused = await tool('delete_records', { objectName: LOCKED, where: { batch: 'q4' } }); |
| 149 | + |
| 150 | + expect(refused.isError, refused.text).toBe(true); |
| 151 | + expect(refused.payload.error).toMatchObject({ |
| 152 | + code: 'ACTION_CONFIRMATION_REQUIRED', |
| 153 | + status: 428, |
| 154 | + details: { actionName: 'delete_records', objectName: LOCKED, confirmationMember: AI_ACTION_CONFIRMATION_MEMBER }, |
| 155 | + }); |
| 156 | + expect(refused.payload.preview).toMatchObject({ object: LOCKED, matched: 4, wouldAttempt: 4, cap: 200 }); |
| 157 | + expect([...refused.payload.preview.sampleRecordIds].sort()).toEqual([...open, ...closed].sort()); |
| 158 | + |
| 159 | + // Nothing was deleted: every record still reads over REST. |
| 160 | + for (const id of [...open, ...closed, other]) expect(await readStatus(LOCKED, id), `record ${id}`).toBe(200); |
| 161 | + }, 60_000); |
| 162 | + |
| 163 | + it('control: REST DELETE refuses the same administrator on a locked row', async () => { |
| 164 | + const res = await stack.apiAs(admin, 'DELETE', `/data/${LOCKED}/${closed[0]}`); |
| 165 | + expect(res.status, await res.clone().text()).toBe(409); |
| 166 | + expect(await readStatus(LOCKED, closed[0]!)).toBe(200); |
| 167 | + }, 60_000); |
| 168 | + |
| 169 | + it('confirmed, as an administrator: the unlocked rows go, the locked rows stay and are answered as one group', async () => { |
| 170 | + const done = await tool('delete_records', { |
| 171 | + objectName: LOCKED, |
| 172 | + where: { batch: 'q4' }, |
| 173 | + [AI_ACTION_CONFIRMATION_MEMBER]: true, |
| 174 | + }); |
| 175 | + |
| 176 | + expect(done.isError, done.text).toBe(false); |
| 177 | + expect(done.payload).toMatchObject({ object: LOCKED, matched: 4, attempted: 4, deleted: 2, refused: 2, remaining: 2 }); |
| 178 | + expect(done.payload.refusals).toHaveLength(1); |
| 179 | + const [group] = done.payload.refusals; |
| 180 | + expect(group).toMatchObject({ code: 'RECORD_LOCKED', status: 409, reason: LOCK_SENTENCE, count: 2 }); |
| 181 | + expect([...group.recordIds].sort()).toEqual([...closed].sort()); |
| 182 | + |
| 183 | + // Ground truth over REST: the administrator's delete did not get past the lock. |
| 184 | + for (const id of closed) expect(await readStatus(LOCKED, id), `locked record ${id}`).toBe(200); |
| 185 | + for (const id of open) expect(await readStatus(LOCKED, id), `open record ${id}`).toBe(404); |
| 186 | + // Outside the selection: untouched. |
| 187 | + expect(await readStatus(LOCKED, other)).toBe(200); |
| 188 | + }, 60_000); |
| 189 | + }); |
| 190 | + |
| 191 | + it('the cap: 203 matching rows, one call deletes 200 and says 3 remain, the next call deletes the 3', async () => { |
| 192 | + const rows = Array.from({ length: 203 }, (_, i) => ({ name: `bulk ${i}`, batch: 'cap' })); |
| 193 | + for (const slice of [rows.slice(0, 200), rows.slice(200)]) { |
| 194 | + const res = await stack.apiAs(admin, 'POST', `/data/${BULK}/createMany`, slice); |
| 195 | + expect(res.status, await res.clone().text()).toBeLessThan(300); |
| 196 | + } |
| 197 | + |
| 198 | + const preview = await tool('delete_records', { objectName: BULK, where: { batch: 'cap' } }); |
| 199 | + expect(preview.isError).toBe(true); |
| 200 | + expect(preview.payload.preview).toMatchObject({ matched: 203, wouldAttempt: 200, cap: 200 }); |
| 201 | + |
| 202 | + const first = await tool('delete_records', { objectName: BULK, where: { batch: 'cap' }, [AI_ACTION_CONFIRMATION_MEMBER]: true }); |
| 203 | + expect(first.isError, first.text).toBe(false); |
| 204 | + expect(first.payload).toMatchObject({ matched: 203, attempted: 200, deleted: 200, refused: 0, remaining: 3 }); |
| 205 | + expect(first.payload.next).toContain('3 matching record(s) were past this call\'s cap of 200'); |
| 206 | + |
| 207 | + const second = await tool('delete_records', { objectName: BULK, where: { batch: 'cap' }, [AI_ACTION_CONFIRMATION_MEMBER]: true }); |
| 208 | + expect(second.payload).toMatchObject({ matched: 3, attempted: 3, deleted: 3, remaining: 0 }); |
| 209 | + |
| 210 | + const after = await tool('delete_records', { objectName: BULK, where: { batch: 'cap' } }); |
| 211 | + expect(after.payload.preview).toMatchObject({ matched: 0, wouldAttempt: 0 }); |
| 212 | + }, 180_000); |
| 213 | +}); |
0 commit comments