Skip to content

Commit dbb2f68

Browse files
feat(mcp): query_records expand and get_record related, every reached object judged by the read guard (#35225)
Fixes #35145 (PR 2 of 2: `expand` on `query_records` and `related` on `get_record`; PR 1, `latestPer`, landed as #35199) Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 改了什么:MCP 的 `query_records` 新增 `expand`(一次把商机的客户、负责人等查找字段展开成完整记录),`get_record` 新增 `related`(一次读出客户及其商机、活动等子记录列表)。 - 为什么改:问数场景里“这个客户和它的商机/活动”“每笔商机连同客户名”原本要 AI 连发多次调用再自己拼接;现在一次调用完成,且仍在调用者的权限、行级安全和字段屏蔽之下。 - 风险与回滚:不传新参数的调用完全不变;展开或关联到的每个对象都要过 MCP 读守卫,被守卫拒绝的对象让整次调用失败、不读任何数据;守卫放行但调用者无权读的展开目标不展开,字段保留原 id,调用照常返回。回滚即撤销本 PR,无数据迁移。 - 先看:`packages/mcp/src/mcp-relation-reads.ts`(读守卫对目标对象的判定、关联字段校验、上限),`packages/mcp/src/mcp-http-tools.ts` 中 `get_record` 处理函数(先读父记录、再按父链接读子列表、截断标记),`packages/mcp/src/stdio-data-bridge.ts` 的 `stdioExpandMap`。 - 两分钟验证:`pnpm --filter @objectstack/mcp exec vitest run --maxWorkers=2 src/mcp-relation-reads.test.ts`,预期 28 条全绿(含系统对象目标整单拒绝、什么都没读)。 - 需要你做的:无,席位落地。 ## What changes - **`query_records` gains `expand`** (`packages/mcp/src/mcp-http-tools.ts`): up to 3 (`QUERY_EXPAND_MAX_FIELDS`) of the queried object's lookup, master-detail, user or tree fields, one level deep (no dotted path). Each name is judged against the object as the caller is served it (`servedObjectDefinitionOf`), and the object it points at passes the MCP read guard, before any read. The names go to the bridge as `expand`; the HTTP bridge hands them to `findData` (which lowers and gates them as on REST: `assertExpandTargetsExist`, `servedExpand`), and the engine expands them through its one expansion path: one batched `id IN (...)` read per field via `engine.find`, under the target's permissions, row-level security and field masking. It combines with `latestPer` (the engine expands after the window read). Only the MCP read guard's refusal refuses the call: a target the guard admits but the engine does not expand for the caller (for example, no object permission on it) leaves the field holding its stored id, and the call is answered. The tool text says exactly that. - **`get_record` gains `related`**: up to 3 (`GET_RECORD_MAX_RELATED_LISTS`) entries `{ object, field?, fields?, orderBy?, limit? }`, strict (no caller filter). Every child object passes the read guard first; then its link `field` must be a reference field of the child, as the caller is served it, that points at the parent (left out, the child's one such field is used; none or several is refused with the candidates named). The record is read first; each list is then one `query_records`-shaped bridge read of the child with `where` = the link to that record alone (`$contains` for a multi-value link), the child's own `fields` and `orderBy`, and `limit + 1`. Each list carries the same delegation-narrowing notice (`delegationNarrowed`, `warning`; ADR-0090 D10) that `query_records` adds when the agent ceiling narrowed that object. A list's rows are capped at 20 (`RELATED_LIST_MAX_ROWS`, never above `maxQueryLimit`) and served by the shared `servedQueryPage`, so a capped list carries `truncated: true`. The answer is `{ record, related: [{ object, field, records, total, hasMore, truncated? }] }`; without `related` it is the record alone, as before. - **The rule** (`packages/mcp/src/mcp-relation-reads.ts`): 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 and nothing is read. Other refusals, all before any read: `INVALID_FIELD` / 400 (unknown or non-relation `expand` name, a link field that does not point at the parent, ambiguous or missing link), `OBJECT_NOT_FOUND` / 404 (a related object whose definition is not served to the caller), `NOT_IMPLEMENTED` / 501 (a bridge that serves no object definitions). A related list's own read refusal is the whole call's, with its code. - **`withheldFields`**: the record and each related list name the fields withheld from them, as plain reads do (#35179's helper, applied per row set). - **HTTP bridge** (`packages/runtime/src/domains/mcp.ts`): forwards `expand` into the `findData` query. One line. - **stdio bridge** (`packages/mcp/src/stdio-data-bridge.ts`): serves `expand` too, built as the data door builds it (`stdioExpandMap`): a non-reference name is `INVALID_FIELD`, a target whose declaration does not serve `get` is withheld (its field keeps the stored id, as `servedExpand` does). - `McpDataBridge.query` gains an optional `expand?: string[]`. `@objectstack/spec` is unchanged. Docs: `content/docs/ai/connect-mcp.mdx` gains an `expand` / `related` section. Changeset: `@objectstack/mcp`, `@objectstack/runtime`, `patch`. ## Tests - `packages/mcp/src/mcp-relation-reads.test.ts` (28): the tool against a recording bridge. `expand`: the judged, de-duplicated names reach the one query; a guard-refused target (`sys_organization`) is `PERMISSION_DENIED` with no read; unknown, non-relation and dotted names are `INVALID_FIELD`; more than 3 is refused at the door; no definition member is `NOT_IMPLEMENTED`; a control without `expand`. `related`: the record is read before the lists, each list filtered by the link alone with `limit + 1`, the default cap 20, `truncated: true` from the probe row; a guard-refused child refuses the call with zero bridge calls; link inference, the several-links and no-link refusals, a field that points elsewhere, an unserved object; `$contains` for a multi-value link; an unreadable record reads no list; a list's own refusal is the call's; 4 lists, a limit above 20 and a caller `where` are refused at the door; each list's `withheldFields` equals a plain `query_records` of that object; a list the agent ceiling narrowed carries the delegation notice and the others do not; a diagnosis that throws never fails the list; a control without `related`. The stdio bridge: the expand map, a target that does not serve `get` withheld, a non-reference name refused before the engine. - `packages/qa/dogfood/test/related-read-over-mcp.dogfood.test.ts` (10, plus parity with plain reads on `withheldFields`): the CRM example over the live `/mcp` transport, real SecurityPlugin, SQL driver, `multiTenant: 'posture-only'` with two organizations. A member with read on accounts, deals and activities (not contacts), a row policy hiding closed-lost deals, `crm_opportunity.probability` and `crm_account.annual_revenue` withheld. Pins: deals expand `account` and `owner_id` into records with the account's withheld field still withheld; `expand` with `latestPer`; an account's related deals and activities, the RLS-hidden deal never in the list, withheld fields withheld on the rows; the tenant wall (organization B's deal pointing at A's account never appears in A's list; A's account is `RECORD_NOT_FOUND` for B; B sees only its own deal); a 25-row list answers 20 rows with `truncated: true` and `total` 25, `limit: 5` with an order answers the first 5 and `truncated: true`; `expand: ['organization_id']` and a `related` `sys_organization` refuse the whole call with `PERMISSION_DENIED` and no record data; a related object the member may not read refuses with `OBJECT_NOT_FOUND`; `expand` of `crm_activity.contact` onto `crm_contact`, which the guard admits but the member may not read, answers the call with the field holding its stored id and no contact data (the account on the same rows still expands); unknown and non-relation names are `INVALID_FIELD`; a control without either. Armed controls: the wall is real, the hidden deal and the cross-tenant deal exist at rest, the row policy binds, contacts are unreadable. - Ablation of the read-guard check on targets (`judgeTarget`'s admit line mutated to admit every target, via `scripts/ablation-replace.mjs`; readings below). ## Acceptance notes - **Push-down.** `expand`: one batched `id IN (...)` read per expanded field through `engine.find` (the engine's existing expansion path, no per-row loop). `related`: one list read per related list through `findData` / `engine.find` with the parent-id filter, plus the door's match count that serves `total` (the same count a plain `query_records` page runs). No in-app join. - **A related object the caller lacks object permission on** answers `OBJECT_NOT_FOUND` / 404, not `PERMISSION_DENIED`: its definition is not served to the caller, so the call is refused while the relation is judged, before any record read. The dispatch named "a target object the caller cannot read refuses the call"; it does, with that code. - **An expanded target the engine does not expand for the caller** (for example, no object permission on it) keeps the stored id on the row and the call is answered (the engine's existing expansion behaviour, and `referenceNameVisible` where declared); only the MCP read guard's refusal refuses the whole call. Pinned in the dogfood run (`crm_activity.contact` onto `crm_contact`); the tool text, docs and changeset say exactly this. - **Delegation notice on related lists.** Each list runs the same `diagnoseDelegation` check on its child object that `query_records` runs and carries `withDelegationNotice` when narrowed; a diagnosis that fails leaves the list as is. - **Repo pin classification.** `packages/core/src/security/second-object-read-exposure.pin.test.ts` classifies every non-test caller of `referenceTargetOf`; it now lists the two new callers (`stdioExpandMap` in `stdio-data-bridge.ts` as the decided `get` serving check, pinned by `mcp-relation-reads.test.ts`; `mcp-relation-reads.ts` as executing what the data door decides). This file is outside the claimed file surface: the classification is the pin's own requirement for any new caller. Its absence was the `Test Core (9/10)` failure on `3d6e7691fee` (this PR's, not main's); green on `0e7914f180e` and after. - **`withheldFields`** (#35179) landed on `main` while this was built and is merged in: the record and each related list carry `withheldFields` exactly as a plain `get_record` / `query_records` of that object does (pinned in the unit suite with a visibility double, and in the dogfood run as parity with the plain reads). Rows nested under `expand` stay masked as a plain read of the target masks them; no per-target `withheldFields` is stated for them, because the note is per row set and an expanded record is nested in another object's rows. - **A third-party bridge** that ignores the new `expand` member answers unexpanded ids. Both in-repo bridges serve it. - **Overlap.** `overlap-check` at this head: `origin/main` merges cleanly; and the one open PR sharing files (#35193) merges cleanly too. (Earlier in the build #35179 and #35198 conflicted; #35179 has since landed and is merged in.) - `#35145` closes on merge: PR 1 (#35199) carried `latestPer`; this PR carries the related-objects read. The ask-card kinds named in the card's "Done when" live on #35113. ## Verification Rework readings from head `977e416ad0a` (merge of `origin/main` into `0e7914f180e`; this PR's files unchanged by the merge) unless a line says otherwise. Every heavy run went through `os-verify-lock`; each exit code was captured before any pipe. <details><summary>Targeted suites (rework)</summary> - `mcp-relation-reads.test.ts`: Tests 28 passed (28) - dogfood `related-read-over-mcp.dogfood.test.ts` (10) + `latest-per-over-mcp.dogfood.test.ts` (7): Test Files 2 passed (2), Tests 17 passed (17) - `@objectstack/core` repo pin `second-object-read-exposure.pin.test.ts`: Tests 4 passed (4); `@objectstack/core` `--project repo` at `0e7914f180e`: Test Files 8 passed, Tests 108 passed - `@objectstack/mcp` typecheck (with `check:test-typecheck`): exit 0 - `@objectstack/mcp` full suite at `3d6e7691fee`: Test Files 76 passed (76), Tests 1376 passed (1376) </details> <details><summary>Dogfood battery</summary> - Not re-run this round: the rework touches the mcp package (tool text, the per-list notice), docs, changeset, one dogfood file and one core repo pin; the two dogfood files that read it are run above. The full battery at `fb450168623`: Test Files 482 passed, 3 skipped (485); Tests 4091 passed, 68 skipped (4159). </details> <details><summary>Ablation of the read-guard check on targets (round 1, `judgeTarget` unchanged since)</summary> `judgeTarget`'s admit line `if (bad === undefined) return;` mutated to admit every target (`scripts/ablation-replace.mjs`, anchor 1 to 0): unit 2 failed / 23 passed (exactly the two guard pins); dogfood through `dist/` (rebuild + `ablation-dist-preflight`) 1 failed / 8 passed (exactly THE RULE pin). Restore legs: blob == HEAD, `git diff HEAD` empty, preflight `--absent`. </details> <details><summary>Gates</summary> - `dispatch-gates --commands` at `977e416ad0a`: 101 families, all run locally, all exit 0 (including `check:skill-examples` and `check:dual-build-cjs-loads` after building the six packages they read). `--ran` reconciliation with every exit code recorded: 101 derived, 101 run, 0 NOT-MEASURED (a derived zero). - CI on `977e416ad0a`: all 70 check-runs completed, 60 success and 10 skipped by their selectors, none failed; `PR-body guards`, `Check Changeset`, `Test Core` (all 10 shards) and `Lint & Repo Gates` success. - `overlap-check` at `977e416ad0a`: `origin/main` merges cleanly; #35193 now conflicts in `packages/mcp/src/stdio-data-bridge.ts` (it changed after round 1); the second of the two to land resolves it. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL)_ <!-- signed: repo:objectstack#1 · os-warren · session_01JQwxbaX2qDxUq9sF93EqqL --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 7bd5d28 commit dbb2f68

9 files changed

Lines changed: 1259 additions & 8 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
'@objectstack/mcp': patch
3+
'@objectstack/runtime': patch
4+
---
5+
6+
feat(mcp): a record with its related records in one call — `expand` on `query_records`, `related` on `get_record`
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: none
10+
11+
`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 }] }`.
12+
13+
- 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.
14+
- 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`.
15+
- `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.
16+
- 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`.
17+
- Each related list carries the delegation notice `query_records` carries (`delegationNarrowed`, `warning`) when the agent ceiling narrowed the read.
18+
- The record and each related list carry `withheldFields` exactly as a plain `get_record` and a plain `query_records` of that object do.
19+
- 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.
20+
21+
Without `expand` or `related`, both tools answer exactly as before. `@objectstack/spec` is unchanged.

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

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,7 @@ service is installed:
269269
|:---|:---|
270270
| `list_objects` / `describe_object` | Discover which objects exist and their fields |
271271
| `validate_expression` | Check a CEL expression against an object's schema before authoring it into a formula, validation, or flow condition |
272-
| `query_records` / `get_record` | Read data (list queries are capped at 50 rows per page by default) |
272+
| `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 |
273273
| `aggregate_records` | Grouped aggregation (registered when the active driver supports it) |
274274
| `create_record` / `update_record` / `delete_record` | Write data |
275275
| `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,55 @@ names the groups and the order that picks each group's row:
313313
is read, as it is for an object with an `afterFind` hook or object-scoped read
314314
middleware.
315315

316+
### A record with its related records: `expand` and `related`
317+
318+
`query_records` takes `expand`: up to 3 of the object's lookup, master-detail,
319+
user or tree fields. Each one comes back as the record it names, one level
320+
deep:
321+
322+
```json
323+
{ "objectName": "crm_opportunity", "expand": ["account", "owner_id"] }
324+
```
325+
326+
`get_record` takes `related`: up to 3 child objects that point at the record,
327+
each answered as a list of at most 20 rows (`limit` lowers it):
328+
329+
```json
330+
{
331+
"objectName": "crm_account",
332+
"recordId": "acc_1",
333+
"related": [
334+
{ "object": "crm_opportunity", "orderBy": [{ "field": "close_date", "order": "desc" }] },
335+
{ "object": "crm_activity", "field": "account", "limit": 5 }
336+
]
337+
}
338+
```
339+
340+
- The answer is then `{ record, related: [{ object, field, records, total, hasMore }] }`.
341+
A list with more rows than came back also carries `truncated: true`.
342+
- `field` is the child's field that points at the record. It can be left out
343+
when the child has exactly one such field.
344+
- A related list is filtered only by the link to the record. It takes the
345+
child's own `fields` and `orderBy`, and no other filter.
346+
- Every expanded or related object is read as you, under that object's
347+
permissions, row-level security and field masking. A field you may not read is
348+
not offered for `expand` or as a link.
349+
- The record and each related list name the fields withheld from them in
350+
`withheldFields`, as a plain `get_record` and `query_records` do.
351+
- Every object a new read shape reaches is judged by the MCP read guard exactly
352+
as the object the call names. An object the guard refuses (a system object
353+
that is not opted into AI reads) refuses the whole call with
354+
`PERMISSION_DENIED` before anything is read. A related object that is not
355+
served to you refuses it too. An expanded field is different: when the guard
356+
admits its object but you may not read the record it names (no permission on
357+
that object, or a row it hides from you), the call is answered and the field
358+
keeps its stored id.
359+
- Each related list carries the delegation notice (`delegationNarrowed`,
360+
`warning`) that `query_records` carries when the agent ceiling narrowed the
361+
read.
362+
- A name that is not a relationship field, or a `field` that does not point at
363+
the record, is refused with `INVALID_FIELD`.
364+
316365
### Governed metrics and the `initialize` instructions
317366

318367
`list_datasets` and `query_dataset` are registered with the `data:read` scope,

‎packages/core/src/security/second-object-read-exposure.pin.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,27 @@ const CALLERS: Record<string, Classification> = {
218218
wiring: { file: 'packages/services/service-analytics/src/analytics-service.ts', call: 'assertObjectsExposed(objects, provider' },
219219
pin: 'packages/services/service-analytics/src/__tests__/cross-object-relation-group-join.test.ts',
220220
},
221+
// [#35145] The MCP stdio bridge's `expand` (`query_records`), built as the data door builds it.
222+
'packages/mcp/src/stdio-data-bridge.ts': {
223+
kind: 'decided',
224+
read: "the MCP stdio bridge's `expand` on `query_records` (the engine's expansion sub-read, entered from an engine-only bridge)",
225+
operation: 'get',
226+
decision: { file: 'packages/mcp/src/stdio-data-bridge.ts', fn: 'stdioExpandMap' },
227+
wiring: { file: 'packages/mcp/src/stdio-data-bridge.ts', call: 'stdioExpandMap(reads, object' },
228+
pin: 'packages/mcp/src/mcp-relation-reads.test.ts',
229+
},
230+
// [#35145] The MCP tools' relation judging for `expand` and `related`.
231+
'packages/mcp/src/mcp-relation-reads.ts': {
232+
kind: 'executes',
233+
read:
234+
"the MCP tools' `expand` (`query_records`) and `related` (`get_record`): the targets are judged here by the MCP " +
235+
"read guard, then read through the data door, whose `servedExpand` decides each expansion target",
236+
decidedIn: 'packages/metadata-protocol/src/protocol-query-validation.ts',
237+
also:
238+
'reads no record: `referenceTargetOf` names the object an `expand` field points at (asked of the MCP read guard, ' +
239+
'then expanded by `findData`, which asks its exposure) and checks that a `related` link field points at the parent ' +
240+
'record; each related list is a `findData` read of the child it names, judged by that door as any list.',
241+
},
221242
'packages/core/src/utils/relation-condition-sites.ts': {
222243
kind: 'not-a-served-read',
223244
reason:
@@ -527,6 +548,7 @@ describe('[#22661] every read that reaches a second object asks that object its
527548
'servesPayloadDisplayTarget',
528549
'servesReferenceTarget',
529550
'servesSummaryTitleTarget',
551+
'stdioExpandMap',
530552
]);
531553

532554
for (const d of decided) {

0 commit comments

Comments
 (0)