Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/27411-mcp-validate-blank-expression.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@objectstack/mcp': patch
---

fix(mcp): `validate_expression` refuses a blank or whitespace-only expression with the save gate's verdict

Clause-②: no
Metadata-protocol: none

The `validate_expression` MCP tool used to answer `ok: true` for an empty or whitespace-only expression, while saving that same expression is refused with `422 INVALID_METADATA` ("An expression in an evaluated slot needs a non-blank `source` …"). An agent that validated first and then saved was told the expression was fine.

The tool now parses the expression with the same spec input schema the save/build gate uses for the slot (`EvaluatedExpressionInputSchema` for the `formula`, `validation` and `flow_condition` sites, `TemplateExpressionInputSchema` for the `template` site) before it runs the formula checks. When that schema refuses, the tool answers `ok: false` with that schema's own issue: the `code` is the schema's issue code and the `message` is the published sentence (`EVALUATED_EXPRESSION_SOURCE_REQUIRED`, or `TYPED_EXPRESSION_SOURCE_REQUIRED.template` for a template). The fields and functions in scope still come back. A non-blank expression gets the same answer as before.
47 changes: 39 additions & 8 deletions packages/mcp/src/mcp-http-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ import {
// the `packages/spec` campaign standardised on — already carried in
// `api-surface/shared.json`, so reusing it adds nothing to any public surface.
import { strictUnknownKeyError } from '@objectstack/spec/shared';
// [#27411] The input schemas the save/build gate parses an expression slot
// with. `validate_expression` parses with the SAME schema before it runs the
// formula checks, so a blank source gets the gate's verdict and its published
// sentence, never a second blank rule written here.
import { EvaluatedExpressionInputSchema, TemplateExpressionInputSchema } from '@objectstack/spec/shared';
import {
METADATA_UNAVAILABLE_CODE,
metadataPartialListingSentence,
Expand Down Expand Up @@ -481,12 +486,22 @@ function jsonText(value: unknown): string {
* whose fields are flattened to top level; a `template` is a text template.
* Exposing a single friendly `site` keeps the tool aligned with how an author
* thinks about *where* the expression goes.
*
* `slot` is the spec input schema the save/build gate parses that site's slot
* with: an evaluated CEL slot (`EvaluatedExpressionInputSchema` — the formula
* `expression`, validation and flow-edge conditions) or a `{{ }}` template slot
* (`TemplateExpressionInputSchema`). The tool parses with it first, so whatever
* the gate refuses at the envelope level — today a source that is blank after
* trimming — the tool refuses too, with the gate's own issue.
*/
const VALIDATE_SITE_MAP: Record<string, { role: FieldRole; scope: 'record' | 'flattened' }> = {
formula: { role: 'value', scope: 'record' },
validation: { role: 'predicate', scope: 'record' },
flow_condition: { role: 'predicate', scope: 'flattened' },
template: { role: 'template', scope: 'record' },
const VALIDATE_SITE_MAP: Record<
string,
{ role: FieldRole; scope: 'record' | 'flattened'; slot: z.ZodType }
> = {
formula: { role: 'value', scope: 'record', slot: EvaluatedExpressionInputSchema },
validation: { role: 'predicate', scope: 'record', slot: EvaluatedExpressionInputSchema },
flow_condition: { role: 'predicate', scope: 'flattened', slot: EvaluatedExpressionInputSchema },
template: { role: 'template', scope: 'record', slot: TemplateExpressionInputSchema },
};

// ── Tool arguments: an undeclared key is REFUSED, not stripped (#16913) ──────
Expand Down Expand Up @@ -828,11 +843,27 @@ export function registerObjectTools(
fields.push(f.name);
if (typeof f?.type === 'string') fieldTypes[f.name] = f.type;
}
const { role, scope } = VALIDATE_SITE_MAP[site ?? 'formula'];
const { role, scope, slot } = VALIDATE_SITE_MAP[site ?? 'formula'];
const hint = { objectName, fields, fieldTypes, scope } as const;
const result = validateExpression(role, expression, hint);
// The gate's envelope verdict first: `validateExpression` treats a
// blank source as "not authored" and answers ok, while the save gate
// refuses it. Each issue is the spec schema's own (code and message),
// so the tool and the gate cannot drift apart on this rule.
const slotParse = slot.safeParse(expression);
const result = slotParse.success
? validateExpression(role, expression, hint)
: {
ok: false,
errors: slotParse.error.issues.map((issue) => ({
source: expression,
message: issue.message,
code: issue.code,
})),
warnings: [],
};
const inScope = introspectScope(role, hint);
const inferredType = role === 'value' ? inferExpressionType(expression, hint) : undefined;
const inferredType =
slotParse.success && role === 'value' ? inferExpressionType(expression, hint) : undefined;
return textResult({
ok: result.ok,
errors: result.errors,
Expand Down
49 changes: 49 additions & 0 deletions packages/mcp/src/mcp-validate-expression.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

import { describe, it, expect, beforeEach } from 'vitest';

import {
EVALUATED_EXPRESSION_SOURCE_REQUIRED,
TYPED_EXPRESSION_SOURCE_REQUIRED,
} from '@objectstack/spec/shared';

import { MCPServerRuntime } from './mcp-server-runtime.js';
import type { McpDataBridge } from './mcp-http-tools.js';

Expand Down Expand Up @@ -117,6 +122,50 @@ describe('validate_expression MCP tool (#1928)', () => {
expect(json.result.content[0].text).toMatch(/not found/i);
});

// A blank source is refused by the save/build gate (the spec's evaluated-slot
// and template-slot input schemas). The tool's verdict must be that gate's:
// ok:false, the schema's own issue code, and its published sentence.
describe('a blank or whitespace-only expression gets the save gate verdict', () => {
for (const expression of ['', ' ', '\t\n ']) {
for (const site of ['formula', 'validation', 'flow_condition'] as const) {
it(`refuses ${JSON.stringify(expression)} at site ${site}`, async () => {
const r = await validate(runtime, bridge, { objectName: 'crm_opportunity', expression, site });
expect(r.ok).toBe(false);
expect(r.errors).toHaveLength(1);
expect(r.errors[0].code).toBe('invalid_union');
expect(r.errors[0].message).toBe(EVALUATED_EXPRESSION_SOURCE_REQUIRED);
expect(r.warnings).toHaveLength(0);
expect(r.inferredType).toBeUndefined();
// The scope context still comes back, so the agent can self-correct.
expect(r.inScope.fields).toContain('amount');
});
}
it(`refuses ${JSON.stringify(expression)} at site template with the template sentence`, async () => {
const r = await validate(runtime, bridge, { objectName: 'crm_opportunity', expression, site: 'template' });
expect(r.ok).toBe(false);
expect(r.errors).toHaveLength(1);
expect(r.errors[0].code).toBe('invalid_union');
expect(r.errors[0].message).toBe(TYPED_EXPRESSION_SOURCE_REQUIRED.template);
});
}

it('defaults to the formula site when none is given', async () => {
const r = await validate(runtime, bridge, { objectName: 'crm_opportunity', expression: '' });
expect(r.ok).toBe(false);
expect(r.errors[0].message).toBe(EVALUATED_EXPRESSION_SOURCE_REQUIRED);
});

it('keeps the verdict of a non-blank control expression unchanged', async () => {
const r = await validate(runtime, bridge, { objectName: 'crm_opportunity', expression: ' record.amount / 100 ', site: 'formula' });
expect(r.ok).toBe(true);
expect(r.errors).toHaveLength(0);
expect(r.inferredType).toBeDefined();
const t = await validate(runtime, bridge, { objectName: 'crm_opportunity', expression: 'Hi {{ record.title }}', site: 'template' });
expect(t.ok).toBe(true);
expect(t.errors).toHaveLength(0);
});
});

it('refuses system objects (fail-closed guard)', async () => {
const { json } = await call(runtime, toolsCall(1, 'validate_expression', { objectName: 'sys_user', expression: 'record.x > 1' }), bridge);
expect(json.result.isError).toBe(true);
Expand Down
Loading