From 88af8ca5628657f24af474514ddec677eee0751f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 23:15:52 +0000 Subject: [PATCH 1/5] fix(mcp): stdio get_record refuses a missing or hidden id with the coded RECORD_NOT_FOUND The stdio bridge answers a by-id miss with null, and get_record rendered that as a bare sentence, while the HTTP door's bridge throws the shared recordNotFoundError and answers the coded 404 envelope. get_record now throws that same value into its own catch, so both doors render one throw through one renderer. A missing id and an id the caller may not read reach the tool as the same empty read and answer alike. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvhQvy8SbR3j9f7kcb --- packages/mcp/src/mcp-http-tools.ts | 12 +- .../src/stdio-data-bridge.not-found.test.ts | 155 ++++++++++++++++++ packages/mcp/src/stdio-data-bridge.ts | 5 +- 3 files changed, 169 insertions(+), 3 deletions(-) diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 14afb65c8bd..012350c74d2 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -52,6 +52,9 @@ import { AggregationNodeSchema } from '@objectstack/spec/data'; // [#23529] The catalogue's spelling of `PERMISSION_DENIED`, the code whose // `details` `errorResultFromThrown` withholds. Imported, never hand-spelled. import { StandardErrorCode, type ErrorCode } from '@objectstack/spec/api'; +// The repo's ONE not-found envelope, which the HTTP bridge's `get` throws: +// `get_record` refuses a null read with it, so both doors answer one 404. +import { recordNotFoundError } from '@objectstack/core'; // [#23701] The one key every door that translates the engine's unique-violation // envelope asks (the registered code AND the class name, never message text), // and the one classification whose arm states the wire code for it. @@ -2796,7 +2799,14 @@ export function registerObjectTools( if (bad) return errorResult(bad); try { const record = await bridge.get(objectName, recordId); - if (record == null) return errorResult(`Record "${recordId}" not found in "${objectName}"`); + // A bridge that answers a miss with `null` (the stdio bridge, by + // design) is refused with the repo's ONE not-found envelope, thrown + // into the catch below: the HTTP bridge's `get` throws that same + // value (`protocol.getData`, through `callData`), so both doors + // render one throw through one renderer and answer one coded + // `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); } catch (err) { return dataDoorErrorResult(err, 'get_record', objectName); diff --git a/packages/mcp/src/stdio-data-bridge.not-found.test.ts b/packages/mcp/src/stdio-data-bridge.not-found.test.ts index cfef1303cea..7cac51e523e 100644 --- a/packages/mcp/src/stdio-data-bridge.not-found.test.ts +++ b/packages/mcp/src/stdio-data-bridge.not-found.test.ts @@ -20,9 +20,14 @@ */ import { describe, it, expect, vi } from 'vitest'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { recordNotFoundError } from '@objectstack/core'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; import { createStdioDataBridge } from './stdio-data-bridge.js'; +import { MCPServerRuntime } from './mcp-server-runtime.js'; +import type { McpDataBridge } from './mcp-http-tools.js'; import { assertEngineFindOnePredicate, type EngineFindOneQueryInput } from '@objectstack/metadata-core'; /** An engine that resolves NO row for any id — every by-id write is a miss. */ @@ -124,3 +129,153 @@ describe('#8422 stdio bridge by-id writes throw the shared not-found envelope', expect(updateErr?.code).toBe('RECORD_NOT_FOUND'); }); }); + +// --------------------------------------------------------------------------- +// The tool door: `get_record` over the long-lived server stdio attaches +// --------------------------------------------------------------------------- + +/** + * One row, `secret1`, that only its owner reads: the engine double answers the + * row to `owner` and nothing to anyone else, which is what the security + * middleware's row filter does to a by-id read the caller may not see. So for + * {@link PRINCIPAL} `secret1` is HIDDEN and `ghost` is MISSING, and the two + * reach the bridge as the same empty read. + */ +function makeRowFilteringEngine() { + const row = { id: 'secret1', title: 'owner only' }; + const visibleTo = (opts?: { context?: { userId?: string } }) => opts?.context?.userId === 'owner'; + return { + find: vi.fn(async (_object: string, query?: { where?: { id?: unknown } }, opts?: { context?: { userId?: string } }) => + query?.where?.id === row.id && visibleTo(opts) ? [row] : []), + findOne: vi.fn(async (object: string, query?: EngineFindOneQueryInput) => { assertEngineFindOnePredicate(object, query); return null; }), + insert: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + count: vi.fn(async () => 0), + aggregate: vi.fn(async () => [{ n: 0 }]), + }; +} + +function stdioBridgeAs(principal: ExecutionContext) { + const engine = makeRowFilteringEngine(); + const bridge = createStdioDataBridge({ + engine: engine as unknown as IDataEngine, + metadataService: makeMetadata() as unknown as IMetadataService, + resolvePrincipal: async () => principal, + }); + return { bridge, engine }; +} + +/** A `tools/call` on the long-lived server (`runtime.server`, the one `start()` attaches stdio to). */ +async function callOnLongLivedServer(bridge: McpDataBridge, name: string, args: Record) { + const runtime = new MCPServerRuntime({ name: 'pin', version: '0.0.0' }); + runtime.bridgeDataTools(bridge); + const [clientSide, serverSide] = InMemoryTransport.createLinkedPair(); + await runtime.server.connect(serverSide); + const client = new Client({ name: 'pin', version: '0.0.0' }); + await client.connect(clientSide); + try { + return await client.callTool({ name, arguments: args }); + } finally { + await client.close(); + } +} + +/** + * The HTTP `/mcp` door's answer to the same call: its bridge's `get` reaches + * `protocol.getData` through `callData`, which throws `recordNotFoundError` + * for an id that names no row the caller may read (pinned as the HTTP face's + * answer in `mcp-coded-refusal.test.ts`). Driven through `handleHttpRequest`, + * the real Streamable HTTP transport, so the two answers compared below come + * from the two doors' own tool registrations. + */ +async function getRecordOverHttp(objectName: string, recordId: string) { + const bridge: McpDataBridge = { + async listObjects() { return [{ name: 'task', label: 'Task', fieldCount: 0 }]; }, + async describeObject() { return null; }, + async query(object) { return { object, records: [], total: 0 }; }, + async get(object, id) { throw recordNotFoundError(object, id); }, + async create(object, data) { return { object, id: 'n1', record: data }; }, + async update(object, id, data) { return { object, id, record: data }; }, + async remove(object, id) { return { object, id, success: true }; }, + }; + const body = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'get_record', arguments: { objectName, recordId } } }; + const res = await new MCPServerRuntime({ name: 'pin', version: '0.0.0' }).handleHttpRequest( + new Request('http://localhost/api/v1/mcp', { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, + body: JSON.stringify(body), + }), + { bridge, parsedBody: body }, + ); + expect(res.status).toBe(200); + return ((await res.json()) as { result: unknown }).result; +} + +/** The coded envelope `get_record` answers a miss with, as both doors put it on the wire. */ +function notFoundWire(object: string, id: string) { + return { error: { code: 'RECORD_NOT_FOUND', message: `Record ${id} not found in ${object}`, status: 404 } }; +} + +describe('stdio get_record answers a missing or hidden id with the coded RECORD_NOT_FOUND / 404', () => { + it('a MISSING id: isError, and the text is the coded envelope, not a bare sentence', async () => { + const { bridge } = stdioBridgeAs(PRINCIPAL); + const result = (await callOnLongLivedServer(bridge, 'get_record', { objectName: 'task', recordId: 'ghost' })) as { + isError?: boolean; + content: Array<{ text: string }>; + }; + expect(result.isError).toBe(true); + expect(JSON.parse(result.content[0]!.text)).toEqual(notFoundWire('task', 'ghost')); + }); + + it('a HIDDEN id answers the same envelope as a missing one: no existence oracle', async () => { + const { bridge, engine } = stdioBridgeAs(PRINCIPAL); + const hidden = (await callOnLongLivedServer(bridge, 'get_record', { objectName: 'task', recordId: 'secret1' })) as { + isError?: boolean; + content: Array<{ text: string }>; + }; + expect(hidden.isError).toBe(true); + expect(JSON.parse(hidden.content[0]!.text)).toEqual(notFoundWire('task', 'secret1')); + // The read ran as the caller, so the row filter is what hid it. + expect(engine.find).toHaveBeenCalledWith('task', expect.objectContaining({ where: { id: 'secret1' } }), { context: PRINCIPAL }); + }); + + it('CONTROL: the hidden row is served to its owner, so the refusal above is the row filter, not a missing row', async () => { + const { bridge } = stdioBridgeAs({ userId: 'owner', isSystem: false } as unknown as ExecutionContext); + const served = (await callOnLongLivedServer(bridge, 'get_record', { objectName: 'task', recordId: 'secret1' })) as { + isError?: boolean; + content: Array<{ text: string }>; + }; + expect(served.isError).toBeFalsy(); + expect(JSON.parse(served.content[0]!.text)).toEqual({ id: 'secret1', title: 'owner only' }); + }); + + it('PARITY: the stdio answer equals the HTTP /mcp answer for the same call, byte for byte', async () => { + for (const recordId of ['ghost', 'secret1']) { + const { bridge } = stdioBridgeAs(PRINCIPAL); + const overStdio = await callOnLongLivedServer(bridge, 'get_record', { objectName: 'task', recordId }); + const overHttp = await getRecordOverHttp('task', recordId); + expect(overStdio, `get_record ${recordId}`).toEqual(overHttp); + } + }); + + it('update_record and delete_record on the same ids answer the same coded envelope (already coded, held here)', async () => { + for (const recordId of ['ghost', 'secret1']) { + const { bridge } = stdioBridgeAs(PRINCIPAL); + const updated = (await callOnLongLivedServer(bridge, 'update_record', { + objectName: 'task', + recordId, + data: { title: 'x' }, + })) as { isError?: boolean; content: Array<{ text: string }> }; + expect(updated.isError).toBe(true); + expect(JSON.parse(updated.content[0]!.text)).toEqual(notFoundWire('task', recordId)); + const deleted = (await callOnLongLivedServer(bridge, 'delete_record', { + objectName: 'task', + recordId, + confirm: true, + })) as { isError?: boolean; content: Array<{ text: string }> }; + expect(deleted.isError).toBe(true); + expect(JSON.parse(deleted.content[0]!.text)).toEqual(notFoundWire('task', recordId)); + } + }); +}); diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index 6f525a09a0a..813d8ac45bb 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -1246,8 +1246,9 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge async get(object, id) { const context = await resolvePrincipal(); await enforceApiExposure(reads, object, GATED_ACTIONS.get, context); - // `null` rather than a throw: `get_record` owns the not-found wording on - // this path and already branches on a nullish record. + // `null` rather than a throw: `get_record` branches on a nullish record + // and refuses it with the shared `recordNotFoundError`, the value the + // HTTP bridge's `get` throws, so the two doors answer one coded 404. // [#21207] A stored metadata body is served as its type's projection, // and its stored content hash keyed (or not at all). return serveStoredMetadataHashes( From 5e3055b345947e711a1d9eece8d210accb9304c7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 23:19:05 +0000 Subject: [PATCH 2/5] wip: stdio describe readonly from the declared field Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvhQvy8SbR3j9f7kcb --- packages/mcp/src/mcp-server-runtime.ts | 72 +++++++++-- ...dio-data-bridge.object-schema-mask.test.ts | 122 +++++++++++++++++- packages/mcp/src/stdio-data-bridge.ts | 40 ++++-- .../domains/mcp-object-schema-mask.test.ts | 20 +++ 4 files changed, 232 insertions(+), 22 deletions(-) diff --git a/packages/mcp/src/mcp-server-runtime.ts b/packages/mcp/src/mcp-server-runtime.ts index 23c79165575..487fb1756a7 100644 --- a/packages/mcp/src/mcp-server-runtime.ts +++ b/packages/mcp/src/mcp-server-runtime.ts @@ -127,13 +127,16 @@ interface ServedFieldDef { * One projection for this package's two readers of it: the stdio bridge's * `describeObject` (`stdio-data-bridge.ts`) and the `objectstack://objects/{name}` * resource ({@link buildObjectSchemaResource}), each handing it the object as - * the caller is served it, so the two answer alike (#25245). The HTTP bridge's + * the caller is served it, so the two answer alike (#25245), and the + * declaration that object was projected from ({@link readObjectWithDeclaration}): + * `readonly` is judged on the declared field, {@link writeNeverSetsField}, and + * nothing else is read from it. The HTTP bridge's * twin is `describeServedObject` in `packages/runtime/src/domains/mcp.ts` * (`@objectstack/runtime` does not depend on this package): the transports * answer one shape, and the `describe_object` description (`mcp-http-tools.ts`) * states it. */ -export function describeServedObject(def: ServedObjectDef): Record { +export function describeServedObject(def: ServedObjectDef, declared: ServedObjectDef = def): Record { return { name: def.name, label: def.label ?? def.name, @@ -142,7 +145,12 @@ export function describeServedObject(def: ServedObjectDef): Record; */ const runtimeObjectViews = new WeakMap(); +/** One object as a view serves it, beside the declaration it was projected from. */ +export interface ObjectWithDeclaration { + served: unknown; + declared: unknown; +} + +/** + * The read a MASKING view ({@link setDeclaredObjectRead}) answers both halves + * of {@link ObjectWithDeclaration} with, from one read of the definition it + * masks. Keyed weakly by the view, so a view and its read are collected + * together; package-internal, like {@link setRuntimeObjectView}. + */ +const declaredObjectReads = new WeakMap Promise>(); + +/** + * Register `read` as the declared-object read of `view`, a view that serves a + * caller a projection of each definition (the stdio caller view, + * `callerObjectView` in `stdio-data-bridge.ts`). Package-internal; not + * re-exported from `index.ts`. + */ +export function setDeclaredObjectRead(view: McpObjectView, read: (name: string) => Promise): void { + declaredObjectReads.set(view, read); +} + +/** + * `name` as `view` serves it, and the declaration it was projected from: what + * {@link describeServedObject} needs to judge `readonly` on the declared field + * while serving only the projection. A view that registered no declared read + * masks nothing, so the object it serves IS the declaration. + * + * ⛔ The declaration never leaves this package's two describe readers: only + * {@link writeNeverSetsField}'s boolean is read off it, so nothing the caller's + * mask withholds (an expression naming a field they cannot read) is served. + */ +export async function readObjectWithDeclaration(view: McpObjectView, name: string): Promise { + const read = declaredObjectReads.get(view); + if (read) return read(name); + const def = await view.getObject(name); + return { served: def, declared: def }; +} + /** * [#31605] The long-lived server's principal: the `OS_MCP_STDIO_API_KEY` * identity the plugin resolves per call (ADR-0101), bound by the plugin once @@ -1324,9 +1371,12 @@ export async function buildObjectSchemaResource( // refuses a schema whose field visibility it could not evaluate) answers // in this resource's `{ error, code, status }` vocabulary // ({@link objectResourceRefusal}); an uncoded throw travels, as before. + // …beside the declaration it was projected from, for `readonly` alone + // ({@link readObjectWithDeclaration}). let objectDef: unknown; + let declared: unknown; try { - objectDef = await objects.getObject(objectName); + ({ served: objectDef, declared } = await readObjectWithDeclaration(objects, objectName)); } catch (err) { const refusal = objectResourceRefusal(err); if (refusal) return body(refusal); @@ -1361,7 +1411,7 @@ export async function buildObjectSchemaResource( contents: [{ uri, mimeType: 'application/json', - text: JSON.stringify(describeServedObject(objectDef as ServedObjectDef), null, 2), + text: JSON.stringify(describeServedObject(objectDef as ServedObjectDef, declared as ServedObjectDef), null, 2), }], }; } diff --git a/packages/mcp/src/stdio-data-bridge.object-schema-mask.test.ts b/packages/mcp/src/stdio-data-bridge.object-schema-mask.test.ts index b6c00889952..f18303ff42d 100644 --- a/packages/mcp/src/stdio-data-bridge.object-schema-mask.test.ts +++ b/packages/mcp/src/stdio-data-bridge.object-schema-mask.test.ts @@ -43,7 +43,7 @@ import { assertEngineUpdateDispatch, type ObjectSchemaReadDelegateSource, } from '@objectstack/metadata-core'; -import { createStdioDataBridge } from './stdio-data-bridge.js'; +import { callerObjectView, createStdioDataBridge, stdioObjectView } from './stdio-data-bridge.js'; import { registerObjectTools } from './mcp-http-tools.js'; import { MCPServerPlugin } from './plugin.js'; import { buildObjectSchemaResource, type MCPServerRuntime } from './mcp-server-runtime.js'; @@ -601,3 +601,123 @@ describe('[#32530] stdio describe_object and the objects resource serve readonly expect(readonlyOf(JSON.parse(result.contents[0]!.text))).toEqual(EXPECTED); }); }); + +describe('stdio describe_object and the objects resource judge readonly on the DECLARED field, as the HTTP twin does', () => { + // The HTTP twin's fixture (`packages/runtime/src/domains/mcp-object-schema-mask.test.ts`, + // "describe_object serves readonly where a write never stands — the real + // engine and security layer"): `marked_up` is a stored expression over + // `hidden_cost`, which the member may not read, so the member's mask deletes + // `marked_up.expression` while the engine still computes the field. + const TICKET = { + name: 'ticket', + label: 'Ticket', + fields: { + title: { type: 'text', label: 'Title' }, + qty: { type: 'number', label: 'Qty' }, + frozen_note: { type: 'text', label: 'Frozen note', readonly: true }, + ticket_no: { type: 'autonumber', label: 'Ticket No' }, + total: { type: 'formula', label: 'Total', expression: 'record.qty * 2' }, + bare_formula: { type: 'formula', label: 'Bare formula' }, + doubled: { type: 'number', label: 'Doubled', expression: 'record.qty * 2' }, + locked_note: { type: 'text', label: 'Locked note' }, + hidden_cost: { type: 'number', label: 'Hidden cost' }, + marked_up: { type: 'number', label: 'Marked up', expression: 'record.hidden_cost * 2' }, + }, + }; + /** + * The member's answer, field for field: the map the HTTP twin's PARITY pin + * holds for the same declaration and the same mask. `hidden_cost` is not + * served at all; `marked_up` is served, without its expression, as readonly. + */ + const MEMBER_READONLY = { + title: false, + qty: false, + frozen_note: true, + ticket_no: true, + total: true, + bare_formula: true, + doubled: true, + locked_note: false, + marked_up: true, + }; + const READABLE = Object.keys(TICKET.fields).filter((f) => f !== 'hidden_cost'); + const memberSecurity = { + getReadableFields: async () => [...READABLE], + getMetadataReadableFields: async () => [...READABLE], + canReadObject: async () => true, + }; + const readonlyOf = (described: any) => Object.fromEntries(described.fields.map((f: any) => [f.name, f.readonly])); + const metadataService = () => { + const object = () => JSON.parse(JSON.stringify(TICKET)); + return { + listObjects: vi.fn(async () => [object()]), + getObject: vi.fn(async (name: string) => (name === TICKET.name ? object() : undefined)), + } as unknown as IMetadataService; + }; + const MEMBER = async () => ({ userId: 'u_member' }) as unknown as ExecutionContext; + + async function describeOverStdio(): Promise<{ text: string; json: any }> { + const bridge = createStdioDataBridge({ + engine: {} as unknown as IDataEngine, + metadataService: metadataService(), + resolvePrincipal: MEMBER, + security: () => memberSecurity, + }); + 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); + try { + const res = (await client.callTool({ name: 'describe_object', arguments: { objectName: TICKET.name } })) as { + isError?: boolean; + content: Array<{ text: string }>; + }; + expect(res.isError === true).toBe(false); + return { text: res.content[0]!.text, json: JSON.parse(res.content[0]!.text) }; + } finally { + await client.close(); + } + } + + /** The resource as the plugin wires it for a stdio principal: the caller view over `stdioObjectView`. */ + async function describeOverResource(): Promise<{ text: string; json: any }> { + const service = metadataService(); + const view = callerObjectView(stdioObjectView({ metadataService: service }), { + resolvePrincipal: MEMBER, + security: () => memberSecurity, + }); + const result = await buildObjectSchemaResource(service, TICKET.name, undefined, view); + const text = String(result.contents[0]!.text); + return { text, json: JSON.parse(text) }; + } + + it('precondition: the member\'s served object carries marked_up WITHOUT its expression', async () => { + const view = callerObjectView(stdioObjectView({ metadataService: metadataService() }), { + resolvePrincipal: MEMBER, + security: () => memberSecurity, + }); + const served = (await view.getObject(TICKET.name)) as any; + expect(served.fields.marked_up, 'the member is served the field').toBeDefined(); + expect(served.fields.marked_up.expression, 'the mask deleted the expression').toBeUndefined(); + expect(served.fields.hidden_cost, 'the field it names is not served').toBeUndefined(); + }); + + for (const [door, describe] of [ + ['describe_object over stdio', describeOverStdio], + ['the objectstack://objects/{name} resource', describeOverResource], + ] as const) { + it(`${door}: marked_up is readonly: true, and neither its expression nor hidden_cost is served`, async () => { + const { text, json } = await describe(); + expect(readonlyOf(json)).toEqual(MEMBER_READONLY); + expect(mentions(text, 'hidden_cost')).toBe(false); + expect(text).not.toContain('record.'); + expect(json.fields.find((f: any) => f.name === 'marked_up')).not.toHaveProperty('expression'); + }); + } + + it('the tool and the resource answer the member the same fields', async () => { + expect((await describeOverResource()).json.fields).toEqual((await describeOverStdio()).json.fields); + }); +}); diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index 813d8ac45bb..e2d8e4dde5d 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -147,7 +147,14 @@ import { apiKeyManagementCredentialRefusal } from '@objectstack/core'; import { declaresOptions } from '@objectstack/formula'; import type { McpDataBridge, McpObjectSummary } from './mcp-http-tools.js'; import type { ListDatasetsOutput, QueryDatasetOutput } from '@objectstack/spec/ai'; -import { describeServedObject, metaItemsArray, type McpObjectView } from './mcp-server-runtime.js'; +import { + describeServedObject, + metaItemsArray, + readObjectWithDeclaration, + setDeclaredObjectRead, + type McpObjectView, + type ServedObjectDef, +} from './mcp-server-runtime.js'; import { diagnoseObjectListRead, type DiagnosedObjectListing, @@ -584,22 +591,31 @@ export function callerObjectView(view: McpObjectView, deps: CallerObjectViewDeps return masked.document; }; }; - return { + // One read of the definition, served to the principal, with the declaration + // it was projected from beside it: `getObject` answers the first half, and + // the describe readers ask both (`readObjectWithDeclaration`) to judge + // `readonly` on the declared field, as the HTTP twin does. + const readWithDeclaration = async (name: string) => { + const serve = await servedToPrincipal(); + const def = (await view.getObject(name)) as ObjectDef | undefined; + return { served: def ? await serve(def) : def, declared: def }; + }; + const served: McpObjectView = { async listObjects() { const serve = await servedToPrincipal(); - const served: ObjectDef[] = []; + const listed: ObjectDef[] = []; for (const def of ((await view.listObjects()) ?? []) as ObjectDef[]) { const one = await serve(def); - if (one !== undefined) served.push(one); + if (one !== undefined) listed.push(one); } - return served; + return listed; }, async getObject(name) { - const serve = await servedToPrincipal(); - const def = (await view.getObject(name)) as ObjectDef | undefined; - return def ? await serve(def) : def; + return (await readWithDeclaration(name)).served; }, }; + setDeclaredObjectRead(served, readWithDeclaration); + return served; } /** @@ -1172,15 +1188,19 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge // describe, and a name the listing omits (a disabled package's object among // them) is "not found" here too, as on the HTTP bridge. // [ADR-0106 D1/D5] …as the principal is served it ({@link callerObjectView}). + // …and `readonly` judged on the declaration that view masked, as the HTTP + // twin judges it ({@link readObjectWithDeclaration}): only that boolean + // is read off the declaration. async describeObject(name: string): Promise { - const def = (await servedView.getObject(name)) as ObjectDef | undefined; + const { served, declared } = await readObjectWithDeclaration(servedView, name); + const def = served as ObjectDef | undefined; 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); + return describeServedObject(def, declared as ServedObjectDef); }, // [#28715] From the object `describeObject` reads: the protocol's served 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 1de1d1c1e58..e43ad7e72ae 100644 --- a/packages/runtime/src/domains/mcp-object-schema-mask.test.ts +++ b/packages/runtime/src/domains/mcp-object-schema-mask.test.ts @@ -1663,6 +1663,26 @@ describe('[#32530] describe_object serves readonly where a write never stands expect({ code: refused?.code, status: refused?.status }).toEqual({ code: 'PERMISSION_DENIED', status: 403 }); }); + // The stdio twin holds this same map for the same declaration and mask + // (`packages/mcp/src/stdio-data-bridge.object-schema-mask.test.ts`, "stdio + // describe_object and the objects resource judge readonly on the DECLARED + // field"): neither package depends on the other, so the two doors' parity + // is this literal, pinned on each side, field for field. + it('PARITY: the member is served exactly the readonly map the stdio door serves the same member', async () => { + const { bridge } = await bridgeFor(kernelOver(services), MEMBER); + expect(readonlyOf(await bridge.describeObject(OBJ))).toEqual({ + title: false, + qty: false, + frozen_note: true, + ticket_no: true, + total: true, + bare_formula: true, + doubled: true, + locked_note: false, + marked_up: true, + }); + }); + it('a stored expression over a field the caller cannot read is still served readonly: true, and neither the expression nor that field is served', async () => { const { bridge } = await bridgeFor(kernelOver(services), MEMBER); const described: any = await bridge.describeObject(OBJ); From c1b63360b2dd34c7b0fbb2a0d0a90df425fea04b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 23:24:20 +0000 Subject: [PATCH 3/5] fix(mcp): stdio describe_object and the objects resource judge readonly on the declared field The stdio caller view served only the masked object, so a stored field whose expression names a field the caller cannot read lost its expression in the mask and was described readonly: false, while the engine still computes it. The caller view now registers a read that answers the served object beside the declaration it was projected from, from one read of the definition; describe_object and the objects resource judge readonly on the declared field, as the HTTP twin does, and build the answer from the served object only. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvhQvy8SbR3j9f7kcb --- .../33030-stdio-get-record-coded-not-found.md | 10 ++++++++++ .../33156-stdio-describe-readonly-declared.md | 10 ++++++++++ .../src/domains/mcp-object-schema-mask.test.ts | 16 ++++++++++++---- 3 files changed, 32 insertions(+), 4 deletions(-) create mode 100644 .changeset/33030-stdio-get-record-coded-not-found.md create mode 100644 .changeset/33156-stdio-describe-readonly-declared.md diff --git a/.changeset/33030-stdio-get-record-coded-not-found.md b/.changeset/33030-stdio-get-record-coded-not-found.md new file mode 100644 index 00000000000..346f93bad28 --- /dev/null +++ b/.changeset/33030-stdio-get-record-coded-not-found.md @@ -0,0 +1,10 @@ +--- +'@objectstack/mcp': patch +--- + +fix(mcp): stdio `get_record` answers a missing or hidden id with the coded `RECORD_NOT_FOUND` + +Clause-②: no +Metadata-protocol: none + +Over the stdio transport, `get_record` on an id that names no row, or a row the caller may not read, answered the bare sentence `Record "" not found in ""` with no code. It now answers the coded envelope the HTTP `/mcp` door answers for the same call, `{ "error": { "code": "RECORD_NOT_FOUND", "message": "Record not found in ", "status": 404 } }`, so a stdio client can branch on the code. A missing id and a hidden id answer the same envelope. `update_record` and `delete_record` already answered it and are unchanged. diff --git a/.changeset/33156-stdio-describe-readonly-declared.md b/.changeset/33156-stdio-describe-readonly-declared.md new file mode 100644 index 00000000000..1e33531286e --- /dev/null +++ b/.changeset/33156-stdio-describe-readonly-declared.md @@ -0,0 +1,10 @@ +--- +'@objectstack/mcp': patch +--- + +fix(mcp): stdio `describe_object` and the objects resource judge `readonly` on the declared field + +Clause-②: no +Metadata-protocol: none + +Over stdio and on the `objectstack://objects/{name}` resource, a stored field that declares an `expression` the caller is not shown (it names a field they cannot read) was described `readonly: false`, so an agent could send a value the engine then replaced. `readonly` is now judged on the field as declared, as the HTTP `/mcp` door judges it, so that field answers `readonly: true` on every transport. The expression itself, and the field it names, are still not served: only the `readonly` answer is read from the declaration. 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 e43ad7e72ae..1fc72b8a059 100644 --- a/packages/runtime/src/domains/mcp-object-schema-mask.test.ts +++ b/packages/runtime/src/domains/mcp-object-schema-mask.test.ts @@ -1667,10 +1667,11 @@ describe('[#32530] describe_object serves readonly where a write never stands // (`packages/mcp/src/stdio-data-bridge.object-schema-mask.test.ts`, "stdio // describe_object and the objects resource judge readonly on the DECLARED // field"): neither package depends on the other, so the two doors' parity - // is this literal, pinned on each side, field for field. + // is this literal, pinned on each side, field for field. Read over the + // authored fields: the registry adds its audit, tenant and owner columns + // here, which the stdio fixture does not declare. it('PARITY: the member is served exactly the readonly map the stdio door serves the same member', async () => { - const { bridge } = await bridgeFor(kernelOver(services), MEMBER); - expect(readonlyOf(await bridge.describeObject(OBJ))).toEqual({ + const STDIO_TWIN_MEMBER_READONLY = { title: false, qty: false, frozen_note: true, @@ -1680,7 +1681,14 @@ describe('[#32530] describe_object serves readonly where a write never stands doubled: true, locked_note: false, marked_up: true, - }); + }; + const { bridge } = await bridgeFor(kernelOver(services), MEMBER); + const served = readonlyOf(await bridge.describeObject(OBJ)); + expect(served).not.toHaveProperty('hidden_cost'); + const authored = Object.fromEntries( + Object.keys(STDIO_TWIN_MEMBER_READONLY).map((k) => [k, served[k]]), + ); + expect(authored).toEqual(STDIO_TWIN_MEMBER_READONLY); }); it('a stored expression over a field the caller cannot read is still served readonly: true, and neither the expression nor that field is served', async () => { From 59ccee50263e07126439c54cfdca93ece78dc21c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 23:39:31 +0000 Subject: [PATCH 4/5] test(mcp): reuse the not-found file's engine double for the row-filtering read Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvhQvy8SbR3j9f7kcb --- .../mcp/src/stdio-data-bridge.not-found.test.ts | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/packages/mcp/src/stdio-data-bridge.not-found.test.ts b/packages/mcp/src/stdio-data-bridge.not-found.test.ts index 7cac51e523e..ac250ab7896 100644 --- a/packages/mcp/src/stdio-data-bridge.not-found.test.ts +++ b/packages/mcp/src/stdio-data-bridge.not-found.test.ts @@ -144,16 +144,11 @@ describe('#8422 stdio bridge by-id writes throw the shared not-found envelope', function makeRowFilteringEngine() { const row = { id: 'secret1', title: 'owner only' }; const visibleTo = (opts?: { context?: { userId?: string } }) => opts?.context?.userId === 'owner'; - return { - find: vi.fn(async (_object: string, query?: { where?: { id?: unknown } }, opts?: { context?: { userId?: string } }) => - query?.where?.id === row.id && visibleTo(opts) ? [row] : []), - findOne: vi.fn(async (object: string, query?: EngineFindOneQueryInput) => { assertEngineFindOnePredicate(object, query); return null; }), - insert: vi.fn(), - update: vi.fn(), - delete: vi.fn(), - count: vi.fn(async () => 0), - aggregate: vi.fn(async () => [{ n: 0 }]), - }; + // The file's one engine double, with its by-id read made row-filtering. + const engine = makeEmptyEngine(); + const find = vi.fn(async (_object: string, query?: { where?: { id?: unknown } }, opts?: { context?: { userId?: string } }) => + query?.where?.id === row.id && visibleTo(opts) ? [row] : []); + return Object.assign(engine, { find }); } function stdioBridgeAs(principal: ExecutionContext) { From 532a02e508b59b19c5954b46dd125c2c7630d538 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 00:08:22 +0000 Subject: [PATCH 5/5] docs(mcp,runtime): say the stdio door judges readonly on the declaration too The HTTP twin's writeNeverSetsField JSDoc and the unreleased describe_object readonly changeset still said the stdio door and the objects resource judge the masked field. They now say what holds: every transport judges readonly on the declared field. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvhQvy8SbR3j9f7kcb --- .changeset/32530-describe-object-readonly-computed.md | 2 +- packages/runtime/src/domains/mcp.ts | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.changeset/32530-describe-object-readonly-computed.md b/.changeset/32530-describe-object-readonly-computed.md index 406ac2c3161..49f90a44d48 100644 --- a/.changeset/32530-describe-object-readonly-computed.md +++ b/.changeset/32530-describe-object-readonly-computed.md @@ -8,6 +8,6 @@ fix(mcp,runtime): `describe_object` serves `readonly: true` where a write never Clause-②: yes (widening) Metadata-protocol: none -`describe_object` and the `objectstack://objects/{name}` resource served each field's `readonly` from the declared flag alone, so an agent was told it could write fields whose sent value the engine drops or replaces. Both transports now also answer `readonly: true` for a runtime-owned type (`autonumber`, including a hand-written field literal with no flag), for a `formula` field, and for a stored field that declares an `expression`. On the HTTP transport, `readonly` is judged on the field as declared, so a stored expression the caller is not shown (it names a field they cannot read) still answers `true`, and the expression itself stays hidden. Over stdio and on the resource, which hold only the object as the caller is served it, the expression case answers `true` where the caller is shown the expression. An ordinary field still answers `readonly: false`, and a declared `readonly` still answers `true`. +`describe_object` and the `objectstack://objects/{name}` resource served each field's `readonly` from the declared flag alone, so an agent was told it could write fields whose sent value the engine drops or replaces. Both transports now also answer `readonly: true` for a runtime-owned type (`autonumber`, including a hand-written field literal with no flag), for a `formula` field, and for a stored field that declares an `expression`. On every transport, the resource included, `readonly` is judged on the field as declared, so a stored expression the caller is not shown (it names a field they cannot read) still answers `true`, and the expression itself stays hidden. An ordinary field still answers `readonly: false`, and a declared `readonly` still answers `true`. `readonly` is the schema's answer, not the caller's field edit permission: a field the caller may read but not edit still answers `readonly: false`, and a write naming it is refused as before. The tool description now says so, and it also says that a `defaultValue` may be a token the server resolves (`NOW()`, `current_user`) or an expression object, so an agent omits the field instead of copying the value. diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index 7eb152e708f..ed713308969 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -666,8 +666,10 @@ function describeServedObject(def: any, declared: any): Record * caller cannot read, while the engine still computes the column from it. * * The twin is `writeNeverSetsField` in `packages/mcp/src/mcp-server-runtime.ts`, - * which has only the masked object to ask: there the expression arm holds where - * the caller is served the expression. + * which the stdio bridge and the `objectstack://objects/{name}` resource ask of + * the declared field too: the stdio caller view hands the declaration it masked + * beside the served object (`readObjectWithDeclaration`), so every transport + * answers this verdict alike. */ function writeNeverSetsField(f: any): boolean { if (!f || typeof f !== 'object') return false;