Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

P8 part E: mcp.advertised_surface narrows tools/list while every tool stays callable

garrytane97137d94dbf
diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.md
index eb71e23d38..25f2310fb9 100644
--- a/docs/architecture/key-files/mcp.md
+++ b/docs/architecture/key-files/mcp.md
@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/mcp/source-preflight.ts` — `assertStdioSourceBindable(engine, env?)`: stdio-lane boot preflight called first thing in `startMcpServer`, before any transport attaches. A well-formed `GBRAIN_SOURCE` that names no ACTIVE source row (`SELECT id FROM sources WHERE id = $1 AND archived = false`, the same predicate as `assertSourceExists` in `src/core/source-resolver.ts`) throws a message naming the value and the fix (`gbrain sources list`), so serve exits 1 instead of binding every call to a phantom scope where reads return `[]` and writes die on the sources FK while health stays green. An inherited `__all__` emits an engine-free stderr warning with a source-binding recovery action, without widening its fail-closed scope. Unset env and malformed values are left to the resolver; an engine error fail-opens (guards config, not connectivity); a degraded engine (`isEngineDegraded`) is never touched so the boot does not spend the proxy's reconnect attempt. HTTP is out of scope (tokens carry their own source grant). Pinned by `test/mcp-stdio-source-preflight.test.ts` and real PostgreSQL/PGLite processes in `test/e2e/mcp-search-transport-matrix.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), `resolveSurface` (flag > config `mcp_surface` > full), `filterOpsForSurface`, `allowedOpNames`. 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`, 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`.
+- `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), `resolveSurface` (flag > config `mcp_surface` > full), `filterOpsForSurface`, `allowedOpNames`. 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`, 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.serial.test.ts`.
- `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/docs/mcp/DEPLOY.md b/docs/mcp/DEPLOY.md
index a9f1ffa211..bbf8baaa5d 100644
--- a/docs/mcp/DEPLOY.md
+++ b/docs/mcp/DEPLOY.md
@@ -71,6 +71,21 @@ No server, no tunnel, no token needed. Works on both PGLite and Postgres engines
`--surface starter` sits between (~27 ops: the verbs plus the daily-driver set);
omit the flag (default `full`) for every operation.
+`--surface` is the callable ceiling. To keep every operation callable while
+listing fewer tools to the agent, set `mcp.advertised_surface`:
+
+```bash
+gbrain config set mcp.advertised_surface verbs # list the 7 verbs; everything else stays callable
+```
+
+`tools/list` then shows the advertised surface, and the initialize
+instructions tell the agent how many more tools are callable. On stdio,
+`request_tools` with `tools: [names]` returns their schemas and adds them to
+that session's list (the server sends `tools/list_changed`). On the OAuth HTTP
+server, a client that set its own surface (`request_tools` with `surface`, or
+`gbrain auth rescope-client`) has that surface listed in full. Unset
+advertises the whole callable set.
+
#### Stdio source binding
Do not inherit `GBRAIN_SOURCE=__all__` from a trusted CLI session into a
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 4512794515..35a8b19f34 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -25,7 +25,7 @@ src/core/postgres-engine.ts 2917 ratchet +1 System One v1 evals: search arms cla
src/core/search/hybrid.ts 1584 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key
src/core/types.ts 2124 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field)
src/core/minions/queue.ts 2522 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys
-src/commands/init.ts 1869 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle)
+src/commands/init.ts 1870 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +1 P8: newInstallAdvertisedSurface import (logic in mcp/surface.ts)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
src/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch
src/commands/bootstrap.ts 2142 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags)
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
-src/core/config.ts 1840 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +2 P8: dream.quote_verify and think.quote_verify known keys
+src/core/config.ts 1842 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts)
src/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 663 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts)
diff --git a/src/commands/init.ts b/src/commands/init.ts
index d5450e8916..92e4b184c2 100644
--- a/src/commands/init.ts
+++ b/src/commands/init.ts
@@ -18,6 +18,7 @@ import type { BrainEngine } from '../core/engine.ts';
import { readPrimaryEmbeddingStores, readStoredEmbeddingIdentity } from '../core/stored-embedding-identity.ts';
import { deferInitJsonError, flushInitJsonResult, initJsonError, setInitJsonResult, writeDeferredInitJsonError } from './init-json.ts';
import { deferredEmbeddingHint, firstRunBundle, firstRunJson, harnessRegistrationCommand } from './init-first-run.ts';
+import { newInstallAdvertisedSurface } from '../mcp/surface.ts';
import { writeCliNotices } from '../core/interop-notices.ts';
import { exitCodeForCode } from '../core/error-catalogue.ts';
import { promptLineStderr } from '../core/interaction.ts';
@@ -1228,7 +1229,7 @@ export async function initPGLite(opts: {
}
// PR1: new installs publish their skill catalog over MCP by default
// (existing config wins on re-init, so a prior opt-out is preserved).
- config.mcp = { ...(freshContentDatabase && !existingFile.engine ? { publish_skills: true } : {}), ...(config.mcp ?? {}) };
+ config.mcp = { ...(freshContentDatabase && !existingFile.engine ? { publish_skills: true, ...newInstallAdvertisedSurface() } : {}), ...(config.mcp ?? {}) };
// v0.42: new installs default self-upgrade to NOTIFY (a nudge on every
// gbrain invocation). mode_prompted=true so the upgrade-time banner doesn't
// also fire on a fresh install. Hands-off: gbrain config set self_upgrade.mode auto
@@ -1564,7 +1565,7 @@ export async function initPostgresCore(opts: {
}
// PR1: new installs publish their skill catalog over MCP by default
// (existing config wins on re-init, so a prior opt-out is preserved).
- config.mcp = { ...(freshContentDatabase && !existingFile.engine ? { publish_skills: true } : {}), ...(config.mcp ?? {}) };
+ config.mcp = { ...(freshContentDatabase && !existingFile.engine ? { publish_skills: true, ...newInstallAdvertisedSurface() } : {}), ...(config.mcp ?? {}) };
// v0.42: new installs default self-upgrade to NOTIFY (a nudge on every
// gbrain invocation). mode_prompted=true so the upgrade-time banner doesn't
// also fire on a fresh install. Hands-off: gbrain config set self_upgrade.mode auto
diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.ts
index 3021ae5829..c22ed48fad 100644
--- a/src/commands/serve-http-mcp.ts
+++ b/src/commands/serve-http-mcp.ts
@@ -30,6 +30,8 @@ import { GBRAIN_CLIENT_HEADER, resolveResultRowsMode, resultRowsForRequest, type
import { buildToolDefs } from '../mcp/tool-defs.ts';
import {
filterOpsForSurface,
+ advertisedOps,
+ resolveAdvertisedSurface,
clampSurface,
minSurface,
resolveClientRowSurface,
@@ -229,9 +231,10 @@ async function listMcpTools(ctx: ServeHttpContext, state: McpRequestState) {
// stays as the fail-closed backstop for all three layers.
// Both per-request config reads are independent — issue them
// concurrently (one RTT of latency on network Postgres, not two).
- const [gateDisabled, strictParamsMode] = await Promise.all([
+ const [gateDisabled, strictParamsMode, advertised] = await Promise.all([
disabledOpsForPublishGates(engine, config),
resolveStrictParamsMode(engine, config),
+ resolveAdvertisedSurface(engine, config),
]);
// FOV-4: `agent` deliberately implies only itself, which would strand
// agent-only tokens with ZERO discovery — ops flagged `agentCallable`
@@ -251,7 +254,9 @@ async function listMcpTools(ctx: ServeHttpContext, state: McpRequestState) {
// 'reject' closes each schema with additionalProperties:false and
// declares the _meta/dry_run passthrough keys (D14.1).
const strictParams = strictParamsMode === 'reject';
- const tools = buildToolDefs(visibleOps, { strictParams });
+ // mcp.advertised_surface narrows the list only; dispatch below keeps the callable set (request_tools reaches the rest).
+ // A client that chose its own surface (request_tools {surface}, an operator rescope) gets that surface listed in full.
+ const tools = buildToolDefs(authInfo.surface ? visibleOps : advertisedOps(visibleOps, surface, advertised), { strictParams });
// v0.28.10: log every JSON-RPC method, not just successful tools/call.
// Pre-fix, /admin/api/requests showed nothing for clients that only
// ever called tools/list, and the v0.26.3 persistence regression test
diff --git a/src/core/config.ts b/src/core/config.ts
index 709ea9d456..934c3f5c94 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -551,6 +551,8 @@ export interface GBrainConfig {
* over this file slot. Always bounded by the server ceiling (D2).
*/
default_surface_dcr?: 'verbs' | 'starter' | 'full';
+ /** Tools listed to agents (callable set unchanged; request_tools reaches the rest). Dual-plane, DB > file. */
+ advertised_surface?: 'verbs' | 'starter' | 'full';
/** Search/query row shape for remote MCP callers: 'lean' (default) | 'full'. Dual-plane, DB > file. */
result_rows?: 'lean' | 'full';
};
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index 68dfa9b008..2d38727bdc 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -445,6 +445,12 @@ export interface OperationContext {
* treated as 'full'.
*/
surfaceCeiling?: 'verbs' | 'starter' | 'full';
+ /**
+ * Set by transports that can widen a session's listed tools (stdio): when
+ * `request_tools` returns schemas, the named tools join this session's
+ * tools/list and the client is notified (tools/list_changed).
+ */
+ revealTools?: (names: string[]) => void;
/**
* Subagent runtime context (v0.16+). Set by the subagent tool dispatcher when
* dispatching an op as a tool call from an LLM loop. Used to enforce per-op
diff --git a/src/core/ops/request-tools.ts b/src/core/ops/request-tools.ts
index fe8f2a3a54..82e3cb44a8 100644
--- a/src/core/ops/request-tools.ts
+++ b/src/core/ops/request-tools.ts
@@ -265,6 +265,10 @@ const request_tools: Operation = {
const { buildToolDefs } = await import('../../mcp/tool-defs.ts');
const { resolveStrictParamsMode } = await import('../../mcp/validate-params.ts');
const strictParams = (await resolveStrictParamsMode(ctx.engine, ctx.config)) === 'reject';
+ if (ctx.revealTools && picked.length) {
+ ctx.revealTools(picked.map(o => o.name));
+ return { tools: buildToolDefs(picked, { strictParams }), listed: true, note: 'These tools are now in your tool list (tools/list_changed was sent); call them directly.' };
+ }
return { tools: buildToolDefs(picked, { strictParams }) };
}
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index 11d9a2ba91..0e02bb5c06 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -258,6 +258,8 @@ export interface DispatchOpts {
* treated as 'full'.
*/
surfaceCeiling?: 'verbs' | 'starter' | 'full';
+ /** Threaded into OperationContext.revealTools (stdio session tool reveal). */
+ revealTools?: (names: string[]) => void;
/** #5232: commit wait for coordinated writes (OperationContext.writeWaitMs); unset = agent default. */
writeWaitMs?: number;
/** C1: search/query row shape chosen by the transport (OperationContext.resultRows); unset = lean for remote callers. */
@@ -646,6 +648,7 @@ export function buildOperationContext(
...(opts.localFederatedSourceIds ? { localFederatedSourceIds: opts.localFederatedSourceIds } : {}),
...(opts.explicitReadBinding ? { explicitReadBinding: opts.explicitReadBinding } : {}),
...(opts.surfaceCeiling ? { surfaceCeiling: opts.surfaceCeiling } : {}),
+ ...(opts.revealTools ? { revealTools: opts.revealTools } : {}),
...(opts.writeWaitMs !== undefined ? { writeWaitMs: opts.writeWaitMs } : {}),
...(opts.resultRows ? { resultRows: opts.resultRows } : {}),
auth: opts.auth,
diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.ts
index 7946bd7b99..6dfdbd790c 100644
--- a/src/mcp/http-transport.ts
+++ b/src/mcp/http-transport.ts
@@ -43,7 +43,7 @@ import { VERSION } from '../version.ts';
import { dispatchToolCall, requestLogStatusForResult, errorResult } from './dispatch.ts';
import { GBRAIN_CLIENT_HEADER, resolveResultRowsMode, resultRowsForRequest } from './result-rows.ts';
import { parseStrictParamsMode } from './validate-params.ts';
-import { filterOpsForSurface, clampSurface, type McpSurface } from './surface.ts';
+import { filterOpsForSurface, clampSurface, advertisedOps, resolveAdvertisedSurface, type McpSurface } from './surface.ts';
import { disabledOpsForPublishGates } from './publish-gates.ts';
import { loadConfig } from '../core/config.ts';
import { buildDefaultLimiters, type RateLimiter } from './rate-limit.ts';
@@ -214,7 +214,8 @@ export async function startHttpTransport(opts: HttpTransportOptions) {
// enforcement still resolves per call.
const fileConfig = loadConfig();
const strictParams = parseStrictParamsMode(fileConfig?.mcp?.strict_params) === 'reject';
- const tools = buildToolDefs(surfacedOps, { strictParams });
+ // mcp.advertised_surface (file plane, read once like strict_params) narrows the list only; dispatch keeps surfacedOps.
+ const tools = buildToolDefs(advertisedOps(surfacedOps, surface, await resolveAdvertisedSurface(null, fileConfig)), { strictParams });
/**
* v0.41.3 (T6): single consolidated CORS header builder. Pre-fix there were
diff --git a/src/mcp/initialize-context.ts b/src/mcp/initialize-context.ts
index a8b0183ca1..98638187cb 100644
--- a/src/mcp/initialize-context.ts
+++ b/src/mcp/initialize-context.ts
@@ -14,6 +14,7 @@ import { configReadiness, probedReadiness, readinessHttpView, readinessTail, typ
import { isEngineDegraded } from '../core/degraded-marker.ts';
import { disabledOpsForPublishGates } from './publish-gates.ts';
import type { InstructionTools } from './instructions.ts';
+import { advertisedOps, resolveAdvertisedSurface } from './surface.ts';
/** Readiness entries the instructions tail may name, most limiting first. */
const TAIL_PRIORITY = ['embeddings', 'chat_llm', 'migrations', 'worker', 'local_transcripts'] as const;
@@ -43,7 +44,9 @@ export async function httpInstructionTools(
const names = new Set(opts.ops.filter(op =>
isCallable(op, { transport: 'http', surface: opts.surface, scopes: opts.auth.scopes, publishGates, allowedOps: opts.allowedOps })
&& opAllowedForBoundClient(opts.auth, op)).map(op => op.name));
- return { callable: n => names.has(n), readiness: await instructionReadiness(engine, config, 'http', opts.cache) };
+ const callable = opts.ops.filter(op => names.has(op.name));
+ const listed = opts.auth.surface ? callable : advertisedOps(callable, opts.surface, await resolveAdvertisedSurface(engine, config));
+ return { callable: n => names.has(n), readiness: await instructionReadiness(engine, config, 'http', opts.cache), hiddenCallable: callable.length - listed.length };
}
/**
diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.ts
index 5d01f0a5fb..983cae9804 100644
--- a/src/mcp/instructions.ts
+++ b/src/mcp/instructions.ts
@@ -31,6 +31,8 @@ export interface InstructionTools {
readiness?: readonly ReadinessEntry[];
/** Status-only serve (F4): one line naming gbrain_status. */
statusLine?: string;
+ /** Callable tools left out of the listed set (mcp.advertised_surface narrower than the callable set). */
+ hiddenCallable?: number;
}
const ALL: CallablePredicate = () => true;
@@ -94,6 +96,9 @@ export function buildMcpInstructions(opts?: { writeback?: AmbientWritebackOpts |
const clauses = contractClauses(tools?.callable ?? ALL);
let text = `GBrain agent operating contract (apply on every cold start):\n${clauses.map((c, i) => `${i + 1}. ${c}`).join('\n')}`;
if (tools?.statusLine) text += `\n${tools.statusLine}`;
+ if (tools?.hiddenCallable && tools.callable('request_tools')) {
+ text += `\nThe tool list shows the everyday tools; ${tools.hiddenCallable} more are callable. Call request_tools with no arguments to list them, or with tools: [names] for their schemas, then call them directly.`;
+ }
if (opts?.writeback) text += `\n\n${buildAmbientWritebackSection(opts.writeback)}`;
const tail = tools?.readiness ? readinessTail(tools.readiness, tools.callable) : null;
if (tail) text += `\n\n${tail}`;
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 14fc75f87d..f510c14275 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -9,7 +9,7 @@ import { VERSION } from '../version.ts';
import { buildToolDefs } from './tool-defs.ts';
import { dispatchToolCall, buildOperationContext } from './dispatch.ts';
import { findInvalidParam, schemaInvalidParams, parseStrictParamsMode } from './validate-params.ts';
-import { filterOpsForSurface, allowedOpNames, clampSurface, isReadOnlyOperation, type McpAccess, type McpSurface } from './surface.ts';
+import { filterOpsForSurface, allowedOpNames, clampSurface, isReadOnlyOperation, resolveAdvertisedSurface, stdioToolListing, type McpAccess, type McpSurface } from './surface.ts';
import { disabledOpsForPublishGates } from './publish-gates.ts';
import { parseResultRowsMode, resolveResultRowsMode } from './result-rows.ts';
import type { Operation } from '../core/operations.ts';
@@ -259,16 +259,16 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
instructions: resolveMcpInstructions(config, process.env, { writeback: writebackOpts }),
},
);
- // F1: the contract for the effective callable set + readiness tail (or the
- // status-only line), resolved when the client initializes.
+ const listing = stdioToolListing(() => resolveAdvertisedSurface(isEngineDegraded(engine) ? null : engine, config), surface, server);
+ // F1: callable-set contract + readiness tail (or status-only line), resolved at client initialize.
installInstructionsResolver(server, async () => {
if (statusMode && isEngineDegraded(engine)) {
return resolveMcpInstructions(config, process.env, { tools: { callable: n => n === STATUS_TOOL_NAME, statusLine: statusInstructionLine(statusMode) } });
}
- const visible = new Set((await stdioVisibleTools(engine, surfacedOps)).map(op => op.name));
+ const visibleOps = await stdioVisibleTools(engine, surfacedOps), visible = new Set(visibleOps.map(op => op.name));
return resolveMcpInstructions(config, process.env, {
writeback: writebackOpts,
- tools: { callable: n => visible.has(n), readiness: await instructionReadiness(engine, config, 'stdio') },
+ tools: { callable: n => visible.has(n), readiness: await instructionReadiness(engine, config, 'stdio'), hiddenCallable: visibleOps.length - (await listing.listed(visibleOps)).length },
});
});
@@ -315,7 +315,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
server.setRequestHandler(ListToolsRequestSchema, async () => trackStdioRpc(async () => ({
tools: statusMode && isEngineDegraded(engine)
? [STATUS_TOOL_DEF]
- : buildToolDefs(await stdioVisibleTools(engine, surfacedOps), { strictParams }),
+ : buildToolDefs(await listing.listed(await stdioVisibleTools(engine, surfacedOps)), { strictParams }),
})));
// #4583 (fixes #4564's misrouted-write symptom): once-per-process advisory
@@ -394,7 +394,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
surface,
// WP4 (D2): stdio has no per-client rows; its surface is the ceiling
// request_tools bounds its catalog by (persist no-ops without auth).
- surfaceCeiling: surface,
+ surfaceCeiling: surface, revealTools: listing.reveal,
resultRows,
});
}));
diff --git a/src/mcp/surface.ts b/src/mcp/surface.ts
index ec921ece9e..68bd0f76e0 100644
--- a/src/mcp/surface.ts
+++ b/src/mcp/surface.ts
@@ -286,6 +286,68 @@ export async function resolveDefaultClientSurface(
return isMcpSurface(fileVal) ? fileVal : null;
}
+/**
+ * The surface fresh installs list to agents (`gbrain init` writes it to
+ * `mcp.advertised_surface`). The held-out agent benchmark chooses between
+ * 'verbs' and 'starter'; until it does, fresh installs list everything.
+ */
+export const NEW_INSTALL_ADVERTISED_SURFACE: McpSurface = 'full';
+
+/**
+ * `mcp.advertised_surface`: which tools `tools/list` shows. The callable set
+ * (the ceiling: --surface > mcp_surface > full, per-client rows on HTTP) is
+ * unchanged, so a tool outside the advertised list is still callable and
+ * `request_tools` returns its schema. The ceiling stays the security boundary;
+ * the advertised list is a context-cost choice. DB plane wins, file plane
+ * falls back; unset or unrecognized = advertise the whole callable set.
+ */
+export async function resolveAdvertisedSurface(engine: BrainEngine | null, config: GBrainConfig | null | undefined): Promise<McpSurface | null> {
+ if (engine) {
+ try {
+ const dbVal = await engine.getConfig('mcp.advertised_surface');
+ if (isMcpSurface(dbVal)) return dbVal;
+ if (dbVal != null) return null;
+ } catch { /* file plane decides */ }
+ }
+ const fileVal = (config?.mcp as Record<string, unknown> | undefined)?.advertised_surface;
+ return isMcpSurface(fileVal) ? fileVal : null;
+}
+
+/** The tools to list: the callable set narrowed to the advertised surface (never wider). */
+export function advertisedOps<T extends Operation>(callable: T[], callableSurface: McpSurface, advertised: McpSurface | null): T[] {
+ if (!advertised || !surfaceWiderThan(callableSurface, advertised)) return callable;
+ const listed = new Set(filterOpsForSurface(callable as Operation[], advertised).map(op => op.name));
+ return callable.filter(op => listed.has(op.name));
+}
+
+/**
+ * A stdio session's tool listing: the advertised surface, plus every tool
+ * `request_tools` described in this session (`reveal`), which notifies the
+ * client with tools/list_changed. `mcp.advertised_surface` narrows only this
+ * listing; dispatch keeps the callable set.
+ */
+export function stdioToolListing(advertised: () => Promise<McpSurface | null>, callableSurface: McpSurface,
+ server: { sendToolListChanged(): Promise<void> }) {
+ const revealed = new Set<string>();
+ const notify = () => { Promise.resolve(server.sendToolListChanged()).catch(() => { /* best-effort */ }); };
+ return {
+ async listed<T extends Operation>(visible: T[]): Promise<T[]> {
+ const listed = advertisedOps(visible, callableSurface, await advertised());
+ return listed.length === visible.length ? visible : visible.filter(op => revealed.has(op.name) || listed.includes(op));
+ },
+ reveal(names: string[]): void {
+ const before = revealed.size;
+ for (const name of names) revealed.add(name);
+ if (revealed.size > before) notify();
+ },
+ };
+}
+
+/** What a fresh `gbrain init` writes into `mcp`: the advertised surface, unless it is 'full'. */
+export function newInstallAdvertisedSurface(): { advertised_surface?: 'verbs' | 'starter' } {
+ return NEW_INSTALL_ADVERTISED_SURFACE === 'full' ? {} : { advertised_surface: NEW_INSTALL_ADVERTISED_SURFACE };
+}
+
/**
* D2 CEILING resolution — the per-request effective surface on the OAuth
* HTTP transport:
diff --git a/test/mcp-advertised-surface.serial.test.ts b/test/mcp-advertised-surface.serial.test.ts
new file mode 100644
index 0000000000..95ccc913d9
--- /dev/null
+++ b/test/mcp-advertised-surface.serial.test.ts
@@ -0,0 +1,100 @@
+/**
+ * `mcp.advertised_surface` narrows what tools/list shows without narrowing
+ * what can be called. On stdio: a tool outside the listed set is still
+ * callable, and once request_tools describes it, it joins this session's
+ * list (tools/list_changed). The callable ceiling (--surface) still blocks.
+ * Initialize instructions name request_tools when tools are left unlisted.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } 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 { ToolListChangedNotificationSchema } from '@modelcontextprotocol/sdk/types.js';
+import { operations } from '../src/core/operations.ts';
+import { advertisedOps, filterOpsForSurface, resolveAdvertisedSurface } from '../src/mcp/surface.ts';
+import { buildMcpInstructions } from '../src/mcp/instructions.ts';
+import { keylessBrainEnv } from './helpers/provider-env.ts';
+
+const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');
+let home: string;
+
+function childEnv(): Record<string, string> {
+ return keylessBrainEnv(process.env, home, {
+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_SOURCE: undefined,
+ GBRAIN_NON_INTERACTIVE: '1', GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_NO_BANNER: '1', NO_COLOR: '1',
+ });
+}
+
+async function gbrain(args: string[]): Promise<{ code: number; out: string }> {
+ const proc = Bun.spawn([process.execPath, '--no-env-file', CLI, ...args], { cwd: home, env: childEnv(), stdin: Bun.file('/dev/null'), stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ return { code, out: `${stdout}\n${stderr}` };
+}
+
+async function session<T>(serveArgs: string[], fn: (client: Client, changed: () => number) => Promise<T>): Promise<T> {
+ const transport = new StdioClientTransport({ command: process.execPath, args: ['--no-env-file', CLI, 'serve', ...serveArgs], env: childEnv(), cwd: home, stderr: 'pipe' });
+ const client = new Client({ name: 'advertised-surface', version: '1' }, { capabilities: {} });
+ let changes = 0;
+ client.setNotificationHandler(ToolListChangedNotificationSchema, async () => { changes++; });
+ await client.connect(transport);
+ try { return await fn(client, () => changes); } finally { await client.close().catch(() => {}); }
+}
+
+beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-advertised-'));
+ const init = await gbrain(['init', '--pglite', '--no-embedding']);
+ if (init.code !== 0) throw new Error(`init failed: ${init.out}`);
+ const set = await gbrain(['config', 'set', 'mcp.advertised_surface', 'verbs']);
+ if (set.code !== 0) throw new Error(`config set failed: ${set.out}`);
+}, 180_000);
+afterAll(() => { rmSync(home, { recursive: true, force: true }); });
+
+describe('advertised surface (pure)', () => {
+ test('narrows the callable list, never widens it', () => {
+ const full = filterOpsForSurface(operations, 'full');
+ expect(advertisedOps(full, 'full', 'verbs').map(o => o.name).sort()).toEqual(filterOpsForSurface(operations, 'verbs').map(o => o.name).sort());
+ const verbs = filterOpsForSurface(operations, 'verbs');
+ expect(advertisedOps(verbs, 'verbs', 'full')).toBe(verbs);
+ expect(advertisedOps(full, 'full', null)).toBe(full);
+ });
+
+ test('the database plane wins over the file plane; unrecognized values advertise everything', async () => {
+ const engine = { getConfig: async (k: string) => (k === 'mcp.advertised_surface' ? 'starter' : null) } as never;
+ expect(await resolveAdvertisedSurface(engine, { mcp: { advertised_surface: 'verbs' } } as never)).toBe('starter');
+ expect(await resolveAdvertisedSurface(null, { mcp: { advertised_surface: 'verbs' } } as never)).toBe('verbs');
+ const junk = { getConfig: async () => 'everything' } as never;
+ expect(await resolveAdvertisedSurface(junk, { mcp: { advertised_surface: 'verbs' } } as never)).toBeNull();
+ });
+
+ test('instructions name request_tools only when tools are unlisted and request_tools is callable', () => {
+ expect(buildMcpInstructions({ tools: { callable: () => true, hiddenCallable: 130 } })).toContain('130 more are callable. Call request_tools');
+ expect(buildMcpInstructions({ tools: { callable: () => true } })).not.toContain('more are callable');
+ expect(buildMcpInstructions({ tools: { callable: n => n !== 'request_tools', hiddenCallable: 5 } })).not.toContain('more are callable');
+ });
+});
+
+describe('stdio session', () => {
+ test('lists the verbs, calls an unlisted tool, and lists it once request_tools describes it', async () => {
+ await session([], async (client, changed) => {
+ const listed = (await client.listTools()).tools.map(t => t.name);
+ expect(listed.sort()).toEqual(filterOpsForSurface(operations, 'verbs').map(o => o.name).sort());
+ expect(listed).not.toContain('put_page');
+ const put = await client.callTool({ name: 'put_page', arguments: { slug: 'notes/advertised', content: '---\ntype: note\ntitle: Advertised\n---\nHidden but callable.\n' } });
+ expect(put.isError).toBeFalsy();
+ const req = await client.callTool({ name: 'request_tools', arguments: { tools: ['put_page'] } });
+ expect(req.isError).toBeFalsy();
+ for (let i = 0; i < 50 && changed() === 0; i++) await Bun.sleep(50);
+ expect(changed()).toBe(1);
+ expect((await client.listTools()).tools.map(t => t.name)).toContain('put_page');
+ });
+ }, 120_000);
+
+ test('the callable ceiling still blocks', async () => {
+ await session(['--surface', 'verbs'], async (client) => {
+ const put = await client.callTool({ name: 'put_page', arguments: { slug: 'notes/blocked', content: 'x' } });
+ expect(put.isError).toBe(true);
+ });
+ }, 120_000);
+});