Skip to content
Merged
20 changes: 20 additions & 0 deletions .changeset/35137-mcp-withheld-fields.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
'@objectstack/mcp': patch
'@objectstack/runtime': patch
---

feat(mcp, runtime): `query_records` and `get_record` name the fields field-level security withheld from the caller

Clause-②: yes (widening)
Metadata-protocol: none

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:

- `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.
- `withheldFieldsNote`: one sentence saying these fields exist and are not visible to the caller, and that they must not be described as empty.

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.

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.

`aggregate_records` is unchanged: a withheld field asked as a measure or a group is already refused `403 PERMISSION_DENIED`.
1 change: 1 addition & 0 deletions packages/mcp/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export {
} from './mcp-http-tools.js';
export type {
McpDataBridge,
McpFieldVisibility,
McpObjectSummary,
RegisterObjectToolsOptions,
McpActionBridge,
Expand Down
117 changes: 112 additions & 5 deletions packages/mcp/src/mcp-http-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,23 @@ export interface McpObjectSummary {
fieldCount?: number;
}

/**
* [#35137] What {@link McpDataBridge.fieldVisibilityOf} answers for one
* object, both halves asked AS the caller:
*
* - `served` — the field names the caller's own served schema shows: the
* object as `describe_object` serves it to this caller (ADR-0106 D1/D5, the
* `/meta` object door's projection), so a field removed from their schema
* is not in it;
* - `readable` — the fields the security service answers this caller may
* READ on the object (`ISecurityService.getReadableFields`), the exact
* complement of what the read path's field mask deletes from a row.
*/
export interface McpFieldVisibility {
served: readonly string[];
readable: readonly string[];
}

/**
* Data access seam for the HTTP MCP tools. Implemented by the runtime/dispatcher
* so execution flows through the existing permission + RLS path bound to the
Expand Down Expand Up @@ -262,6 +279,21 @@ export interface McpDataBridge {
* only where one was established.
*/
diagnoseDelegation?(object: string): Promise<{ narrowed: boolean; statement?: string } | undefined>;
/**
* [#35137] The two framework answers `query_records` and `get_record` name
* the fields field-level security withholds from: both asked AS the caller,
* neither derived from rows ({@link McpFieldVisibility}). The tool layer
* names a field only when the first shows it and the second leaves it out
* (`withheldFieldNames`), so a field the caller's schema does not show is
* never named.
*
* OPTIONAL, with the graceful-degradation contract of
* {@link McpDataBridge.diagnoseDelegation}: a bridge that omits it, answers
* `undefined` (no security service, or no answer from it) or throws gets no
* `withheldFields`, and the tools render exactly what they rendered before.
* ⛔ The probe never fails the read it annotates.
*/
fieldVisibilityOf?(object: string): Promise<McpFieldVisibility | undefined>;
get(object: string, id: string): Promise<unknown>;
create(object: string, data: Record<string, unknown>): Promise<unknown>;
update(object: string, id: string, data: Record<string, unknown>): Promise<unknown>;
Expand Down Expand Up @@ -2051,6 +2083,76 @@ function withDelegationNotice(value: unknown, statement: string): unknown {
return { result: value, ...notice };
}

/**
* [#35137] The sentence served beside `withheldFields`. It names no field and
* no value: the list beside it does the naming.
*/
const WITHHELD_FIELDS_NOTE =
'The fields in withheldFields exist on this object, but field-level security does not let you read them, '
+ 'so they are left out of these records. Say they are not visible to you; never say they are empty or blank.';

/**
* [#35137] The one line `query_records` and `get_record` describe the member with.
*/
const WITHHELD_FIELDS_DESCRIPTION =
'A field that field-level security hides from you is left out of the records and named in withheldFields: '
+ 'it exists but is not visible to you, which is not the same as empty.';

/**
* [#35137] Which fields `query_records` / `get_record` name as withheld: of
* the fields the call asked for (or, asking none, every field the caller's
* served schema shows), those the caller's served schema shows AND the
* security service does not answer readable. ⛔ A field the served schema does
* not show is never named, whatever the readable answer says: that is the
* card's bound, and the `served.has` test below is what holds it.
*/
function withheldFieldNames(visibility: McpFieldVisibility, asked: readonly string[] | undefined): string[] {
const served = new Set(visibility.served);
const readable = new Set(visibility.readable);
const candidates = asked !== undefined && asked.length > 0 ? asked : visibility.served;
const named: string[] = [];
for (const name of candidates) {
if (!served.has(name)) continue;
if (readable.has(name) || named.includes(name)) continue;
named.push(name);
}
return named;
}

/**
* [#35137] The withheld names for one read, or `[]` when the bridge cannot
* say. ⛔ Never fails the read it annotates: no member, `undefined` and a
* throw all answer `[]`, which renders exactly what the tool rendered before.
*/
async function withheldFieldsFor(
bridge: McpDataBridge,
objectName: string,
asked: readonly string[] | undefined,
): Promise<string[]> {
if (typeof bridge.fieldVisibilityOf !== 'function') return [];
try {
const visibility = await bridge.fieldVisibilityOf(objectName);
return visibility ? withheldFieldNames(visibility, asked) : [];
} catch {
return [];
}
}

/**
* [#35137] `value` with the withheld names and {@link WITHHELD_FIELDS_NOTE}
* beside it, or `value` itself when nothing is withheld, so an unrestricted
* caller's answer is byte-identical to before. A record's own keys cannot
* collide: field names are snake_case, these members camelCase.
*/
function withWithheldFields(value: unknown, withheld: readonly string[]): unknown {
if (withheld.length === 0) return value;
const member = { withheldFields: [...withheld], withheldFieldsNote: WITHHELD_FIELDS_NOTE };
if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
return { ...(value as Record<string, unknown>), ...member };
}
return { result: value, ...member };
}

function jsonText(value: unknown): string {
try {
return JSON.stringify(value, null, 2);
Expand Down Expand Up @@ -3163,7 +3265,8 @@ export function registerObjectTools(
// [latest per group] "each X with its latest Y" in one call.
'For "each X with its latest Y", pass latestPer: one record per group, e.g. each account\'s latest deal: ' +
'latestPer {"by":["account"],"orderBy":[{"field":"close_date","order":"desc"}]}; ties go by record id. ' +
'where filters the records first; limit counts groups; truncated: true means more groups exist than came back.',
'where filters the records first; limit counts groups; truncated: true means more groups exist than came back. ' +
WITHHELD_FIELDS_DESCRIPTION,
inputSchema: strictToolInput(
{
surface: 'this query_records call',
Expand Down Expand Up @@ -3260,8 +3363,11 @@ export function registerObjectTools(
const diagnosed = typeof bridge.diagnoseDelegation === 'function'
? await bridge.diagnoseDelegation(objectName).catch(() => undefined)
: undefined;
if (!diagnosed?.narrowed || !diagnosed.statement) return textResult(result);
return textResult(withDelegationNotice(result, diagnosed.statement));
// [#35137] …and the fields field-level security withheld from these
// rows named beside them, so a left-out field is not read as blank.
const answer = withWithheldFields(result, await withheldFieldsFor(bridge, objectName, fields));
if (!diagnosed?.narrowed || !diagnosed.statement) return textResult(answer);
return textResult(withDelegationNotice(answer, diagnosed.statement));
} catch (err) {
return dataDoorErrorResult(err, 'query_records', objectName);
}
Expand Down Expand Up @@ -3382,7 +3488,7 @@ export function registerObjectTools(
server.registerTool(
note('get_record'),
{
description: 'Fetch a single record by id.',
description: `Fetch a single record by id. ${WITHHELD_FIELDS_DESCRIPTION}`,
inputSchema: strictToolInput(
{ surface: 'this get_record call', aliases: { ...OBJECT_NAME_ALIASES, ...RECORD_ID_ALIASES } },
{
Expand All @@ -3405,7 +3511,8 @@ 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);
// [#35137] …with the fields field-level security withheld from it named.
return textResult(withWithheldFields(record, await withheldFieldsFor(bridge, objectName, undefined)));
} catch (err) {
return dataDoorErrorResult(err, 'get_record', objectName);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,9 @@ const RECIPES: Record<string, Recipe> = {
// [#32872] The object definition `describeObject` reads, handed to the
// publish gate's passes and rendered to nobody: no engine read, no record.
servedObjectDefinitionOf: { invoke: (b) => b.servedObjectDefinitionOf('vault'), writesRecords: false },
// [#35137] Field NAMES off the served object definition and the security
// service's readable answer: no engine read, no record.
fieldVisibilityOf: { invoke: (b) => b.fieldVisibilityOf('vault'), writesRecords: false },
query: { invoke: (b) => b.query('vault', {}), writesRecords: false },
get: { invoke: (b) => b.get('vault', 'row-1'), writesRecords: false },
aggregate: { invoke: (b) => b.aggregate('vault', {}), writesRecords: false },
Expand Down
Loading
Loading