diff --git a/.changeset/35137-mcp-withheld-fields.md b/.changeset/35137-mcp-withheld-fields.md new file mode 100644 index 00000000000..eff54a9fbf8 --- /dev/null +++ b/.changeset/35137-mcp-withheld-fields.md @@ -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`. diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index aa00f6fcdce..f281afd9c62 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -49,6 +49,7 @@ export { } from './mcp-http-tools.js'; export type { McpDataBridge, + McpFieldVisibility, McpObjectSummary, RegisterObjectToolsOptions, McpActionBridge, diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 6a68cf338da..855da417fa0 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -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 @@ -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; get(object: string, id: string): Promise; create(object: string, data: Record): Promise; update(object: string, id: string, data: Record): Promise; @@ -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 { + 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), ...member }; + } + return { result: value, ...member }; +} + function jsonText(value: unknown): string { try { return JSON.stringify(value, null, 2); @@ -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', @@ -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); } @@ -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 } }, { @@ -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); } diff --git a/packages/mcp/src/mcp-write-response-internal-fields.tripwire.test.ts b/packages/mcp/src/mcp-write-response-internal-fields.tripwire.test.ts index 602244ee9e8..740548e15e1 100644 --- a/packages/mcp/src/mcp-write-response-internal-fields.tripwire.test.ts +++ b/packages/mcp/src/mcp-write-response-internal-fields.tripwire.test.ts @@ -161,6 +161,9 @@ const RECIPES: Record = { // [#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 }, diff --git a/packages/mcp/src/query-records-withheld-fields.test.ts b/packages/mcp/src/query-records-withheld-fields.test.ts new file mode 100644 index 00000000000..ee6d25ae785 --- /dev/null +++ b/packages/mcp/src/query-records-withheld-fields.test.ts @@ -0,0 +1,294 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35137] `query_records` and `get_record` name the fields field-level + * security withheld from the caller (`withheldFields`, with a note), so a + * left-out field is said to be not visible, never read as blank. + * + * The rule: a field is named only when the caller's own served schema shows + * it AND the security service does not answer it readable — both the + * framework's answers, asked as the caller (`McpDataBridge.fieldVisibilityOf`), + * never derived from rows. A field the served schema does not show is never + * named, anywhere in the result. + * + * Two halves: + * 1. the tool layer every door shares, over the HTTP runtime with a bridge + * whose two answers the case sets; + * 2. the stdio bridge itself (`createStdioDataBridge`): its served schema is + * the object-schema mask's (ADR-0106), so the same security answers name + * a field for a caller whose schema shows it (a D4-exempt caller, or the + * D8 switch off) and for no caller whose schema hides it. + * The HTTP bridge's two answers are pinned on the real security layer in + * `packages/runtime/src/domains/mcp-object-schema-mask.test.ts`. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; +import { OBJECT_SCHEMA_MASK_DISABLE_ENV } from '@objectstack/metadata-core'; +import { SEARCH_COMPANION_FIELD } from '@objectstack/spec/data'; +import { MCPServerRuntime } from './mcp-server-runtime.js'; +import { registerObjectTools, type McpDataBridge, type McpFieldVisibility } from './mcp-http-tools.js'; +import { createStdioDataBridge } from './stdio-data-bridge.js'; + +const OBJECT = 'crm_rate_card'; +const HIDDEN = 'secret_margin'; + +/** Does `name` occur in `text` as an identifier token? */ +const mentions = (text: string, name: string) => (text.match(/[A-Za-z_][A-Za-z0-9_]*/g) ?? ([] as string[])).includes(name); + +// ── 1. The tool layer ────────────────────────────────────────────────────── + +const ROW = { id: 'r1', name: 'Ada', notes: null }; + +function makeBridge(visibility?: McpDataBridge['fieldVisibilityOf']): McpDataBridge { + const bridge: any = { + async listObjects() { return [{ name: OBJECT, label: 'Rate card' }]; }, + async describeObject(name: string) { return { name }; }, + async query(object: string) { return { object, records: [{ ...ROW }], total: 1 }; }, + async get() { return { ...ROW }; }, + async create(object: string, data: any) { return { object, data }; }, + async update(object: string, id: string) { return { object, id }; }, + async remove(object: string, id: string) { return { object, id, success: true }; }, + }; + if (visibility) bridge.fieldVisibilityOf = visibility; + return bridge; +} + +const answering = (v: McpFieldVisibility) => async () => v; + +async function callTool(bridge: McpDataBridge, name: string, args: Record) { + 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(); + expect(json.result?.isError, JSON.stringify(json)).toBeFalsy(); + const text: string = json.result.content[0].text; + return { text, payload: JSON.parse(text) }; +} + +const queryRecords = (bridge: McpDataBridge, args: Record = {}) => + callTool(bridge, 'query_records', { objectName: OBJECT, ...args }); +const getRecord = (bridge: McpDataBridge) => callTool(bridge, 'get_record', { objectName: OBJECT, recordId: 'r1' }); + +describe('query_records / get_record — withheldFields, the tool layer', () => { + /** The caller's schema shows `cost_rate`; the security service does not answer it readable. */ + const WITHHELD = { served: ['id', 'name', 'notes', 'cost_rate'], readable: ['id', 'name', 'notes'] }; + + it('a field the served schema shows and the readable answer leaves out is named, with the note', async () => { + for (const { payload } of [await queryRecords(makeBridge(answering(WITHHELD))), await getRecord(makeBridge(answering(WITHHELD)))]) { + expect(payload.withheldFields).toEqual(['cost_rate']); + expect(typeof payload.withheldFieldsNote).toBe('string'); + expect(payload.withheldFieldsNote).toMatch(/not visible to you/); + expect(payload.withheldFieldsNote).toMatch(/never say they are empty/); + // Names only: the note names no field, and no value is added anywhere. + expect(mentions(payload.withheldFieldsNote, 'cost_rate')).toBe(false); + } + const { payload } = await queryRecords(makeBridge(answering(WITHHELD))); + expect(payload.records).toEqual([ROW]); + expect(payload.total).toBe(1); + }); + + it('a field the served schema does not show is never named, anywhere in the result, even when asked for', async () => { + // The readable answer leaves it out too; the served schema not showing it is what decides. + const bridge = makeBridge(answering({ served: ['id', 'name', 'notes'], readable: ['id', 'name', 'notes'] })); + const asked = await queryRecords(bridge, { fields: ['name', HIDDEN] }); + expect(mentions(asked.text, HIDDEN)).toBe(false); + expect(asked.payload.withheldFields).toBeUndefined(); + const whole = await getRecord(bridge); + expect(mentions(whole.text, HIDDEN)).toBe(false); + }); + + it('a readable field with an empty value is not named', async () => { + const { payload } = await queryRecords(makeBridge(answering(WITHHELD))); + expect(payload.records[0].notes).toBeNull(); + expect(payload.withheldFields).not.toContain('notes'); + }); + + it('only the fields the call asked for are named when it asks for some', async () => { + const none = await queryRecords(makeBridge(answering(WITHHELD)), { fields: ['name', 'notes'] }); + expect(none.payload.withheldFields).toBeUndefined(); + expect(none.payload.withheldFieldsNote).toBeUndefined(); + const one = await queryRecords(makeBridge(answering(WITHHELD)), { fields: ['name', 'cost_rate', 'cost_rate'] }); + expect(one.payload.withheldFields).toEqual(['cost_rate']); + }); + + it('a caller with nothing withheld gets no member and no note — the answer is byte-identical to before', async () => { + const unrestricted = makeBridge(answering({ served: ['id', 'name', 'notes'], readable: ['id', 'name', 'notes', 'created_at'] })); + const before = makeBridge(undefined); + expect((await queryRecords(unrestricted)).text).toBe((await queryRecords(before)).text); + expect((await getRecord(unrestricted)).text).toBe((await getRecord(before)).text); + expect((await queryRecords(unrestricted)).payload).toEqual({ object: OBJECT, records: [ROW], total: 1 }); + }); + + it('a bridge that cannot answer, or whose answer throws, names nothing and never fails the read', async () => { + for (const visibility of [async () => undefined, async () => { throw new Error('security service unhealthy (test)'); }]) { + const { payload } = await queryRecords(makeBridge(visibility)); + expect(payload).toEqual({ object: OBJECT, records: [ROW], total: 1 }); + expect((await getRecord(makeBridge(visibility))).payload).toEqual(ROW); + } + }); + + it('beside a delegation narrowing, both are stated', async () => { + const bridge: any = makeBridge(answering(WITHHELD)); + bridge.diagnoseDelegation = async () => ({ narrowed: true, statement: 'Narrowed by the agent ceiling.' }); + const { payload } = await queryRecords(bridge); + expect(payload.withheldFields).toEqual(['cost_rate']); + expect(payload.delegationNarrowed).toBe(true); + }); +}); + +// ── 2. The stdio bridge ──────────────────────────────────────────────────── + +const DECLARED = () => ({ + name: OBJECT, + label: 'Rate card', + fields: { + id: { name: 'id', type: 'text', label: 'Id' }, + name: { name: 'name', type: 'text', label: 'Name' }, + notes: { name: 'notes', type: 'text', label: 'Notes' }, + [HIDDEN]: { name: HIDDEN, type: 'currency', label: 'Secret margin' }, + }, +}); +/** What the data plane serves a caller denied {@link HIDDEN}: the key deleted. */ +const SERVED_ROW = { id: 'r1', name: 'Ada', notes: null }; +const READABLE = ['id', 'name', 'notes']; + +/** A security service that denies {@link HIDDEN} on both planes, as field-level security does. */ +const denyingSecurity = () => ({ + getReadableFields: vi.fn(async () => [...READABLE]), + getMetadataReadableFields: vi.fn(async () => [...READABLE]), + canReadObject: async () => true, +}); + +async function stdioSession( + context: Record, + security?: Record, + declared: () => ReturnType = DECLARED, +) { + const engine = { + find: vi.fn(async () => [{ ...SERVED_ROW }]), + } as unknown as IDataEngine; + const bridge = createStdioDataBridge({ + engine, + metadataService: { + listObjects: async () => [declared()], + getObject: async (name: string) => (name === OBJECT ? declared() : undefined), + } as unknown as IMetadataService, + resolvePrincipal: async () => ({ ...context }) as unknown as ExecutionContext, + ...(security ? { security: () => security } : {}), + }); + const server = new McpServer({ name: 'pin', version: '0' }); + registerObjectTools(server, bridge); + const [clientSide, serverSide] = InMemoryTransport.createLinkedPair(); + await server.connect(serverSide); + const client = new Client({ name: 'pin', version: '0' }); + await client.connect(clientSide); + const call = async (name: string, args: Record) => { + const res = (await client.callTool({ name, arguments: args })) as { isError?: boolean; content: Array<{ text: string }> }; + const text = res.content[0]!.text; + expect(res.isError, text).toBeFalsy(); + return { text, payload: JSON.parse(text) }; + }; + return { + query: (args: Record = {}) => call('query_records', { objectName: OBJECT, ...args }), + get: () => call('get_record', { objectName: OBJECT, recordId: 'r1' }), + describe: () => call('describe_object', { objectName: OBJECT }), + close: () => client.close(), + }; +} + +const MEMBER = { userId: 'u_member', systemPermissions: [] }; +/** ADR-0106 D4: may write the schema, so is served all of it, while field-level security still withholds data. */ +const AUTHOR = { userId: 'u_author', systemPermissions: ['manage_metadata'] }; + +describe('stdio bridge — withheldFields from the served schema and the readable answer', () => { + let previousSwitch: string | undefined; + beforeEach(() => { + previousSwitch = process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV]; + delete process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV]; + }); + afterEach(() => { + if (previousSwitch === undefined) delete process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV]; + else process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV] = previousSwitch; + }); + + it('a caller whose served schema shows the field is told it is withheld, on query_records and get_record', async () => { + const session = await stdioSession(AUTHOR, denyingSecurity()); + try { + expect(mentions((await session.describe()).text, HIDDEN), 'precondition: the schema shows it').toBe(true); + for (const { payload } of [await session.query(), await session.get()]) { + expect(payload.withheldFields).toEqual([HIDDEN]); + expect(payload.withheldFieldsNote).toMatch(/not visible to you/); + } + expect((await session.query()).payload.records).toEqual([SERVED_ROW]); + } finally { + await session.close(); + } + }); + + it('a caller whose served schema hides the field never sees it named, even asking for it', async () => { + const session = await stdioSession(MEMBER, denyingSecurity()); + try { + expect(mentions((await session.describe()).text, HIDDEN), 'precondition: the schema hides it').toBe(false); + for (const { text, payload } of [await session.query({ fields: ['name', HIDDEN] }), await session.query(), await session.get()]) { + expect(mentions(text, HIDDEN)).toBe(false); + expect(payload.withheldFields).toBeUndefined(); + expect(payload.withheldFieldsNote).toBeUndefined(); + } + } finally { + await session.close(); + } + }); + + it('with the D8 switch off the schema shows the field to the member, so it is named', async () => { + process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV] = '1'; + const session = await stdioSession(MEMBER, denyingSecurity()); + try { + expect((await session.query()).payload.withheldFields).toEqual([HIDDEN]); + } finally { + await session.close(); + } + }); + + it('the served list is describe_object\'s field list, on an object served with a column describe_object does not list', async () => { + const withCompanion = () => { + const def = DECLARED(); + return { ...def, fields: { ...def.fields, [SEARCH_COMPANION_FIELD]: { name: SEARCH_COMPANION_FIELD, type: 'text', label: 'Search' } } }; + }; + const session = await stdioSession(AUTHOR, denyingSecurity(), withCompanion as unknown as typeof DECLARED); + try { + const described = (await session.describe()).payload.fields.map((f: { name: string }) => f.name); + expect(described, 'precondition: describe_object does not list the column').not.toContain(SEARCH_COMPANION_FIELD); + for (const { payload } of [await session.query(), await session.get()]) { + expect(payload.withheldFields).toEqual([HIDDEN]); + } + } finally { + await session.close(); + } + }); + + it('CONTROL — nothing withheld, or no security service: no member, and the readable answer is asked as the principal', async () => { + const security = { ...denyingSecurity(), getReadableFields: vi.fn(async () => [...READABLE, HIDDEN]) }; + const unrestricted = await stdioSession(AUTHOR, security); + const unsecured = await stdioSession(AUTHOR, undefined); + try { + const a = await unrestricted.query(); + expect(a.payload).toEqual({ object: OBJECT, records: [SERVED_ROW], hasMore: false }); + expect(security.getReadableFields).toHaveBeenCalledWith(OBJECT, expect.objectContaining({ userId: AUTHOR.userId })); + expect((await unsecured.query()).text).toBe(a.text); + expect((await unsecured.get()).payload).toEqual(SERVED_ROW); + } finally { + await unrestricted.close(); + await unsecured.close(); + } + }); +}); diff --git a/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts b/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts index b66daa3c159..f26373d804f 100644 --- a/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts +++ b/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts @@ -469,6 +469,7 @@ const BRIDGE_MEMBERS: Record = { aiReadExposed: 'no row body — a boolean read off one object definition (isAiReadExposed)', optionFieldsOf: 'no row body — field names from the same object definition describeObject reads', servedObjectDefinitionOf: 'no row body — the same object definition describeObject reads, judged by the gate and rendered to nobody', + fieldVisibilityOf: 'no row body — field names from the object definition describeObject reads, and the security service\'s readable answer', query: 'seam — serveStoredMetadataRows; filter / sort on the body column refused', get: 'seam — serveStoredMetadataRow', aggregate: 'refuses — group / filter / aggregate member on the body column', diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index 6715d710635..471e30055aa 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -146,7 +146,7 @@ import { apiKeyManagementCredentialRefusal } from '@objectstack/core'; // [#28715] The engine's own reading of "this field declares options" (its // `label()` map is built from it), never a second spelling here. import { declaresOptions } from '@objectstack/formula'; -import type { McpDataBridge, McpObjectSummary } from './mcp-http-tools.js'; +import type { McpDataBridge, McpFieldVisibility, McpObjectSummary } from './mcp-http-tools.js'; import type { ListDatasetsOutput, QueryDatasetOutput } from '@objectstack/spec/ai'; import { authoredDescription, @@ -1239,6 +1239,18 @@ function enforceApiKeyManagementCredential(object: string, action: string): void if (refusal) throw refusal; } +/** + * [#35137] The field names a {@link describeServedObject} answer lists, in its + * order: the served-schema half of `fieldVisibilityOf`. The HTTP twin is + * `describedFieldNames` in `packages/runtime/src/domains/mcp.ts`. + */ +function describedFieldNames(described: Record): string[] { + const fields = described.fields; + return Array.isArray(fields) + ? fields.map((f) => String((f as { name?: unknown } | null)?.name ?? '')).filter(Boolean) + : []; +} + /** * Build the stdio transport's principal-bound data bridge. * @@ -1264,6 +1276,27 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge // `objectstack://objects` resources read, so the two answer alike. const localizedView = servedLocaleObjectView(servedView, { i18n: deps.i18n, protocol }); + /** + * `describe_object`'s answer for the principal: the object as they are + * served it ({@link callerObjectView}), [#34872] in the locale this + * transport speaks ({@link servedLocaleObjectView}), [#32435] each field and + * rule carrying what a write needs ({@link describeServedObject}), with + * `readonly` judged on the declaration that view masked + * ({@link readObjectWithDeclaration}; `declared` is read for that verdict + * alone). `null` for an object not served. [#35137] Also the served-schema + * half of `fieldVisibilityOf`, so the fields `withheldFields` may name are + * exactly the ones this answer lists. + */ + const describeForPrincipal = async (name: string): Promise | null> => { + const { served: def, declared } = await readObjectWithDeclaration(localizedView, name); + if (!def) return null; + // The field list is an ARRAY here, not the stored map: `validate_expression` + // reads `Array.isArray(def.fields)` off this very value, and the HTTP + // bridge projects the same shape. A map would type-check and silently + // leave that tool with zero fields in scope. + return describeServedObject(def as ServedObjectDef, declared as ServedObjectDef); + }; + const bridge: McpDataBridge = { async listObjects(): Promise { // [#25138] The protocol's merged listing ({@link readMergedObjects}), @@ -1313,16 +1346,7 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge // twin judges it ({@link readObjectWithDeclaration}): only that boolean // is read off the declaration. async describeObject(name: string): Promise { - // [#34872] …in the locale this transport speaks ({@link servedLocaleObjectView}); - // `declared` is read for the `readonly` verdict alone. - const { served: def, declared } = await readObjectWithDeclaration(localizedView, name); - if (!def) return null; - // The field list is an ARRAY here, not the stored map: `validate_expression` - // reads `Array.isArray(def.fields)` off this very value, and the HTTP - // bridge projects the same shape. A map would type-check and silently - // leave that tool with zero fields in scope. - // [#32435] …each field and rule carrying what a write needs. - return describeServedObject(def as ServedObjectDef, declared as ServedObjectDef); + return describeForPrincipal(name); }, // [#28715] From the object `describeObject` reads: the protocol's served @@ -1435,6 +1459,26 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge return { object, records, total: counted, hasMore: offset + records.length < counted }; }, + /** + * [#35137] The two answers `query_records` and `get_record` name withheld + * fields from ({@link McpFieldVisibility}), both asked as the principal: + * the field names `describe_object` lists for them, read off the very + * answer it serves ({@link describeForPrincipal}, so whatever it leaves + * out is left out here too), and the security service's readable answer. + * No security service, an object not served, or no readable answer: + * `undefined`, and nothing is named. + */ + async fieldVisibilityOf(object: string): Promise { + const surface = security?.(); + if (typeof surface?.getReadableFields !== 'function') return undefined; + const context = await resolvePrincipal(); + const described = await describeForPrincipal(object); + if (!described) return undefined; + const readable = await surface.getReadableFields(object, context); + if (!Array.isArray(readable)) return undefined; + return { served: describedFieldNames(described), readable }; + }, + async get(object, id) { const context = await resolvePrincipal(); await enforceApiExposure(reads, object, GATED_ACTIONS.get, context); diff --git a/packages/runtime/src/domains/mcp-object-schema-mask.test.ts b/packages/runtime/src/domains/mcp-object-schema-mask.test.ts index bda9900433a..c7a6fc8e8f1 100644 --- a/packages/runtime/src/domains/mcp-object-schema-mask.test.ts +++ b/packages/runtime/src/domains/mcp-object-schema-mask.test.ts @@ -330,6 +330,51 @@ describe('[ADR-0106] HTTP MCP bridge and the /metadata object door agree — the expect(JSON.stringify(await staff.bridge.listObjects())).toBe(JSON.stringify(readable)); }); + /** + * [#35137] `fieldVisibilityOf`, the two answers `query_records` and + * `get_record` name withheld fields from: the served schema (the same + * projection `describe_object` serves) and the security service's readable + * answer, both asked as this request's caller. The tool layer names a field + * the first shows and the second leaves out + * (`packages/mcp/src/query-records-withheld-fields.test.ts`). + */ + const withheldBy = (v: { served: readonly string[]; readable: readonly string[] }) => + v.served.filter((name) => !v.readable.includes(name)); + + it('withheld fields: an exempt author whose schema shows the denied field has it withheld from reads', async () => { + const { bridge, describe: described } = await readBoth(PERSONAS.author); + const visibility = await bridge.fieldVisibilityOf(OBJ); + expect(visibility.served).toEqual(described.fields.map((f: any) => f.name)); + expect(visibility.served).toContain(DENIED); + expect(visibility.readable).not.toContain(DENIED); + expect(withheldBy(visibility)).toEqual([DENIED]); + }); + + it('withheld fields: a member whose schema hides the denied field is never answered it', async () => { + const { bridge } = await readBoth(PERSONAS.member); + const visibility = await bridge.fieldVisibilityOf(OBJ); + expect(visibility.served).not.toContain(DENIED); + expect(withheldBy(visibility)).toEqual([]); + }); + + it('withheld fields: with object-schema masking off the member\'s schema shows the denied field, so it is withheld from reads', async () => { + process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV] = '1'; + const { bridge, describe: described } = await readBoth(PERSONAS.member); + const visibility = await bridge.fieldVisibilityOf(OBJ); + expect(visibility.served).toEqual(described.fields.map((f: any) => f.name)); + expect(visibility.served).toContain(DENIED); + expect(withheldBy(visibility)).toEqual([DENIED]); + }); + + it('withheld fields: CONTROL — an unrestricted member is withheld nothing, and no security service answers nothing', async () => { + const { bridge } = await readBoth(PERSONAS.staff); + const visibility = await bridge.fieldVisibilityOf(OBJ); + expect(visibility.served).toContain(DENIED); + expect(withheldBy(visibility)).toEqual([]); + const unsecured = await bridgeFor(kernelOver({ ...services, security: undefined }), PERSONAS.staff); + expect(await unsecured.bridge.fieldVisibilityOf(OBJ)).toBeUndefined(); + }); + it('a member denied every field is refused on both doors, never served an object with no fields', async () => { const { bridge, describe: refused, meta } = await readBoth(PERSONAS.walled); expect(meta.status).toBe(503); @@ -1794,4 +1839,26 @@ describe('describe_object never lists the hidden search companion — the real e const { bridge } = await bridgeFor(kernelOver(services), CALLER); expect(JSON.stringify(await bridge.describeObject(OBJ))).not.toContain(SEARCH_COMPANION_FIELD); }); + + // [#35137] The served-schema half of `fieldVisibilityOf` is the field list + // `describe_object` serves this caller, read off that very answer: on an + // object whose served definition carries a column `describe_object` does + // not list, the two still agree, and only the field the readable answer + // leaves out of that list is withheld. Under masking off (ADR-0106 D8), + // where the caller's schema is the whole declaration. + it('withheld fields: the served list is describe_object\'s field list, on an object served with a column it does not list', async () => { + process.env[OBJECT_SCHEMA_MASK_DISABLE_ENV] = '1'; + const describedFields = await describedNames(); + const security = { + canReadObject: async () => true, + getReadableFields: vi.fn(async () => describedFields.filter((name) => name !== 'email')), + }; + const { bridge } = await bridgeFor(kernelOver({ ...services, security }), CALLER); + const definition = Object.keys((await bridge.servedObjectDefinitionOf(OBJ)).fields); + expect(definition, 'precondition: the served definition carries a column describe_object does not list').toContain(SEARCH_COMPANION_FIELD); + const visibility = await bridge.fieldVisibilityOf(OBJ); + expect(visibility.served).toEqual(((await bridge.describeObject(OBJ)) as any).fields.map((f: any) => f.name)); + expect(visibility.served.filter((name: string) => !visibility.readable.includes(name))).toEqual(['email']); + expect(security.getReadableFields).toHaveBeenCalledWith(OBJ, expect.objectContaining({ userId: CALLER.userId })); + }); }); diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index c85895e7864..01fcb3f7a56 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -733,6 +733,16 @@ function describeServedObject(def: any, declared: any): Record }; } +/** + * [#35137] The field names a {@link describeServedObject} answer lists, in its + * order: the served-schema half of `fieldVisibilityOf`. The stdio twin is + * `describedFieldNames` in `packages/mcp/src/stdio-data-bridge.ts`. + */ +function describedFieldNames(described: Record): string[] { + const fields = described.fields; + return Array.isArray(fields) ? fields.map((f: any) => String(f?.name ?? '')).filter(Boolean) : []; +} + /** * [#34721] An object's or a field's `description` as `list_objects` and * `describe_object` serve it: `{ description }` when the definition, as the @@ -1081,6 +1091,24 @@ export function buildMcpBridge( return out; }; + /** + * `describe_object`'s answer for THIS caller: the object as they are + * served it ({@link readObjectForCaller}'s two steps, kept apart so the + * declaration it masks is in hand, [#32530] `readonly`), [#34872] in + * their locale, [#32435] each field and rule carrying what a write needs + * ({@link describeServedObject}). `null` for an object not served. + * [#35137] Also the served-schema half of `fieldVisibilityOf`, so the + * fields `withheldFields` may name are exactly the ones this answer lists. + */ + const describeForCaller = async (name: string): Promise | null> => { + const declared: any = await readServedObject(name); + const def: any = declared ? await servedToCaller(declared) : declared; + if (!def) return null; + // `declared` is read for the `readonly` verdict alone, which no translation touches. + const [localized] = await inCallerLocale([def]); + return describeServedObject(localized, declared); + }; + return { listObjects: listObjectSummaries, /** @@ -1148,18 +1176,7 @@ export function buildMcpBridge( : await ((await getMeta()) as any)?.getObject?.(name); return isAiReadExposed(def); }, - describeObject: async (name: string) => { - // {@link readObjectForCaller}'s two steps, kept apart so the - // declaration it masks is in hand ([#32530] `readonly`). - const declared: any = await readServedObject(name); - const def: any = declared ? await servedToCaller(declared) : declared; - if (!def) return null; - // [#34872] …in the caller's locale. `declared` is read for the - // `readonly` verdict alone, which no translation touches. - const [localized] = await inCallerLocale([def]); - // [#32435] …each field and rule carrying what a write needs. - return describeServedObject(localized, declared); - }, + describeObject: describeForCaller, // [#28715] The fields `validate_expression` judges a `label()` call // against, from the object `describeObject` reads: the served object, // where a picklist-bound field carries its list's resolved `options`, @@ -1225,6 +1242,27 @@ export function buildMcpBridge( return { narrowed: false }; } }, + /** + * [#35137] The two answers `query_records` and `get_record` name + * withheld fields from (`McpFieldVisibility`, `@objectstack/mcp`), both + * asked as THIS request's caller: the field names `describe_object` + * lists for them, read off the very answer it serves + * ({@link describeForCaller}, so whatever it leaves out is left out + * here too), and this request's security service's readable answer + * (`getReadableFields`). No security service, an object not served, + * or no readable answer: `undefined`, and nothing is named. A throw + * reaches the tool layer, which names nothing either. + */ + fieldVisibilityOf: async (object: string) => { + const security = await deps.resolveService(context, 'security', envId) as + Partial | undefined; + if (typeof security?.getReadableFields !== 'function') return undefined; + const described = await describeForCaller(object); + if (!described) return undefined; + const readable = await security.getReadableFields(object, ec); + if (!Array.isArray(readable)) return undefined; + return { served: describedFieldNames(described), readable }; + }, get: async (object: string, id: string) => { const res: any = await callData('get', { object, id }, driver, envId, ec); return res?.record ?? res ?? null;