From 139ec16bcc3c6f00c6053ae560649494180a7e26 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 13:53:58 +0000 Subject: [PATCH 01/11] feat(mcp): query_records expand and get_record related, judged by the read guard WIP: tool surface, relation judging, runtime and stdio bridge forwarding. Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL Co-authored-by: Claude --- packages/mcp/src/mcp-http-tools.ts | 124 +++++++++++- packages/mcp/src/mcp-relation-reads.ts | 257 +++++++++++++++++++++++++ packages/mcp/src/stdio-data-bridge.ts | 67 ++++++- packages/runtime/src/domains/mcp.ts | 4 + 4 files changed, 445 insertions(+), 7 deletions(-) create mode 100644 packages/mcp/src/mcp-relation-reads.ts diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 5908040c1e0..b739e32d5e0 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -126,6 +126,15 @@ import { // [#30892] The file seam and what `read_file` renders from it. import { READ_FILE_MAX_BYTES, ReadFileExtractionBusyError, renderReadFile, type McpFileBridge } from './file-content.js'; import { actionConfirmationElicitorFor, type McpActionCallDoor } from './action-confirmation-elicitation.js'; +// [#35145] `expand` and `related`: the relation reads, judged before any read. +import { + GET_RECORD_MAX_RELATED_LISTS, + QUERY_EXPAND_MAX_FIELDS, + RELATED_LIST_MAX_ROWS, + judgeQueryExpand, + judgeRelatedLists, + relatedListWhere, +} from './mcp-relation-reads.js'; export interface McpObjectSummary { name: string; @@ -228,6 +237,14 @@ export interface McpDataBridge { limit?: number; offset?: number; orderBy?: Array<{ field: string; order: 'asc' | 'desc' }>; + /** + * [#35145] Reference fields of `object` to answer with the record each + * one names (`query_records`' `expand`), one level deep. The tool has + * judged every name and the read guard every target before it calls; the + * bridge resolves them through the engine's one expansion path, under + * each target's own permissions, row and field security. + */ + expand?: string[]; }, ): Promise; /** @@ -3118,7 +3135,12 @@ export function registerObjectTools( // Names repeat (ruling 6867150851), so the text says to tell // namesakes apart by email. 'To fill a person field, find the colleague\'s id: objectName "sys_user", where {"email":"..."} for exactly ' + - 'one person, or {"name":{"$contains":"..."}}; names repeat, so tell people who share a name apart by email.', + 'one person, or {"name":{"$contains":"..."}}; names repeat, so tell people who share a name apart by email. ' + + // [#35145] One level of forward relations in the same call. + `To read the records a lookup points at in the same call, pass expand: up to ${QUERY_EXPAND_MAX_FIELDS} of the ` + + 'object\'s lookup, master-detail, user or tree fields, e.g. expand ["account","owner_id"]; each one comes back ' + + 'as the record it names, under your permissions on that object. One level only; a field whose object you ' + + 'may not read refuses the call.', inputSchema: strictToolInput( { surface: 'this query_records call', @@ -3159,14 +3181,27 @@ export function registerObjectTools( .array(z.object({ field: z.string(), order: z.enum(['asc', 'desc']) })) .optional() .describe('Sort order'), + expand: z + .array(z.string().min(1)) + .min(1) + .max(QUERY_EXPAND_MAX_FIELDS) + .optional() + .describe( + `Up to ${QUERY_EXPAND_MAX_FIELDS} lookup / master-detail fields of this object to return as the record ` + + 'each one names, one level deep, e.g. ["account","owner_id"]', + ), }, ), annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, }, - async ({ objectName, where, fields, limit, offset, orderBy }) => { + async ({ objectName, where, fields, limit, offset, orderBy, expand }) => { const bad = await readGuard(objectName); if (bad) return errorResult(bad); try { + // [#35145] Every expanded field's target is judged by the read guard + // as `objectName` was, before anything is read; a refused one + // refuses the call (`judgeQueryExpand`). + const expanded = expand !== undefined ? await judgeQueryExpand(bridge, readGuard, objectName, expand) : undefined; // [#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); @@ -3178,6 +3213,7 @@ export function registerObjectTools( limit: probed ? page + 1 : page, offset, orderBy, + ...(expanded !== undefined ? { expand: expanded } : {}), }), page, probed, @@ -3312,23 +3348,72 @@ export function registerObjectTools( ); } + // [#35145] A related list's row cap: never above the door's own page cap. + const relatedMaxRows = Math.min(RELATED_LIST_MAX_ROWS, maxLimit); server.registerTool( note('get_record'), { - description: 'Fetch a single record by id.', + description: + 'Fetch a single record by id. ' + + // [#35145] A parent with its children in one call. + `To read it with the records that point at it, pass related: up to ${GET_RECORD_MAX_RELATED_LISTS} child ` + + 'objects, e.g. an account with its deals and activities: related [{"object":"crm_opportunity"},' + + '{"object":"crm_activity","field":"account"}]. Name field when the child points at this object through ' + + `several fields. Each list holds at most ${relatedMaxRows} rows (limit), filtered only by the link to this ` + + 'record, under your permissions on that object; fields and orderBy are that object\'s. The answer is then ' + + '{ record, related: [{ object, field, records, total, hasMore }] }; a list that carries "truncated": true ' + + 'has more rows than came back. An object you may not read refuses the call.', inputSchema: strictToolInput( { surface: 'this get_record call', aliases: { ...OBJECT_NAME_ALIASES, ...RECORD_ID_ALIASES } }, { objectName: z.string().describe('The object/table name'), recordId: z.string().describe(RECORD_ID_DESCRIPTION), + related: z + .array( + z + .object({ + object: z.string().min(1).describe('A child object that points at this record'), + field: z + .string() + .min(1) + .optional() + .describe('Its field that points at this record; needed only when it has several'), + fields: z.array(z.string()).optional().describe('Field names to return (defaults to all)'), + orderBy: z + .array(z.object({ field: z.string(), order: z.enum(['asc', 'desc']) }).strict()) + .optional() + .describe('Sort order'), + limit: z + .number() + .int() + .positive() + .max(relatedMaxRows) + .optional() + .describe(`Max rows in this list (≤ ${relatedMaxRows}, the default)`), + }) + .strict(), + ) + .min(1) + .max(GET_RECORD_MAX_RELATED_LISTS) + .optional() + .describe(`Up to ${GET_RECORD_MAX_RELATED_LISTS} lists of child records that point at this record`), }, ), annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, }, - async ({ objectName, recordId }) => { + async ({ objectName, recordId, related }) => { const bad = await readGuard(objectName); if (bad) return errorResult(bad); + // A related list's refusal is the whole call's, rendered against the + // child object it was read on. + let refusedOn: string | undefined; try { + // [#35145] Every related object is judged by the read guard as + // `objectName` was, and each link field against the child as the + // caller is served it, before any record is read. + const plans = related !== undefined + ? await judgeRelatedLists(bridge, readGuard, objectName, related, relatedMaxRows) + : undefined; const record = await bridge.get(objectName, recordId); // A bridge that answers a miss with `null` (the stdio bridge, by // design) is refused with the repo's ONE not-found envelope, thrown @@ -3338,9 +3423,36 @@ export function registerObjectTools( // `RECORD_NOT_FOUND` / 404. A missing id and an id the caller may not // read reach here as the same empty read, so they answer alike. if (record == null) throw recordNotFoundError(objectName, recordId); - return textResult(record); + if (plans === undefined) return textResult(record); + // [#35145] Each list is one `query_records` read of the child as the + // caller, filtered by the link to the record just read (so no list + // is read for a record the caller cannot see), capped the way a + // `query_records` page is: a probe row past the cap is `truncated`. + const parentId = (record as { id?: unknown }).id; + const linkId = typeof parentId === 'string' || typeof parentId === 'number' ? String(parentId) : recordId; + const lists = await Promise.all(plans.map(async (plan) => { + const probed = queryPageProbeFits(plan.limit, undefined); + let read: unknown; + try { + read = await bridge.query(plan.object, { + where: relatedListWhere(plan, linkId), + ...(plan.fields !== undefined ? { fields: plan.fields } : {}), + ...(plan.orderBy !== undefined ? { orderBy: plan.orderBy } : {}), + limit: probed ? plan.limit + 1 : plan.limit, + }); + } catch (err) { + refusedOn ??= plan.object; + throw err; + } + const page = servedQueryPage(read, plan.limit, probed); + const answer = page !== null && typeof page === 'object' && !Array.isArray(page) + ? (page as Record) + : { records: page }; + return { ...answer, object: plan.object, field: plan.field }; + })); + return textResult({ record, related: lists }); } catch (err) { - return dataDoorErrorResult(err, 'get_record', objectName); + return dataDoorErrorResult(err, 'get_record', refusedOn ?? objectName); } }, ); diff --git a/packages/mcp/src/mcp-relation-reads.ts b/packages/mcp/src/mcp-relation-reads.ts new file mode 100644 index 00000000000..75852d2fb57 --- /dev/null +++ b/packages/mcp/src/mcp-relation-reads.ts @@ -0,0 +1,257 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35145] The two related-object reads of the open MCP door, judged before + * anything is read: + * + * - `query_records`' `expand`: forward reference fields of the queried object, + * each answered with the record it names, through the engine's one expansion + * path (one batched `id IN (...)` read per field, under the TARGET's own + * permissions, row and field security); + * - `get_record`'s `related`: child objects that point at the record, each one + * capped list read as `query_records` reads it, filtered by the parent link. + * + * ⭐ THE RULE: every object a new read shape reaches is judged by the MCP read + * guard exactly as the object the call names is. A target the guard refuses + * refuses the WHOLE call, with a coded `PERMISSION_DENIED`, before any record + * is read — never a silently smaller answer. + * + * Both reads are bounded by constants here, and both judge relations against + * the object definition AS THE CALLER IS SERVED IT + * (`McpDataBridge.servedObjectDefinitionOf`): a field the caller may not read + * is not in it, so it can be neither expanded nor used as a parent link. A + * bridge that cannot serve that definition refuses both reads (fail closed). + * + * What a reference field points at is the spec's one arbiter + * (`referenceTargetOf`, over `REFERENCE_VALUE_TYPES`): the judgement the + * engine's expansion and the record page's related lists ask too. + */ + +import { StandardErrorCode } from '@objectstack/spec/api'; +import { REFERENCE_VALUE_TYPES, isMultiValueField, referenceTargetOf } from '@objectstack/spec/data'; +import type { McpDataBridge } from './mcp-http-tools.js'; + +/** The most reference fields one `query_records` call may expand (one level each). */ +export const QUERY_EXPAND_MAX_FIELDS = 3; + +/** The most related lists one `get_record` call may read. */ +export const GET_RECORD_MAX_RELATED_LISTS = 3; + +/** + * The most rows one related list serves (and its default), held at or below + * the door's own `maxQueryLimit`. A list with more children answers + * `truncated: true`, as a capped `query_records` page does. + */ +export const RELATED_LIST_MAX_ROWS = 20; + +/** The MCP door's read guard: `undefined` admits the object, a sentence refuses it. */ +export type McpReadGuard = (objectName: string) => Promise; + +/** One `related` entry as the caller sends it. */ +export interface RelatedListRequest { + object: string; + field?: string; + fields?: string[]; + orderBy?: Array<{ field: string; order: 'asc' | 'desc' }>; + limit?: number; +} + +/** One related list, judged: the child object, its link field and how the parent id is matched. */ +export interface RelatedListPlan { + object: string; + field: string; + /** The link field holds an array of ids (`multiple: true`): matched with `$contains`. */ + multiValue: boolean; + fields?: string[]; + orderBy?: Array<{ field: string; order: 'asc' | 'desc' }>; + limit: number; +} + +type Refusal = Error & { code: string; status: number; object?: string; field?: string; param?: string }; + +function refusal( + code: string, + status: number, + message: string, + extra: { object?: string; field?: string; param?: string } = {}, +): Refusal { + const err = new Error(message) as Refusal; + err.code = code; + err.status = status; + Object.assign(err, extra); + return err; +} + +/** + * The fields of `objectName` as this caller is served them, or a refusal: no + * definition member on the bridge (`NOT_IMPLEMENTED`), no such object served + * (`OBJECT_NOT_FOUND`). Unlike the annotation reads, this read DECIDES the + * request, so it never degrades to "no fields". + */ +async function servedFieldMap( + bridge: McpDataBridge, + objectName: string, + param: string, +): Promise>> { + if (typeof bridge.servedObjectDefinitionOf !== 'function') { + throw refusal( + StandardErrorCode.enum.NOT_IMPLEMENTED, + 501, + `'${param}' needs the object definitions this host's data bridge does not serve, so nothing was read. ` + + 'Read the related records with their own query_records call.', + { object: objectName, param }, + ); + } + const def = await bridge.servedObjectDefinitionOf(objectName); + if (!def) { + throw refusal( + StandardErrorCode.enum.OBJECT_NOT_FOUND, + 404, + `Object '${objectName}' named in '${param}' is not served to you, so nothing was read.`, + { object: objectName, param }, + ); + } + const raw = def.fields; + const out: Record> = {}; + if (Array.isArray(raw)) { + for (const f of raw) { + if (f && typeof f === 'object' && typeof (f as { name?: unknown }).name === 'string') { + out[(f as { name: string }).name] = f as Record; + } + } + } else if (raw && typeof raw === 'object') { + for (const [name, f] of Object.entries(raw as Record)) { + if (f && typeof f === 'object') out[name] = f as Record; + } + } + return out; +} + +/** The object a reference field points at, or `undefined` for any other field. */ +function targetOf(def: Record | undefined): string | undefined { + if (!def || typeof def.type !== 'string' || !REFERENCE_VALUE_TYPES.has(def.type)) return undefined; + try { + return referenceTargetOf(def); + } catch { + // A carrier no reader can read is no relationship. + return undefined; + } +} + +/** The guard's verdict on a target, as the whole call's coded refusal. */ +async function judgeTarget( + readGuard: McpReadGuard, + target: string, + reachedBy: string, +): Promise { + const bad = await readGuard(target); + if (bad === undefined) return; + throw refusal( + StandardErrorCode.enum.PERMISSION_DENIED, + 403, + `${reachedBy} reaches object '${target}', which this door does not serve you: ${bad}. ` + + 'Nothing was read. Remove it from the request.', + { object: target }, + ); +} + +/** + * Judge `query_records`' `expand` on `objectName`: each name is a reference + * field of the object as the caller is served it (one level, no dotted path), + * and the object it points at passes the read guard. Answers the names to + * expand, de-duplicated; throws the coded refusal otherwise. + */ +export async function judgeQueryExpand( + bridge: McpDataBridge, + readGuard: McpReadGuard, + objectName: string, + names: readonly string[], +): Promise { + const unique = [...new Set(names)]; + const fields = await servedFieldMap(bridge, objectName, 'expand'); + const targets: Array<[string, string]> = []; + for (const name of unique) { + const def = Object.prototype.hasOwnProperty.call(fields, name) ? fields[name] : undefined; + const target = targetOf(def); + if (!target) { + throw refusal( + StandardErrorCode.enum.INVALID_FIELD, + 400, + def === undefined + ? `Unknown field '${name}' in 'expand' on object '${objectName}'. 'expand' takes the object's own ` + + 'lookup, master-detail, user or tree fields, one level deep. Nothing was read.' + : `Field '${name}' in 'expand' on object '${objectName}' is not a relationship: only lookup, ` + + 'master-detail, user or tree fields can be expanded. Nothing was read.', + { object: objectName, field: name, param: 'expand' }, + ); + } + targets.push([name, target]); + } + for (const [name, target] of targets) await judgeTarget(readGuard, target, `'expand' field '${name}'`); + return unique; +} + +/** + * Judge `get_record`'s `related` on the parent `objectName`: each child object + * passes the read guard FIRST (nothing about a refused object is read, its + * definition included), then its link field is a reference field of the child, + * as the caller is served it, that points at the parent. A request that names + * no `field` takes the child's one such field; none, or several, is refused + * with the candidates named. + */ +export async function judgeRelatedLists( + bridge: McpDataBridge, + readGuard: McpReadGuard, + objectName: string, + entries: readonly RelatedListRequest[], + maxRows: number, +): Promise { + for (const entry of entries) await judgeTarget(readGuard, entry.object, `'related' list '${entry.object}'`); + const plans: RelatedListPlan[] = []; + for (const entry of entries) { + const fields = await servedFieldMap(bridge, entry.object, 'related'); + let field = entry.field; + if (field === undefined) { + const links = Object.keys(fields).filter((name) => targetOf(fields[name]) === objectName); + if (links.length !== 1) { + throw refusal( + StandardErrorCode.enum.INVALID_FIELD, + 400, + links.length === 0 + ? `Object '${entry.object}' has no field you can read that points at '${objectName}', so it has no ` + + `related list there. Nothing was read.` + : `Object '${entry.object}' points at '${objectName}' through several fields (${links.join(', ')}): ` + + `name the one to follow with 'field'. Nothing was read.`, + { object: entry.object, param: 'related' }, + ); + } + field = links[0]; + } else { + const def = Object.prototype.hasOwnProperty.call(fields, field) ? fields[field] : undefined; + if (targetOf(def) !== objectName) { + throw refusal( + StandardErrorCode.enum.INVALID_FIELD, + 400, + `'${field}' on '${entry.object}' is not a lookup, master-detail, user or tree field that points at ` + + `'${objectName}'. Nothing was read.`, + { object: entry.object, field, param: 'related' }, + ); + } + } + const def = fields[field]; + plans.push({ + object: entry.object, + field, + multiValue: isMultiValueField(def as { type: string; multiple?: boolean }), + ...(entry.fields !== undefined ? { fields: entry.fields } : {}), + ...(entry.orderBy !== undefined ? { orderBy: entry.orderBy } : {}), + limit: Math.min(entry.limit ?? maxRows, maxRows), + }); + } + return plans; +} + +/** The one filter a related list is read with: its link field holds the parent's id. */ +export function relatedListWhere(plan: RelatedListPlan, parentId: string): Record { + return { [plan.field]: plan.multiValue ? { $contains: parentId } : parentId }; +} diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index 847ac8aaef7..2dc65641305 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -59,7 +59,9 @@ * * `callData` prefers the `protocol` service (metadata-protocol) and falls back * to the engine; this bridge is engine-only. So the HTTP tools additionally get - * that layer's existence probes, its spec-shaped receipts and `expand`/`select`. + * that layer's existence probes, its spec-shaped receipts and `select` +(`expand` is served here since #35145, built as that layer builds it: +{@link stdioExpandMap}). * (That layer's create-side `readonly` strip used to head this list; since the * maintainer ruling of 2026-09-03 — option C, #14147 — the static `readonly` * strip runs inside `engine.insert` for every non-system caller and the @@ -132,6 +134,10 @@ import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts' import { resolveObjectSortability } from '@objectstack/spec/api'; // [#32442] The ONE reading of `enable.aiReadable` (ruling A, #32865). import { isAiReadExposed } from '@objectstack/spec/data'; +// [#35145] What a reference field points at, and whether that object serves +// the read an expansion is (`get`): the spec's one arbiter of each, the pair +// the data door's expand gate asks. +import { REFERENCE_VALUE_TYPES, canServeApiOperation, referenceTargetOf } from '@objectstack/spec/data'; // [commit 4810dd628] The repo's ONE single-record 404 (#4435/#5138/#7867). Imported from // `@objectstack/core` rather than re-minted here or reached via // `@objectstack/metadata-protocol`'s re-export: this package already declares @@ -302,6 +308,60 @@ interface ObjectDef { enable?: Record; } +/** + * [#35145] `query_records`' `expand` on this transport, as the data door + * builds it (`assertExpandTargetsExist`, then `servedExpand`): each name is a + * reference field of the object as the caller is served it (`served`), else + * the door's `400 INVALID_FIELD`; a target whose declaration does not serve + * `get` is withheld, and its field answers as the stored id. The map is the + * engine's own `expand`, which reads each target in one batched `id IN (...)` + * read under the target's permissions, row and field security. + */ +async function stdioExpandMap( + reads: StdioObjectReads, + object: string, + served: ObjectDef | undefined, + names: readonly string[], +): Promise | undefined> { + const out: Record = {}; + for (const name of names) { + const def = served?.fields && Object.prototype.hasOwnProperty.call(served.fields, name) + ? served.fields[name] + : undefined; + let target: string | undefined; + try { + target = def && typeof def.type === 'string' && REFERENCE_VALUE_TYPES.has(def.type) ? referenceTargetOf(def) : undefined; + } catch { + target = undefined; + } + if (!target) { + const err = new Error( + def === undefined + ? `Unknown field '${name}' on object '${object}'. 'expand' resolves a reference field into the related record.` + : `Field '${name}' on object '${object}' is not a relationship: only lookup / master_detail / user / tree ` + + 'fields can be expanded.', + ) as Error & { code: string; status: number; field: string; object: string; param: string }; + err.code = 'INVALID_FIELD'; + err.status = 400; + err.field = name; + err.object = object; + err.param = 'expand'; + throw err; + } + let declared: ObjectDef | undefined; + try { + declared = await readObjectDeclaration(reads, target); + } catch (err) { + // A target whose package is disabled serves nothing: withheld. + if (isObjectPackageDisabledRefusal(err)) continue; + throw err; + } + if (!canServeApiOperation(declared?.enable as EnableLike | undefined, 'get')) continue; + out[name] = { object: target }; + } + return Object.keys(out).length > 0 ? out : undefined; +} + /** * Unwrap what the engine's read path resolves to. * @@ -1368,6 +1428,11 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge if (opts?.orderBy) query.orderBy = opts.orderBy; if (typeof opts?.limit === 'number') query.limit = opts.limit; if (typeof opts?.offset === 'number') query.offset = opts.offset; + // [#35145] `expand`, built as the data door builds it (`stdioExpandMap`). + if (Array.isArray(opts?.expand) && opts.expand.length > 0) { + const expand = await stdioExpandMap(reads, object, (await servedView.getObject(object)) as ObjectDef | undefined, opts.expand); + if (expand) query.expand = expand; + } // [#21207] The content-hash columns are served keyed, or not at all. const digest = keyedDigest?.(); const records = await Promise.all( diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index fba506411a7..9dea9936ee9 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -1187,6 +1187,10 @@ export function buildMcpBridge( if (typeof o?.limit === 'number') query.limit = o.limit; if (typeof o?.offset === 'number') query.offset = o.offset; if (o?.orderBy) query.orderBy = o.orderBy; + // [#35145] `query_records`' `expand`: the names, which `findData` + // lowers, gates (`assertExpandTargetsExist`, `servedExpand`) and + // the engine expands in one batched read per field, as on REST. + if (Array.isArray(o?.expand) && o.expand.length > 0) query.expand = o.expand; return await callData('query', { object, query }, driver, envId, ec); }, /** From 854003388ffd2361a11c1e6aab986b85af5475f6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 14:00:29 +0000 Subject: [PATCH 02/11] test(mcp): pin expand and related on the tool and the stdio bridge Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL Co-authored-by: Claude --- packages/mcp/src/mcp-relation-reads.test.ts | 315 ++++++++++++++++++++ 1 file changed, 315 insertions(+) create mode 100644 packages/mcp/src/mcp-relation-reads.test.ts diff --git a/packages/mcp/src/mcp-relation-reads.test.ts b/packages/mcp/src/mcp-relation-reads.test.ts new file mode 100644 index 00000000000..cfa9eb9de31 --- /dev/null +++ b/packages/mcp/src/mcp-relation-reads.test.ts @@ -0,0 +1,315 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35145] `query_records`' `expand` and `get_record`'s `related`: a record + * with the records it points at, and a parent with its children, in one call. + * + * The tool half, against a recording bridge: + * + * - ⭐ THE RULE: every object a new read shape reaches is judged by the MCP + * read guard exactly as the named object is. A target the guard refuses + * refuses the whole call with a coded `PERMISSION_DENIED`, and nothing is + * read (no `query`, no `get`); + * - a name that is not a reference field of the object as the caller is + * served it, or a link field that does not point at the parent, is a coded + * `INVALID_FIELD`, before any read; + * - the bounds: at most 3 expand fields, at most 3 related lists, at most 20 + * rows a list (never above `maxQueryLimit`); a capped list answers + * `truncated: true` from the probe row, as a capped `query_records` page; + * - a related list is read only after the parent record was, filtered by the + * link to it alone. + * + * The stdio bridge half: `expand` is built as the data door builds it. + * + * The whole read over MCP, under real row, field and tenant security, is in + * the dogfood harness (`related-read-over-mcp.dogfood.test.ts`). + */ + +import { describe, it, expect, vi } from 'vitest'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; +import { MCPServerRuntime } from './mcp-server-runtime.js'; +import { createStdioDataBridge } from './stdio-data-bridge.js'; + +const OPP = 'crm_opportunity'; +const ACCOUNT = 'crm_account'; +const ACTIVITY = 'crm_activity'; +const NOTE = 'crm_note'; + +const DEFS: Record> }> = { + [OPP]: { + name: OPP, + fields: { + name: { type: 'text' }, + account: { type: 'lookup', reference: ACCOUNT }, + owner_id: { type: 'lookup', reference: 'sys_user' }, + organization_id: { type: 'lookup', reference: 'sys_organization' }, + renewal_of: { type: 'lookup', reference: OPP }, + }, + }, + [ACCOUNT]: { name: ACCOUNT, fields: { name: { type: 'text' } } }, + [ACTIVITY]: { + name: ACTIVITY, + fields: { + subject: { type: 'text' }, + account: { type: 'lookup', reference: ACCOUNT }, + opportunity: { type: 'lookup', reference: OPP }, + contact_account: { type: 'lookup', reference: ACCOUNT }, + }, + }, + [NOTE]: { name: NOTE, fields: { body: { type: 'text' }, accounts: { type: 'lookup', reference: ACCOUNT, multiple: true } } }, +}; + +interface Recorded { op: string; object: string; opts?: any } + +function makeBridge(opts: { + answers?: Record; + record?: unknown; + definitions?: boolean; + queryThrows?: Record; +} = {}) { + const calls: Recorded[] = []; + const bridge: any = { + async listObjects() { return Object.values(DEFS).map((d) => ({ name: d.name, label: d.name })); }, + async describeObject(name: string) { return DEFS[name] ?? null; }, + // `sys_user` attests its AI read opt-in; `sys_organization` does not. + async aiReadExposed(name: string) { return name === 'sys_user'; }, + async query(object: string, o: any) { + calls.push({ op: 'query', object, opts: o }); + if (opts.queryThrows?.[object]) throw opts.queryThrows[object]; + return opts.answers?.[object] ?? { object, records: [], total: 0, hasMore: false }; + }, + async get(object: string, id: string) { + calls.push({ op: 'get', object, opts: { id } }); + return opts.record === undefined ? { id, name: 'Acme' } : opts.record; + }, + async create() { return {}; }, + async update() { return {}; }, + async remove() { return { success: true }; }, + }; + if (opts.definitions !== false) { + bridge.servedObjectDefinitionOf = async (name: string) => { + calls.push({ op: 'definition', object: name }); + return DEFS[name] ?? null; + }; + } + return { bridge, calls }; +} + +async function call( + bridge: any, + name: string, + args: Record, +): Promise<{ isError: boolean; payload: any; text: string }> { + const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); + const body = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }; + const req = new Request('http://localhost/api/v1/mcp', { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, + body: JSON.stringify(body), + }); + const res = await runtime.handleHttpRequest(req, { bridge, parsedBody: body }); + const json: any = await res.json(); + const text = String(json.result?.content?.[0]?.text ?? json.error?.message ?? ''); + let payload: any; + try { payload = JSON.parse(text); } catch { payload = { message: text }; } + return { isError: json.result?.isError === true || json.error !== undefined, payload, text }; +} + +const reads = (calls: Recorded[]) => calls.filter((c) => c.op === 'query' || c.op === 'get'); +const envelope = (payload: any) => ({ code: payload?.error?.code, status: payload?.error?.status }); + +describe('query_records expand — the tool', () => { + it('hands the judged names to the bridge as expand, in the one query it reads', async () => { + const { bridge, calls } = makeBridge(); + const answer = await call(bridge, 'query_records', { objectName: OPP, expand: ['account', 'owner_id', 'account'] }); + expect(answer.isError, answer.text).toBe(false); + expect(reads(calls)).toHaveLength(1); + expect(reads(calls)[0]).toMatchObject({ object: OPP, opts: { expand: ['account', 'owner_id'] } }); + }); + + it('control: a call without expand hands the bridge no expand key and reads no definition', async () => { + const { bridge, calls } = makeBridge(); + await call(bridge, 'query_records', { objectName: OPP }); + expect('expand' in reads(calls)[0].opts).toBe(false); + expect(calls.some((c) => c.op === 'definition')).toBe(false); + }); + + it('⭐ a field whose target the read guard refuses refuses the whole call: PERMISSION_DENIED, nothing read', async () => { + const { bridge, calls } = makeBridge(); + const answer = await call(bridge, 'query_records', { objectName: OPP, expand: ['account', 'organization_id'] }); + expect(answer.isError).toBe(true); + expect(envelope(answer.payload)).toEqual({ code: 'PERMISSION_DENIED', status: 403 }); + expect(answer.text).toContain('sys_organization'); + expect(reads(calls)).toHaveLength(0); + }); + + for (const [label, name, fragment] of [ + ['an unknown field', 'nope', 'Unknown field'], + ['a field that is not a relationship', 'name', 'not a relationship'], + ['a dotted path (one level only)', 'account.owner_id', 'Unknown field'], + ] as const) { + it(`refuses ${label}: INVALID_FIELD, nothing read`, async () => { + const { bridge, calls } = makeBridge(); + const answer = await call(bridge, 'query_records', { objectName: OPP, expand: [name] }); + expect(envelope(answer.payload)).toEqual({ code: 'INVALID_FIELD', status: 400 }); + expect(answer.text).toContain(fragment); + expect(reads(calls)).toHaveLength(0); + }); + } + + it('more than three fields is refused at the door', async () => { + const { bridge, calls } = makeBridge(); + const answer = await call(bridge, 'query_records', { objectName: OPP, expand: ['account', 'owner_id', 'renewal_of', 'organization_id'] }); + expect(answer.isError).toBe(true); + expect(calls).toHaveLength(0); + }); + + it('a bridge that serves no object definitions refuses expand (NOT_IMPLEMENTED), nothing read', async () => { + const { bridge, calls } = makeBridge({ definitions: false }); + const answer = await call(bridge, 'query_records', { objectName: OPP, expand: ['account'] }); + expect(envelope(answer.payload)).toEqual({ code: 'NOT_IMPLEMENTED', status: 501 }); + expect(reads(calls)).toHaveLength(0); + }); +}); + +describe('get_record related — the tool', () => { + it('reads the record, then each list filtered by the link alone, capped with a probe row', async () => { + const opps = { object: OPP, records: [{ id: 'o1' }, { id: 'o2' }, { id: 'o3' }], total: 3, hasMore: false }; + const { bridge, calls } = makeBridge({ answers: { [OPP]: opps } }); + const answer = await call(bridge, 'get_record', { + objectName: ACCOUNT, + recordId: 'a1', + related: [ + { object: OPP, fields: ['id', 'name'], orderBy: [{ field: 'name', order: 'asc' }], limit: 2 }, + { object: ACTIVITY, field: 'account' }, + ], + }); + expect(answer.isError, answer.text).toBe(false); + expect(reads(calls).map((c) => `${c.op}:${c.object}`)).toEqual([`get:${ACCOUNT}`, `query:${OPP}`, `query:${ACTIVITY}`]); + expect(reads(calls)[1].opts).toEqual({ + where: { account: 'a1' }, fields: ['id', 'name'], orderBy: [{ field: 'name', order: 'asc' }], limit: 3, + }); + // The default cap is 20 rows, read with one probe row. + expect(reads(calls)[2].opts).toEqual({ where: { account: 'a1' }, limit: 21 }); + expect(answer.payload.record).toEqual({ id: 'a1', name: 'Acme' }); + expect(answer.payload.related[0]).toEqual({ + object: OPP, field: 'account', records: [{ id: 'o1' }, { id: 'o2' }], total: 3, hasMore: true, truncated: true, + }); + expect(answer.payload.related[1]).toMatchObject({ object: ACTIVITY, field: 'account', records: [] }); + expect(answer.payload.related[1].truncated).toBeUndefined(); + }); + + it('control: a call without related answers the record alone, as before', async () => { + const { bridge, calls } = makeBridge(); + const answer = await call(bridge, 'get_record', { objectName: ACCOUNT, recordId: 'a1' }); + expect(answer.payload).toEqual({ id: 'a1', name: 'Acme' }); + expect(calls.map((c) => c.op)).toEqual(['get']); + }); + + it('⭐ a related object the read guard refuses refuses the whole call before anything about it is read', async () => { + const { bridge, calls } = makeBridge(); + const answer = await call(bridge, 'get_record', { + objectName: ACCOUNT, recordId: 'a1', related: [{ object: OPP }, { object: 'sys_audit_log', field: 'record_id' }], + }); + expect(envelope(answer.payload)).toEqual({ code: 'PERMISSION_DENIED', status: 403 }); + expect(answer.text).toContain('sys_audit_log'); + expect(calls).toEqual([]); + }); + + it('several link fields and none named: refused, the candidates named', async () => { + const { bridge, calls } = makeBridge(); + const answer = await call(bridge, 'get_record', { objectName: ACCOUNT, recordId: 'a1', related: [{ object: ACTIVITY }] }); + expect(envelope(answer.payload)).toEqual({ code: 'INVALID_FIELD', status: 400 }); + expect(answer.text).toContain('account, contact_account'); + expect(reads(calls)).toHaveLength(0); + }); + + for (const [label, entry] of [ + ['a child with no field that points at the parent', { object: ACCOUNT }], + ['an object not served to the caller', { object: 'crm_unknown' }], + ['a named field that points elsewhere', { object: ACTIVITY, field: 'opportunity' }], + ['a named field that is not a relationship', { object: ACTIVITY, field: 'subject' }], + ] as const) { + it(`refuses ${label}, before any read`, async () => { + const { bridge, calls } = makeBridge(); + const answer = await call(bridge, 'get_record', { objectName: ACCOUNT, recordId: 'a1', related: [entry] }); + expect(answer.isError).toBe(true); + expect(['INVALID_FIELD', 'OBJECT_NOT_FOUND']).toContain(answer.payload?.error?.code); + expect(reads(calls)).toHaveLength(0); + }); + } + + it('a multi-value link field is matched with $contains', async () => { + const { bridge, calls } = makeBridge(); + await call(bridge, 'get_record', { objectName: ACCOUNT, recordId: 'a1', related: [{ object: NOTE }] }); + expect(reads(calls)[1].opts.where).toEqual({ accounts: { $contains: 'a1' } }); + }); + + it('a record the caller cannot read: RECORD_NOT_FOUND, and no list is read', async () => { + const { bridge, calls } = makeBridge({ record: null }); + const answer = await call(bridge, 'get_record', { objectName: ACCOUNT, recordId: 'a1', related: [{ object: OPP }] }); + expect(answer.payload?.error?.code).toBe('RECORD_NOT_FOUND'); + expect(reads(calls).map((c) => c.op)).toEqual(['get']); + }); + + it('a list\'s own refusal is the whole call\'s, with its code', async () => { + const denied = Object.assign(new Error('no read on crm_opportunity'), { code: 'PERMISSION_DENIED', status: 403 }); + const { bridge } = makeBridge({ queryThrows: { [OPP]: denied } }); + const answer = await call(bridge, 'get_record', { objectName: ACCOUNT, recordId: 'a1', related: [{ object: OPP }] }); + expect(envelope(answer.payload)).toEqual({ code: 'PERMISSION_DENIED', status: 403 }); + expect(answer.payload.record).toBeUndefined(); + }); + + for (const [label, related] of [ + ['four lists', [{ object: OPP }, { object: OPP }, { object: OPP }, { object: OPP }]], + ['a limit above 20', [{ object: OPP, limit: 21 }]], + ['a caller filter on the list', [{ object: OPP, where: { name: 'x' } }]], + ] as const) { + it(`refused at the door: ${label}`, async () => { + const { bridge, calls } = makeBridge(); + const answer = await call(bridge, 'get_record', { objectName: ACCOUNT, recordId: 'a1', related }); + expect(answer.isError).toBe(true); + expect(calls).toHaveLength(0); + }); + } +}); + +describe('query_records expand — the stdio bridge', () => { + const PRINCIPAL = { userId: 'u1', isSystem: false } as unknown as ExecutionContext; + + function makeStdio(defs: Record) { + const engine = { find: vi.fn(async () => [{ id: 'o1' }]), count: vi.fn(async () => 1) }; + const metadataService = { getObject: vi.fn(async (name: string) => defs[name]) }; + const bridge = createStdioDataBridge({ + engine: engine as unknown as IDataEngine, + metadataService: metadataService as unknown as IMetadataService, + resolvePrincipal: async () => PRINCIPAL, + }); + return { bridge, engine }; + } + + it('hands the engine the expand map, keyed by field, naming each target', async () => { + const { bridge, engine } = makeStdio({ [OPP]: DEFS[OPP], [ACCOUNT]: DEFS[ACCOUNT] }); + await bridge.query(OPP, { expand: ['account'] }); + const [, query] = engine.find.mock.calls[0] as unknown as [string, any]; + expect(query.expand).toEqual({ account: { object: ACCOUNT } }); + }); + + it('a target that does not serve get is withheld, as the data door withholds it', async () => { + const { bridge, engine } = makeStdio({ + [OPP]: DEFS[OPP], + [ACCOUNT]: { ...DEFS[ACCOUNT], enable: { apiEnabled: false } }, + }); + await bridge.query(OPP, { expand: ['account'] }); + const [, query] = engine.find.mock.calls[0] as unknown as [string, any]; + expect('expand' in query).toBe(false); + }); + + it('a name that is not a reference field: the door\'s INVALID_FIELD, before the engine', async () => { + const { bridge, engine } = makeStdio({ [OPP]: DEFS[OPP] }); + const err: any = await bridge.query(OPP, { expand: ['name'] }).then(() => null, (e: unknown) => e); + expect({ code: err?.code, status: err?.status, field: err?.field }).toEqual({ code: 'INVALID_FIELD', status: 400, field: 'name' }); + expect(engine.find).not.toHaveBeenCalled(); + }); +}); From 2ba02fce44949aec2b7a1b6bfa917d1fb10fe710 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 14:01:35 +0000 Subject: [PATCH 03/11] test(dogfood): expand and related over MCP on the CRM example Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL Co-authored-by: Claude --- .../related-read-over-mcp.dogfood.test.ts | 317 ++++++++++++++++++ 1 file changed, 317 insertions(+) create mode 100644 packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts diff --git a/packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts b/packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts new file mode 100644 index 00000000000..0b84000dde6 --- /dev/null +++ b/packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts @@ -0,0 +1,317 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// A record with the records it points at, and a parent with its children, in +// one MCP call: `query_records` with `expand` and `get_record` with `related` +// on the CRM example, as a member's agent asks them, over the live `/mcp` +// transport — real SecurityPlugin, real MCP plugin, the SQL driver, a real +// organization wall (`multiTenant: 'posture-only'`, the `isolated` posture). +// +// The member of organization A holds one app set: read on accounts, deals and +// activities (not contacts), a row-level policy that hides closed-lost deals, +// and `crm_opportunity.probability` and `crm_account.annual_revenue` withheld. +// +// ⭐ expand: each deal answers its account and its owner as records, the +// account's withheld field still withheld; +// ⭐ related: an account answers its deals and its activities, filtered by +// the link alone; a deal the row policy hides never appears in the list; +// a withheld field stays withheld on the listed rows; +// ⭐ THE RULE: an object the MCP read guard refuses, reached through expand +// or related, refuses the whole call with PERMISSION_DENIED and no rows; +// a related object the member may not read refuses it too; +// ⭐ the organization wall: a deal of organization B that points at A's +// account never appears in A's list, and A's account is not B's to read; +// ⭐ a list with more rows than its cap answers the cap and truncated: true; +// ⭐ an unknown field, or a field that is no relation, is INVALID_FIELD; +// ⭐ controls: without expand / related each tool answers as before. + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import crmStack from '@objectstack/example-crm'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { MCPServerPlugin } from '@objectstack/mcp'; +import { PermissionSetSchema, type PermissionSet } from '@objectstack/spec/security'; +import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; +import { assertArmed, armedWhen } from './armed.js'; + +const OPP = 'crm_opportunity'; +const ACCOUNT = 'crm_account'; +const ACTIVITY = 'crm_activity'; +const CONTACT = 'crm_contact'; +const SYS = { context: { isSystem: true } } as const; +type Row = Record; +const rowsOf = (r: any): Row[] => + (Array.isArray(r) ? r : Array.isArray(r?.records) ? r.records : Array.isArray(r?.value) ? r.value : []); + +const DOMAIN = 'relatedread.verify.test'; +const OWNER_A = `owner-a@${DOMAIN}`; +const OWNER_B = `owner-b@${DOMAIN}`; +const MEMBER_A = `member-a@${DOMAIN}`; +const MEMBER_B = `member-b@${DOMAIN}`; +/** A related list's row cap (`RELATED_LIST_MAX_ROWS`, under the door's 50). */ +const LIST_CAP = 20; +const MANY = LIST_CAP + 5; + +/** The member's app set: read on accounts, deals and activities; closed-lost deals hidden; two fields withheld. */ +const memberSet: PermissionSet = PermissionSetSchema.parse({ + name: 'relatedread_member', + label: 'Related reads over MCP — a CRM member', + objects: { + [OPP]: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }, + [ACCOUNT]: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }, + [ACTIVITY]: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }, + }, + fields: { + [`${OPP}.probability`]: { readable: false, editable: false }, + [`${ACCOUNT}.annual_revenue`]: { readable: false, editable: false }, + }, + rowLevelSecurity: [ + { name: 'relatedread_hide_lost', object: OPP, operation: 'select', using: "record.stage != 'closed_lost'" }, + ], +}); + +describe('query_records expand and get_record related over MCP on the CRM example — under row, field and tenant security', () => { + let stack: VerifyStack; + let ql: any; + const tok: Record = {}; + const org: Record = {}; + const uid: Record = {}; + const acct: Record = {}; + const opp: Record = {}; + + const idOf = (b: any): string => String(b?.id ?? b?.record?.id ?? ''); + const userId = async (email: string): Promise => + String((await ql.findOne('sys_user', { where: { email }, context: SYS.context }))?.id ?? ''); + + /** One MCP `tools/call` over the live transport, as a bearer; its first content block parsed. */ + const tool = async (bearer: string, name: string, args: Record) => { + const res = await stack.api('/mcp', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json, text/event-stream', + Authorization: `Bearer ${bearer}`, + }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }), + }); + expect(res.status).toBe(200); + const body: any = await res.json(); + const text = String(body.result?.content?.[0]?.text ?? body.error?.message ?? ''); + let payload: any; + try { payload = JSON.parse(text); } catch { payload = { message: text }; } + return { isError: body.result?.isError === true || body.error !== undefined, payload, text }; + }; + const ok = async (bearer: string, name: string, args: Record) => { + const answer = await tool(bearer, name, args); + expect(answer.isError, answer.text).toBe(false); + return answer.payload; + }; + const refused = async (bearer: string, name: string, args: Record) => { + const answer = await tool(bearer, name, args); + expect(answer.isError, answer.text).toBe(true); + return { code: answer.payload?.error?.code, status: answer.payload?.error?.status, text: answer.text }; + }; + const ids = (rows: Row[]): string[] => rows.map((r) => String(r.id)).sort(); + const listOf = (payload: any, object: string): Row => payload.related.find((l: Row) => l.object === object); + + /** A new organization, created and made active by its owner. */ + const organization = async (ownerEmail: string, name: string, slug: string): Promise => { + const owner = await stack.signUp(ownerEmail); + const created = await stack.apiAs(owner, 'POST', '/auth/organization/create', { name, slug }); + expect(created.status, `org create ${slug}: ${await created.clone().text()}`).toBe(200); + const id = String(((await created.json()) as { id: string }).id); + const active = await stack.apiAs(owner, 'POST', '/auth/organization/set-active', { organizationId: id }); + expect(active.status, `set-active ${slug}: ${await active.clone().text()}`).toBe(200); + return id; + }; + /** A plain member of `orgId`, active in it. */ + const memberOf = async (email: string, orgId: string): Promise => { + const bearer = await stack.signUp(email); + await ql.insert('sys_member', { user_id: await userId(email), organization_id: orgId, role: 'member' }, SYS); + const active = await stack.apiAs(bearer, 'POST', '/auth/organization/set-active', { organizationId: orgId }); + expect(active.status, `member set-active: ${await active.clone().text()}`).toBe(200); + return bearer; + }; + const deal = async (key: string, o: string, account: string, owner: string, stage: string) => { + opp[key] = idOf(await ql.insert(OPP, { + name: `RR ${key}`, account, owner_id: owner, stage, close_date: '2031-06-30', amount: 100, probability: 40, organization_id: o, + }, SYS)); + }; + const activity = async (o: string, account: string, subject: string) => + idOf(await ql.insert(ACTIVITY, { subject, type: 'call', status: 'planned', account, organization_id: o }, SYS)); + + beforeAll(async () => { + stack = await bootStack(crmStack as never, { + multiTenant: 'posture-only', + security: new SecurityPlugin({ + defaultPermissionSets: [...securityDefaultPermissionSets, memberSet], + fallbackPermissionSet: memberSet.name, + }), + extraPlugins: [new MCPServerPlugin()], + }); + ql = await stack.kernel.getServiceAsync('objectql'); + + org.a = await organization(OWNER_A, 'RR Org A', 'relatedread-a'); + org.b = await organization(OWNER_B, 'RR Org B', 'relatedread-b'); + tok.a = await memberOf(MEMBER_A, org.a); + tok.b = await memberOf(MEMBER_B, org.b); + uid.a = await userId(MEMBER_A); + uid.b = await userId(MEMBER_B); + + for (const [key, o] of [['a1', org.a], ['a2', org.a], ['b1', org.b]] as const) { + acct[key] = idOf(await ql.insert(ACCOUNT, { name: `RR account ${key}`, annual_revenue: 1000, organization_id: o }, SYS)); + } + // Account a1: two readable deals and one closed-lost deal the member may + // not read. Organization B: a deal of its own on b1, and one that points + // at A's account a1 (a cross-tenant link a related list must not follow). + await deal('x1', org.a, acct.a1, uid.a, 'proposal'); + await deal('x2', org.a, acct.a1, uid.a, 'qualification'); + await deal('lost', org.a, acct.a1, uid.a, 'closed_lost'); + await deal('y1', org.a, acct.a2, uid.a, 'prospecting'); + await deal('b1', org.b, acct.b1, uid.b, 'proposal'); + await deal('bx', org.b, acct.a1, uid.b, 'proposal'); + // Activities: two on a1, MANY on a2 (more than a list's cap). + await activity(org.a, acct.a1, 'RR call 1'); + await activity(org.a, acct.a1, 'RR call 2'); + for (let i = 0; i < MANY; i++) await activity(org.a, acct.a2, `RR many ${String(i).padStart(2, '0')}`); + + await assertArmed([ + armedWhen({ + control: 'a real wall: two organizations, each member active in its own', + disarmedBy: 'a single organization would pass every tenant pin over one tenant', + observe: async () => { + const tenancy = await stack.kernel.getServiceAsync<{ posture: string; isolationActive: boolean }>('tenancy'); + return { posture: tenancy.posture, active: tenancy.isolationActive, distinct: org.a !== org.b && !!org.a && !!org.b }; + }, + armed: (o) => o.posture === 'isolated' && o.active && o.distinct, + describe: (o) => `posture ${o.posture}, active ${o.active}, distinct orgs ${o.distinct}`, + }), + armedWhen({ + control: 'at rest, account a1 has the hidden deal and organization B\'s deal pointing at it', + disarmedBy: 'without them at rest, the row-security and tenant pins would pass over rows that do not exist', + observe: async () => ({ ids: ids(rowsOf(await ql.find(OPP, { where: { account: acct.a1 }, context: SYS.context }))) }), + armed: (o) => o.ids.includes(opp.lost) && o.ids.includes(opp.bx) && o.ids.length === 4, + describe: (o) => `${o.ids.length} deals point at a1 at rest`, + }), + armedWhen({ + control: 'the member\'s row policy really hides the closed-lost deal from an ordinary query', + disarmedBy: 'a policy that never bound would let the related-list pin pass without testing it', + observe: async () => ({ ids: ids(rowsOf(await ok(tok.a, 'query_records', { objectName: OPP, where: { account: acct.a1 } }))) }), + armed: (o) => !o.ids.includes(opp.lost) && o.ids.includes(opp.x1), + describe: (o) => `member reads ${o.ids.length} deals of a1`, + }), + armedWhen({ + control: 'the member may not read contacts at all', + disarmedBy: 'a readable contact object would pass the unreadable-related-object pin without testing it', + observe: async () => { + const answer = await tool(tok.a, 'query_records', { objectName: CONTACT }); + return { isError: answer.isError, code: String(answer.payload?.error?.code) }; + }, + armed: (o) => o.isError && o.code === 'PERMISSION_DENIED', + describe: (o) => `contact read isError ${o.isError} (${o.code})`, + }), + ]); + }, 300_000); + + afterAll(async () => { + await stack?.stop?.(); + }); + + it('⭐ expand: each deal answers its account and its owner as records; the account\'s withheld field stays withheld', async () => { + const payload = await ok(tok.a, 'query_records', { + objectName: OPP, where: { account: acct.a1 }, expand: ['account', 'owner_id'], + }); + const rows = rowsOf(payload); + expect(ids(rows)).toEqual([opp.x1, opp.x2].sort()); + for (const row of rows) { + expect(row.account?.id, JSON.stringify(row.account)).toBe(acct.a1); + expect(row.account.name).toBe('RR account a1'); + expect(row.account.annual_revenue).toBeUndefined(); + expect(row.probability).toBeUndefined(); + expect(row.owner_id?.id, JSON.stringify(row.owner_id)).toBe(uid.a); + } + }); + + it('⭐ related: an account answers its deals and activities by the link alone; the hidden deal never appears; withheld fields stay withheld', async () => { + const payload = await ok(tok.a, 'get_record', { + objectName: ACCOUNT, recordId: acct.a1, related: [{ object: OPP }, { object: ACTIVITY }], + }); + expect(payload.record.id).toBe(acct.a1); + expect(payload.record.annual_revenue).toBeUndefined(); + const deals = listOf(payload, OPP); + expect(deals.field).toBe('account'); + expect(ids(rowsOf(deals))).toEqual([opp.x1, opp.x2].sort()); + expect(ids(rowsOf(deals))).not.toContain(opp.lost); + for (const row of rowsOf(deals)) expect(row.probability).toBeUndefined(); + expect(deals.truncated).toBeUndefined(); + const acts = listOf(payload, ACTIVITY); + expect(rowsOf(acts).map((r) => r.subject).sort()).toEqual(['RR call 1', 'RR call 2']); + }); + + it('⭐ the organization wall: B\'s deal pointing at A\'s account is not in A\'s list, and A\'s account is not B\'s to read', async () => { + const a = await ok(tok.a, 'get_record', { objectName: ACCOUNT, recordId: acct.a1, related: [{ object: OPP }] }); + expect(ids(rowsOf(listOf(a, OPP)))).not.toContain(opp.bx); + expect(JSON.stringify(a)).not.toContain(opp.bx); + + const b = await ok(tok.b, 'get_record', { objectName: ACCOUNT, recordId: acct.b1, related: [{ object: OPP }] }); + expect(ids(rowsOf(listOf(b, OPP)))).toEqual([opp.b1]); + + const crossed = await refused(tok.b, 'get_record', { objectName: ACCOUNT, recordId: acct.a1, related: [{ object: OPP }] }); + expect(crossed.code).toBe('RECORD_NOT_FOUND'); + expect(crossed.text).not.toContain(opp.x1); + expect(crossed.text).not.toContain(opp.bx); + }); + + it('⭐ a list with more rows than its cap answers the cap and truncated: true; a smaller limit is a cap too', async () => { + const capped = await ok(tok.a, 'get_record', { objectName: ACCOUNT, recordId: acct.a2, related: [{ object: ACTIVITY }] }); + const list = listOf(capped, ACTIVITY); + expect(rowsOf(list)).toHaveLength(LIST_CAP); + expect(list.truncated).toBe(true); + expect(list.total).toBe(MANY); + + const small = await ok(tok.a, 'get_record', { + objectName: ACCOUNT, recordId: acct.a2, related: [{ object: ACTIVITY, limit: 5, orderBy: [{ field: 'subject', order: 'asc' }] }], + }); + expect(rowsOf(listOf(small, ACTIVITY)).map((r) => r.subject)).toEqual( + ['RR many 00', 'RR many 01', 'RR many 02', 'RR many 03', 'RR many 04'], + ); + expect(listOf(small, ACTIVITY).truncated).toBe(true); + }); + + it('⭐ THE RULE: an object the MCP read guard refuses, reached through expand or related, refuses the whole call', async () => { + const viaExpand = await refused(tok.a, 'query_records', { objectName: OPP, expand: ['account', 'organization_id'] }); + expect({ code: viaExpand.code, status: viaExpand.status }).toEqual({ code: 'PERMISSION_DENIED', status: 403 }); + expect(viaExpand.text).toContain('sys_organization'); + expect(viaExpand.text).not.toContain(opp.x1); + + const viaRelated = await refused(tok.a, 'get_record', { + objectName: ACCOUNT, recordId: acct.a1, related: [{ object: OPP }, { object: 'sys_organization', field: 'id' }], + }); + expect({ code: viaRelated.code, status: viaRelated.status }).toEqual({ code: 'PERMISSION_DENIED', status: 403 }); + expect(viaRelated.text).not.toContain(opp.x1); + expect(viaRelated.text).not.toContain('RR account a1'); + }); + + it('⭐ a related object the member may not read refuses the whole call', async () => { + const answer = await refused(tok.a, 'get_record', { objectName: ACCOUNT, recordId: acct.a1, related: [{ object: OPP }, { object: CONTACT }] }); + expect(answer.code).toBe('PERMISSION_DENIED'); + expect(answer.text).not.toContain(opp.x1); + }); + + it('⭐ an unknown field, or a field that is no relation, is INVALID_FIELD', async () => { + for (const expand of [['nope'], ['stage']]) { + const answer = await refused(tok.a, 'query_records', { objectName: OPP, expand }); + expect({ code: answer.code, status: answer.status }).toEqual({ code: 'INVALID_FIELD', status: 400 }); + } + for (const field of ['nope', 'stage', 'renewal_of']) { + const answer = await refused(tok.a, 'get_record', { objectName: ACCOUNT, recordId: acct.a1, related: [{ object: OPP, field }] }); + expect({ code: answer.code, status: answer.status }).toEqual({ code: 'INVALID_FIELD', status: 400 }); + } + }); + + it('control: without expand or related, each tool answers as before', async () => { + const plain = await ok(tok.a, 'query_records', { objectName: OPP, where: { account: acct.a1 } }); + for (const row of rowsOf(plain)) expect(row.account).toBe(acct.a1); + const record = await ok(tok.a, 'get_record', { objectName: ACCOUNT, recordId: acct.a1 }); + expect(record.id).toBe(acct.a1); + expect(record.related).toBeUndefined(); + }); +}); From 3cf56f578ef9dafcd0de2d65f887412d20f8185d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 14:09:38 +0000 Subject: [PATCH 04/11] test(dogfood): an unreadable related object is refused while the relation is judged Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL Co-authored-by: Claude --- .../qa/dogfood/test/related-read-over-mcp.dogfood.test.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts b/packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts index 0b84000dde6..8cf6ab093ac 100644 --- a/packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts +++ b/packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts @@ -290,10 +290,14 @@ describe('query_records expand and get_record related over MCP on the CRM exampl expect(viaRelated.text).not.toContain('RR account a1'); }); - it('⭐ a related object the member may not read refuses the whole call', async () => { + it('⭐ a related object the member may not read refuses the whole call, before any read', async () => { + // Its definition is not served to the member at all, so the call is + // refused while the relation is judged: no record of either list is read. const answer = await refused(tok.a, 'get_record', { objectName: ACCOUNT, recordId: acct.a1, related: [{ object: OPP }, { object: CONTACT }] }); - expect(answer.code).toBe('PERMISSION_DENIED'); + expect({ code: answer.code, status: answer.status }).toEqual({ code: 'OBJECT_NOT_FOUND', status: 404 }); + expect(answer.text).toContain(CONTACT); expect(answer.text).not.toContain(opp.x1); + expect(answer.text).not.toContain('RR account a1'); }); it('⭐ an unknown field, or a field that is no relation, is INVALID_FIELD', async () => { From c8021d04cda3a42c374942e5c2ff44de4323b715 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 14:18:37 +0000 Subject: [PATCH 05/11] test(dogfood): expand combines with latestPer Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL Co-authored-by: Claude --- .../test/related-read-over-mcp.dogfood.test.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts b/packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts index 8cf6ab093ac..726dae6627c 100644 --- a/packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts +++ b/packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts @@ -230,6 +230,18 @@ describe('query_records expand and get_record related over MCP on the CRM exampl } }); + it('expand combines with latestPer: each account\'s latest deal, its account answered as a record', async () => { + const payload = await ok(tok.a, 'query_records', { + objectName: OPP, + where: { account: { $in: [acct.a1, acct.a2] } }, + latestPer: { by: ['account'], orderBy: [{ field: 'name', order: 'desc' }] }, + expand: ['account'], + }); + const byAccount = Object.fromEntries(rowsOf(payload).map((r) => [String(r.account?.id), String(r.id)])); + expect(byAccount).toEqual({ [acct.a1]: opp.x2, [acct.a2]: opp.y1 }); + for (const row of rowsOf(payload)) expect(row.account.annual_revenue).toBeUndefined(); + }); + it('⭐ related: an account answers its deals and activities by the link alone; the hidden deal never appears; withheld fields stay withheld', async () => { const payload = await ok(tok.a, 'get_record', { objectName: ACCOUNT, recordId: acct.a1, related: [{ object: OPP }, { object: ACTIVITY }], From e7b33863c37dcd15436ed4a91693e2ea33801cc4 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 14:23:39 +0000 Subject: [PATCH 06/11] docs(mcp): expand and related on the MCP read tools; changeset Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL Co-authored-by: Claude --- .changeset/35145-mcp-related-read.md | 19 ++++++++++++ content/docs/ai/connect-mcp.mdx | 43 +++++++++++++++++++++++++++- 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 .changeset/35145-mcp-related-read.md diff --git a/.changeset/35145-mcp-related-read.md b/.changeset/35145-mcp-related-read.md new file mode 100644 index 00000000000..2ec8659e8f0 --- /dev/null +++ b/.changeset/35145-mcp-related-read.md @@ -0,0 +1,19 @@ +--- +'@objectstack/mcp': patch +'@objectstack/runtime': patch +--- + +feat(mcp): a record with its related records in one call — `expand` on `query_records`, `related` on `get_record` + +Clause-②: yes (widening) +Metadata-protocol: none + +`query_records` takes `expand`: up to 3 of the queried object's lookup, master-detail, user or tree fields, each answered as the record it names, one level deep. `get_record` takes `related`: up to 3 child objects that point at the record, each answered as a list of at most 20 rows (never above the tool's `maxQueryLimit`), as `{ record, related: [{ object, field, records, total, hasMore }] }`. + +- Every object a new read shape reaches is judged by the MCP read guard exactly as the object the call names. A target the guard refuses refuses the whole call with `PERMISSION_DENIED` / 403 before any record is read. A related object whose definition is not served to the caller refuses it with `OBJECT_NOT_FOUND` / 404, also before any read. +- An `expand` name that is not a relationship field of the object as the caller is served it, and a `related` link `field` that does not point at the record, are refused with `INVALID_FIELD` / 400 before any read. A child that points at the record through several fields needs `field`. +- `expand` runs through the engine's one expansion path: one batched `id IN (...)` read per field, under the target's own permissions, row-level security and field masking. It combines with `latestPer`. +- A related list is one `query_records` read of the child, filtered only by the link to the record, with the child's own `fields` and `orderBy` and no caller filter. It is read only after the record itself. A list with more rows than its cap carries `truncated: true`. +- The stdio bridge serves `expand` too, built as the data door builds it (a target that does not serve `get` keeps its stored id). `McpDataBridge.query` gains an optional `expand` member. + +Without `expand` or `related`, both tools answer exactly as before. `@objectstack/spec` is unchanged. diff --git a/content/docs/ai/connect-mcp.mdx b/content/docs/ai/connect-mcp.mdx index 7e40de20c5c..0897c65953a 100644 --- a/content/docs/ai/connect-mcp.mdx +++ b/content/docs/ai/connect-mcp.mdx @@ -269,7 +269,7 @@ service is installed: |:---|:---| | `list_objects` / `describe_object` | Discover which objects exist and their fields | | `validate_expression` | Check a CEL expression against an object's schema before authoring it into a formula, validation, or flow condition | -| `query_records` / `get_record` | Read data (list queries are capped at 50 rows per page by default) | +| `query_records` / `get_record` | Read data (list queries are capped at 50 rows per page by default); `expand` and `related` read related records in the same call | | `aggregate_records` | Grouped aggregation (registered when the active driver supports it) | | `create_record` / `update_record` / `delete_record` | Write data | | `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`) | @@ -313,6 +313,47 @@ names the groups and the order that picks each group's row: is read, as it is for an object with an `afterFind` hook or object-scoped read middleware. +### A record with its related records: `expand` and `related` + +`query_records` takes `expand`: up to 3 of the object's lookup, master-detail, +user or tree fields. Each one comes back as the record it names, one level +deep: + +```json +{ "objectName": "crm_opportunity", "expand": ["account", "owner_id"] } +``` + +`get_record` takes `related`: up to 3 child objects that point at the record, +each answered as a list of at most 20 rows (`limit` lowers it): + +```json +{ + "objectName": "crm_account", + "recordId": "acc_1", + "related": [ + { "object": "crm_opportunity", "orderBy": [{ "field": "close_date", "order": "desc" }] }, + { "object": "crm_activity", "field": "account", "limit": 5 } + ] +} +``` + +- The answer is then `{ record, related: [{ object, field, records, total, hasMore }] }`. + A list with more rows than came back also carries `truncated: true`. +- `field` is the child's field that points at the record. It can be left out + when the child has exactly one such field. +- A related list is filtered only by the link to the record. It takes the + child's own `fields` and `orderBy`, and no other filter. +- Every expanded or related object is read as you, under that object's + permissions, row-level security and field masking. A field you may not read is + not offered for `expand` or as a link. +- Every object a new read shape reaches is judged by the MCP read guard exactly + as the object the call names. An object the guard refuses (a system object + that is not opted into AI reads) refuses the whole call with + `PERMISSION_DENIED` before anything is read. A related object that is not + served to you refuses it too. +- A name that is not a relationship field, or a `field` that does not point at + the record, is refused with `INVALID_FIELD`. + ### Governed metrics and the `initialize` instructions `list_datasets` and `query_dataset` are registered with the `data:read` scope, From c0e19020664f42471d7c3db086d07874ca393079 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 14:36:41 +0000 Subject: [PATCH 07/11] fix(mcp): the relation refusals stamp literal codes Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL Co-authored-by: Claude --- packages/mcp/src/mcp-relation-reads.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/mcp/src/mcp-relation-reads.ts b/packages/mcp/src/mcp-relation-reads.ts index 75852d2fb57..169726df3ee 100644 --- a/packages/mcp/src/mcp-relation-reads.ts +++ b/packages/mcp/src/mcp-relation-reads.ts @@ -27,7 +27,7 @@ * engine's expansion and the record page's related lists ask too. */ -import { StandardErrorCode } from '@objectstack/spec/api'; +import type { StandardErrorCode } from '@objectstack/spec/api'; import { REFERENCE_VALUE_TYPES, isMultiValueField, referenceTargetOf } from '@objectstack/spec/data'; import type { McpDataBridge } from './mcp-http-tools.js'; @@ -70,7 +70,7 @@ export interface RelatedListPlan { type Refusal = Error & { code: string; status: number; object?: string; field?: string; param?: string }; function refusal( - code: string, + code: StandardErrorCode, status: number, message: string, extra: { object?: string; field?: string; param?: string } = {}, @@ -95,7 +95,7 @@ async function servedFieldMap( ): Promise>> { if (typeof bridge.servedObjectDefinitionOf !== 'function') { throw refusal( - StandardErrorCode.enum.NOT_IMPLEMENTED, + 'NOT_IMPLEMENTED', 501, `'${param}' needs the object definitions this host's data bridge does not serve, so nothing was read. ` + 'Read the related records with their own query_records call.', @@ -105,7 +105,7 @@ async function servedFieldMap( const def = await bridge.servedObjectDefinitionOf(objectName); if (!def) { throw refusal( - StandardErrorCode.enum.OBJECT_NOT_FOUND, + 'OBJECT_NOT_FOUND', 404, `Object '${objectName}' named in '${param}' is not served to you, so nothing was read.`, { object: objectName, param }, @@ -147,7 +147,7 @@ async function judgeTarget( const bad = await readGuard(target); if (bad === undefined) return; throw refusal( - StandardErrorCode.enum.PERMISSION_DENIED, + 'PERMISSION_DENIED', 403, `${reachedBy} reaches object '${target}', which this door does not serve you: ${bad}. ` + 'Nothing was read. Remove it from the request.', @@ -175,7 +175,7 @@ export async function judgeQueryExpand( const target = targetOf(def); if (!target) { throw refusal( - StandardErrorCode.enum.INVALID_FIELD, + 'INVALID_FIELD', 400, def === undefined ? `Unknown field '${name}' in 'expand' on object '${objectName}'. 'expand' takes the object's own ` @@ -215,7 +215,7 @@ export async function judgeRelatedLists( const links = Object.keys(fields).filter((name) => targetOf(fields[name]) === objectName); if (links.length !== 1) { throw refusal( - StandardErrorCode.enum.INVALID_FIELD, + 'INVALID_FIELD', 400, links.length === 0 ? `Object '${entry.object}' has no field you can read that points at '${objectName}', so it has no ` @@ -230,7 +230,7 @@ export async function judgeRelatedLists( const def = Object.prototype.hasOwnProperty.call(fields, field) ? fields[field] : undefined; if (targetOf(def) !== objectName) { throw refusal( - StandardErrorCode.enum.INVALID_FIELD, + 'INVALID_FIELD', 400, `'${field}' on '${entry.object}' is not a lookup, master-detail, user or tree field that points at ` + `'${objectName}'. Nothing was read.`, From 6346f9cb58247f868555a080125e9123b8b235dd Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 15:57:45 +0000 Subject: [PATCH 08/11] test(mcp, dogfood): related lists name withheld fields as a plain read does Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL Co-authored-by: Claude --- packages/mcp/src/mcp-relation-reads.test.ts | 13 +++++++++++++ .../test/related-read-over-mcp.dogfood.test.ts | 9 ++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/packages/mcp/src/mcp-relation-reads.test.ts b/packages/mcp/src/mcp-relation-reads.test.ts index cfa9eb9de31..9ea123eadab 100644 --- a/packages/mcp/src/mcp-relation-reads.test.ts +++ b/packages/mcp/src/mcp-relation-reads.test.ts @@ -240,6 +240,19 @@ describe('get_record related — the tool', () => { }); } + it('each list names the fields withheld from its own rows, as a plain read of that object does', async () => { + const { bridge } = makeBridge(); + bridge.fieldVisibilityOf = async (name: string) => + name === OPP + ? { served: ['name', 'account', 'probability'], readable: ['name', 'account'] } + : { served: ['name'], readable: ['name'] }; + const answer = await call(bridge, 'get_record', { objectName: ACCOUNT, recordId: 'a1', related: [{ object: OPP }] }); + expect(answer.payload.related[0].withheldFields).toEqual(['probability']); + expect(answer.payload.record.withheldFields).toBeUndefined(); + const plain = await call(bridge, 'query_records', { objectName: OPP }); + expect(plain.payload.withheldFields).toEqual(answer.payload.related[0].withheldFields); + }); + it('a multi-value link field is matched with $contains', async () => { const { bridge, calls } = makeBridge(); await call(bridge, 'get_record', { objectName: ACCOUNT, recordId: 'a1', related: [{ object: NOTE }] }); diff --git a/packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts b/packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts index 1a090afa173..43a490b4c70 100644 --- a/packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts +++ b/packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts @@ -253,9 +253,12 @@ describe('query_records expand and get_record related over MCP on the CRM exampl expect(ids(rowsOf(deals))).toEqual([opp.x1, opp.x2].sort()); expect(ids(rowsOf(deals))).not.toContain(opp.lost); for (const row of rowsOf(deals)) expect(row.probability).toBeUndefined(); - // …and the list names it as withheld, as a plain read of the deals does. - expect(deals.withheldFields).toContain('probability'); - expect(payload.record.withheldFields).toContain('annual_revenue'); + // …and the list says what is withheld exactly as a plain read of the + // deals does, and the record as a plain get_record does. + const plainDeals = await ok(tok.a, 'query_records', { objectName: OPP, where: { account: acct.a1 } }); + expect(deals.withheldFields).toEqual(plainDeals.withheldFields); + const plainRecord = await ok(tok.a, 'get_record', { objectName: ACCOUNT, recordId: acct.a1 }); + expect(payload.record.withheldFields).toEqual(plainRecord.withheldFields); expect(deals.truncated).toBeUndefined(); const acts = listOf(payload, ACTIVITY); expect(rowsOf(acts).map((r) => r.subject).sort()).toEqual(['RR call 1', 'RR call 2']); From fb4501686231790f6339cb12d9b6a7d1ef0f1dde Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 15:57:56 +0000 Subject: [PATCH 09/11] docs(mcp): related lists carry withheldFields Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL Co-authored-by: Claude --- .changeset/35145-mcp-related-read.md | 1 + content/docs/ai/connect-mcp.mdx | 2 ++ 2 files changed, 3 insertions(+) diff --git a/.changeset/35145-mcp-related-read.md b/.changeset/35145-mcp-related-read.md index 2ec8659e8f0..26a8f76981e 100644 --- a/.changeset/35145-mcp-related-read.md +++ b/.changeset/35145-mcp-related-read.md @@ -14,6 +14,7 @@ Metadata-protocol: none - An `expand` name that is not a relationship field of the object as the caller is served it, and a `related` link `field` that does not point at the record, are refused with `INVALID_FIELD` / 400 before any read. A child that points at the record through several fields needs `field`. - `expand` runs through the engine's one expansion path: one batched `id IN (...)` read per field, under the target's own permissions, row-level security and field masking. It combines with `latestPer`. - A related list is one `query_records` read of the child, filtered only by the link to the record, with the child's own `fields` and `orderBy` and no caller filter. It is read only after the record itself. A list with more rows than its cap carries `truncated: true`. +- The record and each related list carry `withheldFields` exactly as a plain `get_record` and a plain `query_records` of that object do. - The stdio bridge serves `expand` too, built as the data door builds it (a target that does not serve `get` keeps its stored id). `McpDataBridge.query` gains an optional `expand` member. Without `expand` or `related`, both tools answer exactly as before. `@objectstack/spec` is unchanged. diff --git a/content/docs/ai/connect-mcp.mdx b/content/docs/ai/connect-mcp.mdx index 0897c65953a..335c7fd65d4 100644 --- a/content/docs/ai/connect-mcp.mdx +++ b/content/docs/ai/connect-mcp.mdx @@ -346,6 +346,8 @@ each answered as a list of at most 20 rows (`limit` lowers it): - Every expanded or related object is read as you, under that object's permissions, row-level security and field masking. A field you may not read is not offered for `expand` or as a link. +- The record and each related list name the fields withheld from them in + `withheldFields`, as a plain `get_record` and `query_records` do. - Every object a new read shape reaches is judged by the MCP read guard exactly as the object the call names. An object the guard refuses (a system object that is not opted into AI reads) refuses the whole call with From 3d6e7691fee4d74def88be170708ad48206d4cce Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 17:12:31 +0000 Subject: [PATCH 10/11] fix(mcp): expand's text says only the read guard refuses; related lists carry the delegation notice The query_records description now says a field whose object the door does not serve refuses the call, while a record the caller may not read on a served object keeps its stored id. Each related list carries the delegation notice query_records carries. Docs, changeset and a dogfood pin follow. Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL Co-authored-by: Claude --- .changeset/35145-mcp-related-read.md | 3 ++- content/docs/ai/connect-mcp.mdx | 8 ++++++- packages/mcp/src/mcp-http-tools.ts | 14 +++++++++--- packages/mcp/src/mcp-relation-reads.test.ts | 21 ++++++++++++++++++ packages/mcp/src/stdio-data-bridge.ts | 4 ++-- .../related-read-over-mcp.dogfood.test.ts | 22 ++++++++++++++++--- 6 files changed, 62 insertions(+), 10 deletions(-) diff --git a/.changeset/35145-mcp-related-read.md b/.changeset/35145-mcp-related-read.md index 26a8f76981e..d6c4e2fec21 100644 --- a/.changeset/35145-mcp-related-read.md +++ b/.changeset/35145-mcp-related-read.md @@ -12,8 +12,9 @@ Metadata-protocol: none - Every object a new read shape reaches is judged by the MCP read guard exactly as the object the call names. A target the guard refuses refuses the whole call with `PERMISSION_DENIED` / 403 before any record is read. A related object whose definition is not served to the caller refuses it with `OBJECT_NOT_FOUND` / 404, also before any read. - An `expand` name that is not a relationship field of the object as the caller is served it, and a `related` link `field` that does not point at the record, are refused with `INVALID_FIELD` / 400 before any read. A child that points at the record through several fields needs `field`. -- `expand` runs through the engine's one expansion path: one batched `id IN (...)` read per field, under the target's own permissions, row-level security and field masking. It combines with `latestPer`. +- `expand` runs through the engine's one expansion path: one batched `id IN (...)` read per field, under the target's own permissions, row-level security and field masking. It combines with `latestPer`. Only the read guard's refusal refuses the call: a record the caller may not read on an admitted target object is not expanded, and the field keeps its stored id. - A related list is one `query_records` read of the child, filtered only by the link to the record, with the child's own `fields` and `orderBy` and no caller filter. It is read only after the record itself. A list with more rows than its cap carries `truncated: true`. +- Each related list carries the delegation notice `query_records` carries (`delegationNarrowed`, `warning`) when the agent ceiling narrowed the read. - The record and each related list carry `withheldFields` exactly as a plain `get_record` and a plain `query_records` of that object do. - The stdio bridge serves `expand` too, built as the data door builds it (a target that does not serve `get` keeps its stored id). `McpDataBridge.query` gains an optional `expand` member. diff --git a/content/docs/ai/connect-mcp.mdx b/content/docs/ai/connect-mcp.mdx index 335c7fd65d4..1e3541e96e5 100644 --- a/content/docs/ai/connect-mcp.mdx +++ b/content/docs/ai/connect-mcp.mdx @@ -352,7 +352,13 @@ each answered as a list of at most 20 rows (`limit` lowers it): as the object the call names. An object the guard refuses (a system object that is not opted into AI reads) refuses the whole call with `PERMISSION_DENIED` before anything is read. A related object that is not - served to you refuses it too. + served to you refuses it too. An expanded field is different: when the guard + admits its object but you may not read the record it names (no permission on + that object, or a row it hides from you), the call is answered and the field + keeps its stored id. +- Each related list carries the delegation notice (`delegationNarrowed`, + `warning`) that `query_records` carries when the agent ceiling narrowed the + read. - A name that is not a relationship field, or a `field` that does not point at the record, is refused with `INVALID_FIELD`. diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index dbe4c3e4204..08c2ad71b8b 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -3622,8 +3622,9 @@ export function registerObjectTools( // [#35145] One level of forward relations in the same call. `To read the records a lookup points at in the same call, pass expand: up to ${QUERY_EXPAND_MAX_FIELDS} of the ` + 'object\'s lookup, master-detail, user or tree fields, e.g. expand ["account","owner_id"]; each one comes back ' + - 'as the record it names, under your permissions on that object. One level only; a field whose object you ' + - 'may not read refuses the call. ' + + 'as the record it names, under your permissions on that object. One level only. A field whose object this ' + + 'door does not serve you refuses the call; a record you may not read on a served object is not expanded, ' + + 'and the field keeps its stored id. ' + WITHHELD_FIELDS_DESCRIPTION, inputSchema: strictToolInput( { @@ -3978,10 +3979,17 @@ export function registerObjectTools( ? (page as Record) : { records: page }; // [#35137] …each list naming the fields withheld from its own rows. - return withWithheldFields( + const list = withWithheldFields( { ...answer, object: plan.object, field: plan.field }, await withheldFieldsFor(bridge, plan.object, plan.fields), ); + // [ADR-0090 D10] …and, as `query_records` states it, a list the + // agent ceiling narrowed carries the narrowing beside its `total`. + // ⛔ The probe never fails the list it annotates. + const diagnosed = typeof bridge.diagnoseDelegation === 'function' + ? await bridge.diagnoseDelegation(plan.object).catch(() => undefined) + : undefined; + return diagnosed?.narrowed && diagnosed.statement ? withDelegationNotice(list, diagnosed.statement) : list; })); return textResult({ record: served, related: lists }); } catch (err) { diff --git a/packages/mcp/src/mcp-relation-reads.test.ts b/packages/mcp/src/mcp-relation-reads.test.ts index 9ea123eadab..88c14c67873 100644 --- a/packages/mcp/src/mcp-relation-reads.test.ts +++ b/packages/mcp/src/mcp-relation-reads.test.ts @@ -253,6 +253,27 @@ describe('get_record related — the tool', () => { expect(plain.payload.withheldFields).toEqual(answer.payload.related[0].withheldFields); }); + it('a list the agent ceiling narrowed carries the delegation notice query_records carries; others do not', async () => { + const { bridge } = makeBridge(); + bridge.diagnoseDelegation = async (name: string) => + name === OPP ? { narrowed: true, statement: 'narrowed by the agent ceiling' } : { narrowed: false }; + const answer = await call(bridge, 'get_record', { + objectName: ACCOUNT, recordId: 'a1', related: [{ object: OPP }, { object: ACTIVITY, field: 'account' }], + }); + expect(answer.payload.related[0]).toMatchObject({ delegationNarrowed: true, warning: 'narrowed by the agent ceiling' }); + expect(answer.payload.related[1].delegationNarrowed).toBeUndefined(); + const plain = await call(bridge, 'query_records', { objectName: OPP }); + expect(plain.payload).toMatchObject({ delegationNarrowed: true, warning: 'narrowed by the agent ceiling' }); + }); + + it('a diagnosis that throws never fails the list', async () => { + const { bridge } = makeBridge(); + bridge.diagnoseDelegation = async () => { throw new Error('probe down'); }; + const answer = await call(bridge, 'get_record', { objectName: ACCOUNT, recordId: 'a1', related: [{ object: OPP }] }); + expect(answer.isError, answer.text).toBe(false); + expect(answer.payload.related[0].delegationNarrowed).toBeUndefined(); + }); + it('a multi-value link field is matched with $contains', async () => { const { bridge, calls } = makeBridge(); await call(bridge, 'get_record', { objectName: ACCOUNT, recordId: 'a1', related: [{ object: NOTE }] }); diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index c3a6c437e28..e5a253d048c 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -60,8 +60,8 @@ * `callData` prefers the `protocol` service (metadata-protocol) and falls back * to the engine; this bridge is engine-only. So the HTTP tools additionally get * that layer's existence probes, its spec-shaped receipts and `select` -(`expand` is served here since #35145, built as that layer builds it: -{@link stdioExpandMap}). + * (`expand` is served here since #35145, built as that layer builds it: + * {@link stdioExpandMap}). * (That layer's create-side `readonly` strip used to head this list; since the * maintainer ruling of 2026-09-03 — option C, #14147 — the static `readonly` * strip runs inside `engine.insert` for every non-system caller and the diff --git a/packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts b/packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts index 43a490b4c70..ef6cd7f0db9 100644 --- a/packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts +++ b/packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts @@ -76,6 +76,7 @@ describe('query_records expand and get_record related over MCP on the CRM exampl const uid: Record = {}; const acct: Record = {}; const opp: Record = {}; + let contactId = ''; const idOf = (b: any): string => String(b?.id ?? b?.record?.id ?? ''); const userId = async (email: string): Promise => @@ -135,8 +136,10 @@ describe('query_records expand and get_record related over MCP on the CRM exampl name: `RR ${key}`, account, owner_id: owner, stage, close_date: '2031-06-30', amount: 100, probability: 40, organization_id: o, }, SYS)); }; - const activity = async (o: string, account: string, subject: string) => - idOf(await ql.insert(ACTIVITY, { subject, type: 'call', status: 'planned', account, organization_id: o }, SYS)); + const activity = async (o: string, account: string, subject: string, contact?: string) => + idOf(await ql.insert(ACTIVITY, { + subject, type: 'call', status: 'planned', account, ...(contact ? { contact } : {}), organization_id: o, + }, SYS)); beforeAll(async () => { stack = await bootStack(crmStack as never, { @@ -169,7 +172,9 @@ describe('query_records expand and get_record related over MCP on the CRM exampl await deal('b1', org.b, acct.b1, uid.b, 'proposal'); await deal('bx', org.b, acct.a1, uid.b, 'proposal'); // Activities: two on a1, MANY on a2 (more than a list's cap). - await activity(org.a, acct.a1, 'RR call 1'); + // A contact of a1, which the member may not read, on the first call. + contactId = idOf(await ql.insert(CONTACT, { first_name: 'Rita', last_name: 'Reader', account: acct.a1, organization_id: org.a }, SYS)); + await activity(org.a, acct.a1, 'RR call 1', contactId); await activity(org.a, acct.a1, 'RR call 2'); for (let i = 0; i < MANY; i++) await activity(org.a, acct.a2, `RR many ${String(i).padStart(2, '0')}`); @@ -308,6 +313,17 @@ describe('query_records expand and get_record related over MCP on the CRM exampl expect(viaRelated.text).not.toContain('RR account a1'); }); + it('⭐ expand onto an object the guard admits but the member may not read: the call is answered, the field keeps its stored id', async () => { + const payload = await ok(tok.a, 'query_records', { + objectName: ACTIVITY, where: { subject: 'RR call 1' }, expand: ['contact', 'account'], + }); + const [row] = rowsOf(payload); + expect(row.contact).toBe(contactId); + expect(JSON.stringify(payload)).not.toContain('Rita'); + // …while the readable target in the same call is expanded. + expect(row.account?.id).toBe(acct.a1); + }); + it('⭐ a related object the member may not read refuses the whole call, before any read', async () => { // Its definition is not served to the member at all, so the call is // refused while the relation is judged: no record of either list is read. From 0e7914f180eac40928160ea2b2d455dc6483269d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 17:22:54 +0000 Subject: [PATCH 11/11] test(core): classify the two new reference-target callers in the second-object read pin The MCP stdio bridge's expand asks the target's get exposure in stdioExpandMap (decided); the MCP relation judging reads no record and executes through the data door's servedExpand. Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL Co-authored-by: Claude --- .../second-object-read-exposure.pin.test.ts | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/packages/core/src/security/second-object-read-exposure.pin.test.ts b/packages/core/src/security/second-object-read-exposure.pin.test.ts index 352a8741e6c..b9b2a7f381e 100644 --- a/packages/core/src/security/second-object-read-exposure.pin.test.ts +++ b/packages/core/src/security/second-object-read-exposure.pin.test.ts @@ -218,6 +218,27 @@ const CALLERS: Record = { wiring: { file: 'packages/services/service-analytics/src/analytics-service.ts', call: 'assertObjectsExposed(objects, provider' }, pin: 'packages/services/service-analytics/src/__tests__/cross-object-relation-group-join.test.ts', }, + // [#35145] The MCP stdio bridge's `expand` (`query_records`), built as the data door builds it. + 'packages/mcp/src/stdio-data-bridge.ts': { + kind: 'decided', + read: "the MCP stdio bridge's `expand` on `query_records` (the engine's expansion sub-read, entered from an engine-only bridge)", + operation: 'get', + decision: { file: 'packages/mcp/src/stdio-data-bridge.ts', fn: 'stdioExpandMap' }, + wiring: { file: 'packages/mcp/src/stdio-data-bridge.ts', call: 'stdioExpandMap(reads, object' }, + pin: 'packages/mcp/src/mcp-relation-reads.test.ts', + }, + // [#35145] The MCP tools' relation judging for `expand` and `related`. + 'packages/mcp/src/mcp-relation-reads.ts': { + kind: 'executes', + read: + "the MCP tools' `expand` (`query_records`) and `related` (`get_record`): the targets are judged here by the MCP " + + "read guard, then read through the data door, whose `servedExpand` decides each expansion target", + decidedIn: 'packages/metadata-protocol/src/protocol-query-validation.ts', + also: + 'reads no record: `referenceTargetOf` names the object an `expand` field points at (asked of the MCP read guard, ' + + 'then expanded by `findData`, which asks its exposure) and checks that a `related` link field points at the parent ' + + 'record; each related list is a `findData` read of the child it names, judged by that door as any list.', + }, 'packages/core/src/utils/relation-condition-sites.ts': { kind: 'not-a-served-read', reason: @@ -527,6 +548,7 @@ describe('[#22661] every read that reaches a second object asks that object its 'servesPayloadDisplayTarget', 'servesReferenceTarget', 'servesSummaryTitleTarget', + 'stdioExpandMap', ]); for (const d of decided) {