Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
serve: opt-in --access read-only ceiling for stdio (#4768)
garrytan9d64aa078aa0
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 7631d61404..e4ea64e9bd 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -3,7 +3,7 @@# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in# the same commit as any peel (the guard fails on >50 lines of stale slack).# Columns: path max_lines policy note-src/cli.ts 3198 ratchet +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts)+src/cli.ts 3199 ratchet +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +1 #4768: serve --access help linesrc/commands/autopilot.ts 1635 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195)src/commands/doctor.ts 653 ratchet refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.tssrc/commands/embed.ts 2190 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stalediff --git a/src/cli.ts b/src/cli.tsindex 034e9d26e6..25ee011adc 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -3104,6 +3104,7 @@ ADMIN--surface verbs|starter|full Tool surface: the 7 memory verbs, the ~20-opstarter set, or every op (default full).On --http this is the per-client CEILING.+ --access read-only|full stdio: list and dispatch only read operationsserve --http [--port N] HTTP MCP server with OAuth 2.1--token-ttl N Access token TTL in seconds (default: 3600)--enable-dcr Enable Dynamic Client Registration (DCR clients default to authorization_code)@@ -3113,7 +3114,7 @@ ADMIN[--install] [--json] Print the paste-ready command, or --install to run itauth <create|list|revoke|...> Manage legacy tokens + OAuth 2.1 clientsauth --help Full subcommand list (register-client,- rescope-client, revoke-client, permissions, test, ...)+ rescope-client, rescope-token, revoke-client, permissions, ...)watch [--json] Push-based context: pipe conversation turns in,volunteered brain pages stream out (#2095)call <tool> '<json>' Raw tool invocationdiff --git a/src/commands/serve.ts b/src/commands/serve.tsindex 1b9a6eed95..0328ff42ce 100644--- a/src/commands/serve.ts+++ b/src/commands/serve.ts@@ -77,7 +77,7 @@ export interface ServeOptions {// (which unconditionally attaches a 'data' listener to real// process.stdin and would pollute the test runner's stdin handle).// Defaults to the real implementation when omitted.- startMcpServer?: (engine: BrainEngine, opts?: { surface?: 'verbs' | 'starter' | 'full'; sourceGuard?: boolean }) => Promise<void>;+ startMcpServer?: (engine: BrainEngine, opts?: { surface?: 'verbs' | 'starter' | 'full'; sourceGuard?: boolean; access?: 'full' | 'read-only' }) => Promise<void>;// Test seam for the parent-process watchdog. The default// (`readLiveParentPid`) reads the live kernel PPID via `ps` on POSIX// because `process.ppid` is captured at process creation and does not@@ -213,9 +213,16 @@ export async function runServe(// 'verbs' exposes exactly the seven protocol verbs (the quickstart surface);// 'starter' the ~20-op daily-driver set; 'full' (default) keeps every// operation — existing installs see no change.- const { parseSurfaceFlag, resolveSurface } = await import('../mcp/surface.ts');+ const { parseSurfaceFlag, resolveSurface, parseAccessFlag } = await import('../mcp/surface.ts');const { loadConfig } = await import('../core/config.ts');const surface = resolveSurface(parseSurfaceFlag(args), loadConfig());+ // #4768: stdio read-only access ceiling. HTTP refuses it: per-token grants+ // (auth rescope-token --operations / rescope-client) are its operation control.+ const access = parseAccessFlag(args);+ if (access === 'read-only' && isHttp) {+ throw new Error('--access read-only applies to stdio serve only; for HTTP narrow each token with ' ++ 'gbrain auth rescope-token <name> --operations <op,...> (see docs/mcp/ADMIN.md#read-only-stdio-serve)');+ }// --source-guard (plugin lanes, EV1): fail-closed write routing for// user-global serves whose cwd is meaningless (plugin snapshots). Write/@@ -325,7 +332,7 @@ export async function runServe(// v0.45.7: count derives from VERB_NAMES (7 with context_pack + delta)// so the banner can't drift from the frozen set again.? `Starting GBrain MCP server (stdio) — serving ${VERB_NAMES.length} memory verbs (MEMORY_VERBS v1)...`- : 'Starting GBrain MCP server (stdio)...',+ : `Starting GBrain MCP server (stdio${access === 'read-only' ? ', read-only' : ''})...`,);// stdout is reserved for JSON-RPC frames from here on. Ops that run@@ -370,7 +377,7 @@ export async function runServe(}try {- await start(engine, { surface, ...(sourceGuard ? { sourceGuard } : {}) });+ await start(engine, { surface, ...(sourceGuard ? { sourceGuard } : {}), ...(access === 'read-only' ? { access } : {}) });// `--stdio-idle-timeout` arms its timer during lifecycle installation,// but its stdin activity listener must wait until startMcpServer has// attached the MCP SDK transport listener. Attaching any `data` listenerdiff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 48f8c5ee2f..9d31bdfe14 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -7,7 +7,7 @@ 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 { filterOpsForSurface, allowedOpNames, clampSurface, type McpSurface } from './surface.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';import { getBrainHotMemoryMeta } from '../core/facts/meta-hook.ts';@@ -196,7 +196,7 @@ export async function trackStdioRpc<T>(work: () => Promise<T>): Promise<T> {}}-export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSurface; sourceGuard?: boolean } = {}) {+export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSurface; sourceGuard?: boolean; access?: McpAccess } = {}) {const config = loadConfig();// Refuse to serve a well-formed GBRAIN_SOURCE that no active source row// backs (see source-preflight.ts). Throws before any transport is attached.@@ -213,8 +213,9 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS// (Resolved before Server construction: the initialize instructions need// the allowed-op set to decide whether extract_facts may be advertised.)const surface: McpSurface = clampSurface(opts.surface ?? 'full');- const surfacedOps = filterOpsForSurface(operations, surface);- const allowedOps = surface === 'full' ? undefined : allowedOpNames(operations, surface);+ const readOnly = opts.access === 'read-only';+ const surfacedOps = filterOpsForSurface(operations, surface).filter(op => !readOnly || isReadOnlyOperation(op));+ const allowedOps = readOnly ? new Set(surfacedOps.map(op => op.name)) : surface === 'full' ? undefined : allowedOpNames(operations, surface);// Ambient writeback (opt-in, default off): resolved ONCE at boot — a// config flip needs a serve restart on this lane, the same posture as@@ -256,7 +257,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSif (verified.remote) scopes = verified.grant.scopes;} catch {}}- return { transport: 'stdio', scopes, surface, source_id: scope.sourceId,+ return { transport: 'stdio', scopes, surface, access: readOnly ? 'read-only' : 'full', source_id: scope.sourceId,available_operations: available,administration: mcpAdministrationGuidance(),shared_skills: { protocol_version: 2, catalog: available.includes('list_skills') && available.includes('get_skill'),diff --git a/src/mcp/surface.ts b/src/mcp/surface.tsindex 69603b5166..baf3a8bde2 100644--- a/src/mcp/surface.ts+++ b/src/mcp/surface.ts@@ -138,6 +138,31 @@ export function parseSurfaceFlag(args: string[]): McpSurface | null {return raw;}+/**+ * #4768: stdio access ceiling. `--access read-only` intersects the selected+ * surface with operations that are read-scoped, non-mutating and need no+ * capability scope, so tools/list, the capabilities resource, skill+ * resources and dispatch all see one read-only set (`request_tools` is+ * mutating, so discovery cannot widen it). It denies agent-requested+ * mutations; owner maintenance (startup migrations, hook IPC banking) is a+ * separate control. HTTP enforces per-token operation grants instead.+ */+export type McpAccess = 'full' | 'read-only';++export function parseAccessFlag(args: string[]): McpAccess {+ const idx = args.indexOf('--access');+ if (idx < 0) return 'full';+ const raw = args[idx + 1];+ if (raw !== 'full' && raw !== 'read-only') {+ throw new Error('--access takes read-only or full (default full); see docs/mcp/ADMIN.md#read-only-stdio-serve');+ }+ return raw;+}++export function isReadOnlyOperation(op: Pick<Operation, 'scope' | 'mutating' | 'requiredScopes'>): boolean {+ return op.scope === 'read' && op.mutating !== true && !op.requiredScopes?.length;+}+/** Flag > config `mcp_surface` > 'full'. */export function resolveSurface(flag: McpSurface | null,diff --git a/test/serve-stdio-read-only.test.ts b/test/serve-stdio-read-only.test.tsnew file mode 100644index 0000000000..9e08fa0c19--- /dev/null+++ b/test/serve-stdio-read-only.test.ts@@ -0,0 +1,114 @@+/**+ * #4768 (stdio half): `gbrain serve --access read-only` over a real MCP stdio+ * session on a hermetic PGLite brain, on every surface tier.+ *+ * Protects: the read-only ceiling is one operation set for tools/list, the+ * capabilities resource and dispatch; guessed mutating tools (put_page,+ * delete_page, remember, capture) and request_tools are refused before any+ * handler runs (no page is written); read operations keep working; the+ * default (no flag) is unchanged; `--http --access read-only` refuses.+ * Regression it catches: a catalog-only filter that leaves dispatch resolving+ * the global catalog, or a predicate that admits mutating operations.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';+import { keylessBrainEnv } from './helpers/provider-env.ts';+import { operations } from '../src/core/operations.ts';+import { isReadOnlyOperation } from '../src/mcp/surface.ts';+import { CAPABILITIES_URI } from '../src/mcp/capabilities.ts';++const MARKER = 'readonly-marker-4768';+let home: string;+let env: Record<string, string>;++function cli(args: string[]) {+ return spawnSync('bun', ['--no-env-file', 'run', 'src/cli.ts', ...args], { cwd: process.cwd(), env, encoding: 'utf8' });+}++async function session(args: string[]): Promise<{ client: Client; close: () => Promise<void> }> {+ const transport = new StdioClientTransport({ command: 'bun', args: ['--no-env-file', 'run', 'src/cli.ts', 'serve', ...args], cwd: process.cwd(), env });+ const client = new Client({ name: 'gbrain-read-only-test', version: '1.0.0' }, { capabilities: {} });+ await client.connect(transport);+ return { client, close: async () => { await client.close().catch(() => {}); await transport.close().catch(() => {}); } };+}++const errorOf = (result: unknown): string | undefined => {+ const r = result as { isError?: boolean; content?: Array<{ text?: string }> };+ if (!r.isError) return undefined;+ try { return (JSON.parse(r.content?.[0]?.text ?? '{}') as { error?: string }).error ?? 'error'; } catch { return 'error'; }+};++beforeAll(() => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-stdio-read-only-'));+ env = keylessBrainEnv(process.env, home, { DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_REMOTE_CLIENT_SECRET: undefined });+ delete env.GBRAIN_SOURCE;+ expect(cli(['init', '--pglite', '--no-embedding', '--non-interactive']).status).toBe(0);+ const notes = join(home, 'notes');+ mkdirSync(notes, { recursive: true });+ writeFileSync(join(notes, 'marker.md'), `---\ntitle: ${MARKER} note\n---\n\n# ${MARKER}\n\nRead-only stdio fixture prose.\n`);+ expect(cli(['import', notes, '--no-embed']).status).toBe(0);+}, 120_000);++afterAll(() => { if (home) rmSync(home, { recursive: true, force: true }); });++test('the read-only predicate admits only non-mutating read operations of the live registry', () => {+ for (const op of operations) {+ if (op.scope !== 'read' || op.mutating === true || op.requiredScopes?.length) expect(isReadOnlyOperation(op)).toBe(false);+ }+ for (const name of ['put_page', 'delete_page', 'remember', 'capture', 'forget', 'request_tools', 'think', 'join_brain']) {+ expect(isReadOnlyOperation(operations.find(op => op.name === name)!)).toBe(false);+ }+ for (const name of ['search', 'get_page', 'query', 'recall']) expect(isReadOnlyOperation(operations.find(op => op.name === name)!)).toBe(true);+});++describe('serve --access read-only', () => {+ for (const surface of ['full', 'starter', 'verbs'] as const) {+ test(`${surface}: catalog, capabilities and dispatch agree and refuse every mutation`, async () => {+ const { client, close } = await session(['--surface', surface, '--access', 'read-only']);+ try {+ const listed = (await client.listTools()).tools.map(tool => tool.name).sort();+ expect(listed.length).toBeGreaterThan(0);+ for (const name of listed) expect(isReadOnlyOperation(operations.find(op => op.name === name)!)).toBe(true);+ const resource = (await client.readResource({ uri: CAPABILITIES_URI })).contents[0] as { text: string };+ const capabilities = JSON.parse(resource.text) as { access: string; available_operations: string[] };+ expect(capabilities.access).toBe('read-only');+ expect([...capabilities.available_operations].sort()).toEqual(listed);++ for (const [name, args] of [+ ['put_page', { slug: 'notes/injected', content: '# Injected' }],+ ['delete_page', { slug: 'marker' }],+ ['remember', { fact: 'Injected fact', entity: 'marker' }],+ ['capture', { content: 'Injected capture' }],+ ['request_tools', { tools: ['put_page'] }],+ ] as const) {+ expect(errorOf(await client.callTool({ name, arguments: { ...args } }))).toBe('unknown_tool');+ }+ const read = surface === 'verbs' ? 'recall' : 'search';+ const result = await client.callTool({ name: read, arguments: read === 'recall' ? { query: MARKER } : { query: MARKER, limit: 5 } });+ expect(errorOf(result)).toBeUndefined();+ } finally { await close(); }+ }, 60_000);+ }++ test('nothing was written and the default access is unchanged', async () => {+ const { client, close } = await session([]);+ try {+ const names = new Set((await client.listTools()).tools.map(tool => tool.name));+ expect(names.has('put_page')).toBe(true);+ const page = await client.callTool({ name: 'get_page', arguments: { slug: 'notes/injected' } });+ expect(errorOf(page)).toBe('page_not_found');+ expect(errorOf(await client.callTool({ name: 'get_page', arguments: { slug: 'marker' } }))).toBeUndefined();+ } finally { await close(); }+ }, 60_000);++ test('--http --access read-only refuses with the per-token fix', () => {+ const refused = cli(['serve', '--http', '--access', 'read-only', '--port', '0']);+ expect(refused.status).not.toBe(0);+ expect(refused.stderr).toContain('gbrain auth rescope-token <name> --operations');+ });+});