diff --git a/.changeset/35114-stdio-mcp-dropped-fields.md b/.changeset/35114-stdio-mcp-dropped-fields.md new file mode 100644 index 00000000000..cf18fdd21c1 --- /dev/null +++ b/.changeset/35114-stdio-mcp-dropped-fields.md @@ -0,0 +1,15 @@ +--- +'@objectstack/mcp': patch +'@objectstack/lint': patch +--- + +fix(mcp, lint): `create_record` and `update_record` over stdio answer `droppedFields` and no longer echo a dropped value; a flow write to a roll-up summary field draws a warning + +Clause-②: yes +Metadata-protocol: none + +On the stdio MCP transport, `create_record` and `update_record` now answer `droppedFields`, as the HTTP transport has: each entry names the object, the fields the engine did not store and the reason. A non-system write of a `readonly: true` column or of a roll-up `summary` field (read-only on create and update whether or not it declares `readonly: true`) reports the field there with reason `readonly`. Before, the stdio answer carried no `droppedFields`, and `update_record` answered the caller's own value for such a field over the stored one, so the answer read as if the write had landed. The `record` in both answers now leaves a dropped key's caller value out: an update answers the stored value, and a create answers what the write stored. A write that drops nothing answers as before, with no `droppedFields` key. No MCP tool input, `@objectstack/mcp` export or metadata key changes. + +`os validate`, `os lint` and `os build` now report a new warning, `flow-update-summary-field`, when a flow's `create_record` or `update_record` node that does not run as `runAs: 'system'` writes a roll-up `summary` field that does not declare `readonly: true`. The engine drops that value on create and on update, so the step changes nothing in that column. It is a warning, so no build that passes today fails. Like every warning, it makes `os validate --strict` and `os lint --strict` exit 1; there is no per-rule switch, so a strict run fails until the field is removed from the node. The metadata save and publish answers carry it under `advisories`, never as a refusal: on a flow save whose user-run node writes such a roll-up, and on an object save that makes a field such a roll-up while a live user-run flow of the same package writes it. A roll-up that declares `readonly: true` is reported as `flow-update-readonly-field`, an error, as before. `os explain flow-update-summary-field` gives the details. The fix is to remove the field from the node, since the engine recomputes it from the child records. + +New export: `FLOW_UPDATE_SUMMARY_FIELD` from `@objectstack/lint`, the rule id constant. diff --git a/content/docs/data-modeling/fields.mdx b/content/docs/data-modeling/fields.mdx index 25236373f8e..84634eb4790 100644 --- a/content/docs/data-modeling/fields.mdx +++ b/content/docs/data-modeling/fields.mdx @@ -398,9 +398,14 @@ when multiple relationships target the same parent object. A summary field is read-only on create and on update whether or not it declares `readonly: true`. A value that a `POST`, an import (any `writeMode`), an MCP -create, a `PATCH` or a bulk update sends for it is dropped, the rest of the write -is stored, and the response's `droppedFields` names the field with reason -`readonly`. A record created that way starts as if no value had been sent: `0` +create or update (over HTTP or stdio), a `PATCH` or a bulk update sends for it +is dropped, the rest of the write is stored, and the response's `droppedFields` +names the field with reason `readonly`. Two more doors end in the same create +and drop the value the same way: the `overrides` of a clone, whose answer names +the field in `droppedFields` as a create's does, and a public form submission, +which is anonymous and answers with the created record's id alone, so the +person who submitted it is not shown the drop. A record created with its value +dropped starts as if no value had been sent: `0` for `count` and `sum`, empty for `min`, `max` and `avg`, and the next child write replaces it with the computed value. Under `strictReadonlyWrites` the whole write is refused. Server code that runs with `isSystem: true` can still write the diff --git a/content/docs/protocol/objectql/security.mdx b/content/docs/protocol/objectql/security.mdx index c60d513127f..916959debb1 100644 --- a/content/docs/protocol/objectql/security.mdx +++ b/content/docs/protocol/objectql/security.mdx @@ -276,6 +276,19 @@ rejecting — the offending key is removed from the payload and the rest of the committed. The write therefore **succeeds** (REST answers `200`), and the read-only column simply keeps its stored value. +**A roll-up `summary` field carries this lock implicitly**, whether or not it declares +`readonly: true`: the engine computes its value from the child records, so it reads every +roll-up as `readonly: true` on create and on update. A value a non-system write sends for one +is dropped and reported under the same `readonly` reason, and `strictReadonlyWrites` refuses +the write, exactly as for a declared read-only column; a create that had the value dropped +starts the column as for an empty child list. That covers a flow's `create_record` and +`update_record` steps that do not run as `runAs: 'system'`; `os validate`, `os lint` and +`os build` report such a step as the `flow-update-summary-field` warning, which never blocks a +build, though like every warning it makes `os validate --strict` and `os lint --strict` exit 1 +(a roll-up declared `readonly: true` is the `flow-update-readonly-field` error). Rule 1 below +holds for it: seed data, package installs and the roll-up's own recompute write it from a +system context. See [Calculation types](/docs/data-modeling/fields#calculation-types). + Five rules decide whether a given value survives: | # | Rule | Effect | diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 3a11942b6b9..a3fe2cacbae 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -194,6 +194,7 @@ export { validateReadonlyFlowWrites, FLOW_UPDATE_READONLY_FIELD, FLOW_UPDATE_READONLY_WHEN_FIELD, + FLOW_UPDATE_SUMMARY_FIELD, } from './validate-readonly-flow-writes.js'; export type { ReadonlyFlowWriteFinding, diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 04851ba3e9d..4396381a250 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -1612,6 +1612,27 @@ const FLOW_UPDATE_READONLY_WHEN_FIELD_EXPLANATION: RuleExplanation = { ], }; +const FLOW_UPDATE_SUMMARY_FIELD_EXPLANATION: RuleExplanation = { + rule: 'flow-update-summary-field', + covers: 'why a roll-up summary field write is dropped', + paragraphs: [ + FLOW_FIELDS_CALLER_PAYLOAD, + 'A roll-up `summary` field is computed by the engine from its child records, so the engine treats it ' + + 'as `readonly: true` on create and on update whether or not the field declares it. A value a ' + + 'non-system write sends for it is dropped, the rest of the write lands, the step still reports ' + + 'success and the drop is reported as `readonly`; under `strictReadonlyWrites` the whole write is ' + + 'refused. A created record starts the column as if no child record existed: `0` for `count` and ' + + '`sum`, empty for `min`, `max` and `avg`.', + 'Reported as a warning, so it never blocks a build. A roll-up that declares `readonly: true` is ' + + 'reported as `flow-update-readonly-field` instead, which does. A `runAs: \'system\'` flow writes the ' + + 'column and is not reported, and neither is a create on a platform object, which the create-side ' + + 'strip does not judge.', + 'To fix it, remove the field from the node: the engine recomputes the value whenever a child record ' + + 'is created, changed or deleted. To change what it adds up, change the child records or the ' + + 'roll-up\'s `summaryOperations`.', + ], +}; + const HOOK_API_UPDATE_READONLY_FIELD_EXPLANATION: RuleExplanation = { rule: 'hook-api-update-readonly-field', covers: 'why a readonly field write is silently dropped', @@ -6469,6 +6490,7 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [FLOW_NODE_WRITE_UNPROVISIONED_ANCHOR_EXPLANATION.rule]: FLOW_NODE_WRITE_UNPROVISIONED_ANCHOR_EXPLANATION, [FLOW_UPDATE_READONLY_FIELD_EXPLANATION.rule]: FLOW_UPDATE_READONLY_FIELD_EXPLANATION, [FLOW_UPDATE_READONLY_WHEN_FIELD_EXPLANATION.rule]: FLOW_UPDATE_READONLY_WHEN_FIELD_EXPLANATION, + [FLOW_UPDATE_SUMMARY_FIELD_EXPLANATION.rule]: FLOW_UPDATE_SUMMARY_FIELD_EXPLANATION, [HOOK_API_UPDATE_READONLY_FIELD_EXPLANATION.rule]: HOOK_API_UPDATE_READONLY_FIELD_EXPLANATION, [HOOK_API_UPDATE_READONLY_WHEN_FIELD_EXPLANATION.rule]: HOOK_API_UPDATE_READONLY_WHEN_FIELD_EXPLANATION, [ACTION_API_UPDATE_READONLY_WHEN_FIELD_EXPLANATION.rule]: ACTION_API_UPDATE_READONLY_WHEN_FIELD_EXPLANATION, diff --git a/packages/lint/src/validate-readonly-flow-writes.test.ts b/packages/lint/src/validate-readonly-flow-writes.test.ts index f89ede985f4..c9fd3dc5243 100644 --- a/packages/lint/src/validate-readonly-flow-writes.test.ts +++ b/packages/lint/src/validate-readonly-flow-writes.test.ts @@ -5,6 +5,7 @@ import { validateReadonlyFlowWrites as validateReadonlyFlowWritesUnrecorded, FLOW_UPDATE_READONLY_FIELD, FLOW_UPDATE_READONLY_WHEN_FIELD, + FLOW_UPDATE_SUMMARY_FIELD, } from './validate-readonly-flow-writes.js'; import { explainRule } from './rule-explanations.js'; import { ObjectSchema } from '@objectstack/spec/data'; @@ -828,3 +829,97 @@ describe('[#22161] one-line fixes — the rule ids this file shortened', () => { for (const fact of MOVED_FROM_FIX[rule]) expect(text, `${rule} explanation names ${fact}`).toContain(fact); }); }); + +// [#35114] The implicit roll-up lock: the engine reads every `summary` field as +// `readonly: true` on create and on update, declared or not, so a non-system +// flow write of one is dropped. Reported at its own id as a WARNING (area +// ruling, claim amendment 7035408057, option B), never as the static id's +// ERROR, so a build that passed before keeps passing. +describe('validateReadonlyFlowWrites · a roll-up summary field without readonly: true', () => { + const accountObject = { + name: 'crm_account', + label: 'Account', + fields: { + name: { type: 'text' }, + // The card's shape: a roll-up with no `readonly`. + order_total: { type: 'summary', summaryOperations: { object: 'crm_order', field: 'amount', function: 'sum' } }, + // A roll-up its author did declare read-only: the static branch's. + order_count: { type: 'summary', readonly: true, summaryOperations: { object: 'crm_order', function: 'count' } }, + credit_status: { type: 'text', readonly: true }, + }, + }; + + /** A flow with one `nodeType` node writing `fields` on the account. */ + const flowWriting = (nodeType: 'create_record' | 'update_record', fields: Record, runAs?: string) => ({ + name: 'sync_account', + type: 'record_change', + ...(runAs ? { runAs } : {}), + nodes: [ + { id: 'start', type: 'start', config: {} }, + { + id: 'w', + type: nodeType, + label: 'Write account', + config: { + objectName: 'crm_account', + ...(nodeType === 'update_record' ? { filter: { id: { dialect: 'cel', source: 'recordId' } } } : {}), + fields, + }, + }, + ], + edges: [], + }); + + it.each(['create_record', 'update_record'] as const)('a %s writing the roll-up under a user run: one warning, at its own id', (nodeType) => { + const findings = validateReadonlyFlowWrites({ + objects: [accountObject], + flows: [flowWriting(nodeType, { name: 'Acme', order_total: 100 })], + }); + expect(findings).toHaveLength(1); + expect(findings[0]).toMatchObject({ + severity: 'warning', + rule: FLOW_UPDATE_SUMMARY_FIELD, + path: 'flows[0].nodes[1].config.fields.order_total', + where: 'flow "sync_account" › node "Write account"', + }); + expect(findings[0].message).toContain("roll-up summary field 'order_total' of object 'crm_account'"); + expect(findings[0].message).toContain('on create and update alike'); + expect(findings[0].message).not.toContain('\n'); + expect(findings[0].message.length).toBeLessThanOrEqual(200); + expect(findings[0].hint).toContain(nodeType); + expect(findings[0].hint.length).toBeLessThanOrEqual(200); + }); + + it('control: a declared readonly field, roll-up or not, is still the static id at error', () => { + const findings = validateReadonlyFlowWrites({ + objects: [accountObject], + flows: [flowWriting('update_record', { order_count: 3, credit_status: 'hold' }, 'user')], + }); + expect(findings.map((f) => [f.rule, f.severity, f.path])).toEqual([ + [FLOW_UPDATE_READONLY_FIELD, 'error', 'flows[0].nodes[1].config.fields.order_count'], + [FLOW_UPDATE_READONLY_FIELD, 'error', 'flows[0].nodes[1].config.fields.credit_status'], + ]); + }); + + it('control: a write to a field that is not a roll-up draws nothing', () => { + const findings = validateReadonlyFlowWrites({ + objects: [accountObject], + flows: [flowWriting('update_record', { name: 'Acme' }), flowWriting('create_record', { name: 'Acme' })], + }); + expect(findings).toEqual([]); + }); + + it.each(['create_record', 'update_record'] as const)('control: a runAs:system %s writing the roll-up draws nothing', (nodeType) => { + const findings = validateReadonlyFlowWrites({ + objects: [accountObject], + flows: [flowWriting(nodeType, { order_total: 100 }, 'system')], + }); + expect(findings).toEqual([]); + }); + + it('`os explain flow-update-summary-field` says the engine drops it on both verbs and that it never blocks a build', () => { + const text = explanationOf(FLOW_UPDATE_SUMMARY_FIELD); + expect(text).toContain('on create and on update'); + expect(text).toContain('never blocks a build'); + }); +}); diff --git a/packages/lint/src/validate-readonly-flow-writes.ts b/packages/lint/src/validate-readonly-flow-writes.ts index ab54fd47bb9..848807de9c7 100644 --- a/packages/lint/src/validate-readonly-flow-writes.ts +++ b/packages/lint/src/validate-readonly-flow-writes.ts @@ -59,6 +59,20 @@ // not land → WARNING (advisory). A templated object name or a non-literal // `fields` map is not statically knowable → skipped, no guess. // +// • A roll-up `summary` field WITHOUT `readonly: true` is read-only on both +// verbs all the same: the engine reads every roll-up as `readonly: true` in +// the create and the update strip (`withSummaryRollUpsReadonly`, objectql's +// `engine-top-level.ts`), so a non-system write of one is dropped exactly as +// a declared one is. Reported under its own id, `flow-update-summary-field`, +// as a WARNING by the area ruling on the card (claim amendment 7035408057, +// option B): a flow that writes a roll-up passed `os build` before the +// engine lock landed, and ERROR would refuse that build, a narrowing the +// ruling did not take. The branch is THIS rule's (`summaryFieldIndex`): the +// shared `buildReadonlyIndex` and the hook and action rules do not read it. +// A roll-up that also declares `readonly: true` is the static branch's, +// at ERROR, as before. Same gates as the static branch: `runAs:'system'` +// writes it, and a create on an insert-strip-exempt object is not judged. +// // A pure `(stack) => Finding[]` rule (ADR-0019): no I/O, no runtime. Shared by // the CLI and any other consumer (AI authoring), so hand-authored and generated // flows are held to the same bar. @@ -93,6 +107,12 @@ export interface ReadonlyFlowWriteFinding { // suppression, docs and counts in two. export const FLOW_UPDATE_READONLY_FIELD = 'flow-update-readonly-field'; export const FLOW_UPDATE_READONLY_WHEN_FIELD = 'flow-update-readonly-when-field'; +/** + * A non-system `create_record` / `update_record` write to a roll-up `summary` + * field that does not declare `readonly: true` (the header's last bullet). One + * id for both verbs, as the static id is. + */ +export const FLOW_UPDATE_SUMMARY_FIELD = 'flow-update-summary-field'; /** * [#22161] The clauses the three readonly write rules' one-line verdicts share @@ -266,6 +286,28 @@ export function buildInsertStripExemptObjects(objects: AnyRec[]): Set { return exempt; } +/** + * object name → the names of its roll-up `summary` fields, over the objects as + * served (the fold {@link buildServedReadonlyIndex} reads, tied fields left + * out). Flow-local on purpose: the engine reads a roll-up as read-only on both + * verbs whether or not it declares `readonly: true`, and only THIS rule reports + * that implicit lock, at its own id and severity; the shared readonly index + * keeps answering what the author declared. + */ +function summaryFieldIndex(stack: AnyRec): Map> { + const idx = new Map>(); + for (const obj of objectsWithoutTiedFields(objectsAsServed(stack))) { + const name = typeof obj.name === 'string' ? obj.name : undefined; + if (!name) continue; + const summaries = new Set(); + for (const field of recordsOf(obj.fields)) { + if (typeof field.name === 'string' && field.type === 'summary') summaries.add(field.name); + } + if (summaries.size > 0) idx.set(name, summaries); + } + return idx; +} + /** * The target object of an `update_record` / `create_record` node, when * statically knowable. Both node configs anchor the object on the same key @@ -300,6 +342,7 @@ export function validateReadonlyFlowWrites(stack: AnyRec): ReadonlyFlowWriteFind // and stays on the declared objects. const roIndex = buildServedReadonlyIndex(stack); const insertStripExempt = buildInsertStripExemptObjects(objects); + const summaryIndex = summaryFieldIndex(stack); flows.forEach((flow, flowIndex) => { // `runAs` defaults to 'user' (schema default). Only an explicit 'system' @@ -336,6 +379,8 @@ export function validateReadonlyFlowWrites(stack: AnyRec): ReadonlyFlowWriteFind // `buildInsertStripExemptObjects`); the update branch is not. if (isCreate && insertStripExempt.has(objectName)) return; + const summaryFields = summaryIndex.get(objectName); + const fields = config.fields; // A non-literal write map (templated string, spread, array) is not // statically knowable — skip rather than guess. @@ -394,6 +439,22 @@ export function validateReadonlyFlowWrites(stack: AnyRec): ReadonlyFlowWriteFind : `Declare the flow runAs:'system' if automation maintains '${fieldName}', or remove it from this ` + `update_record node`, }); + } else if (summaryFields?.has(fieldName) && !isSystemRun) { + // The implicit roll-up lock (header, last bullet): a certain drop on + // both verbs, reported as a warning by the area ruling. A roll-up + // declaring `readonly: true` took the static branch above instead. + findings.push({ + severity: 'warning', + rule: FLOW_UPDATE_SUMMARY_FIELD, + where, + path: `${nodePath}.config.fields.${fieldName}`, + message: + `writes roll-up summary field '${fieldName}' of object '${objectName}', which the engine computes and ` + + `drops from a runAs:'${runAs}' write on create and update alike`, + hint: + `Remove '${fieldName}' from this ${nodeType} node; the engine recomputes it whenever a child record ` + + `changes`, + }); } else if (meta.readonlyWhen && !isCreate) { // `!isCreate`: the conditional lock has no prior record to evaluate on // an insert and the engine does not run it there ("INSERT stays diff --git a/packages/mcp/src/stdio-data-bridge.dropped-fields.test.ts b/packages/mcp/src/stdio-data-bridge.dropped-fields.test.ts new file mode 100644 index 00000000000..46c686ef819 --- /dev/null +++ b/packages/mcp/src/stdio-data-bridge.dropped-fields.test.ts @@ -0,0 +1,241 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A create or update over the stdio MCP transport answers `droppedFields`, as + * the HTTP transport does (the protocol's `createData` / `updateData`), and + * never echoes a value the engine dropped. + * + * ## The reading this pins + * + * The stdio bridge called `engine.insert` / `engine.update` with no + * `onFieldsDropped` listener and built its answer from the caller's payload: + * `{ ...data, ...written }` on create, `{ ...existing, ...data }` on update. + * So a non-system write of a `readonly: true` column, or of a roll-up + * `summary` (read-only on both verbs whether or not it declares `readonly`), + * answered success with no `droppedFields`, and the record in the answer + * carried the caller's dropped value wherever the write result did not + * overwrite it. Measured on update: the answer carried `biggest: 99` and + * `locked: 'forged'` over the stored `5` and `'kept'`. On create the real + * engine's write result names every declared field (`null` where nothing was + * stored), so it overwrites the echo here; the create assertions hold the + * answer for any write result that leaves such a key out. + * + * ## What is real here + * + * The engine is a real `ObjectQL` (its strips, its roll-up seed, its + * listener), over a driver that keeps rows and returns the row it was handed. + * The bridge is the real stdio bridge, served through the runtime's HTTP face + * (the tools are one registration for both transports), so the answer read is + * the `create_record` / `update_record` tool answer a caller sees. Controls: a + * write that sends no locked key answers no `droppedFields`. + * + * Keys and values are asserted, never wording. + */ + +import { describe, it, expect } from 'vitest'; +import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; +import type { DroppedFieldsEvent } from '@objectstack/spec/data'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +// The lean engine entry, aliased to the source in this package's vitest config. +import { ObjectQL } from '@objectstack/objectql/core'; + +import { MCPServerRuntime } from './mcp-server-runtime.js'; +import { createStdioDataBridge } from './stdio-data-bridge.js'; +import type { McpDataBridge } from './mcp-http-tools.js'; + +type Row = Record; + +const ACCOUNT = 'dfx_acct'; +const ORDER = 'dfx_ord'; + +const account = { + name: ACCOUNT, + label: 'Account', + fields: { + id: { name: 'id', type: 'text' }, + name: { name: 'name', type: 'text' }, + // A declared read-only column with no default. + locked: { name: 'locked', type: 'text', readonly: true }, + // A roll-up with no `readonly` and no empty-set value (`max`). + biggest: { + name: 'biggest', + type: 'summary', + summaryOperations: { object: ORDER, field: 'amount', function: 'max' }, + }, + }, + enable: {}, +}; +const order = { + name: ORDER, + label: 'Order', + fields: { + id: { name: 'id', type: 'text' }, + amount: { name: 'amount', type: 'number' }, + acct: { name: 'acct', type: 'master_detail', reference: ACCOUNT }, + }, + enable: {}, +}; + +/** A driver that keeps rows and returns the row it was handed: flat equality and `$in` WHERE. */ +function rowDriver() { + const stores = new Map>(); + const storeFor = (o: string) => { + let s = stores.get(o); + if (!s) { s = new Map(); stores.set(o, s); } + return s; + }; + let nextId = 0; + const matches = (row: Row, where: any): boolean => { + if (!where || typeof where !== 'object') return true; + for (const [k, v] of Object.entries(where)) { + if (k === '$and') { + if (!(v as any[]).every((sub) => matches(row, sub))) return false; + continue; + } + if (k.startsWith('$')) continue; + if (v && typeof v === 'object' && Array.isArray((v as any).$in)) { + if (!(v as any).$in.some((x: unknown) => String(x) === String(row[k]))) return false; + continue; + } + const exp = v && typeof v === 'object' && '$eq' in (v as any) ? (v as any).$eq : v; + if ((row[k] ?? null) !== (exp ?? null)) return false; + } + return true; + }; + const driver: any = { + name: 'rows', + version: '0.0.0', + supports: {}, + rowOf: (o: string, id: string) => storeFor(o).get(id), + seed(o: string, row: Row) { storeFor(o).set(String(row.id), { ...row }); }, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, + async syncSchema() {}, + async find(o: string, ast: any) { + const rows = Array.from(storeFor(o).values()).filter((r) => matches(r, ast?.where)); + return (typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows).map((r) => ({ ...r })); + }, + async findOne(o: string, ast: any) { + for (const r of storeFor(o).values()) if (matches(r, ast?.where)) return { ...r }; + return null; + }, + async create(o: string, data: Row) { + nextId += 1; + const id = (data.id as string) ?? `e_${nextId}`; + const row = JSON.parse(JSON.stringify({ ...data, id })); + storeFor(o).set(id, row); + return { ...row }; + }, + async update(o: string, id: string, data: Row) { + const cur = storeFor(o).get(String(id)); + if (!cur) throw new Error(`not found ${o}/${id}`); + const up = { ...cur, ...data, id }; + storeFor(o).set(String(id), up); + return { ...up }; + }, + async delete(o: string, id: string) { return storeFor(o).delete(String(id)); }, + async count(o: string, ast: any) { return (await this.find(o, ast)).length; }, + }; + return driver; +} + +async function stack() { + const engine = new ObjectQL({ logger: { debug() {}, info() {}, warn() {}, error() {} } } as any); + const driver = rowDriver(); + engine.registerDriver(driver, true); + await engine.init(); + for (const o of [account, order]) engine.registry.registerObject(o as any, '__test__'); + driver.seed(ACCOUNT, { id: 'a1', name: 'Acme', locked: 'kept', biggest: 5 }); + const defs: Record = { [ACCOUNT]: account, [ORDER]: order }; + const bridge = createStdioDataBridge({ + engine: engine as unknown as IDataEngine, + metadataService: { + listObjects: async () => Object.values(defs), + getObject: async (name: string) => defs[name], + } as unknown as IMetadataService, + // A person: not the system principal, so both locks apply. + resolvePrincipal: async () => ({ userId: 'u1' }) as unknown as ExecutionContext, + }); + return { bridge, driver }; +} + +let rpcId = 1; +async function callTool(bridge: McpDataBridge, name: string, args: Record) { + const body = { jsonrpc: '2.0', id: rpcId++, method: 'tools/call', params: { name, arguments: args } }; + const runtime = new MCPServerRuntime({ name: 'pin', version: '0.0.0' }); + const res = await runtime.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: bridge as any, parsedBody: body }, + ); + expect(res.status).toBe(200); + const json = (await res.json()) as { result?: any; error?: unknown }; + expect(json.error, JSON.stringify(json.error)).toBeUndefined(); + const result = json.result as { content: Array<{ text: string }>; isError?: boolean }; + expect(result.isError, result.content[0]!.text).not.toBe(true); + return JSON.parse(result.content[0]!.text); +} + +/** The dropped field names of an answer, each with its reason, sorted. */ +const droppedOf = (answer: { droppedFields?: DroppedFieldsEvent[] }) => + (answer.droppedFields ?? []) + .flatMap((e) => e.fields.map((field) => `${e.object}.${field}:${e.reason}`)) + .sort(); + +describe('stdio MCP create_record / update_record answer droppedFields and echo no dropped value', () => { + it('create_record: a readonly column and a roll-up are dropped, named in droppedFields, and not echoed', async () => { + const { bridge, driver } = await stack(); + + const answer = await callTool(bridge, 'create_record', { + objectName: ACCOUNT, + data: { name: 'Globex', locked: 'forged', biggest: 77 }, + }); + + expect(droppedOf(answer)).toEqual([`${ACCOUNT}.biggest:readonly`, `${ACCOUNT}.locked:readonly`]); + expect(answer.record.name).toBe('Globex'); + expect(answer.record.locked ?? null).toBeNull(); + expect(answer.record.biggest ?? null).toBeNull(); + // The answer says what was stored. + const stored = driver.rowOf(ACCOUNT, answer.id); + expect(stored?.locked ?? null).toBeNull(); + expect(stored?.biggest ?? null).toBeNull(); + }); + + it('control: a create_record that sends no locked key answers no droppedFields', async () => { + const { bridge } = await stack(); + + const answer = await callTool(bridge, 'create_record', { objectName: ACCOUNT, data: { name: 'Initech' } }); + + expect(answer).not.toHaveProperty('droppedFields'); + expect(answer.record.name).toBe('Initech'); + }); + + it('update_record: a readonly column and a roll-up are dropped, named in droppedFields, and the stored values stand', async () => { + const { bridge, driver } = await stack(); + + const answer = await callTool(bridge, 'update_record', { + objectName: ACCOUNT, + recordId: 'a1', + data: { name: 'Acme Corp', locked: 'forged', biggest: 99 }, + }); + + expect(droppedOf(answer)).toEqual([`${ACCOUNT}.biggest:readonly`, `${ACCOUNT}.locked:readonly`]); + expect(answer.record).toMatchObject({ id: 'a1', name: 'Acme Corp', locked: 'kept', biggest: 5 }); + expect(driver.rowOf(ACCOUNT, 'a1')).toMatchObject({ name: 'Acme Corp', locked: 'kept', biggest: 5 }); + }); + + it('control: an update_record that sends no locked key answers no droppedFields', async () => { + const { bridge } = await stack(); + + const answer = await callTool(bridge, 'update_record', { + objectName: ACCOUNT, + recordId: 'a1', + data: { name: 'Acme Ltd' }, + }); + + expect(answer).not.toHaveProperty('droppedFields'); + expect(answer.record).toMatchObject({ id: 'a1', name: 'Acme Ltd', locked: 'kept', biggest: 5 }); + }); +}); diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index 5cf5d500c80..bd2c6d16c6d 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -66,7 +66,9 @@ * maintainer ruling of 2026-09-03 — option C, #14147 — the static `readonly` * strip runs inside `engine.insert` for every non-system caller and the * ingress copy is deleted, so on that point the two transports no longer - * differ.) None of those is the authorization boundary + * differ. The receipts' `droppedFields` member is answered here too, from the + * same engine listener that layer wires, on `create` and `update`.) None of + * those is the authorization boundary * — every call here still passes the engine's CRUD/FLS/RLS — but the two * transports should not differ at all, and unifying them behind one * transport-neutral data seam is filed as follow-up work rather than forked @@ -117,7 +119,7 @@ import { DATA_ACTION_TO_API_OPERATION, type EnableLike, } from '@objectstack/spec/data'; -import type { EngineDeleteOptions } from '@objectstack/spec/data'; +import type { DroppedFieldsEvent, EngineDeleteOptions } from '@objectstack/spec/data'; import type { ExecutionContext } from '@objectstack/spec/kernel'; // [#21207] The stored-metadata-body family's ONE projection and its object set, // from where every other surface of the family takes them (the data door, the @@ -1319,6 +1321,32 @@ function describedFieldNames(described: Record): string[] { : []; } +/** + * The caller's write payload without the keys the engine reported dropped + * (`onFieldsDropped`), for the `create` and `update` answers: a dropped key + * echoed from the payload would answer a value the write never stored. A + * `stored_expression` key is dropped here too; the write result carries the + * value the engine stored in its place. + */ +function withoutDroppedKeys( + data: Record, + dropped: readonly DroppedFieldsEvent[], +): Record { + if (dropped.length === 0) return data; + const out = { ...data }; + for (const event of dropped) for (const field of event.fields) delete out[field]; + return out; +} + +/** + * The `droppedFields` member of a write answer, as the protocol's `createData` + * and `updateData` answer it behind the HTTP bridge (`CreateDataResponseSchema`, + * `UpdateDataResponseSchema`): present only when the engine dropped a key. + */ +function droppedFieldsMember(dropped: DroppedFieldsEvent[]): { droppedFields?: DroppedFieldsEvent[] } { + return dropped.length > 0 ? { droppedFields: dropped } : {}; +} + /** * Build the stdio transport's principal-bound data bridge. * @@ -1594,13 +1622,24 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge // the `create_record` tool answers the create it is. let stale: SummaryRecomputeRefusal | undefined; let written: Record | undefined; + // The engine's verdict on the caller's keys it did not store (a + // `readonly` column, a roll-up `summary`, a formula…), answered as + // `droppedFields` through the listener the protocol's `createData` wires + // behind the HTTP bridge, so both transports say the same thing. + const dropped: DroppedFieldsEvent[] = []; try { - written = (await engine.insert(object, data, { context })) as Record | undefined; + written = (await engine.insert(object, data, { + context, + onFieldsDropped: (e: DroppedFieldsEvent) => { dropped.push(e); }, + })) as Record | undefined; } catch (e) { stale = staleSummaryRefusalOrThrow(e); written = stale.written as Record | undefined; } - const record = { ...data, ...(written ?? {}) }; + // The caller's payload fills keys the write result omits, minus every key + // the engine dropped: echoed, a dropped value would read as stored (a + // `readonly` column with no default, a `min` roll-up seeded empty). + const record = { ...withoutDroppedKeys(data, dropped), ...(written ?? {}) }; // [#8497] `written` is the engine's WRITE result, which since #7823 keeps // the stored row whole — flagged columns included. This is a generic data // mouth answering an external caller, so it owns the response-body half @@ -1611,7 +1650,7 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge // is absent for a package's boot-registered object on an `environmentId` // kernel, and with no schema the helper masks and omits nothing. omitInternalFieldsFromWriteResponse(await readObjectDeclaration(reads, object), record); - const answer = { object, id: record.id, record }; + const answer = { object, id: record.id, record, ...droppedFieldsMember(dropped) }; if (stale) throw withEarnedAnswer(stale, answer); return answer; }, @@ -1639,12 +1678,21 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge // attached to the refusal by #28781's carrier as `create` does; every // other throw, a refusal before the write among them, propagates as is. let stale: SummaryRecomputeRefusal | undefined; + // The engine's verdict on the patch keys it did not store, answered as + // `droppedFields` as the protocol's `updateData` answers it (see `create`). + const dropped: DroppedFieldsEvent[] = []; try { - await engine.update(object, data, { where: { id }, context }); + await engine.update(object, data, { + where: { id }, + context, + onFieldsDropped: (e: DroppedFieldsEvent) => { dropped.push(e); }, + }); } catch (e) { stale = staleSummaryRefusalOrThrow(e); } - const record = { ...(existing as Record), ...data }; + // The read-path row under the caller's patch, minus every key the engine + // dropped: the stored value of such a field is the one that stands. + const record = { ...(existing as Record), ...withoutDroppedKeys(data, dropped) }; // [#8497] The engine's update RESULT is deliberately discarded here (this // arm echoes the read-path row plus the caller's own patch), so no STORED // flagged value can reach this line. The strip still runs, for the one @@ -1655,7 +1703,7 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge // property literally true on every verb of this bridge rather than true- // by-argument on one. omitInternalFieldsFromWriteResponse(await readObjectDeclaration(reads, object), record); - const answer = { object, id, record }; + const answer = { object, id, record, ...droppedFieldsMember(dropped) }; if (stale) throw withEarnedAnswer(stale, answer); return answer; },