Skip to content

Commit ec227fc

Browse files
feat(mcp): query_records and get_record name the fields field-level security withheld from the caller (#35179)
Fixes #35137 Clause-②: yes (widening) Metadata-protocol: none Security-touching: yes The card's two remaining halves have their own carriers: the ask-data skill line is carried by #35191, and the example-app scenario question by #35113. This PR is the framework half, built on the maintainer's ruling A recorded on the card (comment 6977609191): keep the bound. ## 维护者速读 - 改了什么:MCP 的 `query_records` 与 `get_record` 在调用者有字段被字段级安全挡掉、而该字段又在调用者自己的 schema 里可见时,结果里多带 `withheldFields`(只给字段名,不给值)和一句固定说明;HTTP 与 stdio 两个入口一致。本轮:「调用者 schema 里有哪些字段」这一半改为直接取 `describe_object` 返回给该调用者的那份字段列表。 - 为什么改:之前被挡掉的字段在行里直接消失,AI 客户端把它读成「空」;现在免于 schema 遮罩的调用者(D4)或关了 schema 遮罩的部署会被告知「对你不可见」,默认遮罩下的普通成员则永远不会被点名(该字段对他们不存在),即裁决 A。 - 风险与回滚:只读、只加结果成员,无人被挡时结果逐字节不变;安全线是「调用者 schema 里看不到的字段永不点名」,由 `withheldFieldNames` 的求交一行和本轮的同源字段列表共同守住,各有消融证明;回滚即 revert 本 PR。 - 先看:`packages/runtime/src/domains/mcp.ts` 的 `describeForCaller` 与 `fieldVisibilityOf`;`packages/mcp/src/stdio-data-bridge.ts` 的 `describeForPrincipal` 与 `fieldVisibilityOf`;`packages/mcp/src/mcp-http-tools.ts` 的 `withheldFieldNames`(`served.has` 一行)。 - 两分钟验证:`pnpm --filter @objectstack/mcp exec vitest run src/query-records-withheld-fields.test.ts`,预期 12 个用例全绿。 - 需要你做的:无,席位落地。 ## What changes - `McpDataBridge` gains an optional member, `fieldVisibilityOf(object)`, answering two framework answers asked as the caller: the field names the caller's own served schema shows, and the security service's readable answer for them (`getReadableFields`). Both bridges implement it. - The served-schema field list now comes from the same projection `describe_object` serves. Each door's `describe_object` answer is built by one local function (`describeForCaller` on the HTTP bridge in `packages/runtime/src/domains/mcp.ts`, `describeForPrincipal` on the stdio bridge in `packages/mcp/src/stdio-data-bridge.ts`), and `fieldVisibilityOf` reads its field names off that answer (`describedFieldNames`), so any later filter on what `describe_object` lists applies to `withheldFields` too. - The shared tool layer (`packages/mcp/src/mcp-http-tools.ts`) names a field as withheld only when the served schema shows it and the readable answer leaves it out; with `fields` in the call only asked fields are candidates. When the list is non-empty, the result carries `withheldFields` and `withheldFieldsNote` (one constant sentence, `WITHHELD_FIELDS_NOTE`). When it is empty, nothing is added. A missing member, an `undefined` answer or a throw adds nothing and never fails the read. - Who is told (ruling A): a caller served the whole schema (ADR-0106 D4 exempt) or any caller where object-schema masking is switched off (D8). A plain member under default masking is never told: the field does not exist in their schema. - `query_records` and `get_record` descriptions gain one sentence about the member. - `aggregate_records` is unchanged: measured on the real security layer, a withheld field asked as a measure or a group is already refused `403 PERMISSION_DENIED` (see Verification). - No change to what field-level security withholds; no write path touched; no new security-service method (the existing `getReadableFields` is the caller-scoped answer). ## Tests - `packages/mcp/src/query-records-withheld-fields.test.ts` (new): the tool layer over the HTTP runtime, and the stdio bridge behind the real tools. Pins: a withheld field named with the note; a field the served schema does not show never named anywhere in the serialized result, even when asked for in `fields`; a readable field with an empty value not named; only asked fields named; nothing withheld means no member and a byte-identical answer; a bridge that cannot answer or throws names nothing; the member beside a delegation narrowing. On stdio: a D4-exempt caller is told; a member under default masking whose schema hides the field never sees it named; with masking off (D8) the member is told; no security service means no member; and (round 2) the served list follows `describe_object`'s field names on an object where the two could differ. - `packages/runtime/src/domains/mcp-object-schema-mask.test.ts`, on the real security layer (`SecurityPlugin` over `ObjectQL` + `SqlDriver`): the D4-exempt author's served list equals `describe_object`'s field names and the denied field is withheld; the member under default masking is answered nothing; (round 2) with masking off the member's served list equals `describe_object`'s field names and the denied field is withheld; an unrestricted member is withheld nothing and no security service answers nothing. And (round 2), on the real engine, the pin "served equals `describe_object`'s field names" extended to an object where the two could differ. - The two bridge-member classification tripwires register the new member. Choice stated: a caller with nothing withheld gets no member (not an empty list), so its result is unchanged. ## Acceptance notes - Ruled persona: the card's done-when is met for a D4-exempt caller or a masking-off deployment, each pinned on both doors above; the plain-member-under-default-masking persona is never told, also pinned on both doors. - `get_record` keeps the two members on the record object, beside its field keys (contract review N2, judged and left): moving them beside the record would mean wrapping it (for example a `record` key) only when something is withheld, so where the record sits in the answer would change with the caller's field security, a shape split every client would have to branch on. The existing precedent for a notice on these tools (the delegation narrowing) also adds keys on the answer object. No collision is possible: field machine names are snake_case, these members camelCase. - The note text lives in one constant (`WITHHELD_FIELDS_NOTE`, `packages/mcp/src/mcp-http-tools.ts`) so a shared result-sentence locale picker can adopt it later; this PR adds no picker and does not touch `truncated`. ## Verification Readings for this round at head `ce2f6fefa12`: this branch merged with `origin/main` at `1caee8cbd36` (which includes #35199, `query_records` latestPer). Earlier rounds' readings (base `55020c331b`) are kept below where nothing in this round touched them. <details><summary>This round: main merged, the stdio control re-pinned</summary> - Main moved under the branch: `query_records` now reads a probe row past the page, and on the stdio door a page read with a limit is counted by `engine.count`. The stdio CONTROL pin's engine fixture has no `count`, so main serves that page as `{ object, records, hasMore: false }` with no `total`. The pin at `packages/mcp/src/query-records-withheld-fields.test.ts` now expects exactly that shape; its point is unchanged: no `withheldFields` member, no note, and the readable answer asked as the principal. - The other pins in that file and in `packages/runtime/src/domains/mcp-object-schema-mask.test.ts` were checked for the same drift on the merged tree: none (results below). - Merge conflict in `packages/mcp/src/mcp-http-tools.ts`, the `query_records` description only: both halves kept, the latestPer sentences followed by `WITHHELD_FIELDS_DESCRIPTION`. The handler auto-merged with both behaviours: the latestPer branch and the probed page both feed `withWithheldFields`. </details> <details><summary>Tests (head ce2f6fe)</summary> - `pnpm --filter @objectstack/mcp exec vitest run --maxWorkers=2` (whole package, under the verify lock): `VERDICT command-exit 0`, Test Files 74 passed (74), Tests 1315 passed (1315). - `pnpm --filter @objectstack/runtime exec vitest run --maxWorkers=2 src/domains/mcp` (all 8 `domains/mcp*` suites, `mcp-object-schema-mask.test.ts` among them): `VERDICT command-exit 0`, Test Files 8 passed (8), Tests 289 passed (289). - `pnpm --filter @objectstack/mcp --filter @objectstack/runtime run typecheck`: `VERDICT command-exit 0`; both `check:test-typecheck: OK`. - Before the re-pin (first merge, main `9c29d732a19`): the withheld-fields file read 1 failed / 11 passed, the failing one being the stdio CONTROL (expected `total: 1`, received `hasMore: false`). </details> <details><summary>Gates (head ce2f6fe)</summary> - `node scripts/pm/dispatch-gates.mjs --commands`: 69 families for this diff (merge base `1caee8cbd`), run in sequence; 67 exit 0 on the first pass. `pnpm check:dts-closure` exited 1 on that pass naming `packages/runtime` and `packages/services/service-automation` declarations as missing; both were present minutes later (written 14:50) and the re-run exits 0 (81 built packages, 260/260 declaration files present). `pnpm check:dual-build-cjs-loads` exits 3 (PREREQUISITE NOT MET: it reads every package's built output, only this diff's closure is built): NOT MEASURED locally, run by Lint & Repo Gates on this PR. - `node scripts/pm/dispatch-gates.mjs --ran`: 69 derived, 68 run, 1 NOT-MEASURED, 0 UNRUN. - `node scripts/pm/check-governed-merges.mjs --branch HEAD`: NOT governed, 631 changed lines. - `node scripts/pm/overlap-check.mjs --branch=HEAD`: VERDICT overlap exit 1. origin/main `1caee8cbd3` merges cleanly; #35202 and #35198 merge cleanly; #35193 conflicts in `packages/mcp/src/stdio-data-bridge.ts` and `packages/runtime/src/domains/mcp.ts` (it also conflicts with main on two other paths, judged not this branch's). One of the two lands behind the other. - PR check-runs on `ce2f6fefa12`: 37 success, 16 skipped, 0 failed, among them Test Core (1/10 to 10/10), Lint & Repo Gates, TypeScript Type Check and Build Core all success. </details> <details><summary>Ablation: the served list bypasses describe_object's answer (round 2)</summary> - HTTP: `node scripts/ablation-replace.mjs --file packages/runtime/src/domains/mcp.ts --anchor 'return { served: describedFieldNames(described), readable };' --replacement` (the round-1 derivation of the served list) `-- pnpm --filter @objectstack/runtime exec vitest run --maxWorkers=2 src/domains/mcp-object-schema-mask.test.ts`: mutation landed (anchor 1 to 0, blob b28efe7 to d00af3f275cc); 1 failed / 79 passed, the failing one being the extended pin; restored (blob equals HEAD, `git diff HEAD` empty). - stdio: the same anchor in `packages/mcp/src/stdio-data-bridge.ts`, replaced the same way, `-- pnpm --filter @objectstack/mcp exec vitest run --maxWorkers=2 src/query-records-withheld-fields.test.ts`: mutation landed (blob 949d972 to 978cd2659f10); 1 failed / 11 passed, the failing one being the new stdio pin; restored (blob equals HEAD). - Both tests import the source directly, so no build step stands between the mutation and the run. </details> <details><summary>Ablation: the schema intersection (round 1)</summary> `node scripts/ablation-replace.mjs --file packages/mcp/src/mcp-http-tools.ts --anchor ' if (!served.has(name)) continue;' --delete -- pnpm --filter @objectstack/mcp exec vitest run --maxWorkers=2 src/query-records-withheld-fields.test.ts`: mutation landed; 2 failed / 9 passed, the two failing being the tool-layer and the stdio "never named" pins; restored (blob equals HEAD, `git diff HEAD` empty). </details> <details><summary>aggregate_records: measured, already refused (round 1)</summary> One-off probe on the real security layer (`SecurityPlugin` over `ObjectQL` + `SqlDriver`, the HTTP bridge), not committed: a field denied to the caller asked as a `sum` measure or as a `groupBy` key answers `PERMISSION_DENIED` / 403 for both a member and a schema-exempt author; an unrestricted member is served. So `aggregate_records` gains no member. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8)_ <!-- signed: repo:objectstack#1 · os-warren · session_01JQwxbWDsbbJizuYnDwBxT8 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent b863d2b commit ec227fc

9 files changed

Lines changed: 603 additions & 28 deletions
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/mcp': patch
3+
'@objectstack/runtime': patch
4+
---
5+
6+
feat(mcp, runtime): `query_records` and `get_record` name the fields field-level security withheld from the caller
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: none
10+
11+
A row served over MCP leaves out every field the caller may not read, and nothing in it said so, so an AI client read a withheld field as blank. `query_records` and `get_record` now add two members to their result when a field was withheld, on the HTTP and the stdio server alike:
12+
13+
- `withheldFields`: the names of the withheld fields, field names only, never values. With `fields` in the call, only the asked fields are named; without it, any field of the object.
14+
- `withheldFieldsNote`: one sentence saying these fields exist and are not visible to the caller, and that they must not be described as empty.
15+
16+
A field is named only when the caller's own served schema shows it (the object as `describe_object` serves it to them) and the security service does not answer it readable for them. Both are asked as the caller; nothing is derived from the rows. A field the caller's schema does not show is never named. Under the default object-schema masking, a field a caller may not read is usually left out of their schema too, so `withheldFields` appears for a caller who is served the whole schema (a caller holding `manage_metadata`, `studio.access` or `setup.access`) or where schema masking is switched off.
17+
18+
A caller with nothing withheld, a deployment with no security service, and a server whose bridge does not provide the new optional `McpDataBridge.fieldVisibilityOf` member get the result they got before, byte for byte. The two tool descriptions gain one sentence about the member.
19+
20+
`aggregate_records` is unchanged: a withheld field asked as a measure or a group is already refused `403 PERMISSION_DENIED`.

‎packages/mcp/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ export {
4949
} from './mcp-http-tools.js';
5050
export type {
5151
McpDataBridge,
52+
McpFieldVisibility,
5253
McpObjectSummary,
5354
RegisterObjectToolsOptions,
5455
McpActionBridge,

‎packages/mcp/src/mcp-http-tools.ts‎

Lines changed: 112 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,23 @@ export interface McpObjectSummary {
143143
fieldCount?: number;
144144
}
145145

146+
/**
147+
* [#35137] What {@link McpDataBridge.fieldVisibilityOf} answers for one
148+
* object, both halves asked AS the caller:
149+
*
150+
* - `served` — the field names the caller's own served schema shows: the
151+
* object as `describe_object` serves it to this caller (ADR-0106 D1/D5, the
152+
* `/meta` object door's projection), so a field removed from their schema
153+
* is not in it;
154+
* - `readable` — the fields the security service answers this caller may
155+
* READ on the object (`ISecurityService.getReadableFields`), the exact
156+
* complement of what the read path's field mask deletes from a row.
157+
*/
158+
export interface McpFieldVisibility {
159+
served: readonly string[];
160+
readable: readonly string[];
161+
}
162+
146163
/**
147164
* Data access seam for the HTTP MCP tools. Implemented by the runtime/dispatcher
148165
* so execution flows through the existing permission + RLS path bound to the
@@ -266,6 +283,21 @@ export interface McpDataBridge {
266283
* only where one was established.
267284
*/
268285
diagnoseDelegation?(object: string): Promise<{ narrowed: boolean; statement?: string } | undefined>;
286+
/**
287+
* [#35137] The two framework answers `query_records` and `get_record` name
288+
* the fields field-level security withholds from: both asked AS the caller,
289+
* neither derived from rows ({@link McpFieldVisibility}). The tool layer
290+
* names a field only when the first shows it and the second leaves it out
291+
* (`withheldFieldNames`), so a field the caller's schema does not show is
292+
* never named.
293+
*
294+
* OPTIONAL, with the graceful-degradation contract of
295+
* {@link McpDataBridge.diagnoseDelegation}: a bridge that omits it, answers
296+
* `undefined` (no security service, or no answer from it) or throws gets no
297+
* `withheldFields`, and the tools render exactly what they rendered before.
298+
* ⛔ The probe never fails the read it annotates.
299+
*/
300+
fieldVisibilityOf?(object: string): Promise<McpFieldVisibility | undefined>;
269301
get(object: string, id: string): Promise<unknown>;
270302
create(object: string, data: Record<string, unknown>): Promise<unknown>;
271303
update(object: string, id: string, data: Record<string, unknown>): Promise<unknown>;
@@ -2387,6 +2419,76 @@ function withDelegationNotice(value: unknown, statement: string): unknown {
23872419
return { result: value, ...notice };
23882420
}
23892421

2422+
/**
2423+
* [#35137] The sentence served beside `withheldFields`. It names no field and
2424+
* no value: the list beside it does the naming.
2425+
*/
2426+
const WITHHELD_FIELDS_NOTE =
2427+
'The fields in withheldFields exist on this object, but field-level security does not let you read them, '
2428+
+ 'so they are left out of these records. Say they are not visible to you; never say they are empty or blank.';
2429+
2430+
/**
2431+
* [#35137] The one line `query_records` and `get_record` describe the member with.
2432+
*/
2433+
const WITHHELD_FIELDS_DESCRIPTION =
2434+
'A field that field-level security hides from you is left out of the records and named in withheldFields: '
2435+
+ 'it exists but is not visible to you, which is not the same as empty.';
2436+
2437+
/**
2438+
* [#35137] Which fields `query_records` / `get_record` name as withheld: of
2439+
* the fields the call asked for (or, asking none, every field the caller's
2440+
* served schema shows), those the caller's served schema shows AND the
2441+
* security service does not answer readable. ⛔ A field the served schema does
2442+
* not show is never named, whatever the readable answer says: that is the
2443+
* card's bound, and the `served.has` test below is what holds it.
2444+
*/
2445+
function withheldFieldNames(visibility: McpFieldVisibility, asked: readonly string[] | undefined): string[] {
2446+
const served = new Set(visibility.served);
2447+
const readable = new Set(visibility.readable);
2448+
const candidates = asked !== undefined && asked.length > 0 ? asked : visibility.served;
2449+
const named: string[] = [];
2450+
for (const name of candidates) {
2451+
if (!served.has(name)) continue;
2452+
if (readable.has(name) || named.includes(name)) continue;
2453+
named.push(name);
2454+
}
2455+
return named;
2456+
}
2457+
2458+
/**
2459+
* [#35137] The withheld names for one read, or `[]` when the bridge cannot
2460+
* say. ⛔ Never fails the read it annotates: no member, `undefined` and a
2461+
* throw all answer `[]`, which renders exactly what the tool rendered before.
2462+
*/
2463+
async function withheldFieldsFor(
2464+
bridge: McpDataBridge,
2465+
objectName: string,
2466+
asked: readonly string[] | undefined,
2467+
): Promise<string[]> {
2468+
if (typeof bridge.fieldVisibilityOf !== 'function') return [];
2469+
try {
2470+
const visibility = await bridge.fieldVisibilityOf(objectName);
2471+
return visibility ? withheldFieldNames(visibility, asked) : [];
2472+
} catch {
2473+
return [];
2474+
}
2475+
}
2476+
2477+
/**
2478+
* [#35137] `value` with the withheld names and {@link WITHHELD_FIELDS_NOTE}
2479+
* beside it, or `value` itself when nothing is withheld, so an unrestricted
2480+
* caller's answer is byte-identical to before. A record's own keys cannot
2481+
* collide: field names are snake_case, these members camelCase.
2482+
*/
2483+
function withWithheldFields(value: unknown, withheld: readonly string[]): unknown {
2484+
if (withheld.length === 0) return value;
2485+
const member = { withheldFields: [...withheld], withheldFieldsNote: WITHHELD_FIELDS_NOTE };
2486+
if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
2487+
return { ...(value as Record<string, unknown>), ...member };
2488+
}
2489+
return { result: value, ...member };
2490+
}
2491+
23902492
function jsonText(value: unknown): string {
23912493
try {
23922494
return JSON.stringify(value, null, 2);
@@ -3499,7 +3601,8 @@ export function registerObjectTools(
34993601
// [latest per group] "each X with its latest Y" in one call.
35003602
'For "each X with its latest Y", pass latestPer: one record per group, e.g. each account\'s latest deal: ' +
35013603
'latestPer {"by":["account"],"orderBy":[{"field":"close_date","order":"desc"}]}; ties go by record id. ' +
3502-
'where filters the records first; limit counts groups; truncated: true means more groups exist than came back.',
3604+
'where filters the records first; limit counts groups; truncated: true means more groups exist than came back. ' +
3605+
WITHHELD_FIELDS_DESCRIPTION,
35033606
inputSchema: strictToolInput(
35043607
{
35053608
surface: 'this query_records call',
@@ -3596,8 +3699,11 @@ export function registerObjectTools(
35963699
const diagnosed = typeof bridge.diagnoseDelegation === 'function'
35973700
? await bridge.diagnoseDelegation(objectName).catch(() => undefined)
35983701
: undefined;
3599-
if (!diagnosed?.narrowed || !diagnosed.statement) return textResult(result);
3600-
return textResult(withDelegationNotice(result, diagnosed.statement));
3702+
// [#35137] …and the fields field-level security withheld from these
3703+
// rows named beside them, so a left-out field is not read as blank.
3704+
const answer = withWithheldFields(result, await withheldFieldsFor(bridge, objectName, fields));
3705+
if (!diagnosed?.narrowed || !diagnosed.statement) return textResult(answer);
3706+
return textResult(withDelegationNotice(answer, diagnosed.statement));
36013707
} catch (err) {
36023708
// [#35138] …with what the call named that the caller's schema does not show.
36033709
return recordReadErrorResult(bridge, err, 'query_records', objectName, queryRecordsSentFields({ where, fields, orderBy }));
@@ -3732,7 +3838,7 @@ export function registerObjectTools(
37323838
server.registerTool(
37333839
note('get_record'),
37343840
{
3735-
description: 'Fetch a single record by id.',
3841+
description: `Fetch a single record by id. ${WITHHELD_FIELDS_DESCRIPTION}`,
37363842
inputSchema: strictToolInput(
37373843
{ surface: 'this get_record call', aliases: { ...OBJECT_NAME_ALIASES, ...RECORD_ID_ALIASES } },
37383844
{
@@ -3755,7 +3861,8 @@ export function registerObjectTools(
37553861
// `RECORD_NOT_FOUND` / 404. A missing id and an id the caller may not
37563862
// read reach here as the same empty read, so they answer alike.
37573863
if (record == null) throw recordNotFoundError(objectName, recordId);
3758-
return textResult(record);
3864+
// [#35137] …with the fields field-level security withheld from it named.
3865+
return textResult(withWithheldFields(record, await withheldFieldsFor(bridge, objectName, undefined)));
37593866
} catch (err) {
37603867
// [#35138] …and an object the caller's schema does not show is said to be not recorded.
37613868
return recordReadErrorResult(bridge, err, 'get_record', objectName, []);

‎packages/mcp/src/mcp-write-response-internal-fields.tripwire.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,9 @@ const RECIPES: Record<string, Recipe> = {
161161
// [#32872] The object definition `describeObject` reads, handed to the
162162
// publish gate's passes and rendered to nobody: no engine read, no record.
163163
servedObjectDefinitionOf: { invoke: (b) => b.servedObjectDefinitionOf('vault'), writesRecords: false },
164+
// [#35137] Field NAMES off the served object definition and the security
165+
// service's readable answer: no engine read, no record.
166+
fieldVisibilityOf: { invoke: (b) => b.fieldVisibilityOf('vault'), writesRecords: false },
164167
query: { invoke: (b) => b.query('vault', {}), writesRecords: false },
165168
get: { invoke: (b) => b.get('vault', 'row-1'), writesRecords: false },
166169
aggregate: { invoke: (b) => b.aggregate('vault', {}), writesRecords: false },

0 commit comments

Comments
 (0)