Skip to content

Commit f45c012

Browse files
fix(mcp): the stdio door answers get_record misses and describe_object readonly as the HTTP door does (#33175)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoAeJD7KJ2LnkshKXv2YBH8q)_ Fixes #33030 Fixes #33156 Clause-②: no Metadata-protocol: none File surface (claim, as amended at review): `packages/mcp/src/stdio-data-bridge.ts`, `packages/mcp/src/mcp-server-runtime.ts`, `packages/mcp/src/mcp-http-tools.ts` (the `get_record` branch only), `packages/runtime/src/domains/mcp.ts` (bridge member, and the `writeNeverSetsField` JSDoc's last sentence), their tests, root `.changeset/` (including `.changeset/32530-describe-object-readonly-computed.md`, one sentence). ## 维护者速读 - 改了什么:stdio 传输的 MCP 门现在和 HTTP `/mcp` 门回答一致。`get_record` 查不到记录(不存在或调用者无权看到)时回带编码的 `RECORD_NOT_FOUND` / 404,不再是一句无编码的文字;`describe_object` 和 `objectstack://objects/{name}` 资源对「表达式被字段遮蔽隐藏的存储计算字段」回 `readonly: true`。 - 为什么改:stdio 客户端按错误码分支,拿不到码就只能解析文字;`readonly: false` 会让代理去写一个引擎随后覆盖的字段,写了等于白写。 - 风险与回滚:只改 stdio 门的回答,使其等于 HTTP 门已有的回答;不放宽任何可读可写范围,隐藏的表达式和它引用的字段依然不下发。不存在与无权看到回同一个信封,不构成存在性探测。回滚 = revert 本 PR,不涉及数据。 - 先看:`packages/mcp/src/mcp-server-runtime.ts` 的 `readObjectWithDeclaration` 与 `describeServedObject(def, declared)`;`packages/mcp/src/stdio-data-bridge.ts` 的 `callerObjectView`(注册声明读取);`packages/mcp/src/mcp-http-tools.ts` 的 `get_record` 空结果分支。 - 两分钟验证:`pnpm --filter @objectstack/mcp exec vitest run --maxWorkers=2 src/stdio-data-bridge.not-found.test.ts src/stdio-data-bridge.object-schema-mask.test.ts`,预期 42/42 通过。 - 需要你做的:无,席位落地。 ## What changes - **`get_record` (#33030).** The stdio bridge's `get` answers a by-id miss with `null` by design, and the tool rendered that as `Record "ID" not found in "OBJECT"` with no code. The null branch now throws `recordNotFoundError(objectName, recordId)` (`@objectstack/core`, the repo's one not-found envelope) into the tool's own catch, which renders it through `dataDoorErrorResult`. That is the value the HTTP bridge's `get` throws (`protocol.getData` through `callData`) and the renderer its catch uses, so both doors render one throw through one renderer: `{ "error": { "code": "RECORD_NOT_FOUND", "message": "Record ID not found in OBJECT", "status": 404 } }`. A missing id and an id the row filter hides reach the tool as the same empty read and answer the same bytes (no existence oracle). `update_record` and `delete_record` were already coded; pinned here, unchanged. - **`describe_object` and the objects resource (#33156).** The stdio caller view (`callerObjectView`) now registers, beside the view it returns, a read that answers the served object AND the declaration it was projected from, from ONE read of the definition (`setDeclaredObjectRead`, package-internal, keyed weakly by the view like `setRuntimeObjectView`). `readObjectWithDeclaration(view, name)` asks it; a view that registered none masks nothing, so its object is its declaration. `describeServedObject(def, declared = def)` judges `readonly` with `writeNeverSetsField(declared.fields[key])`, exactly as the HTTP twin does, and builds every other member from the served object. The stdio bridge's `describeObject` and `buildObjectSchemaResource` both read through it; `plugin.ts` already wires the resource to `callerObjectView`, so it needed no change. - **Why this option of the card's two.** A second `objectView.getObject` read beside the masked one would read the definition twice, and the two reads could disagree mid-write; the registered read answers both halves from one read and serves nothing extra. Only `writeNeverSetsField`'s boolean is read off the declaration: the expression and the field it names stay out of the answer (pinned, and ablated). ## Tests - `packages/mcp/src/stdio-data-bridge.not-found.test.ts`, new top-level describe on the file's existing engine double (its `find` made row-filtering, so no new double enters the `check:engine-double-contract` ledger): over the long-lived server `start()` attaches stdio to, the real `createStdioDataBridge`: - a missing id answers `isError` and the coded envelope; - a hidden id (a row only its owner reads) answers the same envelope, and the read ran as the caller; - CONTROL: the owner is served that row; - PARITY: for both ids, the stdio `tools/call` result equals, deep-equal, the HTTP `/mcp` result from `handleHttpRequest` (real Streamable HTTP transport) over a bridge whose `get` throws `recordNotFoundError`, the value `mcp-coded-refusal.test.ts` pins as the HTTP face's answer; - `update_record` and `delete_record` on both ids answer the same envelope. - `packages/mcp/src/stdio-data-bridge.object-schema-mask.test.ts`, new top-level describe with the HTTP twin's fixture (`marked_up` is a stored expression over `hidden_cost`, which the member may not read): - precondition: the member's served object carries `marked_up` without its expression and no `hidden_cost`; - stdio `describe_object` and the resource (wired as `plugin.ts` wires it: `callerObjectView` over `stdioObjectView`) answer the full readonly map, `marked_up: true`, with no `hidden_cost` token and no `record.` expression text anywhere, and no `expression` member on `marked_up`; - the tool and the resource answer the same fields. - `packages/runtime/src/domains/mcp-object-schema-mask.test.ts`: a PARITY case on the existing real-layer harness (real `ObjectQL` over `SqlDriver`, real `SecurityPlugin`, the real `/mcp` entry) holding the same readonly map for the same member over the authored fields. Neither package depends on the other (the reason the two `describeServedObject` twins exist), so the doors' parity is that one literal, pinned on each side. ## Acceptance notes - **Deviation from the order's wording, declared.** The order names `errorResultWithCode` for the null branch. The PR throws into the catch, which renders through `dataDoorErrorResult`, the renderer the HTTP door's own throw takes. For `RECORD_NOT_FOUND` the two produce the same bytes today (`mcp-coded-refusal.test.ts` pins both shapes); the catch path keeps them equal if the `/data` door ever adds a member (`declaredCode`, `userMessage`) to this code. - **DELIBERATE CORRECTION of a pending release note.** `.changeset/32530-describe-object-readonly-computed.md` (pending, landed with PR #33150) described the stdio door and the objects resource as judging the served field, which this PR makes false. Its two sentences "On the HTTP transport, `readonly` is judged on the field as declared, … 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." now read: "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." `check-empty-changeset.mjs --base origin/main` is red on that file by design (DELIBERATE CORRECTION class); confirmation is the seat's record. - **The HTTP twin's JSDoc.** `writeNeverSetsField`'s last sentence in `packages/runtime/src/domains/mcp.ts` said the stdio twin "has only the masked object to ask"; it now says the stdio bridge and the resource ask the declared field too (`readObjectWithDeclaration`). Prose only. - **Same class, outside the cards: the record resource.** `objectstack://objects/{name}/records/{id}` on a miss answers `{"error":"Record \"ghost\" not found in \"task\""}` with no `code` / `status` (measured over the long-lived server at this head), while its two sibling resources answer `{ error, code, status }` and its own catch already adds them for a thrown coded refusal (`mcp-server-runtime.ts`, `bridgeResources`, `record_by_id`). Reported to the seat as a finding; not fixed here. - **Skills-docs: not owed** (`Metadata-protocol: none`, no narrowing arm); `skill-md.ts` restates neither the not-found wording nor `readonly`. - **Serial.** `#33150` merged before the #33156 half started (`28a2f0f5`, merged into this branch once); `protocol-stdout.ts` and `cli/src/commands/serve.ts` (#33159) untouched. ## Verification All readings at head `59ccee50` (base `28a2f0f5`) unless named. Head `532a02e5` adds only the two prose edits above; its re-run gates are in the last block. <details><summary>Measured at origin/main first (both premises hold)</summary> - #33030, the new pins over the unfixed `get_record` (`47f6c939`): 3 failed | 5 passed. Missing id: `content[0].text` = `Record "ghost" not found in "task"` (not JSON); hidden id: `Record "secret1" not found in "task"`; PARITY: HTTP answered `{"error":{"code":"RECORD_NOT_FOUND","message":"Record ghost not found in task","status":404}}`. `update_record` / `delete_record` already passed (coded). - #33156, the new pins at `28a2f0f5` (after #33150): 2 failed | 32 passed; both doors served `"marked_up": false`, every other field matching. </details> <details><summary>Package tests and typecheck</summary> - `pnpm --filter @objectstack/mcp test` (at `c1b63360`; `59ccee50` only re-shapes the not-found test's double) — Test Files 64 passed (64), Tests 1148 passed (1148), `VERDICT command-exit 0` - `stdio-data-bridge.not-found.test.ts` at `59ccee50` — Tests 8 passed (8) - `mcp-object-schema-mask.test.ts` (runtime) — Tests 73 passed (73) - `pnpm --filter @objectstack/mcp typecheck` and `pnpm --filter @objectstack/runtime typecheck` — exit 0, each including `check:test-typecheck` over `tsconfig.test.json` - The runtime package's only change is that one test file; its full suite is declared to CI. </details> <details><summary>Ablations (4, all red, all restored)</summary> Every leg through `scripts/ablation-replace.mjs` (anchor x1 → x0, blob changed, restored blob == HEAD, `git diff HEAD` empty). The suites import the source, so no `dist/` leg. - `get_record` null branch back to the bare `errorResult` sentence → 3 failed (missing, hidden, PARITY). - `describeServedObject` judging the served field (`writeNeverSetsField(f)`) → 2 failed (tool and resource). - `setDeclaredObjectRead` registration deleted → 2 failed (tool and resource). - stdio `describeObject` building the answer from the DECLARATION → 9 failed, the new "neither its expression nor hidden_cost is served" case and the case-table masking pins among them. </details> <details><summary>Derived gates and lint</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`: 66 families, each run with stdin closed, exit code recorded before any pipe. `--ran` at `59ccee50`: **66 accounted, 65 run, 1 NOT-MEASURED**. - `pnpm check:dual-build-cjs-loads` — exit 3, PREREQUISITE NOT MET (needs `dist/` of packages outside this diff's closure). NOT MEASURED; CI runs it. - `node scripts/check-plugin-teardown-shape.mjs --self-test` first exited 3 (pinned positive control absent from the shallow clone); after fetching `621a4876`, exit 0, 48 cases. - `pnpm check:engine-double-contract` first exited 1 (a second double in the not-found file); the test now reuses the file's one double, exit 0. - The gates that read test files were re-run at `59ccee50`, exit 0. All other families exit 0. - `pnpm check:type-check-debt` — exit 0. `pnpm lint` — exit 0. No export renamed or removed. - At `532a02e5` (the two prose edits), the families that read those files, re-run: `check-adr-0087-registration` (`--base`, `--self-test`), `check-changeset-no-major`, `check:changeset-gate-self-tests`, `check-closing-keyword-parity`, `check:doc-authoring`, `check:nul-bytes`, `check:issue-citations` and its script, `check:adr-symbol-anchors`, both comment-mask gates, both docs-audit scripts, `check:closed-ceremony-text`, `check:keyed-text-bounds`, `check:dispatcher-error-vocabulary`, `check:route-envelope`, and `eslint packages/runtime/src/domains/mcp.ts` — exit 0. `check-empty-changeset.mjs --base origin/main` — exit 1, the DELIBERATE CORRECTION refusal above, expected. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibvhQvy8SbR3j9f7kcb)_ <!-- signed: epic:#32897#1 · os-tesla · session_01L9qibvhQvy8SbR3j9f7kcb --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 16e3486 commit f45c012

10 files changed

Lines changed: 429 additions & 28 deletions

‎.changeset/32530-describe-object-readonly-computed.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,6 @@ fix(mcp,runtime): `describe_object` serves `readonly: true` where a write never
88
Clause-②: yes (widening)
99
Metadata-protocol: none
1010

11-
`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`.
11+
`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`.
1212

1313
`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.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/mcp': patch
3+
---
4+
5+
fix(mcp): stdio `get_record` answers a missing or hidden id with the coded `RECORD_NOT_FOUND`
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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 "<id>" not found in "<object>"` 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 <id> not found in <object>", "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.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/mcp': patch
3+
---
4+
5+
fix(mcp): stdio `describe_object` and the objects resource judge `readonly` on the declared field
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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.

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

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,9 @@ import { AggregationNodeSchema } from '@objectstack/spec/data';
5252
// [#23529] The catalogue's spelling of `PERMISSION_DENIED`, the code whose
5353
// `details` `errorResultFromThrown` withholds. Imported, never hand-spelled.
5454
import { StandardErrorCode, type ErrorCode } from '@objectstack/spec/api';
55+
// The repo's ONE not-found envelope, which the HTTP bridge's `get` throws:
56+
// `get_record` refuses a null read with it, so both doors answer one 404.
57+
import { recordNotFoundError } from '@objectstack/core';
5558
// [#23701] The one key every door that translates the engine's unique-violation
5659
// envelope asks (the registered code AND the class name, never message text),
5760
// and the one classification whose arm states the wire code for it.
@@ -2801,7 +2804,14 @@ export function registerObjectTools(
28012804
if (bad) return errorResult(bad);
28022805
try {
28032806
const record = await bridge.get(objectName, recordId);
2804-
if (record == null) return errorResult(`Record "${recordId}" not found in "${objectName}"`);
2807+
// A bridge that answers a miss with `null` (the stdio bridge, by
2808+
// design) is refused with the repo's ONE not-found envelope, thrown
2809+
// into the catch below: the HTTP bridge's `get` throws that same
2810+
// value (`protocol.getData`, through `callData`), so both doors
2811+
// render one throw through one renderer and answer one coded
2812+
// `RECORD_NOT_FOUND` / 404. A missing id and an id the caller may not
2813+
// read reach here as the same empty read, so they answer alike.
2814+
if (record == null) throw recordNotFoundError(objectName, recordId);
28052815
return textResult(record);
28062816
} catch (err) {
28072817
return dataDoorErrorResult(err, 'get_record', objectName);

‎packages/mcp/src/mcp-server-runtime.ts‎

Lines changed: 61 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -127,13 +127,16 @@ interface ServedFieldDef {
127127
* One projection for this package's two readers of it: the stdio bridge's
128128
* `describeObject` (`stdio-data-bridge.ts`) and the `objectstack://objects/{name}`
129129
* resource ({@link buildObjectSchemaResource}), each handing it the object as
130-
* the caller is served it, so the two answer alike (#25245). The HTTP bridge's
130+
* the caller is served it, so the two answer alike (#25245), and the
131+
* declaration that object was projected from ({@link readObjectWithDeclaration}):
132+
* `readonly` is judged on the declared field, {@link writeNeverSetsField}, and
133+
* nothing else is read from it. The HTTP bridge's
131134
* twin is `describeServedObject` in `packages/runtime/src/domains/mcp.ts`
132135
* (`@objectstack/runtime` does not depend on this package): the transports
133136
* answer one shape, and the `describe_object` description (`mcp-http-tools.ts`)
134137
* states it.
135138
*/
136-
export function describeServedObject(def: ServedObjectDef): Record<string, unknown> {
139+
export function describeServedObject(def: ServedObjectDef, declared: ServedObjectDef = def): Record<string, unknown> {
137140
return {
138141
name: def.name,
139142
label: def.label ?? def.name,
@@ -142,7 +145,12 @@ export function describeServedObject(def: ServedObjectDef): Record<string, unkno
142145
type: f?.type,
143146
label: f?.label ?? key,
144147
required: f?.required ?? false,
145-
readonly: writeNeverSetsField(f),
148+
// Judged on the DECLARED field, never the served one: the caller's mask
149+
// deletes a readable field's `expression` when it names a field they
150+
// cannot read, and the engine still computes the field. Only the boolean
151+
// is read there; the served definition, without that expression, is
152+
// what the answer is built from.
153+
readonly: writeNeverSetsField(declared.fields?.[key]),
146154
system: f?.system === true,
147155
...(declaresOptions(f) ? { options: describedOptions(f.options as unknown[]) } : {}),
148156
...(f?.defaultValue !== undefined ? { defaultValue: f.defaultValue } : {}),
@@ -171,12 +179,10 @@ export function describeServedObject(def: ServedObjectDef): Record<string, unkno
171179
* at the field-level write gate. The served object carries the read projection
172180
* only, and the `describe_object` description says so.
173181
*
174-
* ⚠️ Asked of the object as the caller is SERVED it, the only object this
175-
* package's two readers hand over: the caller's mask deletes a readable
176-
* field's `expression` when it names a field the caller cannot read, so for
177-
* that caller the expression arm does not hold and the field is served
178-
* `readonly: false` while the engine still computes it. The HTTP twin asks
179-
* the declared field instead (the bridge holds the declaration it masks).
182+
* Asked of the DECLARED field ({@link describeServedObject}'s `declared`),
183+
* as the HTTP twin asks it: the caller's mask deletes an `expression` that
184+
* names a field the caller cannot read, while the engine still computes the
185+
* column from it, so the served field alone would answer `readonly: false`.
180186
*
181187
* The twin is `writeNeverSetsField` in `packages/runtime/src/domains/mcp.ts`.
182188
*/
@@ -1243,6 +1249,47 @@ export type McpObjectView = Pick<IMetadataService, 'listObjects' | 'getObject'>;
12431249
*/
12441250
const runtimeObjectViews = new WeakMap<MCPServerRuntime, McpObjectView>();
12451251

1252+
/** One object as a view serves it, beside the declaration it was projected from. */
1253+
export interface ObjectWithDeclaration {
1254+
served: unknown;
1255+
declared: unknown;
1256+
}
1257+
1258+
/**
1259+
* The read a MASKING view ({@link setDeclaredObjectRead}) answers both halves
1260+
* of {@link ObjectWithDeclaration} with, from one read of the definition it
1261+
* masks. Keyed weakly by the view, so a view and its read are collected
1262+
* together; package-internal, like {@link setRuntimeObjectView}.
1263+
*/
1264+
const declaredObjectReads = new WeakMap<McpObjectView, (name: string) => Promise<ObjectWithDeclaration>>();
1265+
1266+
/**
1267+
* Register `read` as the declared-object read of `view`, a view that serves a
1268+
* caller a projection of each definition (the stdio caller view,
1269+
* `callerObjectView` in `stdio-data-bridge.ts`). Package-internal; not
1270+
* re-exported from `index.ts`.
1271+
*/
1272+
export function setDeclaredObjectRead(view: McpObjectView, read: (name: string) => Promise<ObjectWithDeclaration>): void {
1273+
declaredObjectReads.set(view, read);
1274+
}
1275+
1276+
/**
1277+
* `name` as `view` serves it, and the declaration it was projected from: what
1278+
* {@link describeServedObject} needs to judge `readonly` on the declared field
1279+
* while serving only the projection. A view that registered no declared read
1280+
* masks nothing, so the object it serves IS the declaration.
1281+
*
1282+
* ⛔ The declaration never leaves this package's two describe readers: only
1283+
* {@link writeNeverSetsField}'s boolean is read off it, so nothing the caller's
1284+
* mask withholds (an expression naming a field they cannot read) is served.
1285+
*/
1286+
export async function readObjectWithDeclaration(view: McpObjectView, name: string): Promise<ObjectWithDeclaration> {
1287+
const read = declaredObjectReads.get(view);
1288+
if (read) return read(name);
1289+
const def = await view.getObject(name);
1290+
return { served: def, declared: def };
1291+
}
1292+
12461293
/**
12471294
* [#31605] The long-lived server's principal: the `OS_MCP_STDIO_API_KEY`
12481295
* identity the plugin resolves per call (ADR-0101), bound by the plugin once
@@ -1324,9 +1371,12 @@ export async function buildObjectSchemaResource(
13241371
// refuses a schema whose field visibility it could not evaluate) answers
13251372
// in this resource's `{ error, code, status }` vocabulary
13261373
// ({@link objectResourceRefusal}); an uncoded throw travels, as before.
1374+
// …beside the declaration it was projected from, for `readonly` alone
1375+
// ({@link readObjectWithDeclaration}).
13271376
let objectDef: unknown;
1377+
let declared: unknown;
13281378
try {
1329-
objectDef = await objects.getObject(objectName);
1379+
({ served: objectDef, declared } = await readObjectWithDeclaration(objects, objectName));
13301380
} catch (err) {
13311381
const refusal = objectResourceRefusal(err);
13321382
if (refusal) return body(refusal);
@@ -1361,7 +1411,7 @@ export async function buildObjectSchemaResource(
13611411
contents: [{
13621412
uri,
13631413
mimeType: 'application/json',
1364-
text: JSON.stringify(describeServedObject(objectDef as ServedObjectDef), null, 2),
1414+
text: JSON.stringify(describeServedObject(objectDef as ServedObjectDef, declared as ServedObjectDef), null, 2),
13651415
}],
13661416
};
13671417
}

‎packages/mcp/src/stdio-data-bridge.not-found.test.ts‎

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,14 @@
2020
*/
2121

2222
import { describe, it, expect, vi } from 'vitest';
23+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
24+
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
25+
import { recordNotFoundError } from '@objectstack/core';
2326
import type { ExecutionContext } from '@objectstack/spec/kernel';
2427
import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts';
2528
import { createStdioDataBridge } from './stdio-data-bridge.js';
29+
import { MCPServerRuntime } from './mcp-server-runtime.js';
30+
import type { McpDataBridge } from './mcp-http-tools.js';
2631
import { assertEngineFindOnePredicate, type EngineFindOneQueryInput } from '@objectstack/metadata-core';
2732

2833
/** An engine that resolves NO row for any id — every by-id write is a miss. */
@@ -124,3 +129,148 @@ describe('#8422 stdio bridge by-id writes throw the shared not-found envelope',
124129
expect(updateErr?.code).toBe('RECORD_NOT_FOUND');
125130
});
126131
});
132+
133+
// ---------------------------------------------------------------------------
134+
// The tool door: `get_record` over the long-lived server stdio attaches
135+
// ---------------------------------------------------------------------------
136+
137+
/**
138+
* One row, `secret1`, that only its owner reads: the engine double answers the
139+
* row to `owner` and nothing to anyone else, which is what the security
140+
* middleware's row filter does to a by-id read the caller may not see. So for
141+
* {@link PRINCIPAL} `secret1` is HIDDEN and `ghost` is MISSING, and the two
142+
* reach the bridge as the same empty read.
143+
*/
144+
function makeRowFilteringEngine() {
145+
const row = { id: 'secret1', title: 'owner only' };
146+
const visibleTo = (opts?: { context?: { userId?: string } }) => opts?.context?.userId === 'owner';
147+
// The file's one engine double, with its by-id read made row-filtering.
148+
const engine = makeEmptyEngine();
149+
const find = vi.fn(async (_object: string, query?: { where?: { id?: unknown } }, opts?: { context?: { userId?: string } }) =>
150+
query?.where?.id === row.id && visibleTo(opts) ? [row] : []);
151+
return Object.assign(engine, { find });
152+
}
153+
154+
function stdioBridgeAs(principal: ExecutionContext) {
155+
const engine = makeRowFilteringEngine();
156+
const bridge = createStdioDataBridge({
157+
engine: engine as unknown as IDataEngine,
158+
metadataService: makeMetadata() as unknown as IMetadataService,
159+
resolvePrincipal: async () => principal,
160+
});
161+
return { bridge, engine };
162+
}
163+
164+
/** A `tools/call` on the long-lived server (`runtime.server`, the one `start()` attaches stdio to). */
165+
async function callOnLongLivedServer(bridge: McpDataBridge, name: string, args: Record<string, unknown>) {
166+
const runtime = new MCPServerRuntime({ name: 'pin', version: '0.0.0' });
167+
runtime.bridgeDataTools(bridge);
168+
const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
169+
await runtime.server.connect(serverSide);
170+
const client = new Client({ name: 'pin', version: '0.0.0' });
171+
await client.connect(clientSide);
172+
try {
173+
return await client.callTool({ name, arguments: args });
174+
} finally {
175+
await client.close();
176+
}
177+
}
178+
179+
/**
180+
* The HTTP `/mcp` door's answer to the same call: its bridge's `get` reaches
181+
* `protocol.getData` through `callData`, which throws `recordNotFoundError`
182+
* for an id that names no row the caller may read (pinned as the HTTP face's
183+
* answer in `mcp-coded-refusal.test.ts`). Driven through `handleHttpRequest`,
184+
* the real Streamable HTTP transport, so the two answers compared below come
185+
* from the two doors' own tool registrations.
186+
*/
187+
async function getRecordOverHttp(objectName: string, recordId: string) {
188+
const bridge: McpDataBridge = {
189+
async listObjects() { return [{ name: 'task', label: 'Task', fieldCount: 0 }]; },
190+
async describeObject() { return null; },
191+
async query(object) { return { object, records: [], total: 0 }; },
192+
async get(object, id) { throw recordNotFoundError(object, id); },
193+
async create(object, data) { return { object, id: 'n1', record: data }; },
194+
async update(object, id, data) { return { object, id, record: data }; },
195+
async remove(object, id) { return { object, id, success: true }; },
196+
};
197+
const body = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'get_record', arguments: { objectName, recordId } } };
198+
const res = await new MCPServerRuntime({ name: 'pin', version: '0.0.0' }).handleHttpRequest(
199+
new Request('http://localhost/api/v1/mcp', {
200+
method: 'POST',
201+
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
202+
body: JSON.stringify(body),
203+
}),
204+
{ bridge, parsedBody: body },
205+
);
206+
expect(res.status).toBe(200);
207+
return ((await res.json()) as { result: unknown }).result;
208+
}
209+
210+
/** The coded envelope `get_record` answers a miss with, as both doors put it on the wire. */
211+
function notFoundWire(object: string, id: string) {
212+
return { error: { code: 'RECORD_NOT_FOUND', message: `Record ${id} not found in ${object}`, status: 404 } };
213+
}
214+
215+
describe('stdio get_record answers a missing or hidden id with the coded RECORD_NOT_FOUND / 404', () => {
216+
it('a MISSING id: isError, and the text is the coded envelope, not a bare sentence', async () => {
217+
const { bridge } = stdioBridgeAs(PRINCIPAL);
218+
const result = (await callOnLongLivedServer(bridge, 'get_record', { objectName: 'task', recordId: 'ghost' })) as {
219+
isError?: boolean;
220+
content: Array<{ text: string }>;
221+
};
222+
expect(result.isError).toBe(true);
223+
expect(JSON.parse(result.content[0]!.text)).toEqual(notFoundWire('task', 'ghost'));
224+
});
225+
226+
it('a HIDDEN id answers the same envelope as a missing one: no existence oracle', async () => {
227+
const { bridge, engine } = stdioBridgeAs(PRINCIPAL);
228+
const hidden = (await callOnLongLivedServer(bridge, 'get_record', { objectName: 'task', recordId: 'secret1' })) as {
229+
isError?: boolean;
230+
content: Array<{ text: string }>;
231+
};
232+
expect(hidden.isError).toBe(true);
233+
expect(JSON.parse(hidden.content[0]!.text)).toEqual(notFoundWire('task', 'secret1'));
234+
// The read ran as the caller, so the row filter is what hid it.
235+
expect(engine.find).toHaveBeenCalledWith('task', expect.objectContaining({ where: { id: 'secret1' } }), { context: PRINCIPAL });
236+
});
237+
238+
it('CONTROL: the hidden row is served to its owner, so the refusal above is the row filter, not a missing row', async () => {
239+
const { bridge } = stdioBridgeAs({ userId: 'owner', isSystem: false } as unknown as ExecutionContext);
240+
const served = (await callOnLongLivedServer(bridge, 'get_record', { objectName: 'task', recordId: 'secret1' })) as {
241+
isError?: boolean;
242+
content: Array<{ text: string }>;
243+
};
244+
expect(served.isError).toBeFalsy();
245+
expect(JSON.parse(served.content[0]!.text)).toEqual({ id: 'secret1', title: 'owner only' });
246+
});
247+
248+
it('PARITY: the stdio answer equals the HTTP /mcp answer for the same call, byte for byte', async () => {
249+
for (const recordId of ['ghost', 'secret1']) {
250+
const { bridge } = stdioBridgeAs(PRINCIPAL);
251+
const overStdio = await callOnLongLivedServer(bridge, 'get_record', { objectName: 'task', recordId });
252+
const overHttp = await getRecordOverHttp('task', recordId);
253+
expect(overStdio, `get_record ${recordId}`).toEqual(overHttp);
254+
}
255+
});
256+
257+
it('update_record and delete_record on the same ids answer the same coded envelope (already coded, held here)', async () => {
258+
for (const recordId of ['ghost', 'secret1']) {
259+
const { bridge } = stdioBridgeAs(PRINCIPAL);
260+
const updated = (await callOnLongLivedServer(bridge, 'update_record', {
261+
objectName: 'task',
262+
recordId,
263+
data: { title: 'x' },
264+
})) as { isError?: boolean; content: Array<{ text: string }> };
265+
expect(updated.isError).toBe(true);
266+
expect(JSON.parse(updated.content[0]!.text)).toEqual(notFoundWire('task', recordId));
267+
const deleted = (await callOnLongLivedServer(bridge, 'delete_record', {
268+
objectName: 'task',
269+
recordId,
270+
confirm: true,
271+
})) as { isError?: boolean; content: Array<{ text: string }> };
272+
expect(deleted.isError).toBe(true);
273+
expect(JSON.parse(deleted.content[0]!.text)).toEqual(notFoundWire('task', recordId));
274+
}
275+
});
276+
});

0 commit comments

Comments
 (0)