Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

request_tools accepts tools and surface in one call

garrytanf5d3431b014d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 37768e2b03..eb32305521 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,7 @@ identifiers and attribution are available in the pre-removal Git revision
- `get_backlinks` with a `type` that other pages in the brain have, but no page linking to this one has, now returns the normal empty answer plus a note listing the types the linking pages do have. Before, it refused with `unknown type`, so an agent walking several accounts by type was refused once per account. A type no page has is still refused, and the refusal now also lists the brain's own page types. For a remote caller, both checks count only pages that caller can read: a type found only on private pages, pages whose readers leave the caller out, deleted pages or another source is treated as a type that does not exist and is never named.
- `list_pages` with a `type` that no page has still returns the same empty list, but now adds a note naming the page types the brain does have, most common first (up to 12, with counts). Before, a guessed type such as `account` on a brain that files accounts as `crm` came back as a bare `[]`, which reads like "no such pages". A remote caller's note names only types of pages it can read.
- `search` with `match: "keyword"` now labels every row that matches the query as written `keyword_exact`, including rows from your own `"A" OR "B"` query or a one-word query. Their match scores sit below the cutoff the label used to need, so they were labelled `weak_semantic`, which told agents the batched lookup the instructions recommend had found nothing solid. `create_safety` (the "don't write a duplicate" hint) is unchanged for these rows. Rows found only by gbrain's own fallback of loosening a query to any-word matching stay `weak_semantic`, and default (hybrid) search is unchanged.
+- `request_tools` accepts `tools` and `surface` in one call. It changes the tool surface exactly as a `surface`-only call does (same limits and refusals), then returns the requested tool schemas, with the surface answer under `surface_change`. Before, the pair was refused, and some models send it every night. Calls with only one of the two answer as before.
## [0.60.651.0] - 2026-11-10
diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.md
index eb58819954..c1bbc313c2 100644
--- a/docs/architecture/key-files/mcp.md
+++ b/docs/architecture/key-files/mcp.md
@@ -22,7 +22,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/mcp-registration.ts` — `REGISTRATION_SURFACE` (`full` since S0, wave 0: callable and advertised; README, docs/mcp, INSTALL_FOR_AGENTS.md and the plugin manifests name the same value, which the S0 grep test in `test/mcp-registration.test.ts` keeps so), `stdioServeArgv(bin, surface = REGISTRATION_SURFACE)` (`null` → bare `serve`) and `registeredSurface(text)` (an existing entry's pinned surface, `null` for bare, `undefined` when no serve command is visible): every stdio registration gbrain writes builds from them (readiness `harness_wiring`, init's quickstart, `bootstrap hooks` for Claude Code / Codex / opencode, the plugin generator, which also refuses root plugin manifests pinned elsewhere). The OpenClaw manifest stays a bare `serve`. Also the HTTP+bearer wiring helpers `connect.ts` re-exports. Test: `test/mcp-registration.test.ts`.
- `src/core/serve-log.ts` — serve's own log hygiene (#7246), installed by `src/cli/commands/serve.ts` before `runServe`. For each of stderr, and stdout under `--http` only (stdio serve's stdout is the JSON-RPC channel), whose descriptor is a regular file, it routes console and stream writes through a `ServeLogFile`: `LineDeduper` writes the first occurrence of a line at once and counts repeats inside the window (a leading timestamp ignored), then writes one `[gbrain serve-log] repeated N more time(s) in the last Ws: <line>` line when the window ends or the process exits; rotation is copy-then-truncate on the inherited append-mode descriptor (`<log>.N-1` → `<log>.N`, `<log>` → `<log>.1`, truncate), each write placed at the file's current end, and only when the descriptor's path is known (`/proc/self/fd` or the `serveLogPath`/`serveErrPath` inode) and still names the same inode. TTYs, pipes and journald are untouched. `GBRAIN_SERVE_LOG_MAX_BYTES` (10 MiB; 0 off), `GBRAIN_SERVE_LOG_MAX_FILES` (5), `GBRAIN_SERVE_LOG_DEDUPE_SECONDS` (600; 0 off). Tests: `test/serve-log-7246.test.ts`.
-- `src/core/ops/request-tools.ts` — `request_tools`: catalog (no args), descriptors (`{tools}`; D1: an empty list or one with no caller-visible name returns the catalog plus `did_you_mean` drawn only from `visibleOpsForCaller`, never echoing the requested names, so an invisible existing op and a nonexistent one answer byte-identically), and `{surface}`: per OAuth client on HTTP (ceiling, operator lock, rate limit, audit), and on the owner's stdio pipe `widenStdioSession` widens `ctx.stdioSurface` for the session (refused with the persistent route when `mcp.allow_session_widen` is off; clamped by `GBRAIN_MCP_FORCE_SURFACE`; returns `persisted:false, scope:'session'` and the new tools' schemas). A widenable stdio session's catalog lists the full surface. `{tools}` returns each visible op's registry schema, so a starter client also gets the `fullSurfaceOnly` params its tools/list leaves out (dispatch accepts them on every surface). Tests: `test/request-tools.test.ts`, `test/request-tools-stdio.test.ts`.
+- `src/core/ops/request-tools.ts` — `request_tools`: catalog (no args), descriptors (`{tools}`; D1: an empty list or one with no caller-visible name returns the catalog plus `did_you_mean` drawn only from `visibleOpsForCaller`, never echoing the requested names, so an invisible existing op and a nonexistent one answer byte-identically), and `{surface}`: per OAuth client on HTTP (ceiling, operator lock, rate limit, audit), and on the owner's stdio pipe `widenStdioSession` widens `ctx.stdioSurface` for the session (refused with the persistent route when `mcp.allow_session_widen` is off; clamped by `GBRAIN_MCP_FORCE_SURFACE`; returns `persisted:false, scope:'session'` and the new tools' schemas). A widenable stdio session's catalog lists the full surface. `{tools}` returns each visible op's registry schema, so a starter client also gets the `fullSurfaceOnly` params its tools/list leaves out (dispatch accepts them on every surface). `{surface, tools}` together (GBRA-449) runs the `{surface}` branch first, exactly as alone (refusals included), then the `{tools}` branch against the resulting surface, and answers the descriptor shape plus `surface_change` (the surface answer). Tests: `test/request-tools.test.ts`, `test/request-tools-stdio.test.ts`, `test/request-tools-combined-gbra449.test.ts`.
- `src/mcp/surface.ts` — MCP tool-surface modes: `'verbs'` (exactly the ops marked `verb: true`) | `'starter'` (the ~27-op daily-driver set) | `'full'` (default — identity; existing installs unchanged). `STARTER_OPS` is composed PROGRAMMATICALLY: a spread of `VERB_NAMES` (never a hand-count) + the fallback daily slice (`BRAIN_TOOL_ALLOWLIST` + the agent lane `submit_agent`/`get_agent_job`) + `whoami` + `request_tools` + `capture` (a DIRECT literal, deliberately NOT via the allowlist); re-derived from production usage via `scripts/derive-starter-ops.ts` (paste-in proposal, never an auto-edit). `ALWAYS_INCLUDED_STARTER_OPS` (verbs + `whoami` + `request_tools` + the agent lane + `capture`) is the exported always-set consumed by BOTH `derive-starter-ops.ts` and the advisor starter-fit collector, so neither re-types the composition. `parseSurfaceFlag` (strict, loud reject; reads `--surface v` and `--surface=v` through `flagValues` in `src/core/direct-pool-profile.ts`, and a repeated flag takes the narrowest), `resolveSurface`/`resolveSurfaceWithSource` (flag > config `mcp_surface` > full, the `serve --http` order), `resolveStdioSurface` (stdio: `GBRAIN_SURFACE` > flag > config > full; an invalid env value is returned as `invalidEnv`, never fatal; `surfaceEnvInvalidNotice` builds its notice), `SURFACE_SOURCE_LABEL`, `filterOpsForSurface`, `allowedOpNames`, `createStdioSurfaceState` (the stdio session's one mutable allow-set; `widen(to)` recomputes it, read-only stays read-only), `sessionWidenAllowed` (`mcp.allow_session_widen`, DB > file, default true). `STARTER_OPS` also carries `mute_notice`, the dismissal for the coaching notices starter sessions receive. Enforcement is TWO-layer and fail-closed: the advertised list AND `dispatchToolCall`'s `allowedOps` set (a hidden op returns `unknown_tool` even when called by name) — applied on stdio (server.ts) and BOTH HTTP paths (serve-http.ts after `!localOnly`, and the second transport http-transport.ts). Per-client ceiling machinery (OAuth transport only): `effectiveSurfaceForClient` is the pure composition `clamp(min(server ceiling, client row surface ?? mcp.default_surface_dcr ?? ceiling))`; the per-REQUEST application lives in serve-http.ts's `resolveEffectiveSurface`, which short-circuits a `verbs` ceiling (min() cannot go lower, so the config read is skipped) and, on a default-surface read failure, applies the LAST successfully read default (held per process, fail-closed) so a transient config outage cannot silently widen a NULL-surface client to the ceiling; `resolveClientRowSurface` ignores unknown row values with a bounded warn-once (the column's value space is documented OPEN for future tier names); `resolveDefaultClientSurface` reads the DCR default dual-plane (DB > file > null) and never throws; `clampSurface`/`readForceSurfaceEnv` fold in the `GBRAIN_MCP_FORCE_SURFACE` kill switch — NARROW-ONLY by construction (min(); can never widen past the ceiling). `minSurface`/`surfaceWiderThan` own the verbs < starter < full rank math. Pinned by test/mcp-surface.test.ts (membership, monotonicity verbs ⊆ starter ⊆ full, ceiling + force-narrow cases). `--access read-only` (`parseAccessFlag`, either form through `flagValues`, any read-only value wins; stdio only; HTTP refuses it) intersects the surface with `isReadOnlyOperation` (read scope, not mutating, no required capability scope); `src/mcp/server.ts` uses that one set for tools/list, the capabilities resource (`access`), skill resources and dispatch `allowedOps`. Pinned by `test/serve-stdio-read-only.test.ts`. `mcp.advertised_surface` (`resolveAdvertisedSurface`, DB plane > file plane) narrows only what `tools/list` shows (`advertisedOps`, never wider than the callable set); dispatch keeps the ceiling. Stdio lists the advertised set plus tools `request_tools` described in this session (`OperationContext.revealTools` → `tools/list_changed`); the OAuth HTTP server lists a client's own row surface in full and otherwise the advertised set; the simple bearer transport reads the file plane once at startup. Initialize instructions carry `hiddenCallable` and name `request_tools` when tools are unlisted. `NEW_INSTALL_ADVERTISED_SURFACE` is what a fresh `gbrain init` writes (`'full'` writes nothing; the held-out agent benchmark picks verbs or starter). Pinned by `test/mcp-advertised-surface.test.ts`. Once a session widens (`request_tools {surface}`), the whole widened surface is listed.
- `src/mcp/tool-catalog.ts` — `renderToolCatalogMarkdown()`: the docs/TOOL_CATALOG.md renderer. Config-independent + deterministic (no engine/config reads, no timestamps): non-localOnly ops grouped one section per `Operation.area`, per-op first-sentence description (from `buildToolDefs`'s non-strict shape), scope, STARTER_OPS membership, publish-gate key. Generated by `scripts/generate-tool-catalog.ts`; freshness-guarded by `scripts/check-tool-catalog-fresh.sh` in `bun run verify` (the METRIC_GLOSSARY pattern). Pinned by test/tool-catalog.test.ts.
diff --git a/src/core/ops/request-tools.ts b/src/core/ops/request-tools.ts
index 1b6fa71b7a..76d7b651f8 100644
--- a/src/core/ops/request-tools.ts
+++ b/src/core/ops/request-tools.ts
@@ -187,18 +187,14 @@ const request_tools: Operation = {
// callers were never surface-bounded.
const ceiling = ctx.surfaceCeiling ?? 'full';
- // D5: the three branches are mutually exclusive. {surface, tools}
- // together is ambiguous (persist vs descriptor fetch) — reject loudly
- // rather than silently persisting and ignoring the tools list.
+ // GBRA-449: {surface, tools} together runs the surface branch exactly as a surface-only call (its refusals
+ // included), then the descriptor branch against the resulting surface; surface_change carries the first answer.
if (p.surface !== undefined && p.tools !== undefined) {
- throw opError(
- 'invalid_params',
- 'pass either {surface} (persist) or {tools} (descriptor fetch), not both.',
- 'Call request_tools once with `tools` to fetch descriptors, and separately with `surface` to change this client\'s tool surface.',
- );
+ const surfaceChange = await request_tools.handler(ctx, { surface: p.surface });
+ return { ...(await request_tools.handler(ctx, { tools: p.tools }) as Record<string, unknown>), surface_change: surfaceChange };
}
- // ── persist branch (D5: accepts ONLY {surface}) ─────────────────────
+ // ── persist branch ({surface}) ──────────────────────────────────────
if (p.surface !== undefined) {
const requested = p.surface as string;
if (!isMcpSurface(requested)) {
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 6647e48a19..f15ae0feb6 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -511,6 +511,7 @@ test/repair-receipt-compaction.test.ts
test/repair-rename-identity-6729.test.ts
test/repair-secret-spans.test.ts
test/repair-unwithdrawn-facts-8819.test.ts
+test/request-tools-combined-gbra449.test.ts
test/retrieval-coverage-notices.test.ts
test/schema-missing-tables.test.ts
test/schema-replay-deadlock-6143.test.ts
diff --git a/test/request-tools-combined-gbra449.test.ts b/test/request-tools-combined-gbra449.test.ts
new file mode 100644
index 0000000000..3c6cc08f23
--- /dev/null
+++ b/test/request-tools-combined-gbra449.test.ts
@@ -0,0 +1,107 @@
+/**
+ * GBRA-449 fix 4: request_tools {surface, tools} in one call applies the
+ * surface change exactly as a surface-only call does, then returns the
+ * descriptors for tools against the resulting surface.
+ *
+ * Protects (red before: the pair was refused with invalid_params "pass either
+ * {surface} (persist) or {tools} (descriptor fetch), not both"):
+ * - the OAuth client's surface row is written as a surface-only call writes
+ * it, the response's surface_change is that call's answer and its tools are
+ * the descriptors a tools-only call returns;
+ * - a surface refusal (above the server ceiling, operator-pinned) refuses the
+ * pair the same way and writes nothing;
+ * - a tool outside the ceiling is left out exactly as a tools-only call leaves
+ * it out;
+ * - each argument alone answers as before.
+ * Database-only (repo-less) brain: the client rows live in oauth_clients, no
+ * checkout. PGLite always, Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../src/core/postgres-engine.ts';
+import { __resetRequestToolsPersistLimiterForTests, type AuthInfo } from '../src/core/operations.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+for (const backend of testBackends()) {
+ describe('[' + backend + '] request_tools {surface, tools} together (GBRA-449)', () => {
+ let engine: BrainEngine;
+
+ beforeAll(async () => {
+ if (backend === 'postgres') {
+ const pg = new PostgresEngine();
+ await pg.connect({ database_url: requirePostgresTestDatabase() });
+ engine = pg;
+ } else {
+ const lite = new PGLiteEngine();
+ await lite.connect({});
+ engine = lite;
+ }
+ await engine.initSchema();
+ await engine.setConfig('mcp.publish_skills', 'false');
+ await engine.setConfig('mcp.publish_advisor', 'false');
+ }, 180_000);
+ afterAll(async () => { await engine.disconnect(); });
+
+ beforeEach(async () => {
+ __resetRequestToolsPersistLimiterForTests();
+ await engine.executeRaw("DELETE FROM oauth_clients WHERE client_id LIKE 'gbra449-%'");
+ for (const [id, setBy] of [['gbra449-a', null], ['gbra449-b', null], ['gbra449-pinned', 'operator']] as const) {
+ await engine.executeRaw('INSERT INTO oauth_clients (client_id, client_name, surface, surface_set_by) VALUES ($1, $1, $2, $3)',
+ [id, setBy ? 'verbs' : null, setBy]);
+ }
+ });
+
+ const auth = (clientId: string): AuthInfo => ({ token: 't', clientId, scopes: ['read'] });
+ async function call(args: Record<string, unknown>, clientId: string, ceiling: 'verbs' | 'starter' | 'full' = 'full') {
+ const r = await dispatchToolCall(engine, 'request_tools', args, { remote: true, transport: 'http', sourceId: 'default', surfaceCeiling: ceiling, auth: auth(clientId) } as never);
+ return { isError: r.isError === true, body: JSON.parse(r.content[0]!.text) };
+ }
+ const surfaceOf = async (clientId: string) =>
+ (await engine.executeRaw<{ surface: string | null; surface_set_by: string | null }>('SELECT surface, surface_set_by FROM oauth_clients WHERE client_id = $1', [clientId]))[0];
+ const toolNames = (body: { tools?: Array<{ name: string }> }) => (body.tools ?? []).map(t => t.name);
+
+ test('both: the surface is written as a surface-only call writes it, and the descriptors come back', async () => {
+ const both = await call({ surface: 'starter', tools: ['search', 'get_page', 'list_pages'] }, 'gbra449-a');
+ expect(both.isError).toBe(false);
+ expect(await surfaceOf('gbra449-a')).toEqual({ surface: 'starter', surface_set_by: 'self' });
+ const surfaceOnly = await call({ surface: 'starter' }, 'gbra449-b');
+ expect(both.body.surface_change).toEqual(surfaceOnly.body);
+ const toolsOnly = await call({ tools: ['search', 'get_page', 'list_pages'] }, 'gbra449-b');
+ expect(toolNames(both.body)).toEqual(['search', 'get_page', 'list_pages']);
+ expect({ ...both.body, surface_change: undefined }).toEqual({ ...toolsOnly.body, surface_change: undefined });
+ });
+
+ test('both: a surface above the ceiling refuses the pair as a surface-only call does, and writes nothing', async () => {
+ const both = await call({ surface: 'full', tools: ['search'] }, 'gbra449-a', 'starter');
+ const surfaceOnly = await call({ surface: 'full' }, 'gbra449-a', 'starter');
+ expect(both.isError).toBe(true);
+ expect(both.body).toEqual(surfaceOnly.body);
+ expect(both.body.code).toBe('permission_denied');
+ expect(await surfaceOf('gbra449-a')).toEqual({ surface: null, surface_set_by: null });
+ });
+
+ test('both: an operator-pinned client is refused as a surface-only call is', async () => {
+ const both = await call({ surface: 'starter', tools: ['search'] }, 'gbra449-pinned');
+ expect(both.isError).toBe(true);
+ expect(both.body).toEqual((await call({ surface: 'starter' }, 'gbra449-pinned')).body);
+ expect(await surfaceOf('gbra449-pinned')).toEqual({ surface: 'verbs', surface_set_by: 'operator' });
+ });
+
+ test('both: a tool outside the ceiling is left out as a tools-only call leaves it out', async () => {
+ const both = await call({ surface: 'starter', tools: ['search', 'get_health'] }, 'gbra449-a', 'starter');
+ const toolsOnly = await call({ tools: ['search', 'get_health'] }, 'gbra449-b', 'starter');
+ expect(toolNames(toolsOnly.body)).toEqual(['search']);
+ expect(toolNames(both.body)).toEqual(['search']);
+ expect(both.body.surface_change).toMatchObject({ persisted: true, surface: 'starter' });
+ });
+
+ test('each argument alone keeps its answer', async () => {
+ expect((await call({ surface: 'starter' }, 'gbra449-a')).body).toEqual({ persisted: true, surface: 'starter', note: 're-issue tools/list to see the new catalog' });
+ const tools = (await call({ tools: ['search'] }, 'gbra449-a')).body;
+ expect(Object.keys(tools)).toEqual(['tools']);
+ expect(toolNames(tools)).toEqual(['search']);
+ });
+ });
+}
diff --git a/test/request-tools-stdio.test.ts b/test/request-tools-stdio.test.ts
index 4f3ad85afd..8445558913 100644
--- a/test/request-tools-stdio.test.ts
+++ b/test/request-tools-stdio.test.ts
@@ -11,7 +11,8 @@
* stdio resolves GBRAIN_SURFACE > --surface, an invalid value is ignored
* with a stderr line and one `surface_env_invalid` notice, and whoami /
* gbrain://capabilities report the surface and its source. HTTP keeps its
- * per-client branch (test/request-tools.test.ts).
+ * per-client branch (test/request-tools.test.ts). GBRA-449: {tools, surface}
+ * together widens the session and returns the requested schemas.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
@@ -97,6 +98,22 @@ describe('request_tools {surface} on stdio', () => {
}
}, 90_000);
+ test('{tools, surface} together (GBRA-449): the session widens as a surface-only call does and the schemas come back', async () => {
+ const s = await session(['--surface', 'starter']);
+ try {
+ const res = await s.client.callTool({ name: 'request_tools', arguments: { tools: ['search', 'get_page', 'list_pages', 'get_health'], surface: 'full' } });
+ expect(isError(res)).toBe(false);
+ const body = parsed(res) as { surface_change: Record<string, unknown>; tools: Array<{ name: string }> };
+ expect(body.surface_change).toMatchObject({ persisted: false, scope: 'session', surface: 'full', previous: 'starter' });
+ expect(body.tools.map(t => t.name)).toEqual(['search', 'get_page', 'list_pages', 'get_health']);
+ expect(isError(await s.client.callTool({ name: 'get_health', arguments: {} }))).toBe(false);
+ await waitFor(() => s.listChanged() > 0, { timeoutMs: 10_000 });
+ expect(await names(s)).toContain('get_health');
+ } finally {
+ await s.close();
+ }
+ }, 90_000);
+
test('--access read-only still caps the session: request_tools is not callable and the hint stays read-only', async () => {
const s = await session(['--surface', 'starter', '--access', 'read-only']);
try {
diff --git a/test/request-tools.test.ts b/test/request-tools.test.ts
index 1ec800b786..f9b1a720f3 100644
--- a/test/request-tools.test.ts
+++ b/test/request-tools.test.ts
@@ -371,19 +371,19 @@ describe('request_tools {surface} persist branch', () => {
expect(parsed(other).persisted).toBe(true);
});
- test('{surface, tools} together → invalid_params, never a persist (D5 branch exclusivity)', async () => {
+ test('{surface, tools} together → the surface persists and the descriptors come back (GBRA-449; was refused under D5)', async () => {
await seedClient('cl-both');
const res = await dispatchToolCall(engine, 'request_tools', { surface: 'starter', tools: ['query'] }, {
...HTTP, surfaceCeiling: 'full', auth: authFor('cl-both', ['read']),
});
- expect(res.isError).toBe(true);
+ expect(res.isError ?? false).toBe(false);
const body = parsed(res);
- expect(body.error).toBe('invalid_params');
- expect(body.message).toContain('not both');
+ expect(body.surface_change).toEqual({ persisted: true, surface: 'starter', note: 're-issue tools/list to see the new catalog' });
+ expect(body.tools.map((t: { name: string }) => t.name)).toEqual(['query']);
const rows = await engine.executeRaw(
- `SELECT surface FROM oauth_clients WHERE client_id = $1`, ['cl-both'],
+ `SELECT surface, surface_set_by FROM oauth_clients WHERE client_id = $1`, ['cl-both'],
);
- expect(rows[0].surface).toBe(null);
+ expect(rows[0]).toEqual({ surface: 'starter', surface_set_by: 'self' });
});
test('RateLimiter.refund returns a token so a race-lost persist never burns budget (adversarial fix)', async () => {