Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(mcp): isCallable is the one predicate behind stdio and HTTP tools/list
garrytanb1761fea6ff6
diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.tsindex a0cbeb7388..051aed7ebb 100644--- a/src/commands/serve-http-mcp.ts+++ b/src/commands/serve-http-mcp.ts@@ -22,6 +22,7 @@ import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writebackimport { 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 { resolveStrictParamsMode } from '../mcp/validate-params.ts';import { buildToolDefs } from '../mcp/tool-defs.ts';@@ -201,7 +202,7 @@ function createMcpRequestServer(async function listMcpTools(ctx: ServeHttpContext, state: McpRequestState) {const { engine, config, broadcastEvent } = ctx;- const { authInfo, agentName, startTime, mcpOperations } = state;+ const { authInfo, agentName, startTime, mcpOperations, surface, surfaceAllowedOps } = state;// WP1 honest catalog: the advertised list is exactly what THIS token// can call. Three per-request filters, cheapest first:// 1. token scope — a read-only token never sees admin/write tools;@@ -223,10 +224,12 @@ async function listMcpTools(ctx: ServeHttpContext, state: McpRequestState) {// agent-only tokens with ZERO discovery — ops flagged `agentCallable`// (request_tools) are visible to (and callable by, below) agent scope// in addition to their declared scope.+ // Agent contract v1 (A2): the one callability predicate (isCallable) plus+ // the bound-client op fence.+ const publishGates = publishGatesFromDisabled(mcpOperations, gateDisabled);const visibleOps = mcpOperations.filter(op =>- operationScopesAllowed(authInfo.scopes, op)- && opAllowedForBoundClient(authInfo, op)- && !gateDisabled.has(op.name),+ isCallable(op, { transport: 'http', surface, scopes: authInfo.scopes, publishGates, allowedOps: surfaceAllowedOps })+ && opAllowedForBoundClient(authInfo, op),);// WP3 (amendment 14): ONE schema mapper — the inline map this handler// carried is unified onto buildToolDefs so the byte-pin test covers thediff --git a/src/core/ops/callable.ts b/src/core/ops/callable.tsindex a969f1d654..50129a4039 100644--- a/src/core/ops/callable.ts+++ b/src/core/ops/callable.ts@@ -31,3 +31,16 @@ export function isCallable(op: Operation, ctx: CallableContext): boolean {if (ctx.transport === 'http') return operationScopesAllowed(ctx.scopes, op);return !op.requiredScopes?.length || operationScopesAllowed(ctx.scopes, op);}++/**+ * Publish gates keyed by gate key from the resolver's disabled-op set+ * (`disabledOpsForPublishGates`): a gate is on when none of its ops is disabled.+ */+export function publishGatesFromDisabled(ops: readonly Operation[], disabled: ReadonlySet<string>): Record<string, boolean> {+ const gates: Record<string, boolean> = {};+ for (const op of ops) {+ if (!op.publishGateKey) continue;+ gates[op.publishGateKey] = (gates[op.publishGateKey] ?? true) && !disabled.has(op.name);+ }+ return gates;+}diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.tsindex 986fa13158..04a44c88df 100644--- a/src/mcp/http-transport.ts+++ b/src/mcp/http-transport.ts@@ -34,10 +34,11 @@ 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 } from '../core/operations.ts';+import { operations, operationsByName, opAllowedForBoundClient, opError } from '../core/operations.ts';+import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';import type { AuthInfo } from '../core/operations.ts';import { VERSION } from '../version.ts';-import { dispatchToolCall, requestLogStatusForResult } from './dispatch.ts';+import { dispatchToolCall, requestLogStatusForResult, errorResult } from './dispatch.ts';import { parseStrictParamsMode } from './validate-params.ts';import { filterOpsForSurface, clampSurface, type McpSurface } from './surface.ts';import { disabledOpsForPublishGates } from './publish-gates.ts';@@ -485,9 +486,12 @@ export async function startHttpTransport(opts: HttpTransportOptions) {// unconditionally, so gates-off served the exact listed-but-denied// catalog lie E5 (test/truthful-catalog.e2e-lite.test.ts) pins out.const gateDisabled = await disabledOpsForPublishGates(engine, fileConfig);+ // Agent contract v1 (A2): the one callability predicate + the bound-client fence.+ const publishGates = publishGatesFromDisabled(surfacedOps, gateDisabled);const visibleTools = tools.filter(t => {const op = operationsByName[t.name];- return op && !gateDisabled.has(t.name) && operationScopesAllowed(auth.auth!.scopes, op) && opAllowedForBoundClient(auth.auth!, op);+ return op && isCallable(op, { transport: 'http', surface, scopes: auth.auth!.scopes, publishGates, allowedOps: surfaceAllowedOps })+ && opAllowedForBoundClient(auth.auth!, op);});logRequest(auth.tokenName!, 'tools/list', 'success', Date.now() - startedMs);return Response.json(@@ -503,8 +507,10 @@ export async function startHttpTransport(opts: HttpTransportOptions) {const op = operationsByName[toolName];if (op && !op.localOnly && !operationScopesAllowed(auth.auth!.scopes, op)) {logRequest(auth.tokenName!, `tools/call:${toolName}`, 'denied_after_list', Date.now() - startedMs);- return Response.json({ jsonrpc: '2.0', id, result: { isError: true, content: [{ type: 'text',- text: JSON.stringify({ error: 'permission_denied', message: `Tool requires ${op.scope ?? 'read'} scope` }) }] } },+ // 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' });+ return Response.json({ jsonrpc: '2.0', id, result: errorResult(denial, { remote: true, transport: 'http', auth: auth.auth }, { op: toolName }) },{ headers: corsHeaders(origin) });}// v0.28: thread per-token takes-holder allow-list so takes_list /diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 20f4c22d7b..91b7356846 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -4,6 +4,7 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';import type { BrainEngine } from '../core/engine.ts';import { operations, opError, OperationError } from '../core/operations.ts';+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';@@ -142,34 +143,34 @@ export async function stdioVisibleTools(engine: BrainEngine,surfacedOps: Operation[],): Promise<Operation[]> {- if (surfacedOps.some(op => op.requiredScopes?.length)) {- let scopes: readonly string[] = [];- if (!isEngineDegraded(engine)) {- try {- const verified = await verifyLocalWriter(engine, await readLocalWriter(engine, 'stdio'));- if (verified.remote) scopes = verified.grant.scopes;- } catch {}- }- surfacedOps = surfacedOps.filter(op => !op.requiredScopes?.length || operationScopesAllowed(scopes, op));+ let scopes: readonly string[] = [];+ if (surfacedOps.some(op => op.requiredScopes?.length) && !isEngineDegraded(engine)) {+ try {+ const verified = await verifyLocalWriter(engine, await readLocalWriter(engine, 'stdio'));+ if (verified.remote) scopes = verified.grant.scopes;+ } catch {}}- if (!surfacedOps.some(op => op.publishGateKey)) return surfacedOps;// Degraded serve (db-availability 4c): fail-closed WITHOUT touching the- // engine. The gate read below can hit engine.getConfig, which on the- // degraded wrapper would burn the one lazy reconnect attempt — and stall- // the client's INITIAL tools/list handshake behind the reconnect's wait- // cap. Recovery re-sends tools/list_changed, so the full catalog returns.- if (isEngineDegraded(engine)) {- const hidden = new Set(surfacedOps.filter(o => o.publishGateKey).map(o => o.name));- return surfacedOps.filter(op => !hidden.has(op.name));- }- let gateDisabled: ReadonlySet<string>;- try {- gateDisabled = await disabledOpsForPublishGates(engine, loadConfig());- } catch {- gateDisabled = new Set(surfacedOps.filter(o => o.publishGateKey).map(o => o.name));+ // engine. The gate read can hit engine.getConfig, which on the degraded+ // wrapper would burn the one lazy reconnect attempt — and stall the+ // client's INITIAL tools/list handshake behind the reconnect's wait cap.+ // Recovery re-sends tools/list_changed, so the full catalog returns.+ let gateDisabled: ReadonlySet<string> = new Set();+ if (surfacedOps.some(op => op.publishGateKey)) {+ if (isEngineDegraded(engine)) {+ gateDisabled = new Set(surfacedOps.filter(o => o.publishGateKey).map(o => o.name));+ } else {+ try {+ gateDisabled = await disabledOpsForPublishGates(engine, loadConfig());+ } catch {+ gateDisabled = new Set(surfacedOps.filter(o => o.publishGateKey).map(o => o.name));+ }+ }}- if (gateDisabled.size === 0) return surfacedOps;- return surfacedOps.filter(op => !gateDisabled.has(op.name));+ // Agent contract v1 (A2): the one callability predicate. The surface was+ // applied by the caller (surfacedOps), so 'full' here adds no filter.+ const publishGates = publishGatesFromDisabled(surfacedOps, gateDisabled);+ return surfacedOps.filter(op => isCallable(op, { transport: 'stdio', surface: 'full', scopes, publishGates }));}// ─── #4409: in-flight stdio RPC tracking ────────────────────────────────diff --git a/test/callable-predicate.test.ts b/test/callable-predicate.test.tsnew file mode 100644index 0000000000..9ed47ded32--- /dev/null+++ b/test/callable-predicate.test.ts@@ -0,0 +1,85 @@+/**+ * Agent operator contract v1 (A2): isCallable is the one predicate behind+ * tools/list (stdio + HTTP) and dispatch. For every transport × surface ×+ * scope set × gate state, the listed set equals ops.filter(isCallable), and+ * the shared dispatch layer refuses exactly the surface-hidden and+ * network-local ops with the uniform unknown_tool envelope (it never admits+ * an op the list hid on those axes).+ */+import { describe, expect, test } from 'bun:test';+import { operations, type Operation } from '../src/core/operations.ts';+import { isCallable, publishGatesFromDisabled, type CallableContext } from '../src/core/ops/callable.ts';+import { filterOpsForSurface } from '../src/mcp/surface.ts';+import { operationScopesAllowed } from '../src/core/scope.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import type { BrainEngine } from '../src/core/engine.ts';++const SURFACES = ['verbs', 'starter', 'full'] as const;+const SCOPE_SETS: readonly string[][] = [['read'], ['read', 'write'], ['admin'], ['agent'], ['admin', 'skills_member_self']];+const GATE_STATES = [{}, { 'mcp.publish_skills': true, 'mcp.publish_advisor': true }];++/** The pre-A2 HTTP list filter, kept here as the independent oracle. */+function legacyHttpList(surface: typeof SURFACES[number], scopes: string[], gates: Record<string, boolean>): string[] {+ return filterOpsForSurface(operations.filter(op => !op.localOnly), surface)+ .filter(op => operationScopesAllowed(scopes, op) && !(op.publishGateKey && gates[op.publishGateKey] !== true))+ .map(op => op.name);+}++/** The pre-A2 stdio list filter (surface, required-scope grant, gates). */+function legacyStdioList(surface: typeof SURFACES[number], scopes: string[], gates: Record<string, boolean>): string[] {+ return filterOpsForSurface(operations, surface)+ .filter(op => !op.requiredScopes?.length || operationScopesAllowed(scopes, op))+ .filter(op => !(op.publishGateKey && gates[op.publishGateKey] !== true))+ .map(op => op.name);+}++describe('isCallable agrees with the list filters it replaced', () => {+ for (const surface of SURFACES) {+ for (const scopes of SCOPE_SETS) {+ for (const gates of GATE_STATES) {+ const label = `${surface} ${scopes.join('+')} gates=${Object.keys(gates).length ? 'on' : 'off'}`;+ test(`http ${label}`, () => {+ const ctx: CallableContext = { transport: 'http', surface, scopes, publishGates: gates };+ expect(operations.filter(op => isCallable(op, ctx)).map(op => op.name)).toEqual(legacyHttpList(surface, scopes, gates));+ });+ test(`stdio ${label}`, () => {+ const ctx: CallableContext = { transport: 'stdio', surface, scopes, publishGates: gates };+ expect(operations.filter(op => isCallable(op, ctx)).map(op => op.name)).toEqual(legacyStdioList(surface, scopes, gates));+ });+ }+ }+ }++ test('publishGatesFromDisabled: a gate is on only when none of its ops is disabled', () => {+ const gated = operations.filter(op => op.publishGateKey);+ expect(Object.values(publishGatesFromDisabled(operations, new Set())).every(Boolean)).toBe(true);+ const off = publishGatesFromDisabled(operations, new Set([gated[0].name]));+ expect(off[gated[0].publishGateKey!]).toBe(false);+ });+});++describe('dispatch refuses what the list hides on the dispatch-enforced axes', () => {+ const engine = {} as BrainEngine;+ const unknown = async (op: Operation, transport: 'stdio' | 'http', allowed: ReadonlySet<string> | undefined) => {+ const r = await dispatchToolCall(engine, op.name, {}, { remote: true, transport, sourceId: 'default', ...(allowed ? { allowedOps: allowed } : {}) });+ if (!r.isError) return false;+ return JSON.parse(r.content[0].text).code === 'unknown_tool';+ };++ for (const surface of SURFACES) {+ for (const transport of ['stdio', 'http'] as const) {+ test(`${transport} ${surface}: unknown_tool ⇔ not callable on surface/locality`, async () => {+ const allowed = surface === 'full' ? undefined : new Set(filterOpsForSurface(operations, surface).map(o => o.name));+ const allScopes = ['admin', 'agent', ...new Set(operations.flatMap(o => o.requiredScopes ?? []))];+ const ctx: CallableContext = { transport, surface, scopes: allScopes, publishGates: { 'mcp.publish_skills': true, 'mcp.publish_advisor': true } };+ const mismatches: string[] = [];+ for (const op of operations) {+ const hidden = !isCallable(op, ctx);+ const refused = await unknown(op, transport, allowed);+ if (hidden !== refused) mismatches.push(`${op.name}: hidden=${hidden} refused=${refused}`);+ }+ expect(mismatches).toEqual([]);+ });+ }+ }+});