Skip to content

Commit e223b85

Browse files
committed
docs(mcp): delete_records in the MCP guide, the spec contract and a changeset; dogfood pins (WIP)
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibx1NhZMrqCvW7FBxg5
1 parent 5cc50f9 commit e223b85

4 files changed

Lines changed: 260 additions & 3 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
---
2+
'@objectstack/mcp': patch
3+
'@objectstack/spec': patch
4+
---
5+
6+
feat(mcp): `delete_records` deletes many records of one object in one confirmed call, by a filter or an id list (#30891)
7+
8+
Clause-②: yes (widening) — the MCP surface (HTTP `/api/v1/mcp` and the stdio server) registers one more `data:write` tool, `delete_records`; no existing tool, input or answer changes.
9+
Metadata-protocol: none
10+
11+
An agent that had to clear a set of records called `delete_record` once per row, and confirmed each one. `delete_records` takes the selection as `where` (a filter, `{}` for every record) or `recordIds` (an id list), never both.
12+
13+
- **The preview is the refusal.** A call without `confirm: true` deletes nothing. It answers `delete_record`'s refusal (`428` `ACTION_CONFIRMATION_REQUIRED`, the same `details` keys, `details.actionName` naming `delete_records`) with a `preview` member beside `error`: how many records the selection matches for this caller (`matched`), how many a confirmed call attempts (`wouldAttempt`), up to ten sample ids and, for an id list, the ids that name no readable record (`notFound`). The agent shows that to its human and retries with `confirm: true` once they approve.
14+
- **A confirmed call deletes each record as `delete_record` does**, through the same bridge member, under the caller's permissions, row-level security and the object's delete rules (`beforeDelete` hooks, restricted relations). No caller bypasses a package's locking rule, an administrator included. Records a rule refuses stay, and the answer groups them by code, status and reason, with their ids: `{ matched, attempted, deleted, refused, refusals: [{ code, status, reason, count, recordIds }], remaining, cap }`. A refusal's `details` stays off the wire, as on every other tool.
15+
- **At most 200 records per call**, the bound REST `POST /data/:object/deleteMany` applies by default (`batch.maxBatchSize`). A filter is worked in id order; when more than 200 match, the answer says how many remain and the next call with the same selection continues. When the deployment has no aggregate support, the answer says `matchedMoreThan: 200` instead of guessing a count.
16+
17+
What a preview cannot say: which records a delete rule will refuse. The engine has no delete dry run, so the rules are judged when the confirmed call runs, and the preview says so.
18+
19+
`@objectstack/spec` changes only a doc comment: `AIActionConfirmation` names `delete_records` as the third door of the confirmation member.

‎content/docs/ai/connect-mcp.mdx‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,7 @@ decision.
245245

246246
## What the agent gets
247247

248-
Twelve tools, generated from your metadata:
248+
Thirteen tools, generated from your metadata:
249249

250250
| Tool | What it does |
251251
|:---|:---|
@@ -254,6 +254,7 @@ Twelve tools, generated from your metadata:
254254
| `query_records` / `get_record` | Read data (list queries are capped at 50 rows per page by default) |
255255
| `aggregate_records` | Grouped aggregation (registered when the active driver supports it) |
256256
| `create_record` / `update_record` / `delete_record` | Write data |
257+
| `delete_records` | Delete many records of one object, by a filter or an id list, at most 200 per call |
257258
| `list_actions` / `run_action` | Discover and invoke your business actions by name |
258259
| `resume_run` | Finish a flow action that paused on a screen, by submitting the screen's values |
259260

@@ -383,6 +384,18 @@ drive this MCP server. Same word, different layer.
383384
with `confirm: true`; the flag asserts an approval, it does not obtain one.
384385
REST `DELETE /api/v1/data/:object/:id` and `update_record` take no
385386
confirmation.
387+
- **`delete_records` takes the same gate, and its refusal is the preview.** A
388+
call without `confirm: true` reads the selection as the caller and deletes
389+
nothing: the same `428` refusal (`details.actionName` naming
390+
`delete_records`) arrives with a `preview` beside it, saying how many records
391+
match, how many a confirmed call attempts and a sample of their ids, for the
392+
agent to show its human. A confirmed call deletes at most 200 records, each
393+
exactly as `delete_record` would: under the caller's permissions and
394+
row-level security, and through the object's delete rules (a package's
395+
locking hook, a restricted relation), which no caller bypasses, an
396+
administrator included. Records a rule refuses stay, and the answer counts
397+
them grouped by reason with their ids; when more than 200 match it says how
398+
many remain, and the next call continues.
386399

387400
## Verify the connection
388401

@@ -411,7 +424,7 @@ call '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":
411424
# → {"result":{"serverInfo":{"name":"objectstack",...},"capabilities":{"tools":{...},"prompts":{}}},...}
412425

413426
call '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | grep -o '"name":"[a-z_]*"'
414-
# → the twelve tools, list_objects … resume_run
427+
# → the thirteen tools, list_objects … resume_run
415428

416429
call '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"query_records","arguments":{"objectName":"crm_opportunity","limit":3}}}'
417430
# → {"result":{"content":[{"type":"text","text":"{ \"object\": \"crm_opportunity\", \"records\": [ ... ], \"total\": 23, \"hasMore\": true }"}]}}
Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
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+
});

‎packages/spec/src/contracts/ai-service.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,18 @@ export const AI_ACTION_CONFIRMATION_MEMBER = 'confirm';
319319
* The gate's bounds are part of the decision: REST `DELETE /api/v1/data/...`
320320
* (the human path) and the `update_record` tool stay outside it, no object is
321321
* exempt, and any future bulk-delete tool takes the same gate.
322+
*
323+
* ## The third gate: the MCP `delete_records` tool
324+
*
325+
* The bulk delete (#30891) takes that gate, with the same member, code, HTTP
326+
* status and `details` shape, whose `actionName` is `delete_records`. One
327+
* difference, and it is the tool's reason to exist: its unconfirmed call READS
328+
* the selection (a filter or an id list), as the caller, and answers the
329+
* refusal with a `preview` member beside `error` (how many records match, how
330+
* many a confirmed call attempts, sample ids), so the human approves a count
331+
* rather than a filter. Nothing is deleted. A confirmed call deletes each
332+
* selected record as `delete_record` does, under the caller's permissions and
333+
* the object's delete rules, which no caller bypasses.
322334
*/
323335
export interface AIActionConfirmation {
324336
/**
@@ -340,7 +352,7 @@ export interface AIActionConfirmation {
340352
export interface ActionConfirmationRequiredDetails {
341353
/**
342354
* The declarative action name the refused call addressed; on the MCP
343-
* `delete_record` door, the tool's own name, `delete_record`.
355+
* `delete_record` and `delete_records` doors, the tool's own name.
344356
*/
345357
actionName: string;
346358
/** The object the action operates on; omitted for object-less actions. */

0 commit comments

Comments
 (0)