From 74a5e9adc4c08f637a61099f037054bd5f5200c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 10:12:12 +0000 Subject: [PATCH 1/3] feat(mcp): query_records says truncated: true on a capped page, and the stdio door counts its total Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- .changeset/35138-query-records-truncated.md | 12 ++ packages/mcp/src/mcp-http-tools.ts | 75 ++++++- ...p-http-tools.unknown-argument-keys.test.ts | 4 +- .../mcp/src/mcp-server-runtime.http.test.ts | 3 +- .../mcp/src/query-records-truncated.test.ts | 187 ++++++++++++++++++ packages/mcp/src/stdio-data-bridge.ts | 18 +- 6 files changed, 289 insertions(+), 10 deletions(-) create mode 100644 .changeset/35138-query-records-truncated.md create mode 100644 packages/mcp/src/query-records-truncated.test.ts diff --git a/.changeset/35138-query-records-truncated.md b/.changeset/35138-query-records-truncated.md new file mode 100644 index 00000000000..254bff39355 --- /dev/null +++ b/.changeset/35138-query-records-truncated.md @@ -0,0 +1,12 @@ +--- +"@objectstack/mcp": patch +--- + +Clause-②: yes (widening) +Metadata-protocol: none + +`query_records` says when a page hit its row cap. The tool asks for one row more than the page; when that row comes back, it serves the page and adds `truncated: true`. The member is present only when true, so a page that holds every matching row, exactly `limit` rows included, is unchanged. The tool description now tells a model not to sum, count or rank a truncated page as if whole, and to read on with `offset` or use `aggregate_records` for totals. + +The stdio door's `query_records` now answers the same page facts as the HTTP door: a paged read is counted under the same filter, as the caller, so `total` is the match total and `hasMore` says whether rows remain. Before, a capped stdio page answered `total` equal to the page length. If the count fails, `total` is left out and is never estimated. + +When the host's read window (`OS_DATA_MAX_PAGE_SIZE`, `OS_DATA_QUERY_ROW_BUDGET`) would refuse the extra row, the page is read as asked, and the door's counted `hasMore` decides `truncated`. diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 9a18605c784..f10f901f614 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -1819,6 +1819,54 @@ function withDelegationNotice(value: unknown, statement: string): unknown { return { result: value, ...notice }; } +/** + * [#35138] May `query_records` read one row past its page, to learn whether + * the page was capped? + * + * The data door's read window REFUSES, never clamps, a read asking for more + * rows than `OS_DATA_MAX_PAGE_SIZE` or walking past `OS_DATA_QUERY_ROW_BUDGET` + * (`@objectstack/types`' `query-read-limits.ts`). A probe row that crosses + * either would turn a page the caller may read into a refusal, so there the + * page is read exactly as asked and the door's counted `hasMore` decides + * ({@link servedQueryPage}). + */ +function queryPageProbeFits(page: number, offset: number | undefined): boolean { + const { maxPageSize, rowBudget } = resolveQueryReadLimits(); + if (maxPageSize !== undefined && page + 1 > maxPageSize) return false; + if (rowBudget !== undefined && (offset ?? 0) + page + 1 > rowBudget) return false; + return true; +} + +/** + * [#35138] Serve one `query_records` page, and say when it was capped. + * + * A page read with a probe (`probed`: the bridge was asked for `page + 1` + * rows) is capped when the probe row came back: the extra row is dropped and + * the answer carries `truncated: true`. A page read without one is capped + * when the door's own counted `hasMore` says so. `truncated` is present only + * when true, so an answer whose page holds every matching row (exactly + * `page` rows included) is unchanged. `hasMore`, where the bridge answers it, + * states the same fact: it was counted against the probe-widened read, so it + * is restated from the probe rather than left one row out. + * + * Anything that is not a `{ records: [...] }` object is served as it came — + * the {@link withDelegationNotice} posture: no wrapper is invented to carry a + * flag about a shape this tool cannot read. + */ +function servedQueryPage(result: unknown, page: number, probed: boolean): unknown { + if (result === null || typeof result !== 'object' || Array.isArray(result)) return result; + const answer = result as Record; + const records = answer.records; + if (!Array.isArray(records)) return result; + const truncated = probed ? records.length > page : answer.hasMore === true; + return { + ...answer, + records: probed ? records.slice(0, page) : records, + ...(probed && typeof answer.hasMore === 'boolean' ? { hasMore: truncated } : {}), + ...(truncated ? { truncated: true as const } : {}), + }; +} + function jsonText(value: unknown): string { try { return JSON.stringify(value, null, 2); @@ -2910,6 +2958,11 @@ export function registerObjectTools( description: 'Query records from an object with optional filter, field selection, sorting and pagination. ' + 'Runs under the caller\'s permissions and row-level security. ' + + // [#35138] A capped page is one page, never the set: the model is + // told not to sum, count or rank it as if whole. + 'The answer is one page of at most limit rows. When more records match, it carries "truncated": true: ' + + 'the rows are not all of them, so do not sum, count or rank them as if whole; read on with offset, ' + + 'or, where it is offered, use aggregate_records for totals and breakdowns. ' + 'A filter value "{current_user_id}" stands for you. ' + // [#32442] The console's My Pending list, filter for filter: the // participant read alone also serves requests the caller submitted @@ -2971,13 +3024,21 @@ export function registerObjectTools( const bad = await readGuard(objectName); if (bad) return errorResult(bad); try { - const result = await bridge.query(objectName, { - where, - fields, - limit: Math.min(limit ?? maxLimit, maxLimit), - offset, - orderBy, - }); + // [#35138] A capped page says so: one row past the page is asked + // for, and its coming back is the cap (`servedQueryPage`). + const page = Math.min(limit ?? maxLimit, maxLimit); + const probed = queryPageProbeFits(page, offset); + const result = servedQueryPage( + await bridge.query(objectName, { + where, + fields, + limit: probed ? page + 1 : page, + offset, + orderBy, + }), + page, + probed, + ); // [ADR-0090 D10 — ruling 2026-09-08, consequence 2] A delegated read // the agent ceiling NARROWED is served with the narrowing stated. The // rows are still served — a partial answer is the most useful true diff --git a/packages/mcp/src/mcp-http-tools.unknown-argument-keys.test.ts b/packages/mcp/src/mcp-http-tools.unknown-argument-keys.test.ts index 1b51bbbe1e2..813720e4b83 100644 --- a/packages/mcp/src/mcp-http-tools.unknown-argument-keys.test.ts +++ b/packages/mcp/src/mcp-http-tools.unknown-argument-keys.test.ts @@ -197,7 +197,9 @@ describe('MCP tool arguments — undeclared keys are refused (#16913)', () => { where: { status: 'open' }, fields: ['name', 'amount'], orderBy: [{ field: 'amount', order: 'desc' }], - limit: 3, + // [#35138] The page asked for plus the one probe row the handler's + // `truncated` is decided by; the page served is still 3 rows. + limit: 4, offset: 6, }); }); diff --git a/packages/mcp/src/mcp-server-runtime.http.test.ts b/packages/mcp/src/mcp-server-runtime.http.test.ts index 096351103b7..52f737a6587 100644 --- a/packages/mcp/src/mcp-server-runtime.http.test.ts +++ b/packages/mcp/src/mcp-server-runtime.http.test.ts @@ -150,7 +150,8 @@ describe('MCPServerRuntime.handleHttpRequest (Streamable HTTP)', () => { const queryCall = bridge.calls.find((c) => c[0] === 'query'); expect(queryCall[1]).toBe('task'); expect(queryCall[2].where).toEqual({ status: 'open' }); - expect(queryCall[2].limit).toBe(5); + // [#35138] The capped page (5) plus the one probe row `truncated` is decided by. + expect(queryCall[2].limit).toBe(6); }); it('rejects system objects on object-scoped tools (fail-closed)', async () => { diff --git a/packages/mcp/src/query-records-truncated.test.ts b/packages/mcp/src/query-records-truncated.test.ts new file mode 100644 index 00000000000..5541b8ad7af --- /dev/null +++ b/packages/mcp/src/query-records-truncated.test.ts @@ -0,0 +1,187 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35138] A `query_records` page that hit its row cap says so with + * `truncated: true`, on both doors, so a model does not sum or rank one page + * as if it were the whole set. + * + * The flag is decided by a probe: the handler asks the bridge for one row + * more than the page, serves the page, and flags it when the extra row came + * back. A page holding exactly `limit` rows and no more carries no flag. The + * flag is present only when true. + * + * The two doors are the two bridges the tool runs over: the HTTP door's + * (`packages/runtime` `domains/mcp.ts`, `callData('query')` into the data + * door's `findData`, which answers a counted `total` and `hasMore`; the stand + * in below answers the same page facts) and the stdio door's + * (`createStdioDataBridge`, over a stand-in engine). The stdio bridge used to + * answer `total: records.length` with no `hasMore`, so a capped stdio page + * claimed to be whole; it now counts, as the data door does, and never states + * a total it did not count. + * + * Where the host's read window (`OS_DATA_MAX_PAGE_SIZE` / + * `OS_DATA_QUERY_ROW_BUDGET`) would refuse the probe row, the page is read as + * asked and the door's counted `hasMore` decides. + */ + +import { afterEach, describe, it, expect, vi } from 'vitest'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; +import { createStdioDataBridge } from './stdio-data-bridge.js'; +import { registerObjectTools, type McpDataBridge } from './mcp-http-tools.js'; + +const OBJECT = 'cap_deal'; +const DEF = { name: OBJECT, fields: { name: { type: 'text' } } }; +const PRINCIPAL = { userId: 'u1', isSystem: false } as unknown as ExecutionContext; + +const rowsOf = (n: number) => Array.from({ length: n }, (_, i) => ({ id: `d${i + 1}`, name: `deal ${i + 1}` })); + +type QueryOpts = { limit?: number; offset?: number }; + +/** The HTTP door's bridge: the data door's `findData` page facts — a counted total and `hasMore`. */ +function httpDoor(stored: number) { + const rows = rowsOf(stored); + const asked: QueryOpts[] = []; + const bridge = { + async listObjects() { return [{ name: OBJECT, label: 'Deal' }]; }, + async describeObject(name: string) { return { name }; }, + async query(object: string, opts: QueryOpts) { + asked.push({ limit: opts.limit, offset: opts.offset }); + const offset = opts.offset ?? 0; + const records = rows.slice(offset, opts.limit === undefined ? undefined : offset + opts.limit); + return { object, records, total: rows.length, hasMore: offset + records.length < rows.length }; + }, + async get(object: string, id: string) { return { object, id }; }, + async create(object: string, data: unknown) { return { object, data }; }, + async update(object: string, id: string) { return { object, id }; }, + async remove(object: string, id: string) { return { object, id, success: true }; }, + } as unknown as McpDataBridge; + return { bridge, asked }; +} + +/** The stdio door's bridge, over a stand-in engine that honours `limit` / `offset` and counts. */ +function stdioDoor(stored: number, opts: { countThrows?: boolean } = {}) { + const rows = rowsOf(stored); + const asked: QueryOpts[] = []; + const engine = { + find: vi.fn(async (_object: string, query: QueryOpts) => { + asked.push({ limit: query.limit, offset: query.offset }); + const offset = query.offset ?? 0; + return rows.slice(offset, query.limit === undefined ? undefined : offset + query.limit); + }), + count: vi.fn(async () => { + if (opts.countThrows) throw new Error('count unavailable'); + return rows.length; + }), + }; + const metadataService = { getObject: vi.fn(async (name: string) => (name === OBJECT ? DEF : undefined)) }; + const bridge = createStdioDataBridge({ + engine: engine as unknown as IDataEngine, + metadataService: metadataService as unknown as IMetadataService, + resolvePrincipal: async () => PRINCIPAL, + }); + return { bridge, asked, engine }; +} + +async function queryRecords(bridge: McpDataBridge, args: Record): Promise { + const server = new McpServer({ name: 'pin', version: '0' }); + registerObjectTools(server, bridge); + const [clientSide, serverSide] = InMemoryTransport.createLinkedPair(); + await server.connect(serverSide); + const client = new Client({ name: 'pin', version: '0' }); + await client.connect(clientSide); + try { + const res = (await client.callTool({ + name: 'query_records', + arguments: { objectName: OBJECT, ...args }, + })) as { isError?: boolean; content: Array<{ text: string }> }; + expect(res.isError, res.content[0]?.text).toBeFalsy(); + return JSON.parse(res.content[0]!.text); + } finally { + await client.close(); + } +} + +const DOORS = [ + ['HTTP', httpDoor], + ['stdio', stdioDoor], +] as const; + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +describe('query_records — a capped page says `truncated: true` (#35138)', () => { + for (const [door, make] of DOORS) { + it(`${door} door: a page that hit its cap answers truncated: true, with the page only`, async () => { + const { bridge, asked } = make(5); + const payload = await queryRecords(bridge, { limit: 3 }); + expect(payload.truncated).toBe(true); + expect(payload.records.map((r: { id: string }) => r.id)).toEqual(['d1', 'd2', 'd3']); + expect(payload.total).toBe(5); + expect(payload.hasMore).toBe(true); + // The probe: one row past the page was asked for. + expect(asked).toEqual([{ limit: 4, offset: undefined }]); + }); + + it(`${door} door: a page with exactly limit rows and no more answers no truncated`, async () => { + const { bridge } = make(3); + const payload = await queryRecords(bridge, { limit: 3 }); + expect('truncated' in payload).toBe(false); + expect(payload.records).toHaveLength(3); + expect(payload.total).toBe(3); + expect(payload.hasMore).toBe(false); + }); + + it(`${door} door: the last page of a paged read is not capped`, async () => { + const { bridge } = make(5); + const payload = await queryRecords(bridge, { limit: 3, offset: 3 }); + expect('truncated' in payload).toBe(false); + expect(payload.records.map((r: { id: string }) => r.id)).toEqual(['d4', 'd5']); + expect(payload.hasMore).toBe(false); + }); + + it(`${door} door: where the read window would refuse the probe row, the page is read as asked and hasMore decides`, async () => { + vi.stubEnv('OS_DATA_MAX_PAGE_SIZE', '3'); + const capped = make(5); + const payload = await queryRecords(capped.bridge, { limit: 3 }); + expect(capped.asked).toEqual([{ limit: 3, offset: undefined }]); + expect(payload.truncated).toBe(true); + expect(payload.records).toHaveLength(3); + + const whole = make(3); + expect('truncated' in (await queryRecords(whole.bridge, { limit: 3 }))).toBe(false); + }); + } +}); + +describe('stdio query: the page facts are counted, never the page length (#35138)', () => { + it('a capped page answers the match total and hasMore, not total: records.length', async () => { + const { bridge, engine } = stdioDoor(5); + const page: any = await bridge.query(OBJECT, { limit: 3 }); + expect(page.records).toHaveLength(3); + expect(page.total).toBe(5); + expect(page.hasMore).toBe(true); + // Counted as the caller, under the caller's filter. + expect(engine.count).toHaveBeenCalledWith(OBJECT, {}, { context: PRINCIPAL }); + }); + + it('a count that fails states no total at all', async () => { + const { bridge } = stdioDoor(5, { countThrows: true }); + const page: any = await bridge.query(OBJECT, { limit: 3 }); + expect(page.records).toHaveLength(3); + expect('total' in page).toBe(false); + expect(page.hasMore).toBe(true); + }); + + it('an unpaged read is the whole set: its length is the total, and no count runs', async () => { + const { bridge, engine } = stdioDoor(4); + const page: any = await bridge.query(OBJECT, {}); + expect(page.total).toBe(4); + expect(page.hasMore).toBe(false); + expect(engine.count).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index 70f78a7a4cd..847ac8aaef7 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -1375,7 +1375,23 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge dropType: read.addedType, }).map((row) => serveStoredMetadataHashes(object, row, digest)), ); - return { object, records, total: records.length }; + // [#35138] The page facts the data door answers (`findData`): a paged + // read is counted under the same filter, as the caller, so `total` is + // the match total and `hasMore` says whether rows remain past this page. + // Before, a capped page answered `total: records.length` and claimed to + // be the whole set. ⛔ A total this bridge did not count is never stated: + // a count that fails leaves `total` out, and `hasMore` answers from the + // page alone, the door's `$count=false` arm (a full page may have more). + const limit = typeof opts?.limit === 'number' ? opts.limit : undefined; + const offset = typeof opts?.offset === 'number' && opts.offset > 0 ? opts.offset : 0; + if (limit === undefined && offset === 0) return { object, records, total: records.length, hasMore: false }; + let counted: number; + try { + counted = await engine.count(object, opts?.where ? { where: opts.where } : {}, { context }); + } catch { + return { object, records, hasMore: limit !== undefined && records.length >= limit }; + } + return { object, records, total: counted, hasMore: offset + records.length < counted }; }, async get(object, id) { From d85434872fdeb321d0e51959f17fa395c8b75ac3 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 10:24:27 +0000 Subject: [PATCH 2/3] test(mcp): the stdio engine-read census names query's page count Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- .../mcp/src/stdio-data-bridge.stored-metadata-body.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts b/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts index 64fba8a2cd8..985e31f0310 100644 --- a/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts +++ b/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts @@ -491,7 +491,9 @@ const BRIDGE_MEMBERS: Record = { */ const ENGINE_READ_SITES: Record> = { // findById (get, and the update / remove existence probes) and query; aggregate. - 'stdio-data-bridge.ts': { 'find(object)': 2, 'aggregate(object)': 1 }, + // [#35138] `count(object)`: `query`'s page total, a number and never a row, + // counted under the `where` the stored-body and hash refusals already judged. + 'stdio-data-bridge.ts': { 'find(object)': 2, 'aggregate(object)': 1, 'count(object)': 1 }, // The ADR-0101 record resource reader. 'plugin.ts': { 'find(objectName)': 1 }, // [#30891] NOT an engine read: `delete_records` counting its selection From c56f66f4efc04d4e00411e35f0ff6e02463e962a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 11:08:15 +0000 Subject: [PATCH 3/3] refactor(mcp): the query_records page helpers sit above withDelegationNotice Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi Co-authored-by: Claude --- packages/mcp/src/mcp-http-tools.ts | 40 +++++++++++++++--------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index f10f901f614..17a976e9531 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -1799,26 +1799,6 @@ function wireCodeOf(err: unknown, thrownCode: string): string { return typeof armCode === 'string' ? armCode : thrownCode; } -/** - * [ADR-0090 D10 — ruling 2026-09-08, consequence 2] Attach the D10 narrowing - * notice to a query result WITHOUT reshaping it. - * - * The bridge's `query` is typed `Promise`, and the shape that ships is - * the protocol's `{ object, records, total }` — so the object case adds two - * keys beside the existing ones, mirroring `list_objects`' `partial` / `warning` - * pair so a client branches on the same vocabulary on both tools. Anything that - * is NOT a plain object (a bare array from some future bridge) keeps its own - * shape and carries the notice alongside: inventing a `records` wrapper there - * would break a caller to deliver a warning about breaking callers. - */ -function withDelegationNotice(value: unknown, statement: string): unknown { - const notice = { delegationNarrowed: true as const, warning: statement }; - if (value !== null && typeof value === 'object' && !Array.isArray(value)) { - return { ...(value as Record), ...notice }; - } - return { result: value, ...notice }; -} - /** * [#35138] May `query_records` read one row past its page, to learn whether * the page was capped? @@ -1867,6 +1847,26 @@ function servedQueryPage(result: unknown, page: number, probed: boolean): unknow }; } +/** + * [ADR-0090 D10 — ruling 2026-09-08, consequence 2] Attach the D10 narrowing + * notice to a query result WITHOUT reshaping it. + * + * The bridge's `query` is typed `Promise`, and the shape that ships is + * the protocol's `{ object, records, total }` — so the object case adds two + * keys beside the existing ones, mirroring `list_objects`' `partial` / `warning` + * pair so a client branches on the same vocabulary on both tools. Anything that + * is NOT a plain object (a bare array from some future bridge) keeps its own + * shape and carries the notice alongside: inventing a `records` wrapper there + * would break a caller to deliver a warning about breaking callers. + */ +function withDelegationNotice(value: unknown, statement: string): unknown { + const notice = { delegationNarrowed: true as const, warning: statement }; + if (value !== null && typeof value === 'object' && !Array.isArray(value)) { + return { ...(value as Record), ...notice }; + } + return { result: value, ...notice }; +} + function jsonText(value: unknown): string { try { return JSON.stringify(value, null, 2);