Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/35138-query-records-truncated.md
Original file line number Diff line number Diff line change
@@ -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`.
75 changes: 68 additions & 7 deletions packages/mcp/src/mcp-http-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1799,6 +1799,54 @@ function wireCodeOf(err: unknown, thrownCode: string): string {
return typeof armCode === 'string' ? armCode : thrownCode;
}

/**
* [#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<string, unknown>;
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 } : {}),
};
}

/**
* [ADR-0090 D10 — ruling 2026-09-08, consequence 2] Attach the D10 narrowing
* notice to a query result WITHOUT reshaping it.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
});
});
Expand Down
3 changes: 2 additions & 1 deletion packages/mcp/src/mcp-server-runtime.http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
187 changes: 187 additions & 0 deletions packages/mcp/src/query-records-truncated.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>): Promise<any> {
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();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -491,7 +491,9 @@ const BRIDGE_MEMBERS: Record<string, string> = {
*/
const ENGINE_READ_SITES: Record<string, Record<string, number>> = {
// 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
Expand Down
18 changes: 17 additions & 1 deletion packages/mcp/src/stdio-data-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Loading