Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
MCP reads refuse a misspelled scope or filter parameter instead of ignoring it
garrytan30b1871b34c8
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 84bfba7fe0..1fec859971 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -48,6 +48,7 @@ import {findInvalidParam,schemaInvalidParams,findUnknownParams,+ narrowingUnknownParams,resolveStrictParamsMode,} from './validate-params.ts';import { backupCheckDisabled, backupNagGate, backupNoticeText, loadBackupStatus } from '../core/backup/status-file.ts';@@ -1179,7 +1180,9 @@ async function dispatchResolvedCall(const unknownParamWarnings = findUnknownParams(op, safeParams);if (unknownParamWarnings.length > 0) {const strictMode = op.mutating === true ? 'reject' : await resolveStrictParamsMode(engine, opts.config ?? loadConfig());- if (strictMode === 'reject') {+ // GBRA-431: a misspelled scope or filter on a read would answer unnarrowed, so it rejects in every mode.+ const narrowing = strictMode === 'reject' ? [] : narrowingUnknownParams(unknownParamWarnings);+ if (strictMode === 'reject' || narrowing.length > 0) {logVerb(false);// Privacy (amendment 11): the raw unknown key rides `suggestion` ONLY.// serve-http persists the envelope's `message` into@@ -1192,7 +1195,7 @@ async function dispatchResolvedCall(: `Unknown parameter "${w.param}".`).join(' ') + (op.callShape ? ` ${op.callShape}` : '');const strict = new OperationError('invalid_params',- `${n} unknown parameter${n === 1 ? '' : 's'} not declared in the ${name} tool schema (${op.mutating === true ? 'write operations always reject unknown parameters; nothing was written' : 'mcp.strict_params=reject'}). See suggestion for the submitted name${n === 1 ? '' : 's'}.`,+ `${n} unknown parameter${n === 1 ? '' : 's'} not declared in the ${name} tool schema (${op.mutating === true ? 'write operations always reject unknown parameters; nothing was written' : narrowing.length > 0 ? 'a read rejects an unknown scope or filter parameter, which would otherwise return unnarrowed results; nothing was read' : 'mcp.strict_params=reject'}). See suggestion for the submitted name${n === 1 ? '' : 's'}.`,suggestion);if (isVerb) strict.protocolVersion = MEMORY_VERBS_VERSION;return errorResult(strict, opts, { op: name });diff --git a/src/mcp/validate-params.ts b/src/mcp/validate-params.tsindex 8a1ca17d86..5922eba6ab 100644--- a/src/mcp/validate-params.ts+++ b/src/mcp/validate-params.ts@@ -195,6 +195,9 @@ const PARAM_ALIAS_HINTS: Readonly<Record<string, Readonly<Record<string, string>remember: { facts: 'items', text: 'fact' },};+/** GBRA-431: source-scope spellings edit distance ties or misses (`sources` is as near `source_id` as `source_ids`). */+const SOURCE_PARAM_ALIASES: Readonly<Record<string, string>> = { source: 'source_id', sourceid: 'source_id', sources: 'source_ids', sourceids: 'source_ids' };+/*** `_meta.warnings` entry shape (amendment 13) — documented in* docs/protocol/MCP_META_CHANNELS.md. `suggestion` is the nearest DECLARED@@ -226,13 +229,29 @@ export function findUnknownParams(op: Operation, params: Record<string, unknown>const warnings: UnknownParamWarning[] = [];for (const key of Object.keys(params)) {if (declaredSet.has(key) || UNKNOWN_PARAM_ALLOWLIST.has(key)) continue;- const alias = aliases?.[key];+ const alias = aliases?.[key] ?? SOURCE_PARAM_ALIASES[key.toLowerCase().replace(/[^a-z]/g, '')];const nearest = alias && declaredSet.has(alias) ? alias : suggestNearest(key, declared);warnings.push({ code: 'unknown_param', param: key, ...(nearest ? { suggestion: nearest } : {}) });}return warnings;}+/** A parameter name that narrows a read's result: a source scope or a type, tag, entity, date, trust or visibility filter. */+const NARROWING_PARAM_RE = /^(sources?(id|ids|name|names)?|types?|kinds?|tags?|entity|entities|since|until|after|before|mintrust|visibility)$/;++function isNarrowingName(name: string): boolean {+ return NARROWING_PARAM_RE.test(name.toLowerCase().replace(/[^a-z]/g, ''));+}++/**+ * GBRA-431: the unknown keys a read must refuse whatever `mcp.strict_params` says, because ignoring them answers+ * unnarrowed: a key whose own name, or whose nearest declared param, is a scope or filter (`source` for+ * `source_id`, `sources` for `source_ids`, `type` for `types`). Other unknown keys keep the warn grace period.+ */+export function narrowingUnknownParams(warnings: readonly UnknownParamWarning[]): UnknownParamWarning[] {+ return warnings.filter(w => isNarrowingName(w.param) || (w.suggestion !== undefined && isNarrowingName(w.suggestion)));+}+/*** The warn-mode notice lines (one per unknown key) hosts before GST-900 appended* as an extra content block. Dispatch no longer sends it (the warning lives indiff --git a/test/validate-params.test.ts b/test/validate-params.test.tsindex 7e2e2f7650..2f7c1d79dd 100644--- a/test/validate-params.test.ts+++ b/test/validate-params.test.ts@@ -27,6 +27,7 @@ import {resetStrictParamsModeCache,parseStrictParamsMode,UNKNOWN_PARAM_ALLOWLIST,+ narrowingUnknownParams,} from '../src/mcp/validate-params.ts';import { operations, operationsByName } from '../src/core/operations.ts';import type { BrainEngine } from '../src/core/engine.ts';@@ -482,3 +483,56 @@ describe('write operations reject unknown parameters even in warn mode (#5970)',expect(writes).not.toContain('search');});});++// ---------------------------------------------------------------------------+// GBRA-431 — a read rejects a misspelled scope or filter in every mode+// ---------------------------------------------------------------------------++describe('a read rejects an unknown scope or filter parameter even in warn mode (GBRA-431)', () => {+ const ops = ['search', 'query', 'list_pages'].map(name => operations.find(o => o.name === name)!);++ async function withCountedHandlers(fn: (calls: () => number) => Promise<void>) {+ const originals = ops.map(op => op.handler);+ let handlerCalls = 0;+ for (const op of ops) op.handler = async () => { handlerCalls += 1; return { results: [] }; };+ try { await fn(() => handlerCalls); } finally { ops.forEach((op, i) => { op.handler = originals[i]; }); }+ }++ test('a misspelled source or type filter answers invalid_params naming the declared param, before any read runs', async () => {+ await withCountedHandlers(async calls => {+ for (const [op, params, param, suggestion] of [+ ['search', { query: 'roadmap', source: 'source-a' }, 'source', 'source_id'],+ ['search', { query: 'roadmap', sources: ['source-a'] }, 'sources', 'source_ids'],+ ['search', { query: 'roadmap', sourceId: 'source-a' }, 'sourceId', 'source_id'],+ ['query', { query: 'roadmap', source: 'source-a' }, 'source', 'source_id'],+ ['query', { query: 'roadmap', type: 'meeting' }, 'type', 'types'],+ ['list_pages', { source: 'source-a' }, 'source', 'source_id'],+ ] as const) {+ for (const mode of ['warn', null] as const) {+ const out = await dispatchToolCall(stubEngine(mode), op, { ...params }, DISPATCH_OPTS);+ const env = body(out);+ expect({ op, param, mode, isError: out.isError, code: env.code, suggestion: env.suggestion })+ .toEqual({ op, param, mode, isError: true, code: 'invalid_params', suggestion: expect.stringContaining(`Unknown parameter "${param}" — did you mean "${suggestion}"?`) });+ expect(env.message).not.toContain(param + '"');+ }+ }+ expect(calls()).toBe(0);+ });+ });++ test('an unknown parameter that narrows nothing keeps the warn grace period', async () => {+ await withCountedHandlers(async calls => {+ const out = await dispatchToolCall(stubEngine('warn'), 'search', { query: 'roadmap', limt: 3 }, DISPATCH_OPTS);+ expect(out.isError ?? false).toBe(false);+ expect(calls()).toBe(1);+ });+ });++ test('narrowingUnknownParams picks scope and filter names, by the key or by its nearest declared param', () => {+ expect(narrowingUnknownParams([+ { code: 'unknown_param', param: 'source' }, { code: 'unknown_param', param: 'Source-IDs' },+ { code: 'unknown_param', param: 'srcid', suggestion: 'source_id' }, { code: 'unknown_param', param: 'tag' },+ { code: 'unknown_param', param: 'limt', suggestion: 'limit' }, { code: 'unknown_param', param: 'partal', suggestion: 'partial' },+ ]).map(w => w.param)).toEqual(['source', 'Source-IDs', 'srcid', 'tag']);+ });+});