Skip to content

Commit 615c67f

Browse files
fix(mcp): validate_expression keeps the hidden __search companion out of scope (#33451)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9D4Jsmd91BqTVB7dSii9uJMV)_ Fixes #33338 Clause-②: yes (widening) — `@objectstack/spec/data` gains the `SEARCH_COMPANION_FIELD` constant; `@objectstack/objectql` re-exports the same value it exported before. Metadata-protocol: none ## 维护者速读 - 改了什么:MCP 工具 `validate_expression` 不再在 `inScope.fields` 里列出隐藏的 `__search` 搜索伴生列;表达式里读它(如 `record.__search`)现在按 `unknown-field` 拒收,与 `os validate` 的判定一致。 - 为什么改:这一列对调用方不可见(所有读路径都会剥掉它),但 AI 读到列表后会写出引用它的表达式,工具答 ok 而发布门禁拒收,工具和门禁两套答案。 - 第二版(复审后 CI 超时):第一版在首次调用时加载整个引擎包只为读一个字段名,测试里首次调用超过 5 秒。现在字段名放进 `@objectstack/spec/data`(`SEARCH_COMPANION_FIELD`),引擎和 MCP 都读这一个常量,MCP 不再在运行时依赖引擎。首次调用从 5.4 秒降到 60 毫秒。 - 风险与回滚:spec 新增一个导出常量(patch:不改元数据协议),引擎照旧以同名导出;其他字段照旧;回滚即撤销本 PR。 - 先看:`packages/spec/src/data/search-fields.ts`(新常量)、`packages/mcp/src/mcp-http-tools.ts`(跳过伴生列)、`packages/objectql/src/search-companion.ts`(改为转出)。 - 需要你做的:无,区内复审后落地。 ## What changes - `validate_expression` built its field list from the object as the caller is served it. Where pinyin search is on, that object carries the hidden `__search` companion beside the declared fields, so the tool listed `__search` in `inScope.fields` and answered `ok: true` for `record.__search != ''`. `os validate` judges an expression against the declared and injected columns only, so the same rule fails there with `unknown-field`, and every record read strips the column. - The tool now skips the companion when it builds the field list it judges and lists. Only `__search` is removed: other hidden system columns (`organization_id`, `owning_business_unit_id`, `queue`) are injected columns an expression may read, and `os validate` accepts them. Both transports share this handler. - **Where the name lives (second revision).** The first revision imported `SEARCH_COMPANION_FIELD` from `@objectstack/objectql` lazily on the first call. Under the test source alias that first call transformed the engine barrel and outran vitest's 5 s budget (`Test Core (7/8)`: `mcp-validate-expression.option-labels.test.ts` › LIT, reproduced locally at 5433 ms; the lean `/core` entry still took about 2 s, and 3.3 s under load). The name now lives in the protocol as `SEARCH_COMPANION_FIELD` in `@objectstack/spec/data`, next to the search-field resolution that already documents the companion. `@objectstack/objectql` provisions and strips the column under that constant and re-exports it unchanged, and `@objectstack/mcp` imports it statically from the spec. mcp's dependency on the engine becomes a devDependency (the pin provisions the companion with the engine's own `provisionSearchCompanion`). One name, no engine load for a string. ## Tests - New top-level describe in `packages/mcp/src/mcp-validate-expression.test.ts`, served by the real producers (`applyInjectedSystemColumns`, `provisionSearchCompanion`, `describeServedObject`): the served object carries the companion; `inScope.fields` lists `name`, `email`, `created_at` and not `__search`; a read of `__search` is refused `unknown-field` at the validation, formula and flow_condition sites, as `validateStackExpressions` refuses it. Pre-fix red and the ablation of the filter line are recorded in the first revision (2 of 3 red). - The timeout: the LIT case ran 5433 ms (red) on the first revision and 60 ms at the final head. ## Verification <details><summary>Local runs at the final head (after merging origin/main)</summary> - `@objectstack/mcp`: vitest 64/64 files, 1177/1177 tests; typecheck OK. `@objectstack/spec` `src/data`: 169/169 files, 6230 passed, 1 todo. `@objectstack/objectql` search suites: 11/11 files, 205/205 tests. - `dispatch-gates.mjs --commands`: 104 families derived and run, exit codes recorded. All exit 0 after `gen:api-surface` and `gen:export-origins` were committed and spec was rebuilt, except `check:generated`, exit 1, whose only remaining item is `test-typecheck-debt.json`. That is a directional ratchet this diff does not touch (no spec test changes; the file last changed on main 2026-11-13), and the gate itself says not to regenerate it unless `check:test-typecheck` asks. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_016WV4cw787kMeaX7oyz7DDC <!-- signed: domain:server#5 · os-elon-musk · session_016WV4cw787kMeaX7oyz7DDC --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent ccf2899 commit 615c67f

10 files changed

Lines changed: 122 additions & 7 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/mcp': patch
3+
'@objectstack/spec': patch
4+
'@objectstack/objectql': patch
5+
---
6+
7+
fix(mcp): `validate_expression` no longer lists the hidden `__search` search companion in `inScope.fields`, and a read of it is refused as `os validate` refuses it
8+
9+
Clause-②: yes (widening) — `@objectstack/spec/data` gains the `SEARCH_COMPANION_FIELD` constant (`'__search'`); `@objectstack/objectql` re-exports the same value it exported before.
10+
Metadata-protocol: none
11+
12+
Where pinyin search is on, the object an MCP caller is served carries the hidden `__search` companion column beside its declared fields. `validate_expression` took its field list from that object, so it named `__search` in `inScope.fields` and answered `ok` for an expression such as `record.__search != ''`. Every record read strips that column, and `os validate` judges an expression against the declared and injected columns only, so the same rule failed there with `unknown-field`.
13+
14+
The tool now leaves the companion out of the fields it judges and lists. Every other field, injected system columns such as `organization_id` among them, is listed and judged as before.
15+
16+
The companion's name now lives in the protocol, as `SEARCH_COMPANION_FIELD` in `@objectstack/spec/data`, so a layer that only needs the name does not have to load the engine to read it. `@objectstack/objectql` provisions and strips the column under that same constant and still exports it under the same name, so engine callers change nothing. `@objectstack/mcp` reads it from the spec and gains no runtime dependency on the engine.

‎packages/mcp/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
"zod": "^4.6.6"
3939
},
4040
"devDependencies": {
41+
"@objectstack/objectql": "workspace:*",
4142
"@types/node": "^26.6.5",
4243
"typescript": "^6.0.3",
4344
"vitest": "^4.1.11"

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ import type { EngineAggregateOptions } from '@objectstack/spec/data';
4848
// entry IS this node, so this door and the REST query door (which parses
4949
// `FindDataRequestSchema`, whose `aggregations` are this node) judge one shape
5050
// with one refusal.
51-
import { AggregationNodeSchema } from '@objectstack/spec/data';
51+
import { AggregationNodeSchema, SEARCH_COMPANION_FIELD } 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';
@@ -2632,8 +2632,16 @@ export function registerObjectTools(
26322632
const fieldDefs = Array.isArray(def.fields) ? (def.fields as Array<Record<string, unknown>>) : [];
26332633
const fields: string[] = [];
26342634
const fieldTypes: Record<string, string> = {};
2635+
// The hidden search companion is served beside the declared fields
2636+
// (the registry stamps it where pinyin search is on), but no
2637+
// expression may read it: every read strips it, and `os validate`
2638+
// judges against the declared and injected columns, which never
2639+
// include it. Left in, it is listed in `inScope.fields` and a read
2640+
// of it answers ok here while the gate refuses it. The name is the
2641+
// protocol's one constant, the same one the engine provisions under.
26352642
for (const f of fieldDefs) {
26362643
if (typeof f?.name !== 'string') continue;
2644+
if (f.name === SEARCH_COMPANION_FIELD) continue;
26372645
fields.push(f.name);
26382646
if (typeof f?.type === 'string') fieldTypes[f.name] = f.type;
26392647
}

‎packages/mcp/src/mcp-validate-expression.test.ts‎

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,9 @@ import {
1616
} from '@objectstack/lint';
1717

1818
import { applyInjectedSystemColumns } from '@objectstack/metadata-core';
19+
import { provisionSearchCompanion, SEARCH_COMPANION_FIELD } from '@objectstack/objectql/core';
1920

20-
import { MCPServerRuntime } from './mcp-server-runtime.js';
21+
import { MCPServerRuntime, describeServedObject } from './mcp-server-runtime.js';
2122
import type { McpDataBridge } from './mcp-http-tools.js';
2223

2324
/**
@@ -919,3 +920,61 @@ describe('validate_expression judges the field being authored at the formula sit
919920
expect((json as { result: { isError?: boolean } }).result.isError).toBe(true);
920921
});
921922
});
923+
924+
describe('validate_expression keeps the hidden search companion out of scope', () => {
925+
// A field-scoped search object as the registry serves it with pinyin search
926+
// on: the companion stamped beside the declared fields, then projected the
927+
// way the transports project it.
928+
const authored = {
929+
name: 'sc_contact',
930+
label: 'Contact',
931+
fields: {
932+
name: { type: 'text', label: 'Name', required: true },
933+
email: { type: 'email', label: 'Email' },
934+
},
935+
};
936+
const served = provisionSearchCompanion(applyInjectedSystemColumns(authored));
937+
const bridge = (): McpDataBridge => ({
938+
...makeBridge(),
939+
async listObjects() {
940+
return [{ name: 'sc_contact', label: 'Contact', fieldCount: Object.keys(served.fields).length }];
941+
},
942+
async describeObject(name: string) {
943+
return name === 'sc_contact' ? describeServedObject(served as never) : null;
944+
},
945+
});
946+
947+
let runtime: MCPServerRuntime;
948+
beforeEach(() => {
949+
runtime = new MCPServerRuntime({ name: 'objectstack-test', version: '9.9.9' });
950+
});
951+
952+
it('the served object really carries the companion (precondition)', () => {
953+
expect(Object.keys(served.fields)).toContain(SEARCH_COMPANION_FIELD);
954+
});
955+
956+
it('inScope.fields lists the ordinary fields and no companion', async () => {
957+
const r = await validate(runtime, bridge(), { objectName: 'sc_contact', expression: "record.name != ''", site: 'validation' });
958+
expect(r.ok).toBe(true);
959+
expect(r.inScope.fields).toContain('name');
960+
expect(r.inScope.fields).toContain('email');
961+
expect(r.inScope.fields).toContain('created_at');
962+
expect(r.inScope.fields).not.toContain(SEARCH_COMPANION_FIELD);
963+
});
964+
965+
it('a read of the companion is refused as a field the object does not have, as os validate refuses it', async () => {
966+
const expression = `record.${SEARCH_COMPANION_FIELD} != ''`;
967+
const gate = validateStackExpressions({
968+
objects: [{ ...authored, validations: [{ name: AUTHORED_RULE_NAME, type: 'script', condition: expression, message: 'm' }] }],
969+
}).filter((i) => i.where.includes(`'${AUTHORED_RULE_NAME}'`));
970+
expect(gate.map((i) => i.severity ?? 'error')).toEqual(['error']);
971+
expect(gate[0]!.message).toContain(SEARCH_COMPANION_FIELD);
972+
973+
for (const site of ['validation', 'formula', 'flow_condition'] as const) {
974+
const r = await validate(runtime, bridge(), { objectName: 'sc_contact', expression, site });
975+
expect(r.ok, site).toBe(false);
976+
const refused = r.errors.filter((e: { code?: string }) => e.code === 'unknown-field');
977+
expect(refused.map((e: { params?: { field?: string } }) => e.params?.field), site).toEqual([SEARCH_COMPANION_FIELD]);
978+
}
979+
});
980+
});

‎packages/mcp/vitest.config.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,10 +57,18 @@ export default defineConfig({
5757
// which drives the stdio exit through the shared ADR-0106 case table: the
5858
// table is a VALUE import too, and judging this transport against a stale
5959
// build of it would be the same silent wrong-tree verdict.
60+
//
61+
// The `@objectstack/objectql/core` entry (the lean engine entry, ADR-0076)
62+
// is for `mcp-validate-expression.test.ts`, which provisions the search
63+
// companion with the engine's own `provisionSearchCompanion` and reads its
64+
// name from `SEARCH_COMPANION_FIELD`: VALUE imports, judged against the
65+
// source in the checkout, not a build of it. Only the test loads the
66+
// engine; the tool reads the name from `@objectstack/spec/data`.
6067
alias: [
6168
{ find: /^@objectstack\/metadata-core$/, replacement: path.resolve(__dirname, '../metadata-core/src/index.ts') },
6269
{ find: /^@objectstack\/metadata-core\/testing$/, replacement: path.resolve(__dirname, '../metadata-core/src/testing.ts') },
6370
{ find: /^@objectstack\/lint$/, replacement: path.resolve(__dirname, '../lint/src/index.ts') },
71+
{ find: /^@objectstack\/objectql\/core$/, replacement: path.resolve(__dirname, '../objectql/src/core.ts') },
6472
],
6573
},
6674
});

‎packages/objectql/src/search-companion.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,16 +40,17 @@
4040
* the same column.
4141
*/
4242

43-
import { resolveDisplayField, TITLE_ELIGIBLE_TYPES } from '@objectstack/spec/data';
43+
import { resolveDisplayField, SEARCH_COMPANION_FIELD, TITLE_ELIGIBLE_TYPES } from '@objectstack/spec/data';
4444
import { SystemFieldName } from '@objectstack/spec/system';
4545
import { isFederatedObject } from './federated-object.js';
4646

4747
/**
48-
* Name of the hidden companion column. Double-underscore prefixed so it can
49-
* never collide with an author-declared field (machine names are snake_case
50-
* words) and reads as platform plumbing in raw rows.
48+
* Name of the hidden companion column. The name is the protocol's
49+
* (`@objectstack/spec/data`), re-exported here so engine callers keep
50+
* importing it from the engine; see the declaration there for why it lives in
51+
* the spec.
5152
*/
52-
export const SEARCH_COMPANION_FIELD = '__search';
53+
export { SEARCH_COMPANION_FIELD };
5354

5455
/**
5556
* Normalizers applied to the companion column. Generalization seam: pinyin is

‎packages/spec/api-surface/data.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -728,6 +728,7 @@
728728
"SEARCHABLE_TEXTUAL_TYPES (const)",
729729
"SEARCH_AUTO_EXCLUDED_FIELDS (const)",
730730
"SEARCH_AUTO_EXCLUDED_TYPES (const)",
731+
"SEARCH_COMPANION_FIELD (const)",
731732
"SEARCH_FLAG_EXCLUDED_TYPES (const)",
732733
"SEARCH_VIRTUAL_TYPES (const)",
733734
"SECRET_MASK (const)",

‎packages/spec/export-origins/data.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -716,6 +716,7 @@
716716
"SEARCHABLE_TEXTUAL_TYPES": "src/data/search-fields.ts#SEARCHABLE_TEXTUAL_TYPES (const)",
717717
"SEARCH_AUTO_EXCLUDED_FIELDS": "src/data/search-fields.ts#SEARCH_AUTO_EXCLUDED_FIELDS (const)",
718718
"SEARCH_AUTO_EXCLUDED_TYPES": "src/data/search-fields.ts#SEARCH_AUTO_EXCLUDED_TYPES (const)",
719+
"SEARCH_COMPANION_FIELD": "src/data/search-fields.ts#SEARCH_COMPANION_FIELD (const)",
719720
"SEARCH_FLAG_EXCLUDED_TYPES": "src/data/search-fields.ts#SEARCH_FLAG_EXCLUDED_TYPES (const)",
720721
"SEARCH_VIRTUAL_TYPES": "src/data/search-fields.ts#SEARCH_VIRTUAL_TYPES (const)",
721722
"SECRET_MASK": "src/data/secret-mask.ts#SECRET_MASK (const)",

‎packages/spec/src/data/search-fields.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,3 +359,20 @@ export function resolveSearchFields(opts: SearchFieldResolutionOptions): string[
359359
}
360360
return allowed;
361361
}
362+
363+
/**
364+
* Name of the hidden search companion column (#2486): the lowercase,
365+
* normalised copy of an object's searchable text that the engine provisions
366+
* where pinyin search is on, and the one extra `$contains` clause above scans.
367+
* It is platform plumbing: every record read strips it, `resolveSearchFields`
368+
* never returns it, and no expression may read it.
369+
*
370+
* ONE name for every layer that must recognise the column: the engine
371+
* (`@objectstack/objectql` provisions and strips it under this name and
372+
* re-exports it) and the MCP `validate_expression` tool (which leaves it out
373+
* of the fields an expression may name). It lives here, not in the engine, so
374+
* a layer that only needs the name does not have to load the engine to read it.
375+
* Double-underscore prefixed so it can never collide with an author-declared
376+
* field (machine names are snake_case words).
377+
*/
378+
export const SEARCH_COMPANION_FIELD = '__search';

‎pnpm-lock.yaml‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)