Skip to content

Commit ad203a2

Browse files
committed
fix(mcp): delete_records reads at the cap, stops on a fault, needs both data scopes
Contract-review fixes on the delete_records tool (#30891): - The filter selection is read at the cap, not one row past it; whether more match is the aggregate count's answer. The cap+1 probe stays only for a bridge without aggregate. The per-call cap follows the deployment's read window down (OS_DATA_MAX_PAGE_SIZE / OS_DATA_QUERY_ROW_BUDGET), since the data door refuses a larger read; an id list longer than that cap is refused before anything is read. - A row's throw is judged with the REST data door's own classifier (mapDataError): a 4xx verdict is a refusal and is grouped, a 5xx verdict is a fault and stops the call, answered isError with the fault, the record it stopped at and the call's progress. - delete_records registers only under both data:read and data:write. - The error-code ledger's ACTION_CONFIRMATION_REQUIRED rows name both delete tools. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibx1NhZMrqCvW7FBxg5
1 parent ef1973d commit ad203a2

10 files changed

Lines changed: 735 additions & 213 deletions

‎.changeset/30891-mcp-delete-records.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,17 @@
55

66
feat(mcp): `delete_records` deletes many records of one object in one confirmed call, by a filter or an id list (#30891)
77

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.
8+
Clause-②: yes (widening) — the MCP surface (HTTP `/api/v1/mcp` and the stdio server) registers one more tool, `delete_records`, offered to an OAuth token that carries both `data:read` and `data:write`; no existing tool, input or answer changes.
99
Metadata-protocol: none
1010

1111
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.
1212

1313
- **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.
1414
- **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.
15+
- **A fault is not a refusal.** A rule's refusal and a fault are told apart the way the REST `/data` door tells them apart (its own classifier): a 4xx verdict (a coded rule refusal, a sandboxed hook body's `400 HOOK_ABORTED`) is grouped and the call goes on; a 5xx verdict (a code hook's bare `throw new Error`, a lost connection, a driver error, a driver's own string code) stops the call at that record. The tool error names the fault and the record, and carries the call's `progress` (`deleted`, `stoppedAt`, `notAttempted`): the records deleted before it stay deleted.
16+
- **At most 200 records per call**, the bound REST `POST /data/:object/deleteMany` applies by default (`batch.maxBatchSize`). A filter is read in id order at the cap, and the count says whether more match; 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. On a deployment whose read page size or row budget (`OS_DATA_MAX_PAGE_SIZE`, `OS_DATA_QUERY_ROW_BUDGET`) is under 200, one call runs at that size, since the data door refuses a larger read, and the answer's `cap` names it; a longer id list is refused before anything is read.
17+
- **Scopes.** Over OAuth the tool needs both `data:read` and `data:write`: its preview reads the selection's ids and count, a read a `data:write`-only token is not granted.
1618

1719
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.
1820

19-
`@objectstack/spec` changes only a doc comment: `AIActionConfirmation` names `delete_records` as the third door of the confirmation member.
21+
`@objectstack/spec` changes only doc comments: `AIActionConfirmation` names `delete_records` as the third door of the confirmation member, and the error-code ledger's `ACTION_CONFIRMATION_REQUIRED` rows name both delete tools.

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

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,7 @@ Thirteen 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 |
257+
| `delete_records` | Delete many records of one object, by a filter or an id list, at most 200 per call (an OAuth token needs both `data:read` and `data:write`) |
258258
| `list_actions` / `run_action` | Discover and invoke your business actions by name |
259259
| `resume_run` | Finish a flow action that paused on a screen, by submitting the screen's values |
260260

@@ -395,7 +395,14 @@ drive this MCP server. Same word, different layer.
395395
locking hook, a restricted relation), which no caller bypasses, an
396396
administrator included. Records a rule refuses stay, and the answer counts
397397
them grouped by reason with their ids; when more than 200 match it says how
398-
many remain, and the next call continues.
398+
many remain, and the next call continues. On a deployment whose read page
399+
size or row budget (`OS_DATA_MAX_PAGE_SIZE`, `OS_DATA_QUERY_ROW_BUDGET`) is
400+
under 200, one call runs at that size instead, and the answer's `cap` says
401+
so. A fault (a store error, a crash)
402+
is not a refusal: it stops the call, and the error names the record it
403+
stopped at and how many were already deleted. Because the preview reads ids
404+
and a count, an OAuth token is offered the tool only when it carries both
405+
`data:read` and `data:write`.
399406

400407
## Verify the connection
401408

‎packages/mcp/README.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,8 +131,9 @@ and `resume_run` only when it implements `resumeRun`; a bridge without those
131131
seams serves the rest and advertises nothing it cannot do.
132132

133133
OAuth scopes narrow the families at consent time: `data:read` covers
134-
list/describe/query/aggregate/get, `data:write` covers create/update/delete (both delete tools), and
135-
`actions:execute` covers `list_actions` / `run_action` / `resume_run`. A tool outside the grant
134+
list/describe/query/aggregate/get, `data:write` covers create/update/delete, and
135+
`actions:execute` covers `list_actions` / `run_action` / `resume_run`. `delete_records` needs both
136+
`data:read` and `data:write`: its preview reads the selection's ids and count. A tool outside the grant
136137
is **not registered at all**, so the SDK rejects it as an unknown tool — the
137138
grant doubles as dispatch-time enforcement.
138139

‎packages/mcp/src/mcp-delete-records.test.ts‎

Lines changed: 184 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
* `packages/qa/dogfood/test/mcp-delete-records.dogfood.test.ts`.
3030
*/
3131

32-
import { describe, it, expect, vi, beforeEach } from 'vitest';
32+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
3333
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
3434
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
3535
import { AI_ACTION_CONFIRMATION_MEMBER } from '@objectstack/spec/contracts';
@@ -41,10 +41,11 @@ import {
4141
assertEngineFindOnePredicate,
4242
type EngineFindOneQueryInput,
4343
} from '@objectstack/metadata-core';
44+
import { planQueryReadWindow, resolveQueryReadLimits } from '@objectstack/types';
4445

4546
import { MCPServerRuntime } from './mcp-server-runtime.js';
4647
import { createStdioDataBridge } from './stdio-data-bridge.js';
47-
import { DELETE_RECORDS_MAX_PER_CALL, type McpDataBridge } from './mcp-http-tools.js';
48+
import { DELETE_RECORDS_MAX_PER_CALL, deleteRecordsCap, type McpDataBridge } from './mcp-http-tools.js';
4849

4950
const OBJECT = 'dlr_task';
5051

@@ -103,9 +104,11 @@ function staleRefusal(): Error {
103104
* a package's delete rules do: a `locked` row is refused with
104105
* `RECORD_LOCKED` / 409 whoever asks, a row another user owns with
105106
* `PERMISSION_DENIED` / 403 (carrying `details`), and a `stale` row is
106-
* deleted under a roll-up the engine could not recompute.
107+
* deleted under a roll-up the engine could not recompute. A row carrying
108+
* `throws` throws that value instead, whatever it is (a fault, a sandboxed
109+
* body's refusal).
107110
*/
108-
function engineDouble(rows: Map<string, Row>, opts: { aggregate?: boolean } = {}) {
111+
function engineDouble(rows: Map<string, Row>, opts: { aggregate?: boolean; countAsString?: boolean } = {}) {
109112
const contexts: unknown[] = [];
110113
const engine: Record<string, unknown> = {
111114
find: vi.fn(async (_o: string, query?: any, options?: any) => {
@@ -135,6 +138,7 @@ function engineDouble(rows: Map<string, Row>, opts: { aggregate?: boolean } = {}
135138
contexts.push(options?.context);
136139
const id = String(options?.where?.id);
137140
const row = rows.get(id);
141+
if (row?.throws !== undefined) throw row.throws;
138142
if (row?.locked === true) {
139143
throw Object.assign(new Error(LOCKED_REASON), { code: 'RECORD_LOCKED', status: 409 });
140144
}
@@ -155,7 +159,9 @@ function engineDouble(rows: Map<string, Row>, opts: { aggregate?: boolean } = {}
155159
engine.aggregate = vi.fn(async (_o: string, query: any) => {
156160
contexts.push(query?.context);
157161
const count = [...rows.values()].filter((r) => matches(r, query?.where)).length;
158-
return [Object.fromEntries((query.aggregations as Array<{ alias: string }>).map((a) => [a.alias, count]))];
162+
// A SQL driver may answer COUNT(*) as a decimal string (a 64-bit integer).
163+
const value = opts.countAsString ? String(count) : count;
164+
return [Object.fromEntries((query.aggregations as Array<{ alias: string }>).map((a) => [a.alias, value]))];
159165
});
160166
}
161167
return { engine: engine as any, contexts };
@@ -208,6 +214,34 @@ const parsed = (result: ToolResult) => JSON.parse(result.content[0]!.text);
208214

209215
const task = (id: string, extra: Row = {}): [string, Row] => [id, { id, title: `task ${id}`, status: 'done', ...extra }];
210216

217+
/**
218+
* The data door's read window in front of a bridge: every `query` is planned
219+
* with the platform's own rule (`planQueryReadWindow` over the deployment's
220+
* `OS_DATA_*` limits), which REFUSES a read over the window, never clamps it.
221+
* The limits each read asked for are recorded.
222+
*/
223+
function windowedBridge(inner: McpDataBridge): McpDataBridge & { limits: Array<number | undefined> } {
224+
const limits: Array<number | undefined> = [];
225+
return {
226+
...inner,
227+
limits,
228+
async query(object, options) {
229+
const limit = (options as { limit?: number } | undefined)?.limit;
230+
limits.push(limit);
231+
planQueryReadWindow({ surface: 'list', object, ...(limit !== undefined ? { limit } : {}) }, resolveQueryReadLimits());
232+
return inner.query(object, options);
233+
},
234+
};
235+
}
236+
237+
function fillRows(rows: Map<string, Row>, n: number, extra: (i: number) => Row = () => ({})): void {
238+
rows.clear();
239+
for (let i = 0; i < n; i++) {
240+
const [id, row] = task(`r${String(i).padStart(3, '0')}`, extra(i));
241+
rows.set(id, row);
242+
}
243+
}
244+
211245
describe('MCP delete_records: many records of one object in one confirmed call (#30891)', () => {
212246
let rows: Map<string, Row>;
213247
let double: ReturnType<typeof engineDouble>;
@@ -476,6 +510,151 @@ describe('MCP delete_records: many records of one object in one confirmed call (
476510
expect(double.engine.delete).not.toHaveBeenCalled();
477511
});
478512

513+
describe('the selection read stays inside the deployment\'s read window', () => {
514+
afterEach(() => {
515+
vi.unstubAllEnvs();
516+
});
517+
518+
it('a host whose maximum page size is the cap: a filter over it is read at the cap and counted, never refused', async () => {
519+
vi.stubEnv('OS_DATA_MAX_PAGE_SIZE', String(DELETE_RECORDS_MAX_PER_CALL));
520+
fillRows(rows, 205);
521+
const host = windowedBridge(bridge);
522+
523+
// Lit control: the window really refuses one row past the cap.
524+
await expect(host.query(OBJECT, { where: {}, limit: DELETE_RECORDS_MAX_PER_CALL + 1 })).rejects.toMatchObject({
525+
code: 'MAX_RECORDS_EXCEEDED',
526+
});
527+
host.limits.length = 0;
528+
529+
const previewed = await callTool(host, 'delete_records', { objectName: OBJECT, where: {} });
530+
const { preview } = parsed(previewed);
531+
expect(preview, previewed.content[0]!.text).toMatchObject({ matched: 205, wouldAttempt: 200, cap: 200 });
532+
533+
const answer = parsed(await callTool(host, 'delete_records', { objectName: OBJECT, where: {}, [AI_ACTION_CONFIRMATION_MEMBER]: true }));
534+
expect(answer).toMatchObject({ matched: 205, attempted: 200, deleted: 200, remaining: 5, cap: 200 });
535+
expect(rows.size).toBe(5);
536+
// Every selection read asked for at most the cap.
537+
expect(host.limits.length).toBeGreaterThan(0);
538+
for (const limit of host.limits) expect(limit).toBeLessThanOrEqual(DELETE_RECORDS_MAX_PER_CALL);
539+
});
540+
541+
it('exactly the cap matching is answered exactly, with nothing left to continue', async () => {
542+
vi.stubEnv('OS_DATA_MAX_PAGE_SIZE', String(DELETE_RECORDS_MAX_PER_CALL));
543+
fillRows(rows, DELETE_RECORDS_MAX_PER_CALL);
544+
const host = windowedBridge(bridge);
545+
546+
const answer = parsed(await callTool(host, 'delete_records', { objectName: OBJECT, where: {}, [AI_ACTION_CONFIRMATION_MEMBER]: true }));
547+
expect(answer).toMatchObject({ matched: 200, attempted: 200, deleted: 200, remaining: 0 });
548+
expect(answer.next).toBeUndefined();
549+
expect(rows.size).toBe(0);
550+
});
551+
552+
it('a count a SQL driver answers as a decimal string is read as the count', async () => {
553+
fillRows(rows, 203);
554+
const sql = stdioBridge(engineDouble(rows, { countAsString: true }).engine);
555+
556+
const { preview } = parsed(await callTool(sql, 'delete_records', { objectName: OBJECT, where: {} }));
557+
expect(preview).toMatchObject({ matched: 203, wouldAttempt: 200 });
558+
expect('matchedMoreThan' in preview).toBe(false);
559+
});
560+
561+
it.each([
562+
['maximum page size', 'OS_DATA_MAX_PAGE_SIZE'],
563+
['query row budget', 'OS_DATA_QUERY_ROW_BUDGET'],
564+
])('a %s under the cap lowers this call\'s cap to it, and the answer says so', async (_label, variable) => {
565+
vi.stubEnv(variable, '50');
566+
expect(deleteRecordsCap()).toBe(50);
567+
fillRows(rows, 60);
568+
const host = windowedBridge(bridge);
569+
570+
const { preview } = parsed(await callTool(host, 'delete_records', { objectName: OBJECT, where: {} }));
571+
expect(preview).toMatchObject({ matched: 60, wouldAttempt: 50, cap: 50 });
572+
573+
const answer = parsed(await callTool(host, 'delete_records', { objectName: OBJECT, where: {}, [AI_ACTION_CONFIRMATION_MEMBER]: true }));
574+
expect(answer).toMatchObject({ matched: 60, attempted: 50, deleted: 50, remaining: 10, cap: 50 });
575+
expect(answer.next).toContain('cap of 50');
576+
for (const limit of host.limits) expect(limit).toBeLessThanOrEqual(50);
577+
});
578+
579+
it('an id list longer than a lowered cap is refused before anything is read, and nothing is deleted', async () => {
580+
vi.stubEnv('OS_DATA_MAX_PAGE_SIZE', '2');
581+
const result = await callTool(bridge, 'delete_records', {
582+
objectName: OBJECT,
583+
recordIds: ['t1', 't3', 't6'],
584+
[AI_ACTION_CONFIRMATION_MEMBER]: true,
585+
});
586+
587+
expect(result.isError).toBe(true);
588+
expect(result.content[0]!.text).toContain('at most 2 ids per call');
589+
expect(double.engine.find).not.toHaveBeenCalled();
590+
expect(double.engine.delete).not.toHaveBeenCalled();
591+
expect(rows.size).toBe(6);
592+
});
593+
});
594+
595+
describe('a fault stops the call; a rule\'s refusal does not', () => {
596+
it.each([
597+
['an uncoded throw (a code hook\'s bare Error, a lost connection)', new Error('socket hang up'), undefined, undefined],
598+
['a coded 5xx', Object.assign(new Error('The store is unavailable.'), { code: 'INTERNAL_ERROR', status: 500 }), 'INTERNAL_ERROR', 500],
599+
['a driver\'s own string code', Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:5432'), { code: 'ECONNREFUSED' }), 'ECONNREFUSED', undefined],
600+
])('%s ends the call at that row: an error naming it and what was already deleted', async (_label, thrown, code, status) => {
601+
rows.get('t3')!.throws = thrown;
602+
603+
const result = await callTool(bridge, 'delete_records', {
604+
objectName: OBJECT,
605+
where: { status: 'done' },
606+
[AI_ACTION_CONFIRMATION_MEMBER]: true,
607+
});
608+
609+
expect(result.isError).toBe(true);
610+
const { error, progress } = parsed(result);
611+
expect(error.code).toBe(code);
612+
expect(error.status).toBe(status);
613+
expect(error.message).toContain("stopped at record 't3'");
614+
expect(error.message).toContain((thrown as Error).message);
615+
expect(error.message).toContain('1 record(s) were deleted before it and stay deleted; 2 were not attempted');
616+
// t1 deleted, t2 refused by its lock, t3 the fault; t4 and t5 never asked.
617+
expect(progress).toMatchObject({
618+
matched: 5,
619+
attempted: 3,
620+
deleted: 1,
621+
refused: 1,
622+
refusals: [{ code: 'RECORD_LOCKED', status: 409, count: 1, recordIds: ['t2'] }],
623+
stoppedAt: 't3',
624+
notAttempted: 2,
625+
remaining: 4,
626+
});
627+
expect(progress.next).toBeUndefined();
628+
expect(double.engine.delete).toHaveBeenCalledTimes(3);
629+
expect([...rows.keys()]).toEqual(['t2', 't3', 't4', 't5', 't6']);
630+
});
631+
632+
it('a sandboxed hook body\'s refusal (no code) is a refusal: grouped as the data door answers it, and the call goes on', async () => {
633+
const sentence = 'This task is approved and cannot be deleted.';
634+
// The shape the sandbox runner relays a body's own throw in: the body's
635+
// sentence on `innerMessage`, no `code`.
636+
rows.get('t3')!.throws = Object.assign(new Error(`[sandbox] hook body threw: ${sentence}`), {
637+
name: 'SandboxError',
638+
innerMessage: sentence,
639+
});
640+
641+
const result = await callTool(bridge, 'delete_records', {
642+
objectName: OBJECT,
643+
recordIds: ['t1', 't3', 't6'],
644+
[AI_ACTION_CONFIRMATION_MEMBER]: true,
645+
});
646+
647+
expect(result.isError, result.content[0]?.text).toBeFalsy();
648+
expect(parsed(result)).toMatchObject({
649+
attempted: 3,
650+
deleted: 2,
651+
refused: 1,
652+
refusals: [{ code: 'HOOK_ABORTED', status: 400, reason: sentence, count: 1, recordIds: ['t3'] }],
653+
});
654+
expect([...rows.keys()]).toEqual(['t2', 't3', 't4', 't5']);
655+
});
656+
});
657+
479658
it('the long-lived server the stdio transport serves refuses, previews and deletes the same way', async () => {
480659
const runtime = new MCPServerRuntime({ name: 'pin-stdio', version: '0.0.0' });
481660
runtime.bridgeDataTools(bridge);

0 commit comments

Comments
 (0)