Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(mcp): B3 schema invalid_params hints; B5 one scope-denial envelope with the exact gbrain auth command; rate_limited contract for the /token 429

garrytan8d3fd642d745
diff --git a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
index 108622e556..43f2d0906f 100644
--- a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
+++ b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
@@ -163,4 +163,4 @@ src/core/skillpack/brain-resident-locate.ts 12
src/core/skillpack/shared-brain-bridge.ts 7
src/core/skillpack/writer-guard.ts 1
src/core/source-local-reference-index.ts 2
-src/mcp/dispatch.ts 2
+src/mcp/dispatch.ts 1
diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.ts
index bbb0e5dea0..8db20b25ee 100644
--- a/src/commands/serve-http-mcp.ts
+++ b/src/commands/serve-http-mcp.ts
@@ -23,7 +23,7 @@ import { hasScope, operationScopesAllowed } from '../core/scope.ts';
import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult, acceptedPendingReceipt, unknownToolEnvelope, errorResult, dispatchRenderContext, type ToolResult } from '../mcp/dispatch.ts';
import { toAgentError } from '../core/agent-output.ts';
import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';
-import { opError } from '../core/ops/contract.ts';
+import { scopeDeniedError } from '../core/ops/op-fix.ts';
import { resolveStrictParamsMode } from '../mcp/validate-params.ts';
import { buildToolDefs } from '../mcp/tool-defs.ts';
import {
@@ -481,8 +481,7 @@ async function rejectInsufficientMcpScope(
error: { code: 'insufficient_scope', message: `requires '${requiredScope}'` },
timestamp: new Date().toISOString(),
});
- const denial = opError('insufficient_scope', `Operation ${name} requires '${requiredScope}' scope`,
- `Ask the brain host's operator to grant the '${requiredScope}' scope to this client, then reconnect.`);
+ const denial = scopeDeniedError({ op: name, required: [requiredScope], auth: authInfo, transport: 'http' });
const envelope = toAgentError(denial, { transport: 'http', op: name, render: dispatchRenderContext({ remote: true, transport: 'http', auth: authInfo }) });
return { content: [{ type: 'text', text: JSON.stringify({ ...envelope, your_scopes: authInfo.scopes }) }], isError: true };
}
diff --git a/src/core/agent-output.ts b/src/core/agent-output.ts
index d459bc6773..3599944dd7 100644
--- a/src/core/agent-output.ts
+++ b/src/core/agent-output.ts
@@ -427,6 +427,7 @@ type Row = { match: (e: unknown) => boolean; map: (e: any, ctx: AgentErrorContex
/** RemoteMcpError transport reasons (no server envelope) → registry codes. */
const REMOTE_REASON_CODE: Record<string, string> = {
config: 'config_error', discovery: 'unavailable', auth: 'invalid_token', auth_after_refresh: 'invalid_token',
+ rate_limited: 'rate_limited', token: 'unavailable',
'network:timeout': 'timeout', 'network:aborted': 'interrupted', parse: 'internal_error',
};
diff --git a/src/core/mcp-client.ts b/src/core/mcp-client.ts
index ab97968fd3..d5a114af7b 100644
--- a/src/core/mcp-client.ts
+++ b/src/core/mcp-client.ts
@@ -141,6 +141,24 @@ export class RemoteMcpError extends Error {
}
}
+/**
+ * B5 (#5949): a 429 on the /token mint is the host's mint budget, not a
+ * connectivity fault: code `rate_limited`, a provider-side wait, and the
+ * read-only check to run once the wait is over.
+ */
+function rateLimitedMintDetail(retryAfterS: number | undefined): RemoteMcpErrorDetail {
+ const wait = retryAfterS !== undefined ? `${retryAfterS}s` : 'a few minutes';
+ return {
+ code: 'rate_limited',
+ why: `The brain host's OAuth /token mint budget is spent (HTTP 429); it clears by itself in ${wait}.`,
+ suggestion: `Wait ${wait}, then re-run the same command. If this repeats, the host operator can raise GBRAIN_OAUTH_TOKEN_RATE_LIMIT_MAX.`,
+ fix: {
+ argv: ['gbrain', 'remote', 'doctor', '--json'], consent: [], actor: 'provider',
+ why: `Retry after ${wait}; remote doctor confirms the token mint works again.`, requires_exclusive: false,
+ },
+ };
+}
+
/**
* v0.31.1: convert any thrown value into a RemoteMcpError. Used by the
* outermost catch in `callRemoteTool` so the dispatcher's exhaustive switch
@@ -300,6 +318,7 @@ async function getAccessToken(config: GBrainConfig, force = false, signal?: Abor
{
...(tokenRes.status ? { status: tokenRes.status } : {}), ...(tokenRes.kind ? { kind: tokenRes.kind } : {}),
...(tokenRes.retry_after_s !== undefined ? { retry_after_s: tokenRes.retry_after_s } : {}), mcp_url: remote.mcp_url,
+ ...(tokenRes.reason === 'rate_limited' ? rateLimitedMintDetail(tokenRes.retry_after_s) : {}),
},
);
}
diff --git a/src/core/ops/op-fix.ts b/src/core/ops/op-fix.ts
index e55b3ae6e5..3a781eb6a1 100644
--- a/src/core/ops/op-fix.ts
+++ b/src/core/ops/op-fix.ts
@@ -9,7 +9,7 @@
*/
import type { Action, Effect, McpCall, Transport } from '../agent-output.ts';
import type { RegistryCode } from '../error-registry.ts';
-import { opError, type OperationContext, type OperationError, type ParamDef } from './contract.ts';
+import { opError, type AuthInfo, type OperationContext, type OperationError, type ParamDef } from './contract.ts';
type TransportCtx = Pick<OperationContext, 'remote' | 'transport'>;
@@ -118,3 +118,49 @@ export function invalidParam(
return opError('invalid_params', message, `Pass ${name} as ${what}. Example: ${call}.`,
opts.legacy_error ? { legacy_error: opts.legacy_error } : {});
}
+
+const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+/**
+ * B5: the one scope-denial error. Code `insufficient_scope` (the caller's
+ * frozen `error` value rides `legacy_error`), the client id and current
+ * scopes in `why`, and the exact `gbrain auth` command that widens this
+ * connection's grant, run by the brain host's operator.
+ */
+export function scopeDeniedError(opts: {
+ op: string;
+ required: readonly string[];
+ auth?: Pick<AuthInfo, 'clientId' | 'scopes' | 'principal' | 'clientName'>;
+ transport: 'stdio' | 'http';
+ message?: string;
+ legacy_error?: string;
+}): OperationError {
+ const current = opts.auth?.scopes ?? [];
+ const wanted = [...new Set([...current, ...opts.required])];
+ const principal = opts.auth?.principal;
+ const clientId = opts.auth?.clientId;
+ const argv = principal?.kind === 'legacy_token' && UUID.test(principal.id)
+ ? ['gbrain', 'auth', 'rescope-token', '--id', principal.id, '--scopes', wanted.join(',')]
+ : clientId && SAFE_ID.test(clientId) && opts.transport === 'http'
+ ? ['gbrain', 'auth', 'rescope', '--client', clientId, '--scopes', wanted.join(',')]
+ : opts.transport === 'stdio' ? ['gbrain', 'auth', 'local-writer', 'list', '--json'] : ['gbrain', 'auth', 'clients', '--json'];
+ const who = clientId ? `Client ${clientId}` : 'This connection';
+ const why = `${who} has scopes [${current.join(', ') || 'none'}]; ${opts.op} needs ${opts.required.map(s => `'${s}'`).join(' and ')}.`;
+ const grant = argv[2] === 'rescope' || argv[2] === 'rescope-token';
+ return opError('insufficient_scope', opts.message ?? `Operation ${opts.op} requires '${opts.required.join("', '")}' scope`,
+ `Ask the brain host's operator to grant ${opts.required.map(s => `'${s}'`).join(' and ')} to this connection (the command is in fix), then reconnect.`, {
+ ...(opts.legacy_error ? { legacy_error: opts.legacy_error } : {}),
+ reason: 'insufficient_scope',
+ why,
+ fix: {
+ argv, consent: grant ? ['credentials'] : [], actor: opts.transport === 'http' ? 'host_admin' : 'user', why: grant
+ ? `Widens this connection's grant to ${wanted.join(', ')}; only the brain host's operator can change grants.`
+ : 'Shows this connection\'s grant so the operator can widen it.',
+ user_message: opts.transport === 'http'
+ ? `${who} is missing the ${opts.required.join(', ')} scope for ${opts.op}. Please ask whoever runs this gbrain server to run the command shown, then reconnect.`
+ : `This MCP connection is missing the ${opts.required.join(', ')} scope for ${opts.op}. Please run the command shown in a terminal on this machine to review its grant.`,
+ requires_exclusive: false,
+ },
+ });
+}
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index 22592effbc..a7f7ce6112 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -15,13 +15,15 @@ import { resolveBrainId } from '../core/brain-resolver.ts';
import { VERB_NAMES, MEMORY_VERBS_VERSION } from '../core/verbs.ts';
import { cliRenderContext, toAgentError, toolErrorResult, toolResultWithNotices, type Notice, type RenderContext } from '../core/agent-output.ts';
import { isCallable } from '../core/ops/callable.ts';
+import { hostFix, scopeDeniedError } from '../core/ops/op-fix.ts';
import { mutedNoticeCodes, processNoticeLedger, __resetProcessNoticeLedgerForTests, type NoticeLedger } from '../core/notice-ledger.ts';
import { logVerbUsage } from '../core/verbs/usage-log.ts';
import { sourceGuardBlocksWrite } from '../core/source-resolver.ts';
import { suggestNearest } from '../core/levenshtein.ts';
import {
normalizeOptionalParams,
- validateParams,
+ findInvalidParam,
+ schemaInvalidParams,
findUnknownParams,
buildUnknownParamWarnBlock,
resolveStrictParamsMode,
@@ -664,13 +666,12 @@ export async function dispatchToolCall(
}
const safeParams = normalizeOptionalParams(op, params || {});
- const validationError = validateParams(op, safeParams);
- if (validationError) {
+ const validationFailure = findInvalidParam(op, safeParams);
+ if (validationFailure) {
logVerb(false);
- // [c7] verb validation errors speak the protocol envelope (suggestion +
- // protocol_version); non-verb ops keep the pre-existing shape untouched.
- const invalid = new OperationError('invalid_params', validationError,
- isVerb ? 'Check the tool schema — required params and types are declared there.' : undefined);
+ // [c7] verb validation errors speak the protocol envelope (protocol_version);
+ // B3: every op's suggestion names the param's type, choices and an example.
+ const invalid = schemaInvalidParams(op, validationFailure, { remote: opts.remote, transport: dispatchRenderContext(opts).transport === 'http' ? 'http' : 'stdio' });
if (isVerb) invalid.protocolVersion = MEMORY_VERBS_VERSION;
return errorResult(invalid, opts, { op: name });
}
@@ -713,8 +714,16 @@ export async function dispatchToolCall(
// #1924 / #1371. Trusted local callers (remote === false) keep the
// historical fallback via buildOperationContext.
if ((opts.remote ?? true) && !opts.sourceId) {
- return errorResult(new OperationError('missing_source_scope',
- `Remote tool call '${name}' carries no resolved sourceId; refusing the shared 'default' source fallback. Pass an explicit sourceId resolved from the caller's grant.`), opts, { op: name });
+ const viaClient = opts.transport !== 'stdio' && !!opts.auth?.clientId;
+ return errorResult(opError('missing_source_scope',
+ `Remote tool call '${name}' carries no resolved sourceId; refusing the shared 'default' source fallback. Pass an explicit sourceId resolved from the caller's grant.`,
+ viaClient
+ ? 'This connection has no source grant. The brain host operator binds one to this client (gbrain auth rescope-client <client_id> --source <id>), then the call works.'
+ : 'This MCP server resolved no source. Set GBRAIN_SOURCE to a registered source id in the environment that launches it, then restart it.',
+ { fix: hostFix({ remote: true, transport: viaClient ? 'http' : 'stdio' },
+ viaClient ? ['gbrain', 'auth', 'clients', '--json'] : ['gbrain', 'sources', 'list'],
+ viaClient ? 'Shows each OAuth client\'s write source; the operator binds this client to one with `gbrain auth rescope-client`.'
+ : 'Lists the source ids GBRAIN_SOURCE can name.') }), opts, { op: name });
}
const ctx = buildOperationContext(engine, safeParams, opts);
@@ -749,8 +758,8 @@ export async function dispatchToolCall(
scopes = verified.remote ? verified.grant.scopes : [];
}
if (!operationScopesAllowed(scopes ?? [], op)) {
- throw new OperationError('permission_denied', 'This operation requires an explicit shared-skills grant.',
- `Ask the brain owner to grant ${op.requiredScopes.join(', ')} for this connection.`);
+ throw scopeDeniedError({ op: name, required: op.requiredScopes, auth: ctx.auth ? { ...ctx.auth, scopes: scopes ?? [] } : { clientId: '', scopes: scopes ?? [] },
+ transport: ctx.transport === 'stdio' ? 'stdio' : 'http', message: 'This operation requires an explicit shared-skills grant.', legacy_error: 'permission_denied' });
}
}
// Fail-closed gate for slug-bound OAuth clients, applied here because
diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.ts
index cd9018afec..7de0d1bf9a 100644
--- a/src/mcp/http-transport.ts
+++ b/src/mcp/http-transport.ts
@@ -34,7 +34,8 @@ import type { BrainEngine } from '../core/engine.ts';
import { buildToolDefs } from './tool-defs.ts';
import { resolveMcpInstructions } from './instructions.ts';
import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback-config.ts';
-import { operations, operationsByName, opAllowedForBoundClient, opError } from '../core/operations.ts';
+import { operations, operationsByName, opAllowedForBoundClient } from '../core/operations.ts';
+import { scopeDeniedError } from '../core/ops/op-fix.ts';
import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';
import type { AuthInfo } from '../core/operations.ts';
import { VERSION } from '../version.ts';
@@ -507,8 +508,8 @@ export async function startHttpTransport(opts: HttpTransportOptions) {
if (op && !op.localOnly && !operationScopesAllowed(auth.auth!.scopes, op)) {
logRequest(auth.tokenName!, `tools/call:${toolName}`, 'denied_after_list', Date.now() - startedMs);
// Frozen v1 pair: `error: permission_denied` stays; `code: insufficient_scope`.
- const denial = opError('insufficient_scope', `Tool requires ${op.scope ?? 'read'} scope`,
- `Ask the brain host's operator to grant the '${op.scope ?? 'read'}' scope to this token.`, { legacy_error: 'permission_denied' });
+ const denial = scopeDeniedError({ op: toolName, required: [op.scope ?? 'read', ...(op.requiredScopes ?? [])], auth: auth.auth,
+ transport: 'http', message: `Tool requires ${op.scope ?? 'read'} scope`, legacy_error: 'permission_denied' });
return Response.json({ jsonrpc: '2.0', id, result: errorResult(denial, { remote: true, transport: 'http', auth: auth.auth }, { op: toolName }) },
{ headers: corsHeaders(origin) });
}
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 91b7356846..daf95a1ed0 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -8,7 +8,7 @@ import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';
import { VERSION } from '../version.ts';
import { buildToolDefs } from './tool-defs.ts';
import { dispatchToolCall, buildOperationContext } from './dispatch.ts';
-import { validateParams, parseStrictParamsMode } from './validate-params.ts';
+import { findInvalidParam, schemaInvalidParams, parseStrictParamsMode } from './validate-params.ts';
import { filterOpsForSurface, allowedOpNames, clampSurface, isReadOnlyOperation, type McpAccess, type McpSurface } from './surface.ts';
import { disabledOpsForPublishGates } from './publish-gates.ts';
import type { Operation } from '../core/operations.ts';
@@ -487,8 +487,8 @@ export async function handleToolCall(
const op = operations.find(o => o.name === tool);
if (!op) throw opError('unknown_tool', `Unknown tool: ${tool}`, 'Run `gbrain --tools-json` to list the tool names.');
- const validationError = validateParams(op, params);
- if (validationError) throw new OperationError('invalid_params', validationError, `Read the ${tool} schema in \`gbrain --tools-json\` (required params and types).`);
+ const validationFailure = findInvalidParam(op, params);
+ if (validationFailure) throw schemaInvalidParams(op, validationFailure, {});
const ctx = buildOperationContext(engine, params, {
remote: false,
diff --git a/src/mcp/validate-params.ts b/src/mcp/validate-params.ts
index c4e237efd6..e846b80730 100644
--- a/src/mcp/validate-params.ts
+++ b/src/mcp/validate-params.ts
@@ -16,33 +16,58 @@ import type { Operation } from '../core/operations.ts';
import type { BrainEngine } from '../core/engine.ts';
import type { GBrainConfig } from '../core/config.ts';
import { suggestNearest } from '../core/levenshtein.ts';
+import type { OperationError } from '../core/ops/contract.ts';
+import { invalidParam } from '../core/ops/op-fix.ts';
-/** Validate required params exist and have the expected type. Returns null on success, error message on failure. */
-export function validateParams(op: Operation, params: Record<string, unknown>): string | null {
+/** One validation failure: the message (never echoes the caller's value) and the param it names. */
+export interface ParamValidationFailure { message: string; param: string }
+
+/** Validate required params exist and have the expected type. Returns the first failure, or null. */
+export function findInvalidParam(op: Operation, params: Record<string, unknown>): ParamValidationFailure | null {
for (const [key, def] of Object.entries(op.params)) {
+ const fail = (message: string) => ({ message, param: key });
if (def.required && (params[key] === undefined || params[key] === null)) {
- return `Missing required parameter: ${key}`;
+ return fail(`Missing required parameter: ${key}`);
}
if (params[key] !== undefined && params[key] !== null) {
const val = params[key];
const expected = def.type;
- if (expected === 'string' && typeof val !== 'string') return `Parameter "${key}" must be a string`;
- if (expected === 'number' && typeof val !== 'number') return `Parameter "${key}" must be a number`;
- if (expected === 'boolean' && typeof val !== 'boolean') return `Parameter "${key}" must be a boolean`;
- if (expected === 'object' && (typeof val !== 'object' || Array.isArray(val))) return `Parameter "${key}" must be an object`;
- if (expected === 'array' && !Array.isArray(val)) return `Parameter "${key}" must be an array`;
+ if (expected === 'string' && typeof val !== 'string') return fail(`Parameter "${key}" must be a string`);
+ if (expected === 'number' && typeof val !== 'number') return fail(`Parameter "${key}" must be a number`);
+ if (expected === 'boolean' && typeof val !== 'boolean') return fail(`Parameter "${key}" must be a boolean`);
+ if (expected === 'object' && (typeof val !== 'object' || Array.isArray(val))) return fail(`Parameter "${key}" must be an object`);
+ if (expected === 'array' && !Array.isArray(val)) return fail(`Parameter "${key}" must be an array`);
// WP3: enum membership is a TYPE error, enforced in BOTH strict modes
// (warn and reject). The message names the declared values only — the
// caller's raw value is never echoed (it can land in persistent logs
// via the error_message column; declared values are safe by definition).
if (def.enum && typeof val === 'string' && !def.enum.includes(val)) {
- return `Parameter "${key}" must be one of: ${def.enum.join(', ')}`;
+ return fail(`Parameter "${key}" must be one of: ${def.enum.join(', ')}`);
}
}
}
return null;
}
+/** Validate required params exist and have the expected type. Returns null on success, error message on failure. */
+export function validateParams(op: Operation, params: Record<string, unknown>): string | null {
+ return findInvalidParam(op, params)?.message ?? null;
+}
+
+/**
+ * B3: the `invalid_params` error for a schema failure — the param's type,
+ * description, valid choices and one example call on the caller's surface
+ * (from the op's ParamDef), never the caller's raw value.
+ */
+export function schemaInvalidParams(
+ op: Operation,
+ failure: ParamValidationFailure,
+ ctx: { remote?: boolean; transport?: 'stdio' | 'http' },
+): OperationError {
+ return invalidParam({ remote: ctx.remote ?? true, transport: ctx.transport }, op.cliHints?.name && ctx.remote === false ? op.cliHints.name : op.name,
+ failure.param, failure.message, { def: op.params[failure.param] });
+}
+
/**
* Normalize the absent-idioms real MCP clients send for OPTIONAL params
* before validation and dispatch: `null` (any type) and `''` (string-typed
diff --git a/test/e2e/serve-http-oauth.test.ts b/test/e2e/serve-http-oauth.test.ts
index 6d3a7ecc69..113405de0d 100644
--- a/test/e2e/serve-http-oauth.test.ts
+++ b/test/e2e/serve-http-oauth.test.ts
@@ -1550,6 +1550,12 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {
code: 'insufficient_scope',
message: "Operation put_page requires 'write' scope",
your_scopes: ['read'],
+ // B5: the exact grant command, run by the brain host's operator.
+ why: `Client ${id} has scopes [read]; put_page needs 'write'.`,
+ fix: {
+ argv: ['gbrain', 'auth', 'rescope', '--client', id, '--scopes', 'read,write'],
+ consent: ['credentials'], actor: 'host_admin', next: 'tell_user_to_run',
+ },
});
// Allowed control (anti-vacuity): same token, read op succeeds.
diff --git a/test/scope-denial-contract.test.ts b/test/scope-denial-contract.test.ts
new file mode 100644
index 0000000000..79f1696896
--- /dev/null
+++ b/test/scope-denial-contract.test.ts
@@ -0,0 +1,86 @@
+/**
+ * B5 contract: every scope deny path builds one envelope (code
+ * insufficient_scope, the caller's frozen `error`, client id + current scopes
+ * in `why`, the exact `gbrain auth` command, actor host_admin on http), and a
+ * 429 on the thin client's /token mint renders as rate_limited with a
+ * provider-side wait.
+ */
+import { describe, expect, test } from 'bun:test';
+import { scopeDeniedError } from '../src/core/ops/op-fix.ts';
+import { toAgentError } from '../src/core/agent-output.ts';
+import { isScopeErrorCode } from '../src/core/error-catalogue.ts';
+import { RemoteMcpError } from '../src/core/mcp-client.ts';
+
+const render = (transport: 'stdio' | 'http') => ({ transport, isCallable: () => false, preapproved: () => false });
+const envelope = (e: unknown, transport: 'stdio' | 'http' = 'http') => toAgentError(e, { transport, op: 'put_page', render: render(transport) });
+
+describe('scope denials (B5)', () => {
+ test('serve-http OAuth client: frozen error, canonical code, exact rescope command', () => {
+ const env = envelope(scopeDeniedError({ op: 'put_page', required: ['write'], auth: { clientId: 'gbrain_cl_abc', scopes: ['read'] }, transport: 'http' }));
+ expect(env).toMatchObject({
+ error: 'insufficient_scope', code: 'insufficient_scope', reason: 'insufficient_scope',
+ message: "Operation put_page requires 'write' scope",
+ why: "Client gbrain_cl_abc has scopes [read]; put_page needs 'write'.",
+ class: 'host_only', retryable: false,
+ fix: {
+ argv: ['gbrain', 'auth', 'rescope', '--client', 'gbrain_cl_abc', '--scopes', 'read,write'],
+ command: 'gbrain auth rescope --client gbrain_cl_abc --scopes read,write',
+ consent: ['credentials'], actor: 'host_admin', next: 'tell_user_to_run',
+ },
+ });
+ expect(env.fix?.user_message).toContain('whoever runs this gbrain server');
+ expect(env.suggestion).toContain('gbrain auth rescope --client gbrain_cl_abc --scopes read,write');
+ });
+
+ test('legacy bearer token: error stays permission_denied; rescope-token by id', () => {
+ const id = '0f8fad5b-d9cb-469f-a165-70867728950e';
+ const env = envelope(scopeDeniedError({
+ op: 'submit_agent', required: ['agent'], transport: 'http', message: 'Tool requires agent scope', legacy_error: 'permission_denied',
+ auth: { clientId: 'legacy-name', scopes: ['read', 'write'], principal: { kind: 'legacy_token', id } },
+ }));
+ expect(env).toMatchObject({
+ error: 'permission_denied', code: 'insufficient_scope', message: 'Tool requires agent scope',
+ fix: { argv: ['gbrain', 'auth', 'rescope-token', '--id', id, '--scopes', 'read,write,agent'], actor: 'host_admin' },
+ });
+ expect(isScopeErrorCode(env.error, env.code, env.reason)).toBe(true);
+ });
+
+ test('stdio local writer: the user reviews the grant in a terminal on this machine', () => {
+ const env = envelope(scopeDeniedError({
+ op: 'put_skill', required: ['skills_write'], auth: { clientId: '', scopes: ['read', 'write'] }, transport: 'stdio',
+ message: 'This operation requires an explicit shared-skills grant.', legacy_error: 'permission_denied',
+ }), 'stdio');
+ expect(env).toMatchObject({
+ error: 'permission_denied', code: 'insufficient_scope',
+ fix: { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'], consent: [], actor: 'user', next: 'tell_user_to_run' },
+ });
+ });
+
+ test('a hostile client id never reaches argv', () => {
+ const e = scopeDeniedError({ op: 'put_page', required: ['write'], auth: { clientId: '--yes; rm -rf', scopes: [] }, transport: 'http' });
+ expect(e.fix?.argv).toEqual(['gbrain', 'auth', 'clients', '--json']);
+ });
+});
+
+describe('thin-client /token 429 (#5949, B5)', () => {
+ test('rate_limited renders code rate_limited, actor provider, next wait, retryable', () => {
+ const err = new RemoteMcpError('rate_limited', 'OAuth /token failed: rate-limited', {
+ status: 429, retry_after_s: 900, code: 'rate_limited',
+ why: "The brain host's OAuth /token mint budget is spent (HTTP 429); it clears by itself in 900s.",
+ suggestion: 'Wait 900s, then re-run the same command.',
+ fix: { argv: ['gbrain', 'remote', 'doctor', '--json'], consent: [], actor: 'provider', why: 'Retry after 900s.', requires_exclusive: false },
+ });
+ const env = toAgentError(err, { transport: 'cli', command: 'search', render: { transport: 'cli', isCallable: () => false, preapproved: () => false } });
+ expect(env).toMatchObject({
+ error: 'rate_limited', code: 'rate_limited', retryable: true, class: 'retryable',
+ fix: { actor: 'provider', next: 'wait', command: 'gbrain remote doctor --json' },
+ });
+ expect(env.why).toContain('900s');
+ });
+
+ test('a bare rate_limited transport reason still maps to the registry code', () => {
+ const env = toAgentError(new RemoteMcpError('rate_limited', 'OAuth /token failed'), { transport: 'cli', render: { transport: 'cli', isCallable: () => false, preapproved: () => false } });
+ expect(env.code).toBe('rate_limited');
+ expect(env.retryable).toBe(true);
+ });
+});
diff --git a/test/thin-client-token-rate-limit.test.ts b/test/thin-client-token-rate-limit.test.ts
index 15a66008e5..666a7715f8 100644
--- a/test/thin-client-token-rate-limit.test.ts
+++ b/test/thin-client-token-rate-limit.test.ts
@@ -91,7 +91,7 @@ describe('callRemoteTool when /token fails after discovery succeeded', () => {
test('a 429 surfaces as rate_limited, not discovery', async () => {
tokenResponse = rateLimited('900');
await expect(callRemoteTool(config(), 'get_brain_identity')).rejects.toMatchObject({
- reason: 'rate_limited', detail: { status: 429, retry_after_s: 900 },
+ reason: 'rate_limited', detail: { status: 429, retry_after_s: 900, code: 'rate_limited', fix: { actor: 'provider' } },
});
});
diff --git a/test/truthful-catalog.e2e-lite.test.ts b/test/truthful-catalog.e2e-lite.test.ts
index dd87699b1b..2a75b083aa 100644
--- a/test/truthful-catalog.e2e-lite.test.ts
+++ b/test/truthful-catalog.e2e-lite.test.ts
@@ -388,6 +388,8 @@ describe('E5 truthful catalog — legacy bearer transport (real HTTP, PGLite)',
const denied = await legacyToolCall(name, args);
expect(denied.envelope?.error).toBe('permission_denied');
expect(denied.envelope?.message).toBe('Tool requires agent scope');
+ expect(denied.envelope).toMatchObject({ code: 'insufficient_scope', reason: 'insufficient_scope', fix: { actor: 'host_admin', next: 'tell_user_to_run' } });
+ expect((denied.envelope as { fix?: { argv?: string[] } }).fix?.argv?.slice(0, 2)).toEqual(['gbrain', 'auth']);
}
});
diff --git a/test/validate-params.test.ts b/test/validate-params.test.ts
index 15e010ca16..3279f51af3 100644
--- a/test/validate-params.test.ts
+++ b/test/validate-params.test.ts
@@ -377,3 +377,27 @@ describe('query op with neither `query` nor `image` (WP3 typed envelope)', () =>
expect(envelope.message).toContain('`image`');
});
});
+
+// ---------------------------------------------------------------------------
+// B3 — schema failures carry the param's type, choices and an example
+// ---------------------------------------------------------------------------
+
+describe('schema invalid_params hints (agent contract B3)', () => {
+ test('a wrong type names the param type, its description and an example call', async () => {
+ const out = await dispatchToolCall(stubEngine('warn'), 'search', { query: 'x', limit: 'ten' }, DISPATCH_OPTS);
+ const envelope = body(out);
+ expect(envelope).toMatchObject({ error: 'invalid_params', code: 'invalid_params', message: 'Parameter "limit" must be a number' });
+ expect(envelope.suggestion).toMatch(/^Pass `limit` as a number/);
+ expect(envelope.suggestion).toContain('Example: search {"limit": ');
+ expect(envelope.suggestion).not.toContain('ten');
+ });
+
+ test('a missing required param gets an example; verbs keep protocol_version', async () => {
+ const envelope = body(await dispatchToolCall(stubEngine('warn'), 'forget', {}, DISPATCH_OPTS));
+ expect(envelope).toMatchObject({ error: 'invalid_params', message: 'Missing required parameter: id', protocol_version: 1 });
+ expect(envelope.suggestion).toMatch(/^Pass `id` as a string.*Example: forget \{"id": "value"\}\.$/);
+ const search = body(await dispatchToolCall(stubEngine('warn'), 'search', {}, DISPATCH_OPTS));
+ expect(search.message).toBe('Missing required parameter: query');
+ expect(search.suggestion).toMatch(/^Pass `query` as a string/);
+ });
+});