Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(mcp): onboarding coaching and a widenable session surface on the stdio pipe

garrytanc5a952b43a0a
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 91af9af8a5..f19bd15325 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -196,6 +196,7 @@ test/link-source-check-repair.test.ts regex literal drift guard (#4613) 1 readFi
test/longmemeval-embed-cache.test.ts EmbeddingCache — canonical hash 4 readFileSync
test/loops-extract-wiring.test.ts jobs.ts wiring 2 source-surface-helper
test/loops-extract-wiring.test.ts relational edge vocabulary 2 readFileSync,source-surface-helper
+test/mcp-registration.test.ts every stdio registration path builds from REGISTRATION_SURFACE 4 readFileSync
test/meeting-ingestion-attendance-template.test.ts (file-level) 3 readFileSync
test/migrate-stdout-clean.test.ts migration output stays off stdout 2 source-surface-helper
test/migrate.test.ts PR #356 + #363 — session timeouts applied via startup parameters 1 readFileSync,source-surface-helper
diff --git a/src/cli/commands/notices.ts b/src/cli/commands/notices.ts
index 919cba0f45..25ab8218cb 100644
--- a/src/cli/commands/notices.ts
+++ b/src/cli/commands/notices.ts
@@ -4,13 +4,15 @@
* for coaching/info notices. Engine-free.
*/
import { writeStdoutFinal, setCliExitVerdict } from '../../core/cli-force-exit.ts';
-import { mutedNoticeCodes, setNoticeMuted } from '../../core/notice-ledger.ts';
+import { mutedNoticeCodes, setNoticeMuted, unmuteNoticeForOwner } from '../../core/notice-ledger.ts';
import { MUTEABLE_NOTICE_CODES } from '../../core/ops/notices.ts';
const HELP = `Usage: gbrain notices <mute|unmute> <code> | gbrain notices list [--json]
-Mute a coaching or info notice for every agent connected to this brain.
-Safety, degraded and ask notices always show.
+Mute a coaching or info notice (or the first_run_decisions ask) for every
+agent connected to this brain. Unmute clears the owner's mute and the one set
+through mute_notice on the stdio MCP pipe. Other safety, degraded and ask
+notices always show.
Muteable codes: ${MUTEABLE_NOTICE_CODES.join(', ')}
`;
@@ -23,7 +25,7 @@ export async function run(args: string[]): Promise<void> {
return;
}
if (sub === 'list') {
- const muted = [...mutedNoticeCodes()].sort();
+ const muted = [...mutedNoticeCodes('stdio')].sort();
await writeStdoutFinal(json ? `${JSON.stringify({ muted, muteable: MUTEABLE_NOTICE_CODES }, null, 2)}\n` : `${muted.length ? muted.join('\n') : '(no muted notices)'}\n`);
return;
}
@@ -32,6 +34,6 @@ export async function run(args: string[]): Promise<void> {
setCliExitVerdict(2);
return;
}
- const muted = setNoticeMuted(code, sub === 'mute');
+ const muted = sub === 'mute' ? setNoticeMuted(code, true) : unmuteNoticeForOwner(code);
await writeStdoutFinal(json ? `${JSON.stringify({ code, muted: sub === 'mute', muted_codes: muted }, null, 2)}\n` : `${sub === 'mute' ? 'Muted' : 'Unmuted'} ${code}.\n`);
}
diff --git a/src/cli/help/serve.ts b/src/cli/help/serve.ts
index 586acc71ea..bd4b17c6d5 100644
--- a/src/cli/help/serve.ts
+++ b/src/cli/help/serve.ts
@@ -9,7 +9,7 @@ export const help: CliHelpSpec = {
].join('\n'),
flags: [
{ name: '--http', type: 'boolean', desc: 'Serve over HTTP with OAuth 2.1, the admin dashboard and per-token scopes.' },
- { name: '--surface', type: 'enum', values: ['verbs', 'starter', 'full'], desc: 'Tool surface: the 7 memory verbs, the ~20 daily-driver ops, or every operation (default: config mcp_surface, else full).' },
+ { name: '--surface', type: 'enum', values: ['verbs', 'starter', 'full'], desc: 'Tool surface: the 7 memory verbs, the daily-driver ops, or every operation. stdio: env GBRAIN_SURFACE > --surface > config mcp_surface > full; --http ignores GBRAIN_SURFACE.' },
{ name: '--access', type: 'enum', values: ['full', 'read-only'], desc: 'stdio only: read-only exposes read-scoped, non-mutating operations.' },
{ name: '--source-guard', type: 'boolean', desc: 'stdio only: refuse writes unless the source binding is deliberate or unambiguous.' },
{ name: '--stdio-idle-timeout', type: 'number', desc: 'stdio only: exit after this many idle seconds (0 = never).' },
diff --git a/src/commands/doctor/checks/memory-writeback.ts b/src/commands/doctor/checks/memory-writeback.ts
index 47aa47aed6..6e3e30928c 100644
--- a/src/commands/doctor/checks/memory-writeback.ts
+++ b/src/commands/doctor/checks/memory-writeback.ts
@@ -38,6 +38,7 @@ import { readVerbUsage } from '../../../core/verbs/usage-log.ts';
import { readClientOpUsage } from '../../../core/mcp-usage.ts';
import { readHeartbeatTail } from '../../../core/context/hook-heartbeat.ts';
import { readHarnessReceiptState } from '../../../core/bootstrap/format.ts';
+import { mutedFirstRunDecisionsNotice } from '../../../core/onboard/mcp-onboarding.ts';
import {
probeAmbientBlock,
renderAmbientInstructionBlock,
@@ -316,12 +317,15 @@ export async function buildMemoryWritebackCheck(engine: BrainEngine | null): Pro
};
} catch { /* heartbeat unreadable — counters stay absent */ }
+ const mutedDecisions = await mutedFirstRunDecisionsNotice(engine).catch(() => null);
+ if (mutedDecisions) details.first_run_decisions_muted = { why: mutedDecisions.why, unmute: mutedDecisions.fix?.argv };
return {
name: MEMORY_WRITEBACK_CHECK_NAME,
status: problems.length ? 'warn' : 'ok',
- message: problems.length
+ message: (problems.length
? `ambient writeback ${wb.mode}: ${problems.join('; ')}`
- : `ambient writeback ${wb.mode} (ttl ${wb.transient_ttl}, template visibility ${wb.visibility}, audience ${audience.audience})`,
+ : `ambient writeback ${wb.mode} (ttl ${wb.transient_ttl}, template visibility ${wb.visibility}, audience ${audience.audience})`)
+ + (mutedDecisions ? '; first-run decisions are open but muted (`gbrain notices unmute first_run_decisions` shows them again)' : ''),
details,
...(problems.some((p) => p.includes('gbrain bootstrap harness'))
? { fix: {
diff --git a/src/commands/features.ts b/src/commands/features.ts
index 31075cee0d..6e2349544f 100644
--- a/src/commands/features.ts
+++ b/src/commands/features.ts
@@ -228,6 +228,13 @@ export async function scanFeatures(engine: BrainEngine): Promise<FeatureScanResu
};
}
+/** The recommendations `gbrain features` would pitch to this user now; reads the offer state, never writes it. */
+export async function pitchableFeatures(engine: BrainEngine): Promise<FeatureRecommendation[]> {
+ const scan = await scanFeatures(engine);
+ const offers = loadOffers();
+ return scan.recommendations.filter(r => shouldPitch(r, offers, scan.version));
+}
+
// --- Auto-fix ---
async function executeAutoFix(rec: FeatureRecommendation, engine: BrainEngine): Promise<{ success: boolean; output: string }> {
@@ -362,8 +369,8 @@ export async function runFeatures(engine: BrainEngine, args: string[]) {
/** Auto-fixes that embed (paid): they need the user's approval (--yes, --max-usd, --max-cost, tokenmax or a preapproval). */
const PAID_AUTO_FIX_IDS: ReadonlySet<string> = new Set(['missing-embeddings', 'low-coverage']);
-/** F7: the `features_auto_fix` coaching notice; null when nothing is auto-fixable. */
-function featuresAutoFixNotice(pitchable: readonly FeatureRecommendation[]): Notice | null {
+/** F7: the `features_auto_fix` coaching notice; null when nothing is auto-fixable. Pure: the CLI and the stdio onboarding cache share it. */
+export function featuresAutoFixNotice(pitchable: readonly FeatureRecommendation[]): Notice | null {
const fixable = pitchable.filter(r => r.auto_fixable);
if (fixable.length === 0) return null;
const paid = fixable.some(r => PAID_AUTO_FIX_IDS.has(r.id));
diff --git a/src/commands/onboard.ts b/src/commands/onboard.ts
index 58b2c5cdc8..a698dad723 100644
--- a/src/commands/onboard.ts
+++ b/src/commands/onboard.ts
@@ -125,11 +125,15 @@ export async function runOnboard(engine: BrainEngine, args: string[]): Promise<v
if (check && !auto) {
const plan = await computeRemediationPlan(engine, { targetScore, extraRemediations });
const report = buildOnboardReport(plan);
+ const { mutedFirstRunDecisionsNotice } = await import('../core/onboard/mcp-onboarding.ts');
+ const muted = await mutedFirstRunDecisionsNotice(engine).catch(() => null);
if (jsonOutput) {
- process.stdout.write(JSON.stringify(report, null, 2) + '\n');
+ const { cliRenderContext, renderNotice } = await import('../core/agent-output.ts');
+ process.stdout.write(JSON.stringify(muted ? { ...report, notices: [renderNotice(muted, cliRenderContext())] } : report, null, 2) + '\n');
return;
}
process.stdout.write(renderHuman(report) + '\n');
+ if (muted) (await import('../core/interop-notices.ts')).writeCliNotices([muted]);
// v0.42 (T16): --explain extension. Per-cluster narrative for the
// pack_upgrade_available recommendation. Runs unify-types in dry-run
// mode and renders the per-rule diff. No-op when no pack upgrade
diff --git a/src/commands/serve.ts b/src/commands/serve.ts
index 3dd36fd4b8..9c9b86d009 100644
--- a/src/commands/serve.ts
+++ b/src/commands/serve.ts
@@ -82,7 +82,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; onBootPhase?: (phase: string) => void; access?: 'full' | 'read-only' }) => Promise<void>;
+ startMcpServer?: (engine: BrainEngine, opts?: { surface?: 'verbs' | 'starter' | 'full'; surfaceSource?: 'env' | 'flag' | 'config' | 'default'; invalidSurfaceEnv?: string; sourceGuard?: boolean; onBootPhase?: (phase: string) => void; 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
@@ -214,13 +214,23 @@ export async function runServe(
// that used `gbrain auth create` keep working unchanged).
const isHttp = args.includes('--http');
- // MEMORY_VERBS v1: tool-surface mode. Flag > config `mcp_surface` > 'full'.
+ // MEMORY_VERBS v1: tool-surface mode. stdio: GBRAIN_SURFACE > --surface >
+ // config `mcp_surface` > 'full'; --http ignores GBRAIN_SURFACE (an HTTP
+ // ceiling never widens without an explicit --surface restart).
// '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, parseAccessFlag } = await import('../mcp/surface.ts');
+ // 'starter' the ~20-op daily-driver set; 'full' keeps every operation.
+ const { parseSurfaceFlag, resolveSurfaceWithSource, resolveStdioSurface, parseAccessFlag, SURFACE_SOURCE_LABEL } = await import('../mcp/surface.ts');
const { loadConfig } = await import('../core/config.ts');
- const surface = resolveSurface(parseSurfaceFlag(args), loadConfig());
+ const surfaceFlag = parseSurfaceFlag(args);
+ const resolved = isHttp ? resolveSurfaceWithSource(surfaceFlag, loadConfig()) : resolveStdioSurface(surfaceFlag, loadConfig());
+ const surface = resolved.surface;
+ if (isHttp && process.env.GBRAIN_SURFACE) {
+ console.error('[gbrain serve] GBRAIN_SURFACE is ignored with --http: the HTTP surface ceiling is set by --surface (or config mcp_surface); GBRAIN_MCP_FORCE_SURFACE narrows it.');
+ }
+ if (resolved.invalidEnv !== undefined) {
+ console.error(`[gbrain serve] ignoring GBRAIN_SURFACE="${resolved.invalidEnv}" (use verbs | starter | full)`);
+ }
+ console.error(`[gbrain serve] surface=${surface} (source: ${SURFACE_SOURCE_LABEL[resolved.source]})`);
// #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);
@@ -394,7 +404,7 @@ export async function runServe(
}
try {
- await start(engine, { surface, ...(sourceGuard ? { sourceGuard } : {}), onBootPhase: phase => { bootPhase = phase; bootProgressAt = Date.now(); }, ...(access === 'read-only' ? { access } : {}) });
+ await start(engine, { surface, surfaceSource: resolved.source, ...(resolved.invalidEnv !== undefined ? { invalidSurfaceEnv: resolved.invalidEnv } : {}), ...(sourceGuard ? { sourceGuard } : {}), onBootPhase: phase => { bootPhase = phase; bootProgressAt = Date.now(); }, ...(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` listener
diff --git a/src/core/config.ts b/src/core/config.ts
index 60c1fb60d9..e00ab7a8a5 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -553,6 +553,8 @@ export interface GBrainConfig {
default_surface_dcr?: 'verbs' | 'starter' | 'full';
/** Search/query row shape for remote MCP callers: 'lean' (default) | 'full'. Dual-plane, DB > file. */
result_rows?: 'lean' | 'full';
+ /** Stdio `request_tools {surface}` widens the session's tool surface (default true). Dual-plane, DB > file. */
+ allow_session_widen?: boolean | string;
};
}
@@ -1535,6 +1537,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// Read dual-plane by src/mcp/validate-params.ts (DB > file > 'warn').
'mcp.strict_params',
'mcp.result_rows', // C1 row shape, read dual-plane by src/mcp/result-rows.ts
+ 'mcp.allow_session_widen', // stdio request_tools session widening (default on), read dual-plane by src/mcp/surface.ts
// Skill-nag suppression (#2180): brain-resident pack install nag off-switch.
'skillpack.nag_disabled',
// Self-upgrade (v0.42; file plane, read on the hot path)
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 02d15a8203..014a7ae07a 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -314,7 +314,8 @@ export interface NoticeEntry {
export const NOTICE_CODES = {
backup_coverage: { kind: 'coaching', summary: 'Some knowledge assets have no off-machine backup.' },
empty_retrieval: { kind: 'info', summary: 'A retrieval returned no results; the notice says whether recall was degraded.' },
- first_run_decisions: { kind: 'ask', summary: 'init finished; the first-run decisions (search mode, harness wiring, …) carry defaults the user may change.' },
+ first_run_decisions: { kind: 'ask', summary: 'init finished (or a stdio MCP session started on a brain with open decisions); the first-run decisions (search mode, writeback, harness wiring, skills) carry defaults the user may change. The one muteable ask.' },
+ first_run_decisions_muted: { kind: 'info', summary: 'First-run decisions are still open, but the user muted them; the fix shows them again (`gbrain notices unmute first_run_decisions`).' },
migrations_pending: { kind: 'safety', summary: 'Schema migrations are pending or failed to apply on this brain.' },
no_worker: { kind: 'degraded', summary: 'A job was queued but no worker is running to execute it; it waits until a worker runs.' },
unknown_param: { kind: 'info', summary: 'The call passed a parameter the tool does not declare; it was ignored.' },
@@ -326,6 +327,11 @@ export const NOTICE_CODES = {
synthesis_keyless: { kind: 'info', summary: 'think returned gathered evidence without synthesis because no chat-model key is configured (by design on a keyless brain).' },
think_not_saved: { kind: 'info', summary: 'think save/take persist only for the local CLI, so this answer was not saved.' },
onboard_opportunities: { kind: 'coaching', summary: 'Onboarding checks found work that would improve this brain (gbrain onboard --check lists it).' },
+ onboard_stale_chunks: { kind: 'coaching', summary: 'This search could not match chunks that have no embedding; the remedy is an embedding backfill (paid, ask first).' },
+ onboard_link_coverage: { kind: 'coaching', summary: 'Few people/company pages have incoming links, so backlinks and graph answers are thin; the remedy is link extraction.' },
+ onboard_timeline_coverage: { kind: 'coaching', summary: 'Few people/company pages have timeline entries, so dated answers are thin; the remedy is timeline extraction.' },
+ onboard_no_takes: { kind: 'coaching', summary: 'The brain holds no takes, so think and recall cannot cite the user\'s own views; the remedy is recording or extracting takes.' },
+ surface_env_invalid: { kind: 'info', summary: 'GBRAIN_SURFACE holds a value other than verbs, starter or full; the server ignored it and names the surface it serves.' },
features_auto_fix: { kind: 'coaching', summary: 'gbrain features found auto-fixable gaps; the fix is the auto-fix command (it may spend on embeddings).' },
post_upgrade: { kind: 'safety', summary: 'gbrain was upgraded; behavior for scripts and agents changed — read the behavior table once.' },
held_files: { kind: 'degraded', summary: 'Sync holds files in the read scope it cannot import: held new files are missing and pages whose newer file is held are stale; the fix is the repair preview on the brain host.' },
diff --git a/src/core/notice-ledger.ts b/src/core/notice-ledger.ts
index 7bf7c5aacb..d547769c80 100644
--- a/src/core/notice-ledger.ts
+++ b/src/core/notice-ledger.ts
@@ -21,6 +21,8 @@ const MAX_KEYS = 10_000;
const TTL_MS = 24 * 60 * 60 * 1000;
export const COACHING_BUDGET_PER_SESSION = 2;
/** Notices that describe THIS call's result (never deduped): the diagnosis must ride every affected call. */
+/** The one muteable `ask`: an unanswered first-run bundle must stay dismissible. Every other ask always shows. */
+export const MUTEABLE_ASK_CODES: ReadonlySet<string> = new Set(['first_run_decisions']);
export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated', 'source_binding_narrowed', 'local_transcripts', 'held_files']);
export interface NoticeAudience {
@@ -54,7 +56,7 @@ export class NoticeLedger {
const out: Notice[] = [];
const session = this.session(audience);
for (const n of notices) {
- if ((n.kind === 'coaching' || n.kind === 'info') && muted.has(n.code)) continue;
+ if ((n.kind === 'coaching' || n.kind === 'info' || MUTEABLE_ASK_CODES.has(n.code)) && muted.has(n.code)) continue;
const always = PER_CALL_NOTICE_CODES.has(n.code)
|| (audience.transport === 'http' && (n.kind === 'degraded' || n.kind === 'safety'));
const key = `${session}|${n.code}`;
@@ -115,10 +117,27 @@ export function setNoticeMuted(code: string, muted: boolean, principal?: string)
if (muted) list.add(code); else list.delete(code);
const sorted = [...list].sort();
if (principal) f.clients[principal] = sorted; else f.global = sorted;
+ writeMuteFile(f);
+ return sorted;
+}
+
+/**
+ * The owner's unmute: clears the code from the global list and from the
+ * stdio MCP pipe's list (`mute_notice` over stdio stores under `stdio`).
+ * Returns the owner's remaining muted codes across both.
+ */
+export function unmuteNoticeForOwner(code: string): string[] {
+ const f = readMuteFile();
+ f.global = f.global.filter(c => c !== code);
+ if (f.clients.stdio) f.clients.stdio = f.clients.stdio.filter(c => c !== code);
+ writeMuteFile(f);
+ return [...new Set([...f.global, ...(f.clients.stdio ?? [])])].sort();
+}
+
+function writeMuteFile(f: MuteFile): void {
const path = noticeMutePath();
mkdirSync(dirname(path), { recursive: true });
const tmp = `${path}.tmp-${process.pid}`;
writeFileSync(tmp, `${JSON.stringify(f, null, 2)}\n`, { mode: 0o600 });
renameSync(tmp, path);
- return sorted;
}
diff --git a/src/core/onboard/init-nudge.ts b/src/core/onboard/init-nudge.ts
index a029e6a6cf..1eec4f3ac1 100644
--- a/src/core/onboard/init-nudge.ts
+++ b/src/core/onboard/init-nudge.ts
@@ -15,6 +15,7 @@
import type { BrainEngine } from '../engine.ts';
import { writeCliNotices } from '../interop-notices.ts';
+import { collectOnboardOpportunities, LINK_COVERAGE_MIN, TIMELINE_COVERAGE_MIN } from './mcp-onboarding.ts';
const NUDGE_BUDGET_MS = 3000;
@@ -38,77 +39,18 @@ export async function runInitNudge(engine: BrainEngine): Promise<void> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), NUDGE_BUDGET_MS);
- let totalStale = 0;
- let totalEntities = 0;
- let linkedCount = 0;
- let timelineCount = 0;
- let takesCount = 0;
- // -1 = the page-count probe failed: fail-open sentinel, treat as non-empty
- // so current behavior is preserved when the count is unknown.
- let totalPages = -1;
- let checksRan = 0;
- let checksAttempted = 0;
- let partial = false;
-
- // Run 4 cheap counts in parallel against the 3s budget.
- const results = await Promise.allSettled([
- engine.executeRaw<{ count: string | number }>(
- `SELECT COUNT(*) AS count FROM content_chunks WHERE embedding IS NULL`,
- [],
- { signal: controller.signal },
- ),
- engine.executeRaw<{ count: string | number }>(
- `SELECT COUNT(*) AS count FROM pages
- WHERE type IN ('person', 'company', 'organization', 'entity')
- AND deleted_at IS NULL`,
- [],
- { signal: controller.signal },
- ),
- engine.executeRaw<{ count: string | number }>(
- `SELECT COUNT(*) AS count FROM pages p
- WHERE p.type IN ('person', 'company', 'organization', 'entity')
- AND p.deleted_at IS NULL
- AND EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = p.id)`,
- [],
- { signal: controller.signal },
- ),
- engine.executeRaw<{ count: string | number }>(
- `SELECT COUNT(*) AS count FROM pages p
- WHERE p.type IN ('person', 'company', 'organization', 'entity')
- AND p.deleted_at IS NULL
- AND EXISTS (SELECT 1 FROM timeline_entries t WHERE t.page_id = p.id)`,
- [],
- { signal: controller.signal },
- ),
- engine.executeRaw<{ count: string | number }>(
- `SELECT COUNT(*) AS count FROM takes`,
- [],
- { signal: controller.signal },
- ),
- engine.executeRaw<{ count: string | number }>(
- `SELECT COUNT(*) AS count FROM pages WHERE deleted_at IS NULL`,
- [],
- { signal: controller.signal },
- ),
- ]);
+ const counts = await collectOnboardOpportunities(engine, controller.signal);
clearTimeout(timer);
- checksAttempted = results.length;
- for (let i = 0; i < results.length; i++) {
- const r = results[i];
- if (r.status === 'rejected') {
- partial = true;
- continue;
- }
- checksRan++;
- const n = r.value.length > 0 ? Number(r.value[0].count) : 0;
- if (i === 0) totalStale = n;
- else if (i === 1) totalEntities = n;
- else if (i === 2) linkedCount = n;
- else if (i === 3) timelineCount = n;
- else if (i === 4) takesCount = n;
- else if (i === 5) totalPages = n;
- }
+ const totalStale = counts.staleChunks ?? 0;
+ const totalEntities = counts.entities ?? 0;
+ const linkedCount = counts.linkedEntities ?? 0;
+ const timelineCount = counts.timelineEntities ?? 0;
+ const takesCount = counts.takes ?? 0;
+ // -1 = the page-count probe failed: fail-open sentinel, treat as non-empty
+ // so current behavior is preserved when the count is unknown.
+ const totalPages = counts.pages ?? -1;
+ const { checksRan, checksAttempted, partial } = counts;
// A brand-new EMPTY brain has no "opportunities" — telling a fresh user
// "0 takes" at the end of their first init is jargon-noise on the
@@ -122,18 +64,18 @@ export async function runInitNudge(engine: BrainEngine): Promise<void> {
const timelineCoverage = totalEntities > 0 ? timelineCount / totalEntities : 1;
const hasRecommendations =
totalStale > 0
- || (totalEntities > 0 && linkCoverage < 0.7)
- || (totalEntities > 0 && timelineCoverage < 0.9)
+ || (totalEntities > 0 && linkCoverage < LINK_COVERAGE_MIN)
+ || (totalEntities > 0 && timelineCoverage < TIMELINE_COVERAGE_MIN)
|| takesCount === 0;
if (!hasRecommendations && !partial) return;
// Emit one-line nudge. Be terse — init is the activation surface.
const parts: string[] = [];
if (totalStale > 0) parts.push(`${totalStale} stale chunks`);
- if (totalEntities > 0 && linkCoverage < 0.7) {
+ if (totalEntities > 0 && linkCoverage < LINK_COVERAGE_MIN) {
parts.push(`link coverage ${Math.round(linkCoverage * 100)}%`);
}
- if (totalEntities > 0 && timelineCoverage < 0.9) {
+ if (totalEntities > 0 && timelineCoverage < TIMELINE_COVERAGE_MIN) {
parts.push(`timeline coverage ${Math.round(timelineCoverage * 100)}%`);
}
if (takesCount === 0) parts.push('0 takes');
diff --git a/src/core/onboard/mcp-onboarding.ts b/src/core/onboard/mcp-onboarding.ts
new file mode 100644
index 0000000000..2c35dcefa0
--- /dev/null
+++ b/src/core/onboard/mcp-onboarding.ts
@@ -0,0 +1,399 @@
+/**
+ * Onboarding coaching for the owner's stdio MCP pipe (agent operator
+ * contract v1). The counts behind init's nudge live in one shared collector;
+ * a per-brain cache (6 h TTL, persisted under GBRAIN_HOME, refreshed in the
+ * background only while no dispatch is in flight) turns them into one
+ * coaching notice per opportunity class. Each class attaches only to a call
+ * whose result shows the limitation (`ONBOARD_CALL_AFFINITY` plus a result
+ * predicate), so the agent hears about thin link coverage on a backlinks
+ * call, not on a write. Init's first-run decisions ride the second
+ * successful call of a session. HTTP gets none of it: the counts are
+ * brain-wide and every remedy runs on the brain host.
+ */
+import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
+import { dirname } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import type { Action, Notice, RenderContext } from '../agent-output.ts';
+import { gbrainPath, type GBrainConfig } from '../config.ts';
+import { configReadiness } from '../readiness.ts';
+import { recallStagesFor } from '../interop-notices.ts';
+
+export const LINK_COVERAGE_MIN = 0.7;
+export const TIMELINE_COVERAGE_MIN = 0.9;
+const TTL_MS = 6 * 60 * 60 * 1000;
+const REFRESH_BUDGET_MS = 3000;
+const IDLE_POLL_MS = 250;
+const ENTITY_TYPES: ReadonlySet<string> = new Set(['person', 'company', 'organization', 'entity']);
+
+/** The six counts init's nudge reports; null when that probe failed or hit the budget. */
+export interface OnboardCounts {
+ staleChunks: number | null;
+ entities: number | null;
+ linkedEntities: number | null;
+ timelineEntities: number | null;
+ takes: number | null;
+ pages: number | null;
+ linkCoverage: number | null;
+ timelineCoverage: number | null;
+ partial: boolean;
+ checksRan: number;
+ checksAttempted: number;
+}
+
+const COUNT_SQL = [
+ `SELECT COUNT(*) AS count FROM content_chunks WHERE embedding IS NULL`,
+ `SELECT COUNT(*) AS count FROM pages
+ WHERE type IN ('person', 'company', 'organization', 'entity')
+ AND deleted_at IS NULL`,
+ `SELECT COUNT(*) AS count FROM pages p
+ WHERE p.type IN ('person', 'company', 'organization', 'entity')
+ AND p.deleted_at IS NULL
+ AND EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = p.id)`,
+ `SELECT COUNT(*) AS count FROM pages p
+ WHERE p.type IN ('person', 'company', 'organization', 'entity')
+ AND p.deleted_at IS NULL
+ AND EXISTS (SELECT 1 FROM timeline_entries t WHERE t.page_id = p.id)`,
+ `SELECT COUNT(*) AS count FROM takes`,
+ `SELECT COUNT(*) AS count FROM pages WHERE deleted_at IS NULL`,
+] as const;
+
+/**
+ * Run the six counts. Parallel by default (init); with `between`, one at a
+ * time with `between()` awaited before each (the background refresh yields
+ * the single PGLite connection between counts).
+ */
+export async function collectOnboardOpportunities(
+ engine: BrainEngine, signal: AbortSignal, between?: () => Promise<void>,
+): Promise<OnboardCounts> {
+ const run = (sql: string) => engine.executeRaw<{ count: string | number }>(sql, [], { signal });
+ let results: PromiseSettledResult<{ count: string | number }[]>[];
+ if (between) {
+ results = [];
+ for (const sql of COUNT_SQL) {
+ await between();
+ results.push(signal.aborted
+ ? { status: 'rejected', reason: new Error('onboard count budget exceeded') }
+ : await run(sql).then(value => ({ status: 'fulfilled' as const, value }), reason => ({ status: 'rejected' as const, reason })));
+ }
+ } else {
+ results = await Promise.allSettled(COUNT_SQL.map(run));
+ }
+ const n = results.map(r => (r.status === 'fulfilled' ? (r.value.length > 0 ? Number(r.value[0].count) : 0) : null));
+ const [staleChunks, entities, linkedEntities, timelineEntities, takes, pages] = n;
+ const coverage = (part: number | null) => (entities === null || part === null ? null : entities > 0 ? part / entities : 1);
+ const checksRan = n.filter(v => v !== null).length;
+ return {
+ staleChunks, entities, linkedEntities, timelineEntities, takes, pages,
+ linkCoverage: coverage(linkedEntities), timelineCoverage: coverage(timelineEntities),
+ partial: checksRan < results.length, checksRan, checksAttempted: results.length,
+ };
+}
+
+export type OnboardClass = 'stale_chunks' | 'link_coverage' | 'timeline_coverage' | 'no_takes';
+
+/** The calls each class may attach to. Every name is a catalogue op; each class reaches the verbs and starter surfaces. */
+export const ONBOARD_CALL_AFFINITY: Readonly<Record<OnboardClass, readonly string[]>> = {
+ stale_chunks: ['search', 'query', 'recall', 'context_pack'],
+ link_coverage: ['get_backlinks', 'traverse_graph', 'entity'],
+ timeline_coverage: ['get_timeline', 'entity', 'get_page'],
+ no_takes: ['think', 'takes_list', 'recall', 'context_pack'],
+};
+
+/** `features_auto_fix` rides link-graph calls only; the embedding gap is `onboard_stale_chunks`. */
+export const FEATURES_CALL_AFFINITY: readonly string[] = ['get_backlinks', 'traverse_graph'];
+
+/** Brain-wide gaps by init's thresholds; a failed count never reads as a gap, and an empty brain has none. */
+export function onboardGaps(c: OnboardCounts): Record<OnboardClass, boolean> {
+ const brain = c.pages !== 0;
+ return {
+ stale_chunks: brain && (c.staleChunks ?? 0) > 0,
+ link_coverage: brain && (c.entities ?? 0) > 0 && c.linkCoverage !== null && c.linkCoverage < LINK_COVERAGE_MIN,
+ timeline_coverage: brain && (c.entities ?? 0) > 0 && c.timelineCoverage !== null && c.timelineCoverage < TIMELINE_COVERAGE_MIN,
+ no_takes: brain && c.takes === 0,
+ };
+}
+
+// ── cache ───────────────────────────────────────────────────────────────────
+
+/** A pitchable `gbrain features` recommendation (the fields the auto-fix notice reads). */
+export interface CachedFeature { id: string; priority: 1 | 2; title: string; pitch: string; command: string; auto_fixable: boolean }
+
+interface OnboardSnapshot {
+ at: number;
+ counts: OnboardCounts;
+ stale_usd: number | null;
+ features: CachedFeature[];
+}
+
+interface OnboardState {
+ snapshot: OnboardSnapshot | null;
+ firstRun: Notice[] | null;
+ calls: number;
+ started: boolean;
+ refreshing: Promise<void> | null;
+ idle: () => boolean;
+ now: () => number;
+}
+
+const fresh = (): OnboardState => ({ snapshot: null, firstRun: null, calls: 0, started: false, refreshing: null, idle: () => true, now: Date.now });
+let st: OnboardState = fresh();
+
+const optedOut = () => process.env.GBRAIN_NO_ONBOARD_NUDGE === '1';
+
+async function cachePath(): Promise<string> {
+ const { resolveBrainId } = await import('../brain-resolver.ts');
+ const { getCliOptions } = await import('../cli-options.ts');
+ let brainId = 'host';
+ try { brainId = resolveBrainId(getCliOptions().brain); } catch { /* host */ }
+ return gbrainPath(`onboard-counts-${brainId.replace(/[^A-Za-z0-9_-]/g, '_')}.json`);
+}
+
+async function readPersisted(): Promise<OnboardSnapshot | null> {
+ try {
+ const raw = JSON.parse(readFileSync(await cachePath(), 'utf8')) as Partial<OnboardSnapshot>;
+ if (typeof raw.at !== 'number' || !raw.counts || st.now() - raw.at > TTL_MS) return null;
+ return { at: raw.at, counts: raw.counts, stale_usd: raw.stale_usd ?? null, features: Array.isArray(raw.features) ? raw.features : [] };
+ } catch {
+ return null;
+ }
+}
+
+async function persist(snapshot: OnboardSnapshot): Promise<void> {
+ try {
+ const path = await cachePath();
+ mkdirSync(dirname(path), { recursive: true });
+ const tmp = `${path}.tmp-${process.pid}`;
+ writeFileSync(tmp, `${JSON.stringify(snapshot)}\n`, { mode: 0o600 });
+ renameSync(tmp, path);
+ } catch { /* the cache is an optimization */ }
+}
+
+const yieldTurn = () => new Promise<void>(resolve => setImmediate(resolve));
+
+/** The first-run decisions an MCP-only agent can relay: writeback and the skills scaffold (no search mode, no harness wiring). */
+export async function mcpFirstRunNotices(engine: BrainEngine): Promise<Notice[]> {
+ const { writebackAskApplies } = await import('./writeback-nudge.ts');
+ const { initSkillsScaffold } = await import('../skillpack/post-install-advisory.ts');
+ const { buildInitFirstRunNotices } = await import('../../commands/init-first-run.ts');
+ return buildInitFirstRunNotices({ writeback: await writebackAskApplies(engine), skillsScaffold: initSkillsScaffold() });
+}
+
+/**
+ * Doctor and `gbrain onboard --check`: first-run decisions that are still
+ * open while the user muted `first_run_decisions`, with the unmute command.
+ */
+export async function mutedFirstRunDecisionsNotice(engine: BrainEngine): Promise<Notice | null> {
+ const { mutedNoticeCodes } = await import('../notice-ledger.ts');
+ if (!mutedNoticeCodes('stdio').has('first_run_decisions')) return null;
+ const open = (await mcpFirstRunNotices(engine)).flatMap(n => n.decisions ?? []).map(d => d.id);
+ if (open.length === 0) return null;
+ return {
+ code: 'first_run_decisions_muted', kind: 'info',
+ why: `First-run decisions are still open (${open.join(', ')}), but first_run_decisions is muted, so agents no longer relay them.`,
+ user_message: `Some gbrain setup choices are still open (${open.join(', ')}) and their reminder is muted. Want to see them again?`,
+ fix: {
+ argv: ['gbrain', 'notices', 'unmute', 'first_run_decisions'], consent: [], actor: 'user', requires_exclusive: false,
+ why: 'Shows the first-run decisions to agents again; the user muted them, so unmuting is their call.',
+ },
+ };
+}
+
+async function refresh(engine: BrainEngine, counts: boolean): Promise<void> {
+ try {
+ if (!st.firstRun) st.firstRun = await mcpFirstRunNotices(engine).catch(() => []);
+ if (!counts) return;
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), REFRESH_BUDGET_MS);
+ timer.unref?.();
+ const c = await collectOnboardOpportunities(engine, controller.signal, yieldTurn).finally(() => clearTimeout(timer));
+ await yieldTurn();
+ let staleUsd: number | null = null;
+ if ((c.staleChunks ?? 0) > 0) {
+ const { estimateEmbedBackfillUsd } = await import('../embed-consent.ts');
+ staleUsd = await estimateEmbedBackfillUsd(engine, {});
+ }
+ await yieldTurn();
+ let features: CachedFeature[] = [];
+ try {
+ const { pitchableFeatures } = await import('../../commands/features.ts');
+ features = await pitchableFeatures(engine);
+ } catch { /* features coaching is optional */ }
+ const snapshot: OnboardSnapshot = { at: st.now(), counts: c, stale_usd: staleUsd, features };
+ st.snapshot = snapshot;
+ if (!c.partial) await persist(snapshot);
+ } catch { /* coaching never breaks serve */ }
+}
+
+function needsCounts(): boolean {
+ return !st.snapshot || st.now() - st.snapshot.at > TTL_MS;
+}
+
+function scheduleRefresh(engine: BrainEngine): void {
+ if (st.refreshing || (!needsCounts() && st.firstRun)) return;
+ const counts = needsCounts();
+ st.refreshing = new Promise<void>(resolve => {
+ const tick = () => {
+ if (!st.idle()) { setTimeout(tick, IDLE_POLL_MS).unref?.(); return; }
+ void refresh(engine, counts).finally(() => { st.refreshing = null; resolve(); });
+ };
+ setTimeout(tick, 0).unref?.();
+ });
+}
+
+/**
+ * Start the stdio serve's onboarding cache: load the persisted counts, then
+ * refresh in the background when stale. `idle` reports whether no dispatch
+ * is in flight; the refresh starts only then (PGLite has one connection).
+ */
+export async function startOnboardingRefresher(engine: BrainEngine, opts: { idle: () => boolean }): Promise<void> {
+ if (optedOut() || st.started) return;
+ st.started = true;
+ st.idle = opts.idle;
+ st.snapshot ??= await readPersisted();
+ scheduleRefresh(engine);
+}
+
+// ── notices ─────────────────────────────────────────────────────────────────
+
+const LOCK_NOTE = 'CLI commands take the brain lock this server holds, so run them after this session ends or through the running server.';
+
+function previewFix(): Action {
+ return {
+ argv: ['gbrain', 'onboard', '--check'], mcp: { tool: 'get_health', arguments: {} },
+ consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Read-only: shows the brain\'s coverage numbers (gbrain onboard --check also lists each remedy with its command).',
+ };
+}
+
+function dismissal(code: string, render: RenderContext): string {
+ return render.isCallable('mute_notice')
+ ? ` To stop this notice, call mute_notice {"code":"${code}"}.`
+ : ` To stop this notice, the user runs \`gbrain notices mute ${code}\`.`;
+}
+
+const pct = (v: number | null) => `${Math.round((v ?? 0) * 100)}%`;
+
+function classNotice(cls: OnboardClass, s: OnboardSnapshot, render: RenderContext): Notice {
+ const c = s.counts;
+ const code = `onboard_${cls}`;
+ const tail = ` Preview: the fix below (read-only). ${LOCK_NOTE}${dismissal(code, render)}`;
+ const parts: Record<OnboardClass, { why: string; user_message: string }> = {
+ stale_chunks: {
+ why: `${c.staleChunks} chunk(s) in this brain have no embedding, so the semantic part of this search cannot match them. `
+ + `Remedy: an embedding backfill (\`gbrain embed --stale\`${s.stale_usd !== null ? `, estimated $${s.stale_usd.toFixed(2)}` : ''}); `
+ + 'it sends page text to the embedding provider and costs money, so ask the user first.',
+ user_message: `${c.staleChunks} piece(s) of your notes are not indexed for meaning-based search, so searches can miss them. `
+ + `Indexing them sends the text to your embedding provider${s.stale_usd !== null ? ` and costs about $${s.stale_usd.toFixed(2)}` : ' and costs a little money'}. Want me to run it after this session?`,
+ },
+ link_coverage: {
+ why: `Only ${pct(c.linkCoverage)} of this brain's ${c.entities} people/company pages have an incoming link, so backlinks and graph answers come back thin. `
+ + 'Remedy: link extraction (`gbrain extract links`, local, no paid calls).',
+ user_message: 'Many of your people and company pages are not linked to the notes that mention them, so "who is connected to X" answers are thin. Want me to run gbrain\'s link extraction (free, local) after this session?',
+ },
+ timeline_coverage: {
+ why: `Only ${pct(c.timelineCoverage)} of this brain's ${c.entities} people/company pages have timeline entries, so "when did X happen" answers come back thin. `
+ + 'Remedy: timeline extraction (`gbrain extract timeline`, local, no paid calls).',
+ user_message: 'Many of your people and company pages have no dated timeline entries, so "when did X happen" answers are thin. Want me to run gbrain\'s timeline extraction (free, local) after this session?',
+ },
+ no_takes: {
+ why: 'This brain holds no takes (the user\'s recorded opinions and judgments), so think and recall cannot cite the user\'s own views. '
+ + 'Remedy: record takes as they come up (`gbrain takes add`), or extract them from existing pages (`gbrain takes extract --from-pages`, which calls the chat model and costs money, so ask the user first).',
+ user_message: 'Your brain has no recorded opinions yet, so I cannot cite your own views. Want me to extract them from your existing notes (uses the AI model, small cost) after this session?',
+ },
+ };
+ return { code, kind: 'coaching', why: parts[cls].why + tail, user_message: parts[cls].user_message, fix: previewFix() };
+}
+
+const VECTOR_MISS_STAGES: ReadonlySet<string> = new Set(['embed_unavailable', 'keyword_only_no_embedding_provider', 'embed_timeout', 'vector_arm_failed']);
+
+async function pageLacksTimeline(engine: BrainEngine, result: Record<string, unknown>): Promise<boolean> {
+ if (!ENTITY_TYPES.has(String(result.type ?? ''))) return false;
+ if (Array.isArray(result.timeline_entries)) return result.timeline_entries.length === 0;
+ if (typeof result.id !== 'number' && typeof result.id !== 'string') return false;
+ const rows = await engine.executeRaw(`SELECT 1 FROM timeline_entries WHERE page_id = $1 LIMIT 1`, [result.id]);
+ return rows.length === 0;
+}
+
+interface CallEvidence {
+ engine: BrainEngine;
+ op: string;
+ result: unknown;
+ meta: Record<string, unknown>;
+ config?: GBrainConfig | null;
+}
+
+/** The per-class result predicate: the call's own result must show the limitation. */
+async function evidenceFor(cls: OnboardClass, e: CallEvidence): Promise<boolean> {
+ const r = (e.result && typeof e.result === 'object' ? e.result : {}) as Record<string, unknown>;
+ const card = (r.card ?? {}) as { entity?: { type?: string | null }; last_touched?: { last_timeline_date?: string | null }; backlink_count?: number };
+ switch (cls) {
+ case 'stale_chunks': {
+ const embeddings = e.config ? configReadiness(e.config, { transport: 'stdio' }).entries.find(x => x.capability === 'embeddings') : undefined;
+ if (embeddings?.state !== 'ok') return false;
+ return !recallStagesFor(e.op, e.result, e.meta, e.config).some(stage => VECTOR_MISS_STAGES.has(stage));
+ }
+ case 'link_coverage':
+ return e.op !== 'entity' || (r.found === true && card.backlink_count === 0);
+ case 'timeline_coverage':
+ if (e.op === 'get_timeline') return Array.isArray(e.result) && e.result.length === 0;
+ if (e.op === 'entity') return r.found === true && ENTITY_TYPES.has(String(card.entity?.type ?? '')) && !card.last_touched?.last_timeline_date;
+ return pageLacksTimeline(e.engine, r);
+ case 'no_takes':
+ return true;
+ }
+}
+
+function firstRunForMcp(bundle: Notice[], render: RenderContext): Notice[] {
+ return bundle.map(n => ({
+ ...n,
+ why: `${n.why} Finish the user's current request, then ask. Each option's argv applies it on the brain host; ${LOCK_NOTE}${dismissal(n.code, render)}`,
+ }));
+}
+
+/**
+ * Dispatch's one producer call on the stdio success path: the first-run
+ * bundle from the second successful call on, plus the opportunity and
+ * features notices whose class this call shows. A cold cache yields only
+ * the bundle; the caller's ledger applies dedupe, budget and mutes. Never throws.
+ */
+export async function mcpOnboardingNotices(
+ e: CallEvidence & { render: RenderContext },
+): Promise<Notice[]> {
+ try {
+ if (optedOut()) return [];
+ st.calls++;
+ if (st.started) scheduleRefresh(e.engine);
+ const out: Notice[] = [];
+ if (st.calls >= 2 && st.firstRun?.length) out.push(...firstRunForMcp(st.firstRun, e.render));
+ const s = st.snapshot;
+ if (!s) return out;
+ const gaps = onboardGaps(s.counts);
+ for (const cls of Object.keys(ONBOARD_CALL_AFFINITY) as OnboardClass[]) {
+ if (gaps[cls] && ONBOARD_CALL_AFFINITY[cls].includes(e.op) && await evidenceFor(cls, e)) out.push(classNotice(cls, s, e.render));
+ }
+ if (FEATURES_CALL_AFFINITY.includes(e.op) && s.features.some(f => f.id === 'zero-links' && f.auto_fixable)) {
+ const { featuresAutoFixNotice } = await import('../../commands/features.ts');
+ const notice = featuresAutoFixNotice(s.features);
+ if (notice) out.push(notice);
+ }
+ return out;
+ } catch {
+ return [];
+ }
+}
+
+/** Test seam: fill the cache now (ignores the idle gate and the TTL). */
+export async function __warmOnboardingCacheForTests(engine: BrainEngine): Promise<void> {
+ st.started = true;
+ await refresh(engine, true);
+}
+
+/** Test seam: wait for a scheduled background refresh to settle. */
+export async function __awaitOnboardingRefreshForTests(): Promise<void> {
+ await st.refreshing;
+}
+
+/** Test seam: a fresh process state, optionally with an injected clock. */
+export function __resetMcpOnboardingForTests(now: () => number = Date.now): void {
+ st = { ...fresh(), now };
+}
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index 547a12f24a..cc0e4a3252 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -16,6 +16,7 @@ import { publicWriteReceipt, type WriteErrorCode, type WriteReceipt } from '../p
// renderer below when it loads.
import type { Action, Notice } from '../agent-output.ts';
import type { RegistryCode } from '../error-registry.ts';
+import type { StdioSurfaceState } from '../../mcp/surface.ts';
/** Agent contract v1: the wire renderer for `fix`/`notices` in toJSON(), registered by agent-output.ts on load. */
interface OperationErrorWireRenderer { fix(a: Action): unknown; notice(n: Notice): unknown }
@@ -444,6 +445,8 @@ export interface OperationContext {
* treated as 'full'.
*/
surfaceCeiling?: 'verbs' | 'starter' | 'full';
+ /** The stdio session's surface (stdio MCP only): `request_tools` widens it for this session, `whoami` reports it. */
+ stdioSurface?: StdioSurfaceState;
/**
* 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/notices.ts b/src/core/ops/notices.ts
index 96e3cfb315..d97d992b37 100644
--- a/src/core/ops/notices.ts
+++ b/src/core/ops/notices.ts
@@ -6,19 +6,19 @@
import type { Operation } from './contract.ts';
import { opError } from './contract.ts';
import { NOTICE_CODES } from '../error-registry.ts';
-import { setNoticeMuted } from '../notice-ledger.ts';
+import { MUTEABLE_ASK_CODES, setNoticeMuted } from '../notice-ledger.ts';
-const MUTEABLE = Object.entries(NOTICE_CODES).filter(([, e]) => e.kind === 'coaching' || e.kind === 'info').map(([c]) => c).sort();
+const MUTEABLE = Object.entries(NOTICE_CODES)
+ .filter(([c, e]) => e.kind === 'coaching' || e.kind === 'info' || MUTEABLE_ASK_CODES.has(c)).map(([c]) => c).sort();
const mute_notice: Operation = {
name: 'mute_notice',
mutating: true,
idempotent: true,
outputRedaction: 'no_stored_text',
- description: 'Stop a coaching or info notice from appearing for this client (or unmute it with muted: false). '
- + 'Safety, degraded and ask notices cannot be muted.',
+ description: 'Stop a coaching or info notice (or first_run_decisions) from appearing for this client; muted: false unmutes.',
params: {
- code: { type: 'string', required: true, description: 'Notice code, the word after `[gbrain notice` in the block.', enum: MUTEABLE },
+ code: { type: 'string', required: true, description: 'Notice code, the word after `[gbrain notice` in the block.' },
muted: { type: 'boolean', description: 'false unmutes. Default true.' },
},
scope: 'write',
@@ -26,7 +26,7 @@ const mute_notice: Operation = {
const code = String(p.code ?? '');
if (!MUTEABLE.includes(code)) {
throw opError('invalid_params', `Notice ${code || '(empty)'} cannot be muted.`,
- `Mute one of: ${MUTEABLE.join(', ')}. Safety, degraded and ask notices always show.`);
+ `Mute one of: ${MUTEABLE.join(', ')}. Safety, degraded and ask notices always show (first_run_decisions is the one muteable ask).`);
}
const principal = ctx.remote === false ? undefined : ctx.auth?.clientId ?? 'stdio';
const muted = p.muted !== false;
diff --git a/src/core/ops/request-tools.ts b/src/core/ops/request-tools.ts
index fe8f2a3a54..9c75a04169 100644
--- a/src/core/ops/request-tools.ts
+++ b/src/core/ops/request-tools.ts
@@ -114,11 +114,51 @@ async function visibleOpsForCaller(
);
}
+/**
+ * Stdio branch of the {surface} call: widen this session's allow-set (the
+ * one tools/list and dispatch share), never past `--access read-only` or
+ * GBRAIN_MCP_FORCE_SURFACE, then answer with the newly allowed tools'
+ * schemas so a client that ignores `tools/list_changed` can call them by
+ * name. Nothing is written; a new session starts at the registered surface.
+ */
+async function widenStdioSession(ctx: OperationContext, requested: 'verbs' | 'starter' | 'full'): Promise<Record<string, unknown>> {
+ const session = ctx.stdioSurface!;
+ const { clampSurface, sessionWidenAllowed, surfaceWiderThan } = await import('../../mcp/surface.ts');
+ session.widenAllowed = await sessionWidenAllowed(ctx.engine, ctx.config);
+ const persistent = `For a lasting change, set GBRAIN_SURFACE=${requested} in this harness's gbrain server env (or re-register the server with --surface ${requested}) and start a new session.`;
+ if (!session.widenAllowed) {
+ throw opError('permission_denied',
+ 'Session widening is off on this brain (mcp.allow_session_widen is false), so request_tools cannot add tools to this stdio session.',
+ `${persistent} The user can turn session widening back on with \`gbrain config set mcp.allow_session_widen true\`.`,
+ { fix: hostFix(ctx, ['gbrain', 'config', 'set', 'mcp.allow_session_widen', 'true'],
+ `Turns stdio session widening back on (the brain owner turned it off). ${persistent}`) });
+ }
+ const target = clampSurface(requested);
+ if (!surfaceWiderThan(target, session.surface)) {
+ return { persisted: false, scope: 'session', surface: session.surface, widened: false,
+ note: target !== requested
+ ? `GBRAIN_MCP_FORCE_SURFACE caps this server at '${target}', so this session stays at '${session.surface}'.`
+ : `This session already serves '${session.surface}', which includes everything in '${requested}'.` };
+ }
+ if (ctx.dryRun) return { persisted: false, scope: 'session', dry_run: true, surface: target, previous: session.surface };
+ const change = session.widen(target);
+ const added = new Set(change.added);
+ 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';
+ const visible = (await visibleOpsForCaller(ctx, target)).filter(op => added.has(op.name));
+ return {
+ persisted: false, scope: 'session', surface: target, previous: change.from,
+ tools: buildToolDefs(visible, { strictParams }),
+ note: `This session now serves '${target}' (tools/list_changed was sent). Call the new tools by name now; their schemas are above. A new session starts at the registered surface. ${persistent}`,
+ };
+}
+
const request_tools: Operation = {
name: 'request_tools',
idempotent: false,
outputRedaction: 'no_stored_text',
- description: 'More tools: no arguments lists your catalog; {tools: [names]} returns schemas; {surface} persists a wider surface for your OAuth client.',
+ description: 'More tools: no arguments lists your catalog; {tools: [names]} returns schemas; {surface} widens it (per OAuth client; stdio: this session).',
area: 'discovery',
// FOV-4: callable by read OR agent scope — discovery for every token class.
agentCallable: true,
@@ -131,7 +171,7 @@ const request_tools: Operation = {
surface: {
type: 'string',
enum: ['verbs', 'starter', 'full'],
- description: 'Surface to persist for your client.',
+ description: 'Surface to widen to (stdio: this session only).',
},
},
scope: 'read',
@@ -141,7 +181,7 @@ const request_tools: Operation = {
// self-enforces ceiling + operator lock + scopes + rate limit.
mutating: true,
handler: async (ctx, p) => {
- const { surfaceWiderThan, isMcpSurface } = await import('../../mcp/surface.ts');
+ const { surfaceWiderThan, isMcpSurface, clampSurface } = await import('../../mcp/surface.ts');
// Unset ceiling (local CLI / direct dispatch) = 'full' — trusted-local
// callers were never surface-bounded.
const ceiling = ctx.surfaceCeiling ?? 'full';
@@ -166,8 +206,9 @@ const request_tools: Operation = {
throw invalidParam(ctx, 'request_tools', 'surface', 'surface must be one of: verbs, starter, full (got an unrecognized value)', { choices: ['verbs', 'starter', 'full'] });
}
const clientId = ctx.auth?.clientId;
+ if (!clientId && ctx.transport === 'stdio' && ctx.stdioSurface) return widenStdioSession(ctx, requested);
if (!clientId) {
- // stdio has no per-token identity; a surface persist has nowhere to land.
+ // No per-token identity and no stdio session: a surface persist has nowhere to land.
return { persisted: false, reason: NO_CLIENT_SURFACE };
}
if (surfaceWiderThan(requested, ceiling)) {
@@ -248,7 +289,10 @@ const request_tools: Operation = {
return { persisted: true, surface: requested, note: 're-issue tools/list to see the new catalog' };
}
- const visible = await visibleOpsForCaller(ctx, ceiling);
+ // A widenable stdio session lists what request_tools {surface} can add, not only what it serves now.
+ const session = ctx.transport === 'stdio' ? ctx.stdioSurface : undefined;
+ const catalogCeiling = session && session.widenAllowed && !session.readOnly ? clampSurface('full') : ceiling;
+ const visible = await visibleOpsForCaller(ctx, catalogCeiling);
// ── descriptor branch (D5: read-only) ───────────────────────────────
if (p.tools !== undefined) {
@@ -283,7 +327,9 @@ const request_tools: Operation = {
return {
catalog,
total_tools: visible.length,
- note: 'Call request_tools {tools: ["name", ...]} for full schemas, or {surface: "starter"|"full"} to persist a wider tool surface (within the server ceiling), then re-issue tools/list.',
+ note: session
+ ? 'Call request_tools {tools: ["name", ...]} for full schemas, or {surface: "starter"|"full"} to add those tools to this session (nothing is written).'
+ : 'Call request_tools {tools: ["name", ...]} for full schemas, or {surface: "starter"|"full"} to persist a wider tool surface for your OAuth client (within the server ceiling), then re-issue tools/list.',
};
},
};
diff --git a/src/core/ops/sources.ts b/src/core/ops/sources.ts
index 6ae63b0d8b..071adc2c24 100644
--- a/src/core/ops/sources.ts
+++ b/src/core/ops/sources.ts
@@ -62,7 +62,8 @@ const whoami: Operation = {
const verified = await verifyLocalWriter(ctx.engine, await readLocalWriter(ctx.engine, 'stdio'));
if (verified.remote) scopes = verified.grant.scopes;
} catch { /* no registration: no scopes */ }
- return { transport: 'stdio', scopes, readiness: readiness('stdio') };
+ const session = ctx.stdioSurface;
+ return { transport: 'stdio', scopes, ...(session ? { surface: session.surface, surface_source: session.source } : {}), readiness: readiness('stdio') };
}
if (!ctx.auth) {
throw opError(
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index 11d9a2ba91..5be28865b9 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -22,6 +22,7 @@ import { logVerbUsage } from '../core/verbs/usage-log.ts';
import { localTranscriptsNotice, recallInteropNotices, wantsTranscriptHint } from '../core/interop-notices.ts';
import { hiddenToolHint } from './hidden-tool-hint.ts';
import { takePostUpgradeMcpNotice } from '../core/post-upgrade-notice.ts';
+import { mcpOnboardingNotices } from '../core/onboard/mcp-onboarding.ts';
import { sourceGuardBlocksWrite } from '../core/source-resolver.ts';
import { suggestNearest } from '../core/levenshtein.ts';
import {
@@ -258,6 +259,8 @@ export interface DispatchOpts {
* treated as 'full'.
*/
surfaceCeiling?: 'verbs' | 'starter' | 'full';
+ /** The stdio session surface (OperationContext.stdioSurface); its allow-set is the one `allowedOps` mirrors. */
+ stdioSurface?: OperationContext['stdioSurface'];
/** #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. */
@@ -515,7 +518,7 @@ export function unknownToolEnvelope(name: string, opts: DispatchOpts, legacyErro
.filter(op => !op.localOnly && !op.publishGateKey && (allowedOps ? allowedOps.has(op.name) : true))
.map(op => op.name);
const nearest = suggestNearest(name, candidates);
- const hint = hiddenToolHint(operations.find(o => o.name === name), opts); // F6: owner's stdio pipe only
+ const hint = hiddenToolHint(operations.find(o => o.name === name), opts, dispatchRenderContext(opts).isCallable('request_tools') && opts.stdioSurface?.widenAllowed !== false); // F6: owner's stdio pipe only
const suggestion = hint?.suggestion ?? (nearest
? `Did you mean "${nearest}"?`
: 'List the tools this connection can call (tools/list) and use one of those names.');
@@ -571,7 +574,7 @@ function admitNotices(notices: Notice[], opts: DispatchOpts): Notice[] {
const principal = opts.auth?.clientId;
const transport = opts.transport === 'stdio' ? 'stdio' : opts.remote === false ? 'cli' : 'http';
return (opts.noticeLedger ?? processNoticeLedger()).admit(notices,
- { transport, principal, sessionId: opts.sessionId }, mutedNoticeCodes(principal));
+ { transport, principal, sessionId: opts.sessionId }, mutedNoticeCodes(principal ?? (transport === 'stdio' ? 'stdio' : undefined)));
} catch {
return notices;
}
@@ -646,6 +649,7 @@ export function buildOperationContext(
...(opts.localFederatedSourceIds ? { localFederatedSourceIds: opts.localFederatedSourceIds } : {}),
...(opts.explicitReadBinding ? { explicitReadBinding: opts.explicitReadBinding } : {}),
...(opts.surfaceCeiling ? { surfaceCeiling: opts.surfaceCeiling } : {}),
+ ...(opts.stdioSurface ? { stdioSurface: opts.stdioSurface } : {}),
...(opts.writeWaitMs !== undefined ? { writeWaitMs: opts.writeWaitMs } : {}),
...(opts.resultRows ? { resultRows: opts.resultRows } : {}),
auth: opts.auth,
@@ -903,6 +907,7 @@ export async function dispatchToolCall(
}
maybeBackupNotice(notices, opts);
if (opts.transport === 'stdio' && opts.remote !== false) { const up = takePostUpgradeMcpNotice(); if (up) notices.push(up); } // F7
+ if (opts.transport === 'stdio' && opts.remote !== false) notices.push(...await mcpOnboardingNotices({ engine, op: name, result, meta: responseMeta, config: ctx.config, render: dispatchRenderContext(opts) }));
const out: ToolResult = toolResultWithNotices(result, admitNotices(notices, opts), dispatchRenderContext(opts));
if (evidenceBlocks.length > 0) out.content.splice(1, 0, ...evidenceBlocks.map(text => ({ type: 'text' as const, text })));
if (opts.transport === 'stdio') {
diff --git a/src/mcp/hidden-tool-hint.ts b/src/mcp/hidden-tool-hint.ts
index 6f3adb1285..0e08abca28 100644
--- a/src/mcp/hidden-tool-hint.ts
+++ b/src/mcp/hidden-tool-hint.ts
@@ -1,26 +1,51 @@
/**
* F6: the hidden-tool hint on the owner's stdio pipe. A stdio caller that
* names a real tool outside this server's surface (or its read-only access)
- * learns that the tool exists, its CLI equivalent, and how to widen the
- * surface. The stdio pipe is the brain owner's own process, so this is not
- * an existence oracle; HTTP keeps the opaque unknown_tool envelope.
+ * learns that the tool exists and how to reach it. Where `request_tools` is
+ * callable and session widening is on, the fix is one `request_tools
+ * {surface: 'full'}` call (no restart, nothing persists); otherwise it is the
+ * tool's CLI equivalent, relayed to the user. The stdio pipe is the brain
+ * owner's own process, so this is not an existence oracle; HTTP keeps the
+ * opaque unknown_tool envelope.
*/
import type { Action } from '../core/agent-output.ts';
import type { Operation } from '../core/operations.ts';
import { cliEquivalent } from '../core/ops/cli-equivalent.ts';
-export function hiddenToolHint(op: Operation | undefined, opts: { transport?: string; remote?: boolean; surface?: string; allowedOps?: ReadonlySet<string> }):
- { suggestion: string; fix: Action } | null {
+const PERSISTENT_ROUTE = 'To keep the full surface for new sessions, set GBRAIN_SURFACE=full in this harness\'s gbrain server env '
+ + '(`claude mcp add gbrain -e GBRAIN_SURFACE=full -- …`, the env table of the Codex server entry, or the plugin\'s GBRAIN_SURFACE setting on launcher installs), '
+ + 'or re-register the server with `--surface full`. An inherited GBRAIN_SURFACE overrides a pinned --surface.';
+
+export function hiddenToolHint(
+ op: Operation | undefined,
+ opts: { transport?: string; remote?: boolean; surface?: string; allowedOps?: ReadonlySet<string> },
+ canWiden = false,
+): { suggestion: string; fix: Action } | null {
if (!op || op.localOnly || opts.transport !== 'stdio' || opts.remote === false || !opts.allowedOps || opts.allowedOps.has(op.name)) return null;
const name = op.name;
const argv = cliEquivalent(op);
const surface = opts.surface ?? 'full';
- const why = surface === 'full'
- ? `${name} exists, but this server is read-only (access read-only), so it is not listed.`
- : `${name} exists, but this server runs the ${surface} tool surface, which does not include it. Its CLI equivalent does the same on the brain host; to call it here, set GBRAIN_SURFACE=full for this machine's gbrain server and start a new session.`;
+ const inputs = argv.includes('<params_json>') ? { inputs: [{ name: 'params_json', how: `The arguments you passed to ${name}, as one JSON object.` }] } : {};
+ if (surface === 'full') {
+ const why = `${name} exists, but this server is read-only (access read-only), so it is not listed. Its CLI equivalent does the same on the brain host; this connection stays read-only.`;
+ return { suggestion: `${why} CLI equivalent: \`${argv.join(' ')}\`.`, fix: { argv, consent: [], actor: 'agent', requires_exclusive: false, why, ...inputs } };
+ }
+ if (canWiden) {
+ const why = `${name} exists, but this session serves the ${surface} tool surface, which does not include it. `
+ + `Call request_tools {"surface":"full"} to add it to this session (no restart; nothing is written), then call ${name} by name. ${PERSISTENT_ROUTE}`;
+ return {
+ suggestion: `${why} CLI equivalent: \`${argv.join(' ')}\`.`,
+ fix: { mcp: { tool: 'request_tools', arguments: { surface: 'full' } }, argv, consent: [], actor: 'agent', requires_exclusive: false, why, ...inputs },
+ };
+ }
+ const why = `${name} exists, but this server runs the ${surface} tool surface, which does not include it, and this session cannot widen it. `
+ + `Its CLI equivalent does the same on the brain host. ${PERSISTENT_ROUTE}`;
return {
suggestion: `${why} CLI equivalent: \`${argv.join(' ')}\`.`,
- fix: { argv, consent: [], actor: 'agent', requires_exclusive: false, why,
- ...(argv.includes('<params_json>') ? { inputs: [{ name: 'params_json', how: `The arguments you passed to ${name}, as one JSON object.` }] } : {}) },
+ fix: {
+ argv, consent: [], actor: 'user', requires_exclusive: false, why,
+ user_message: `The ${name} tool is not in this session's gbrain tool set. You can run \`${argv.join(' ')}\` on the brain host, or add GBRAIN_SURFACE=full to the gbrain MCP server's env in your agent app and start a new session.`,
+ ...inputs,
+ },
};
}
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 14fc75f87d..927049f32d 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -7,9 +7,11 @@ import { operations, opError, OperationError } from '../core/operations.ts';
import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';
import { VERSION } from '../version.ts';
import { buildToolDefs } from './tool-defs.ts';
-import { dispatchToolCall, buildOperationContext } from './dispatch.ts';
+import { dispatchToolCall, buildOperationContext, dispatchRenderContext, type ToolResult } from './dispatch.ts';
import { findInvalidParam, schemaInvalidParams, parseStrictParamsMode } from './validate-params.ts';
-import { filterOpsForSurface, allowedOpNames, clampSurface, isReadOnlyOperation, type McpAccess, type McpSurface } from './surface.ts';
+import { clampSurface, createStdioSurfaceState, sessionWidenAllowed, surfaceEnvInvalidNotice, type McpAccess, type McpSurface, type SurfaceSource } from './surface.ts';
+import { startOnboardingRefresher } from '../core/onboard/mcp-onboarding.ts';
+import { noticeBlock, renderNotice, type Notice } from '../core/agent-output.ts';
import { disabledOpsForPublishGates } from './publish-gates.ts';
import { parseResultRowsMode, resolveResultRowsMode } from './result-rows.ts';
import type { Operation } from '../core/operations.ts';
@@ -205,7 +207,43 @@ export async function trackStdioRpc<T>(work: () => Promise<T>): Promise<T> {
}
}
-export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSurface; sourceGuard?: boolean; onBootPhase?: (phase: string) => void; access?: McpAccess } = {}) {
+/**
+ * The stdio session surface: one mutable allow-set per process that
+ * tools/list, dispatch, the capabilities resource, whoami and gbrain_status
+ * read. `request_tools {surface}` widens it for this session only (never past
+ * --access read-only); each widen writes a `surface_widened` stderr line and
+ * sends tools/list_changed. `finishResult` adds the once-per-process
+ * `surface_env_invalid` notice to the first successful result.
+ */
+function stdioSurfaceSession(
+ opts: { surface?: McpSurface; surfaceSource?: SurfaceSource; invalidSurfaceEnv?: string; access?: McpAccess },
+ server: () => Server | null,
+) {
+ const session = createStdioSurfaceState(operations, {
+ surface: clampSurface(opts.surface ?? 'full'), source: opts.surfaceSource ?? (opts.surface ? 'flag' : 'default'), readOnly: opts.access === 'read-only',
+ onWiden: ({ from, to, added }) => {
+ process.stderr.write(`[gbrain-serve] surface_widened from=${from} to=${to} op=request_tools added=${added.length}\n`);
+ Promise.resolve(server()?.sendToolListChanged()).catch(() => { /* best-effort */ });
+ },
+ });
+ let pending: Notice | null = opts.invalidSurfaceEnv ? surfaceEnvInvalidNotice(opts.invalidSurfaceEnv, session.surface, session.source) : null;
+ const finishResult = (result: ToolResult): ToolResult => {
+ if (!pending || result.isError) return result;
+ const rendered = renderNotice(pending, dispatchRenderContext({ transport: 'stdio', remote: true, surface: session.surface, allowedOps: session.allowedOps }));
+ result.content.push({ type: 'text', text: noticeBlock(rendered) });
+ result._meta = { ...(result._meta ?? {}), gbrain_notices: [...((result._meta?.gbrain_notices as unknown[]) ?? []), rendered] };
+ pending = null;
+ return result;
+ };
+ const statusResult = (state: NonNullable<ReturnType<typeof statusModeOf>>) => {
+ const status = statusToolResult(state);
+ status.content[0].text = JSON.stringify({ ...JSON.parse(status.content[0].text), surface: session.surface, surface_source: session.source }, null, 2);
+ return status;
+ };
+ return { session, finishResult, statusResult };
+}
+
+export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSurface; surfaceSource?: SurfaceSource; invalidSurfaceEnv?: string; sourceGuard?: boolean; onBootPhase?: (phase: string) => void; access?: McpAccess } = {}) {
const config = loadConfig();
const bootPhase = (phase: string) => { try { opts.onBootPhase?.(phase); } catch { /* diagnostic only */ } };
// Refuse to serve a well-formed GBRAIN_SOURCE that no active source row
@@ -223,10 +261,8 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// remote:true — so gate-off ops are subtracted per tools/list below.
// (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 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);
+ let server: Server | null = null;
+ const { session, finishResult, statusResult } = stdioSurfaceSession(opts, () => server);
// Ambient writeback (opt-in, default off): resolved ONCE at boot — a
// config flip needs a serve restart on this lane, the same posture as
@@ -243,10 +279,10 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
const statusMode = statusModeOf(engine);
const writeback = statusMode ? null : await resolveWritebackConfig(engine, config);
const writebackOpts = writeback ? ambientOptsFrom(writeback, {
- remember: allowedOps ? allowedOps.has('remember') : true,
- extractFacts: allowedOps ? allowedOps.has('extract_facts') : true,
+ remember: session.allowedOps ? session.allowedOps.has('remember') : true,
+ extractFacts: session.allowedOps ? session.allowedOps.has('extract_facts') : true,
}) : null;
- const server = new Server(
+ server = new Server(
{ name: 'gbrain', version: VERSION },
// listChanged: a client that handshakes during DEGRADED mode receives the
// gate-hidden catalog (stdioVisibleTools fail-closes every publishGateKey
@@ -265,7 +301,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
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 visible = new Set((await stdioVisibleTools(engine, session.surfacedOps)).map(op => op.name));
return resolveMcpInstructions(config, process.env, {
writeback: writebackOpts,
tools: { callable: n => visible.has(n), readiness: await instructionReadiness(engine, config, 'stdio') },
@@ -276,7 +312,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
installCapabilitiesResource(server, async () => {
if (statusMode && isEngineDegraded(engine)) return { transport: 'stdio', status_only: statusPayload(statusMode) };
const scope = await resolveMcpStdioSourceScope(engine);
- const available = (await stdioVisibleTools(engine, surfacedOps)).map(op => op.name);
+ const available = (await stdioVisibleTools(engine, session.surfacedOps)).map(op => op.name);
let scopes: readonly string[] = [];
if (!isEngineDegraded(engine)) {
try {
@@ -284,7 +320,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
if (verified.remote) scopes = verified.grant.scopes;
} catch {}
}
- return { transport: 'stdio', scopes, surface, access: readOnly ? 'read-only' : 'full', source_id: scope.sourceId,
+ return { transport: 'stdio', scopes, surface: session.surface, surface_source: session.source, access: session.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'),
@@ -294,7 +330,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
}, createSkillResources(engine, async () => {
const scope = await resolveMcpStdioSourceScope(engine);
return { remote: true, transport: 'stdio', sourceId: scope.sourceId,
- localFederatedSourceIds: scope.localFederatedSourceIds, allowedOps, surface, config: config ?? undefined };
+ localFederatedSourceIds: scope.localFederatedSourceIds, allowedOps: session.allowedOps, surface: session.surface, config: config ?? undefined };
}));
// FILE config plane only — stdio has no per-request list cycle, so a
@@ -305,6 +341,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
const resultRows = isEngineDegraded(engine)
? parseResultRowsMode(config?.mcp?.result_rows) ?? 'lean'
: await resolveResultRowsMode(engine, config);
+ session.widenAllowed = await sessionWidenAllowed(isEngineDegraded(engine) ? null : engine, config);
// Generate tool definitions from operations. Extracted to buildToolDefs so
// the subagent tool registry (v0.15+) can call the same mapper against a
@@ -315,7 +352,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 stdioVisibleTools(engine, session.surfacedOps), { strictParams }),
})));
// #4583 (fixes #4564's misrouted-write symptom): once-per-process advisory
@@ -335,7 +372,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// a tool call's re-probe finds the brain openable (then dispatch normally).
if (statusMode) {
const open = await attemptStatusRecovery(engine, statusMode);
- if (name === STATUS_TOOL_NAME) return statusToolResult(statusMode);
+ if (name === STATUS_TOOL_NAME) return statusResult(statusMode);
if (!open) return statusModeErrorResult(statusMode, name);
}
// #3242 / #3906: stdio resolves its source through the same ambient chain
@@ -366,7 +403,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
sourceScope.tier,
operations.find(o => o.name === name)?.mutating === true,
);
- return dispatchToolCall(engine, name, params, {
+ return finishResult(await dispatchToolCall(engine, name, params, {
remote: true,
// #1061: mark the transport so whoami can report {transport: 'stdio'}
// instead of throwing unknown_transport. Trust posture unchanged —
@@ -390,13 +427,13 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// every tool-call response. Best-effort; absorbs errors.
metaHook: getBrainHotMemoryMeta,
// MEMORY_VERBS v1: fail-closed surface enforcement + usage attribution.
- ...(allowedOps ? { allowedOps } : {}),
- surface,
+ ...(session.allowedOps ? { allowedOps: session.allowedOps } : {}),
+ surface: session.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,
+ // request_tools bounds its catalog by; its {surface} call widens the session.
+ surfaceCeiling: session.surface, stdioSurface: session,
resultRows,
- });
+ }));
}));
const transport = new StdioServerTransport();
@@ -433,6 +470,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// connect, unref'd (can never hold the process open), all errors
// swallowed inside armStartupSweep. Kill switch: GBRAIN_SWEEP=0 (checked
// inside the helper). Lazy import keeps sweep code off the boot path.
+ startOnboardingRefresher(engine, { idle: () => _stdioRpcsInFlight === 0 }).catch(() => { /* coaching is best-effort */ });
bootPhase('startup_sweep');
try {
const { armStartupSweep } = await import('../core/sweep.ts');
diff --git a/src/mcp/surface.ts b/src/mcp/surface.ts
index ec921ece9e..b317c39983 100644
--- a/src/mcp/surface.ts
+++ b/src/mcp/surface.ts
@@ -17,9 +17,10 @@
* op stays uncallable even if a client guesses its name (tool-list filtering
* alone leaves dispatch resolving the global catalog — codex c2).
*
- * Resolution: --surface flag > config `mcp_surface` > 'full'. Why default
- * full: verbs/starter are for agents and quickstarts; full preserves existing
- * advanced tooling.
+ * Resolution: stdio GBRAIN_SURFACE > --surface flag > config `mcp_surface` >
+ * 'full' (resolveStdioSurface); `serve --http` ignores GBRAIN_SURFACE. Why
+ * default full: a bare `serve` keeps existing advanced tooling; the
+ * registrations gbrain writes pin `starter` (src/core/mcp-registration.ts).
*
* WP4 (D2 CEILING): on the OAuth HTTP transport the server-resolved surface is
* a CEILING, not the final answer — each request resolves
@@ -31,6 +32,7 @@
*/
import type { Operation } from '../core/operations.ts';
+import type { Notice } from '../core/agent-output.ts';
import type { GBrainConfig } from '../core/config.ts';
import type { BrainEngine } from '../core/engine.ts';
import { VERB_NAMES } from '../core/verbs.ts';
@@ -103,6 +105,8 @@ export const STARTER_OPS: ReadonlySet<string> = new Set([
'get_write_request', 'list_write_requests', 'cancel_write_request',
'list_skills', 'get_skill', 'list_brain_skillpack', 'get_skill_asset',
'join_brain', 'sync_brain_skills', 'leave_brain', 'put_skill', 'delete_skill',
+ // The dismissal for the coaching notices starter sessions receive (onboarding, features).
+ 'mute_notice',
]);
/**
@@ -169,14 +173,45 @@ export function isReadOnlyOperation(op: Pick<Operation, 'scope' | 'mutating' | '
return op.scope === 'read' && op.mutating !== true && !op.requiredScopes?.length;
}
-/** Flag > config `mcp_surface` > 'full'. */
+export type SurfaceSource = 'env' | 'flag' | 'config' | 'default';
+
+/** How `serve` prints and `whoami` reports a surface source. */
+export const SURFACE_SOURCE_LABEL: Record<SurfaceSource, string> = {
+ env: 'env GBRAIN_SURFACE', flag: '--surface', config: 'config', default: 'default',
+};
+
+/** --surface flag > config `mcp_surface` > 'full', with where the answer came from. */
+export function resolveSurfaceWithSource(
+ flag: McpSurface | null,
+ config: Pick<GBrainConfig, 'mcp_surface'> | null | undefined,
+): { surface: McpSurface; source: SurfaceSource; invalidEnv?: string } {
+ if (flag) return { surface: flag, source: 'flag' };
+ if (config && isMcpSurface(config.mcp_surface)) return { surface: config.mcp_surface, source: 'config' };
+ return { surface: 'full', source: 'default' };
+}
+
+/** Flag > config `mcp_surface` > 'full' (`serve --http`; stdio adds GBRAIN_SURFACE via resolveStdioSurface). */
export function resolveSurface(
flag: McpSurface | null,
config: Pick<GBrainConfig, 'mcp_surface'> | null | undefined,
): McpSurface {
- if (flag) return flag;
- if (config && isMcpSurface(config.mcp_surface)) return config.mcp_surface;
- return 'full';
+ return resolveSurfaceWithSource(flag, config).surface;
+}
+
+/**
+ * Stdio `serve`: GBRAIN_SURFACE > --surface > config `mcp_surface` > 'full',
+ * the plugin launcher's substitute-or-append semantics. An invalid env value
+ * never stops the server (that would end it before the handshake, where no
+ * agent sees it): it is ignored and returned as `invalidEnv`.
+ */
+export function resolveStdioSurface(
+ flag: McpSurface | null,
+ config: Pick<GBrainConfig, 'mcp_surface'> | null | undefined,
+ env: string | undefined = process.env.GBRAIN_SURFACE,
+): { surface: McpSurface; source: SurfaceSource; invalidEnv?: string } {
+ if (env === undefined || env === '') return resolveSurfaceWithSource(flag, config);
+ if (isMcpSurface(env)) return { surface: env, source: 'env' };
+ return { ...resolveSurfaceWithSource(flag, config), invalidEnv: env };
}
export function filterOpsForSurface(ops: Operation[], surface: McpSurface): Operation[] {
@@ -308,3 +343,69 @@ export function effectiveSurfaceForClient(opts: {
const requested = opts.clientSurface ?? opts.defaultSurface ?? opts.ceiling;
return clampSurface(minSurface(opts.ceiling, requested), opts.warn);
}
+
+// ---------------------------------------------------------------------------
+// Stdio session surface — one mutable allow-set per stdio server process
+// ---------------------------------------------------------------------------
+
+/**
+ * The stdio session's surface: tools/list, dispatch, the capabilities
+ * resource and `whoami` read the same object, so a `request_tools` widen is
+ * visible to all of them at once. Widening is session-scoped (nothing is
+ * written) and never passes `--access read-only`.
+ */
+export interface StdioSurfaceState {
+ surface: McpSurface;
+ readonly source: SurfaceSource;
+ readonly readOnly: boolean;
+ /** `mcp.allow_session_widen` as last resolved (boot, then each request_tools call). */
+ widenAllowed: boolean;
+ surfacedOps: Operation[];
+ allowedOps: ReadonlySet<string> | undefined;
+ widen(to: McpSurface): { from: McpSurface; to: McpSurface; added: string[] };
+}
+
+export function createStdioSurfaceState(
+ ops: Operation[],
+ init: { surface: McpSurface; source: SurfaceSource; readOnly: boolean; onWiden?: (change: { from: McpSurface; to: McpSurface; added: string[] }) => void },
+): StdioSurfaceState {
+ const compute = (surface: McpSurface) => {
+ const surfacedOps = filterOpsForSurface(ops, surface).filter(op => !init.readOnly || isReadOnlyOperation(op));
+ const allowedOps = init.readOnly ? new Set(surfacedOps.map(op => op.name)) : surface === 'full' ? undefined : allowedOpNames(ops, surface);
+ return { surface, surfacedOps, allowedOps };
+ };
+ const state: StdioSurfaceState = {
+ source: init.source,
+ readOnly: init.readOnly,
+ widenAllowed: true,
+ ...compute(init.surface),
+ widen(to) {
+ const from = state.surface;
+ const before = new Set(state.surfacedOps.map(op => op.name));
+ Object.assign(state, compute(to));
+ const change = { from, to, added: state.surfacedOps.filter(op => !before.has(op.name)).map(op => op.name) };
+ init.onWiden?.(change);
+ return change;
+ },
+ };
+ return state;
+}
+
+/** `mcp.allow_session_widen` (default true): DB plane, then the file plane (file only when `engine` is null). */
+export async function sessionWidenAllowed(engine: BrainEngine | null, config: GBrainConfig | null | undefined): Promise<boolean> {
+ const off = (v: unknown) => v === false || (typeof v === 'string' && /^(false|0|off|no)$/i.test(v.trim()));
+ try {
+ const dbVal = engine ? await engine.getConfig('mcp.allow_session_widen') : null;
+ if (dbVal != null) return !off(dbVal);
+ } catch { /* the file plane decides */ }
+ return !off(config?.mcp?.allow_session_widen);
+}
+
+/** The once-per-process `surface_env_invalid` info notice for an ignored GBRAIN_SURFACE value. */
+export function surfaceEnvInvalidNotice(raw: string, served: McpSurface, source: SurfaceSource): Notice {
+ return {
+ code: 'surface_env_invalid', kind: 'info',
+ why: `GBRAIN_SURFACE="${raw}" is not a tool surface (use verbs, starter or full), so this server ignored it and serves '${served}' (source: ${SURFACE_SOURCE_LABEL[source]}).`,
+ user_message: `The gbrain MCP server's GBRAIN_SURFACE setting ("${raw}") is not valid; it takes verbs, starter or full. Can you fix it in your agent app's gbrain server env?`,
+ };
+}
diff --git a/test/hidden-tool-hint.test.ts b/test/hidden-tool-hint.test.ts
new file mode 100644
index 0000000000..80485750da
--- /dev/null
+++ b/test/hidden-tool-hint.test.ts
@@ -0,0 +1,60 @@
+/**
+ * F6 hidden-tool hint (src/mcp/hidden-tool-hint.ts): on the owner's stdio
+ * pipe a real tool outside the session's surface names itself; the fix is
+ * one `request_tools {surface:'full'}` call (`next: run`) where request_tools
+ * is callable and session widening is on, else the CLI equivalent relayed to
+ * the user with the persistent routes (`tell_user_to_run`). Read-only access
+ * never offers a widen; HTTP stays opaque.
+ */
+import { describe, expect, test } from 'bun:test';
+import { operations } from '../src/core/operations.ts';
+import { allowedOpNames, isReadOnlyOperation } from '../src/mcp/surface.ts';
+import { hiddenToolHint } from '../src/mcp/hidden-tool-hint.ts';
+import { dispatchRenderContext } from '../src/mcp/dispatch.ts';
+import { renderAction } from '../src/core/agent-output.ts';
+
+const op = (name: string) => operations.find(o => o.name === name)!;
+const starter = allowedOpNames(operations, 'starter');
+const verbs = allowedOpNames(operations, 'verbs');
+const readOnly = new Set(operations.filter(o => starter.has(o.name) && isReadOnlyOperation(o)).map(o => o.name));
+const stdio = (allowedOps: ReadonlySet<string>, surface: 'verbs' | 'starter') => ({ transport: 'stdio' as const, remote: true, surface, allowedOps });
+const rendered = (opts: ReturnType<typeof stdio>, canWiden: boolean) => {
+ const hint = hiddenToolHint(op('get_health'), opts, canWiden)!;
+ return { hint, fix: renderAction(hint.fix, dispatchRenderContext({ ...opts, sourceId: 'default' })) };
+};
+
+describe('hidden-tool hint', () => {
+ test('a widenable starter session: the fix is the request_tools call, next run, CLI equivalent kept as argv', () => {
+ const { hint, fix } = rendered(stdio(starter, 'starter'), true);
+ expect(fix.mcp).toEqual({ tool: 'request_tools', arguments: { surface: 'full' } });
+ expect(fix.next).toBe('run');
+ expect(fix.consent).toEqual([]);
+ expect(fix.argv?.slice(0, 3)).toEqual(['gbrain', 'doctor', '--json']);
+ expect(hint.fix.why).toContain('GBRAIN_SURFACE=full');
+ expect(hint.fix.why).toContain('An inherited GBRAIN_SURFACE overrides a pinned --surface');
+ expect(hint.fix.why).toContain('claude mcp add gbrain -e GBRAIN_SURFACE=full');
+ });
+
+ test('verbs (request_tools absent) or widening off: the persistent route, relayed to the user', () => {
+ for (const [opts, canWiden] of [[stdio(verbs, 'verbs'), false], [stdio(starter, 'starter'), false]] as const) {
+ const { hint, fix } = rendered(opts, canWiden);
+ expect(fix.mcp).toBeUndefined();
+ expect(fix.next).toBe('tell_user_to_run');
+ expect(fix.user_message).toContain('GBRAIN_SURFACE=full');
+ expect(hint.suggestion).toContain('cannot widen it');
+ }
+ });
+
+ test('read-only access names the CLI equivalent and never offers a widen', () => {
+ const opts = { transport: 'stdio' as const, remote: true, surface: 'full' as const, allowedOps: readOnly };
+ const hint = hiddenToolHint(op('put_page'), opts, true)!;
+ expect(hint.fix.mcp).toBeUndefined();
+ expect(hint.fix.why).toContain('this connection stays read-only');
+ });
+
+ test('HTTP, the local CLI and visible tools get no hint', () => {
+ expect(hiddenToolHint(op('get_health'), { transport: 'http', remote: true, surface: 'starter', allowedOps: starter }, true)).toBeNull();
+ expect(hiddenToolHint(op('get_health'), { transport: 'stdio', remote: false, surface: 'starter', allowedOps: starter }, true)).toBeNull();
+ expect(hiddenToolHint(op('search'), stdio(starter, 'starter'), true)).toBeNull();
+ });
+});
diff --git a/test/init-nudge.test.ts b/test/init-nudge.test.ts
index 2710fd90d7..009c4d53e7 100644
--- a/test/init-nudge.test.ts
+++ b/test/init-nudge.test.ts
@@ -153,3 +153,35 @@ describe('runInitNudge — agents get the nudge too (F7)', () => {
expect(out).toContain('gbrain onboard --check');
});
});
+
+describe('shared collector (collectOnboardOpportunities)', () => {
+ test('init output is byte-identical to the pre-collector nudge', async () => {
+ const full = await withEnv({ GBRAIN_NON_INTERACTIVE: '1', GBRAIN_INTERACTIVE: undefined }, () => runNudgeCaptured(
+ stubEngine({ stale: 3, entities: 10, linked: 5, timeline: 2, takes: 0, pages: 20 })));
+ expect(full).toBe("[AGENT]\nwhy: [onboard_opportunities] Brain has opportunities: 3 stale chunks, link coverage 50%, timeline coverage 20%, 0 takes. Run 'gbrain onboard --check' to see the plan.\nactor: agent\nnext: run: gbrain onboard --check\n[/AGENT]\n");
+ const partial = await withEnv({ GBRAIN_NON_INTERACTIVE: '1', GBRAIN_INTERACTIVE: undefined }, () => runNudgeCaptured(
+ stubEngine({ stale: 0, entities: 4, linked: new Error('linked probe failed'), timeline: 4, takes: 2, pages: 9 })));
+ expect(partial).toBe("[AGENT]\nwhy: [onboard_opportunities] Brain has opportunities: link coverage 0%. Run 'gbrain onboard --check' to see the plan. (5/6 checks complete; run gbrain onboard --check for full recommendations)\nactor: agent\nnext: run: gbrain onboard --check\n[/AGENT]\n");
+ });
+
+ test('sequential (background refresh) and parallel (init) runs return the same counts; a failed probe is null, never a gap', async () => {
+ const { collectOnboardOpportunities, onboardGaps } = await import('../src/core/onboard/mcp-onboarding.ts');
+ const engine = stubEngine({ stale: 3, entities: 10, linked: new Error('linked probe failed'), timeline: 2, takes: 0, pages: 20 });
+ let yields = 0;
+ const parallel = await collectOnboardOpportunities(engine, new AbortController().signal);
+ const sequential = await collectOnboardOpportunities(engine, new AbortController().signal, async () => { yields++; });
+ expect(sequential).toEqual(parallel);
+ expect(yields).toBe(6);
+ expect(parallel).toMatchObject({ staleChunks: 3, entities: 10, linkedEntities: null, linkCoverage: null, timelineCoverage: 0.2, takes: 0, pages: 20, partial: true, checksRan: 5, checksAttempted: 6 });
+ expect(onboardGaps(parallel)).toEqual({ stale_chunks: true, link_coverage: false, timeline_coverage: true, no_takes: true });
+ });
+
+ test('an aborted sequential run stops issuing counts', async () => {
+ const { collectOnboardOpportunities } = await import('../src/core/onboard/mcp-onboarding.ts');
+ const controller = new AbortController();
+ controller.abort();
+ const counts = await collectOnboardOpportunities(stubEngine({ stale: 1, pages: 2 }), controller.signal, async () => {});
+ expect(counts.checksRan).toBe(0);
+ expect(counts.partial).toBe(true);
+ });
+});
diff --git a/test/mcp-notice-channels.test.ts b/test/mcp-notice-channels.test.ts
index 519d1dd6b9..01bf0a276c 100644
--- a/test/mcp-notice-channels.test.ts
+++ b/test/mcp-notice-channels.test.ts
@@ -182,17 +182,18 @@ describe('keyless answers ask before spending (F8/F9)', () => {
});
describe('F6 hidden-tool hint (owner stdio only)', () => {
- test('a tool outside the stdio surface names itself, its CLI equivalent and GBRAIN_SURFACE=full', async () => {
+ test('a tool outside the stdio surface names itself, the request_tools widen, its CLI equivalent and GBRAIN_SURFACE=full', async () => {
// A1: the CLI fix names the served brain explicitly.
const { STARTER_OPS } = await import('../src/mcp/surface.ts');
const allowedOps = new Set(STARTER_OPS);
const stdio = await dispatchToolCall(engine as any, 'get_health', {}, { remote: true, transport: 'stdio', sourceId: 'default', allowedOps, surface: 'starter' });
const env = JSON.parse(stdio.content[0].text);
expect(env.code).toBe('unknown_tool');
- expect(env.suggestion).toContain('get_health exists, but this server runs the starter tool surface');
+ expect(env.suggestion).toContain('get_health exists, but this session serves the starter tool surface');
expect(env.suggestion).toContain('GBRAIN_SURFACE=full');
+ expect(env.fix.mcp).toEqual({ tool: 'request_tools', arguments: { surface: 'full' } });
expect(env.fix.command).toBe('gbrain doctor --json --brain host');
- expect(env.fix.next).toBe('tell_user_to_run');
+ expect(env.fix.next).toBe('run');
// HTTP keeps the opaque envelope (no existence oracle).
const http = await dispatchToolCall(engine as any, 'get_health', {}, { remote: true, transport: 'http', sourceId: 'default', allowedOps, surface: 'starter' });
const opaque = JSON.parse(http.content[0].text);
@@ -242,3 +243,39 @@ describe('F7 coaching reaches agents', () => {
}
});
});
+
+describe('onboarding notices on the stdio channel', () => {
+ test('an onboard_* notice renders as a prefixed block and in _meta.gbrain_notices; first_run_decisions carries its decisions', async () => {
+ const { mkdtempSync, rmSync } = await import('node:fs');
+ const { tmpdir } = await import('node:os');
+ const { join } = await import('node:path');
+ const { __resetMcpOnboardingForTests, __warmOnboardingCacheForTests } = await import('../src/core/onboard/mcp-onboarding.ts');
+ const home = mkdtempSync(join(tmpdir(), 'gb-notice-onboard-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, GBRAIN_NO_ONBOARD_NUDGE: undefined }, async () => {
+ __resetMcpOnboardingForTests();
+ __resetBackupNoticeForTests();
+ for (const p of ['alice-example', 'bob-example', 'charlie-example']) {
+ await engine.putPage(`people/${p}`, { type: 'person', title: p, compiled_truth: `${p} notes.` });
+ }
+ await __warmOnboardingCacheForTests(engine as never);
+ const opts = { remote: true, transport: 'stdio' as const, sourceId: 'default' };
+ const first = await dispatchToolCall(engine as never, 'get_backlinks', { slug: 'people/alice-example' }, opts);
+ const block = first.content.map(c => c.text).find(t => t.startsWith('[gbrain notice onboard_link_coverage kind=coaching]'));
+ expect(block).toBeDefined();
+ expect(block).toContain('fix: get_health {}');
+ expect(block).toContain('user_message: ');
+ const meta = (first._meta?.gbrain_notices as Array<{ code: string; contract_version: number }>).find(n => n.code === 'onboard_link_coverage');
+ expect(meta?.contract_version).toBe(1);
+ const second = await dispatchToolCall(engine as never, 'list_pages', {}, opts);
+ const ask = (second._meta?.gbrain_notices as Array<{ code: string; decisions?: Array<{ id: string; options: Array<{ argv?: string[] }> }> }>).find(n => n.code === 'first_run_decisions');
+ const writeback = ask?.decisions?.find(d => d.id === 'writeback');
+ expect(writeback?.options.map(o => o.argv)).toContainEqual(['gbrain', 'config', 'set', 'memory.auto_writeback', 'salient']);
+ expect(second.content.some(c => c.text.startsWith('[gbrain notice first_run_decisions kind=ask]'))).toBe(true);
+ });
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ __resetMcpOnboardingForTests();
+ }
+ });
+});
diff --git a/test/mcp-onboarding.test.ts b/test/mcp-onboarding.test.ts
new file mode 100644
index 0000000000..c138632a5c
--- /dev/null
+++ b/test/mcp-onboarding.test.ts
@@ -0,0 +1,347 @@
+/**
+ * Onboarding coaching over stdio MCP (src/core/onboard/mcp-onboarding.ts):
+ * the affinity map, per-class result predicates, the cache (cold, persisted,
+ * TTL), dedupe/budget/mute through dispatch's ledger, the first-run bundle
+ * on the second call, HTTP silence, and the stdio mute fix (mute_notice over
+ * stdio, `gbrain notices unmute`, a fresh process).
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { operations } from '../src/core/operations.ts';
+import { allowedOpNames, isReadOnlyOperation, STARTER_OPS } from '../src/mcp/surface.ts';
+import { dispatchToolCall, dispatchRenderContext, __resetBackupNoticeForTests, type ToolResult } from '../src/mcp/dispatch.ts';
+import {
+ ONBOARD_CALL_AFFINITY, mcpOnboardingNotices, startOnboardingRefresher,
+ __awaitOnboardingRefreshForTests, __resetMcpOnboardingForTests, __warmOnboardingCacheForTests,
+} from '../src/core/onboard/mcp-onboarding.ts';
+import { processNoticeLedger, setNoticeMuted } from '../src/core/notice-ledger.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ newProcess();
+});
+
+/** A fresh stdio process: onboarding state and the per-process notice ledger. */
+function newProcess(now: () => number = Date.now): void {
+ __resetMcpOnboardingForTests(now);
+ __resetBackupNoticeForTests();
+}
+
+async function inHome<T>(fn: () => Promise<T>, env: Record<string, string | undefined> = {}): Promise<T> {
+ const home = mkdtempSync(join(tmpdir(), 'gb-onboard-mcp-'));
+ try {
+ return await withEnv({ GBRAIN_HOME: home, GBRAIN_NO_ONBOARD_NUDGE: undefined, ...env }, fn);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+}
+
+const PEOPLE = ['alice-example', 'bob-example', 'charlie-example', 'dana-example', 'erin-example', 'frank-example'];
+
+/** Six people pages with no links or timeline, one note, unembedded chunks, no takes. */
+async function seedGaps(): Promise<void> {
+ for (const p of PEOPLE) {
+ await engine.putPage(`people/${p}`, { type: 'person', title: p, compiled_truth: `${p} works at acme-example.` });
+ }
+ await engine.putPage('notes/standup', { type: 'note', title: 'standup', compiled_truth: 'Weekly standup notes.' });
+ await engine.upsertChunks('notes/standup', [{ chunk_index: 0, chunk_text: 'Weekly standup notes.', chunk_source: 'compiled_truth' }]);
+}
+
+const STARTER = new Set(STARTER_OPS);
+const stdio = (allowedOps: ReadonlySet<string> | null = STARTER) => ({
+ remote: true, transport: 'stdio' as const, sourceId: 'default',
+ ...(allowedOps ? { allowedOps, surface: 'starter' as const } : {}),
+});
+const call = (name: string, params: Record<string, unknown>, opts = stdio()) => dispatchToolCall(engine as never, name, params, opts);
+const notices = (r: ToolResult) => ((r._meta?.gbrain_notices ?? []) as Array<{ code: string; kind: string; why: string; user_message?: string; fix?: { next: string; mcp?: { tool: string }; command?: string }; decisions?: Array<{ id: string }> }>);
+const codes = (r: ToolResult) => notices(r).map(n => n.code);
+const onboard = (r: ToolResult) => codes(r).filter(c => c.startsWith('onboard_'));
+
+describe('affinity map', () => {
+ test('every op exists in the catalogue and every class reaches the verbs and starter surfaces', () => {
+ const names = new Set(operations.map(o => o.name));
+ const verbs = allowedOpNames(operations, 'verbs');
+ for (const [cls, ops] of Object.entries(ONBOARD_CALL_AFFINITY)) {
+ for (const op of ops) expect(names.has(op), `${cls}: ${op}`).toBe(true);
+ expect(ops.some(op => verbs.has(op)), `${cls} on verbs`).toBe(true);
+ expect(ops.some(op => STARTER_OPS.has(op)), `${cls} on starter`).toBe(true);
+ }
+ });
+});
+
+describe('opportunity notices on stdio', () => {
+ test('a cold cache delivers nothing', async () => {
+ await inHome(async () => {
+ await seedGaps();
+ expect(onboard(await call('get_backlinks', { slug: 'people/alice-example' }))).toEqual([]);
+ });
+ });
+
+ test('a notice rides an affine call, none rides an unrelated call, and the second matching call is deduped', async () => {
+ await inHome(async () => {
+ await seedGaps();
+ await __warmOnboardingCacheForTests(engine as never);
+ expect(onboard(await call('list_pages', {}))).toEqual([]);
+ expect(onboard(await call('get_backlinks', { slug: 'people/alice-example' }))).toEqual(['onboard_link_coverage']);
+ expect(onboard(await call('get_backlinks', { slug: 'people/bob-example' }))).toEqual([]);
+ });
+ });
+
+ test('two classes are both delivered: stale chunks on search, then link coverage on get_backlinks', async () => {
+ const key = ['sk', 'test', String(Date.now())].join('-');
+ await inHome(async () => {
+ await seedGaps();
+ await __warmOnboardingCacheForTests(engine as never);
+ const config = { engine: 'pglite', embedding_model: 'openai:text-embedding-3-small' } as GBrainConfig;
+ const stale = await mcpOnboardingNotices({ engine: engine as never, op: 'search', result: [], meta: { retrieval: { degraded: [] } }, config, render: dispatchRenderContext(stdio()) });
+ const admitted = processNoticeLedger().admit(stale, { transport: 'stdio' });
+ expect(admitted.map(n => n.code)).toEqual(['onboard_stale_chunks']);
+ expect(admitted[0].why).toContain('gbrain embed --stale');
+ expect(admitted[0].why).toContain('ask the user first');
+ expect(onboard(await call('get_backlinks', { slug: 'people/alice-example' }))).toEqual(['onboard_link_coverage']);
+ }, { OPENAI_API_KEY: key });
+ });
+
+ test('a keyless brain and a search whose vector arm did not run get no stale-chunk notice', async () => {
+ const key = ['sk', 'test', String(Date.now())].join('-');
+ await inHome(async () => {
+ await seedGaps();
+ await __warmOnboardingCacheForTests(engine as never);
+ const render = dispatchRenderContext(stdio());
+ const keyless = { engine: 'pglite', embedding_disabled: true } as GBrainConfig;
+ const staleOnly = async (meta: Record<string, unknown>, config: GBrainConfig) =>
+ (await mcpOnboardingNotices({ engine: engine as never, op: 'search', result: [], meta, config, render })).filter(n => n.code === 'onboard_stale_chunks');
+ expect(await staleOnly({}, keyless)).toEqual([]);
+ const configured = { engine: 'pglite', embedding_model: 'openai:text-embedding-3-small' } as GBrainConfig;
+ const degraded = { retrieval: { degraded: [{ stage: 'embed_unavailable', reason: 'no_provider' }] } };
+ expect(await staleOnly(degraded, configured)).toEqual([]);
+ expect((await staleOnly({ retrieval: { degraded: [] } }, configured)).length).toBe(1);
+ }, { OPENAI_API_KEY: key });
+ });
+
+ test('the coaching budget caps a session at two coaching notices', async () => {
+ await inHome(async () => {
+ await seedGaps();
+ await __warmOnboardingCacheForTests(engine as never);
+ const first = await call('get_backlinks', { slug: 'people/alice-example' });
+ expect(notices(first).filter(n => n.kind === 'coaching').map(n => n.code).sort()).toEqual(['features_auto_fix', 'onboard_link_coverage']);
+ const second = await call('entity', { name: 'people/charlie-example' });
+ expect(notices(second).filter(n => n.kind === 'coaching')).toEqual([]);
+ });
+ });
+
+ test('features_auto_fix rides link-graph calls only', async () => {
+ await inHome(async () => {
+ await seedGaps();
+ await __warmOnboardingCacheForTests(engine as never);
+ expect(codes(await call('entity', { name: 'people/alice-example' }))).not.toContain('features_auto_fix');
+ __resetBackupNoticeForTests();
+ expect(codes(await call('traverse_graph', { slug: 'people/alice-example' }))).toContain('features_auto_fix');
+ });
+ });
+
+ test('timeline coverage: an entity page without timeline gets the notice, a note page does not', async () => {
+ await inHome(async () => {
+ await seedGaps();
+ await __warmOnboardingCacheForTests(engine as never);
+ expect(onboard(await call('get_page', { slug: 'notes/standup' }))).toEqual([]);
+ expect(onboard(await call('get_page', { slug: 'people/alice-example' }))).toEqual(['onboard_timeline_coverage']);
+ });
+ });
+
+ test('zero takes rides recall', async () => {
+ await inHome(async () => {
+ await seedGaps();
+ await __warmOnboardingCacheForTests(engine as never);
+ expect(onboard(await call('recall', { query: 'acme-example' }))).toEqual(['onboard_no_takes']);
+ });
+ });
+
+ test('an empty brain emits nothing', async () => {
+ await inHome(async () => {
+ await __warmOnboardingCacheForTests(engine as never);
+ expect(onboard(await call('recall', { query: 'anything' }))).toEqual([]);
+ expect(onboard(await call('get_backlinks', { slug: 'people/nobody-example' }))).toEqual([]);
+ });
+ });
+
+ test('GBRAIN_NO_ONBOARD_NUDGE=1 silences notices and the first-run bundle', async () => {
+ await inHome(async () => {
+ await seedGaps();
+ await __warmOnboardingCacheForTests(engine as never);
+ for (const name of ['list_pages', 'get_backlinks', 'recall']) {
+ const r = await call(name, name === 'recall' ? { query: 'x' } : name === 'get_backlinks' ? { slug: 'people/alice-example' } : {});
+ expect(codes(r).filter(c => c.startsWith('onboard_') || c === 'first_run_decisions' || c === 'features_auto_fix')).toEqual([]);
+ }
+ }, { GBRAIN_NO_ONBOARD_NUDGE: '1' });
+ });
+
+ test('a rendered notice tells an MCP-only agent to relay the CLI preview, or runs get_health where it is callable', async () => {
+ await inHome(async () => {
+ await seedGaps();
+ await __warmOnboardingCacheForTests(engine as never);
+ const starter = notices(await call('get_backlinks', { slug: 'people/alice-example' })).find(n => n.code === 'onboard_link_coverage')!;
+ expect(starter.fix?.next).toBe('tell_user_to_run');
+ expect(starter.fix?.command).toContain('gbrain onboard --check');
+ expect(starter.user_message).toBeTruthy();
+ expect(starter.why).toContain('gbrain extract links');
+ newProcess();
+ await __warmOnboardingCacheForTests(engine as never);
+ const full = notices(await call('get_backlinks', { slug: 'people/alice-example' }, stdio(null))).find(n => n.code === 'onboard_link_coverage')!;
+ expect(full.fix?.mcp?.tool).toBe('get_health');
+ expect(full.fix?.next).toBe('run');
+ });
+ });
+
+ test('read-only access names the CLI mute instead of mute_notice', async () => {
+ await inHome(async () => {
+ await seedGaps();
+ await __warmOnboardingCacheForTests(engine as never);
+ const readOnly = new Set(operations.filter(o => STARTER_OPS.has(o.name) && isReadOnlyOperation(o)).map(o => o.name));
+ const ro = notices(await call('get_backlinks', { slug: 'people/alice-example' }, stdio(readOnly))).find(n => n.code === 'onboard_link_coverage')!;
+ expect(ro.why).toContain('gbrain notices mute onboard_link_coverage');
+ expect(ro.why).not.toContain('mute_notice');
+ newProcess();
+ await __warmOnboardingCacheForTests(engine as never);
+ const rw = notices(await call('get_backlinks', { slug: 'people/alice-example' })).find(n => n.code === 'onboard_link_coverage')!;
+ expect(rw.why).toContain('call mute_notice {"code":"onboard_link_coverage"}');
+ });
+ });
+
+ test('a TTL refresh drops a gap the user fixed', async () => {
+ let now = Date.now();
+ await inHome(async () => {
+ await seedGaps();
+ newProcess(() => now);
+ await __warmOnboardingCacheForTests(engine as never);
+ expect(onboard(await call('get_backlinks', { slug: 'people/alice-example' }))).toEqual(['onboard_link_coverage']);
+ for (const p of PEOPLE) await engine.addLink('notes/standup', `people/${p}`, 'mentioned');
+ now += 7 * 60 * 60 * 1000;
+ await call('list_pages', {});
+ await __awaitOnboardingRefreshForTests();
+ __resetBackupNoticeForTests();
+ expect(onboard(await call('get_backlinks', { slug: 'people/alice-example' }))).toEqual([]);
+ });
+ });
+
+ test('persisted counts start a new session warm', async () => {
+ await inHome(async () => {
+ await seedGaps();
+ await __warmOnboardingCacheForTests(engine as never);
+ newProcess();
+ await startOnboardingRefresher(engine as never, { idle: () => false });
+ expect(onboard(await call('get_backlinks', { slug: 'people/alice-example' }))).toEqual(['onboard_link_coverage']);
+ });
+ });
+
+ test('HTTP dispatch emits no onboarding notices', async () => {
+ await inHome(async () => {
+ await seedGaps();
+ await __warmOnboardingCacheForTests(engine as never);
+ const http = { remote: true, transport: 'http' as const, sourceId: 'default', auth: { clientId: 'client-example', scopes: ['read'] } };
+ for (const r of [await call('list_pages', {}, http as never), await call('get_backlinks', { slug: 'people/alice-example' }, http as never)]) {
+ expect(codes(r).filter(c => c.startsWith('onboard_') || c === 'first_run_decisions' || c === 'features_auto_fix')).toEqual([]);
+ }
+ });
+ });
+});
+
+describe('stdio mutes', () => {
+ test('a stdio mute applies, and survives a fresh process', async () => {
+ await inHome(async () => {
+ await seedGaps();
+ await __warmOnboardingCacheForTests(engine as never);
+ const muted = JSON.parse((await call('mute_notice', { code: 'onboard_link_coverage' })).content[0].text);
+ expect(muted.muted).toBe(true);
+ expect(onboard(await call('get_backlinks', { slug: 'people/alice-example' }))).toEqual([]);
+ newProcess();
+ await __warmOnboardingCacheForTests(engine as never);
+ expect(onboard(await call('get_backlinks', { slug: 'people/alice-example' }))).toEqual([]);
+ });
+ });
+
+ test('an MCP mute, then `gbrain notices unmute`, then a fresh process shows the notice again', async () => {
+ await inHome(async () => {
+ await seedGaps();
+ await call('mute_notice', { code: 'onboard_link_coverage' });
+ const { run } = await import('../src/cli/commands/notices.ts');
+ const write = process.stdout.write;
+ process.stdout.write = (() => true) as typeof process.stdout.write;
+ try { await run(['unmute', 'onboard_link_coverage']); } finally { process.stdout.write = write; }
+ newProcess();
+ await __warmOnboardingCacheForTests(engine as never);
+ expect(onboard(await call('get_backlinks', { slug: 'people/alice-example' }))).toEqual(['onboard_link_coverage']);
+ });
+ });
+
+ test('the owner global mute applies on stdio', async () => {
+ await inHome(async () => {
+ await seedGaps();
+ setNoticeMuted('onboard_link_coverage', true);
+ await __warmOnboardingCacheForTests(engine as never);
+ expect(onboard(await call('get_backlinks', { slug: 'people/alice-example' }))).toEqual([]);
+ });
+ });
+});
+
+describe('first-run decisions over stdio', () => {
+ const firstRun = (r: ToolResult) => notices(r).find(n => n.code === 'first_run_decisions');
+
+ test('the bundle rides the second successful call once per process, again in a new process', async () => {
+ await inHome(async () => {
+ await seedGaps();
+ await __warmOnboardingCacheForTests(engine as never);
+ expect(firstRun(await call('list_pages', {}))).toBeUndefined();
+ const second = firstRun(await call('list_pages', {}));
+ expect(second?.kind).toBe('ask');
+ expect(second?.why).toContain("Finish the user's current request, then ask.");
+ expect(second?.decisions?.map(d => d.id)).toContain('writeback');
+ expect(second?.decisions?.map(d => d.id)).not.toContain('search_mode');
+ expect(second?.decisions?.map(d => d.id)).not.toContain('harness_wiring');
+ expect(firstRun(await call('list_pages', {}))).toBeUndefined();
+ newProcess();
+ await __warmOnboardingCacheForTests(engine as never);
+ await call('list_pages', {});
+ expect(firstRun(await call('list_pages', {}))?.decisions?.map(d => d.id)).toContain('writeback');
+ });
+ });
+
+ test('the writeback decision is gone once memory.auto_writeback is set', async () => {
+ await inHome(async () => {
+ await seedGaps();
+ await engine.setConfig('memory.auto_writeback', 'salient');
+ await __warmOnboardingCacheForTests(engine as never);
+ await call('list_pages', {});
+ expect(firstRun(await call('list_pages', {}))?.decisions?.map(d => d.id) ?? []).not.toContain('writeback');
+ });
+ });
+
+ test('the bundle is gone after mute_notice first_run_decisions', async () => {
+ await inHome(async () => {
+ await seedGaps();
+ await call('mute_notice', { code: 'first_run_decisions' });
+ newProcess();
+ await __warmOnboardingCacheForTests(engine as never);
+ await call('list_pages', {});
+ expect(firstRun(await call('list_pages', {}))).toBeUndefined();
+ });
+ });
+});
diff --git a/test/mcp-schema-budget.test.ts b/test/mcp-schema-budget.test.ts
index 4a7eff8069..0ddca18ede 100644
--- a/test/mcp-schema-budget.test.ts
+++ b/test/mcp-schema-budget.test.ts
@@ -40,8 +40,8 @@ import { cl100kAvailable, estimateTokens } from '../src/core/chunkers/token-esti
const SERVED_STARTER_MAX_CHARS = 25_000;
const SERVED_STARTER_MAX_TOKENS = 5_700;
-/** The whole tools/list JSON, annotations included (25,735 measured at v0.60.46.0). */
-const SERVED_STARTER_MAX_JSON_CHARS = 26_000;
+/** The whole tools/list JSON, annotations included (25,735 measured at v0.60.46.0; 26,196 once mute_notice, the dismissal for the coaching notices starter sessions receive, joined starter). */
+const SERVED_STARTER_MAX_JSON_CHARS = 26_250;
/** 4,042 at the cost wave + 586 for the operator contract's error protocol, notice prefix and memory loop (F1); no schema guidance moved here. */
const INSTRUCTIONS_MAX_CHARS = 4_628;
const DESCRIPTION_HARD_CAP = 1_200;
@@ -54,7 +54,7 @@ const TOOL_BUDGETS: Record<string, number> = {
get_backlinks: 430, get_ingest_log: 280, get_page: 810, get_recent_salience: 660, get_skill: 910,
get_skill_asset: 790, get_write_request: 330, join_brain: 560, leave_brain: 540, list_brain_skillpack: 230,
list_link_sources: 220, list_pages: 1090, list_skills: 670, list_write_requests: 450, put_page: 1320,
- put_skill: 1420, query: 3250, recall: 1590, remember: 1370, request_tools: 560, resolve_slugs: 410, search: 1760,
+ mute_notice: 460, put_skill: 1420, query: 3250, recall: 1590, remember: 1370, request_tools: 560, resolve_slugs: 410, search: 1760,
submit_agent: 750, sync_brain_skills: 770, synthesize: 550, traverse_graph: 680, whoami: 230,
};
@@ -107,10 +107,10 @@ async function served(publishSkills: boolean): Promise<Operation[]> {
}
describe('served starter tool list (Cat 40 configuration)', () => {
- test('publish_skills on (the fresh-init default): 34 tools within 25,000 characters', async () => {
+ test('publish_skills on (the fresh-init default): 35 tools within 25,000 characters', async () => {
const ops = await served(true);
expect(ops.map(o => o.name)).toContain('get_skill');
- expect(ops.length).toBe(34);
+ expect(ops.length).toBe(35);
expect(size(ops)).toBeLessThanOrEqual(SERVED_STARTER_MAX_CHARS);
expect(json(ops)).toBeLessThanOrEqual(SERVED_STARTER_MAX_JSON_CHARS);
});
diff --git a/test/mcp-surface.test.ts b/test/mcp-surface.test.ts
index 13b583ea22..abecaa4956 100644
--- a/test/mcp-surface.test.ts
+++ b/test/mcp-surface.test.ts
@@ -263,3 +263,59 @@ describe('resolveClientRowSurface (amendment 18)', () => {
expect(warnings[1]).toContain('client-b');
});
});
+
+describe('stdio surface resolution: GBRAIN_SURFACE > --surface > config > full', () => {
+ it('env wins, then the flag, then config, then the default; each with its source', async () => {
+ const { resolveStdioSurface } = await import('../src/mcp/surface.ts');
+ expect(resolveStdioSurface('full', { mcp_surface: 'starter' }, 'verbs')).toEqual({ surface: 'verbs', source: 'env' });
+ expect(resolveStdioSurface('full', { mcp_surface: 'starter' }, undefined)).toEqual({ surface: 'full', source: 'flag' });
+ expect(resolveStdioSurface(null, { mcp_surface: 'starter' }, '')).toEqual({ surface: 'starter', source: 'config' });
+ expect(resolveStdioSurface(null, null, undefined)).toEqual({ surface: 'full', source: 'default' });
+ });
+
+ it('an invalid env value is ignored (never fatal) and reported', async () => {
+ const { resolveStdioSurface, surfaceEnvInvalidNotice } = await import('../src/mcp/surface.ts');
+ const r = resolveStdioSurface('starter', null, 'everything');
+ expect(r).toEqual({ surface: 'starter', source: 'flag', invalidEnv: 'everything' });
+ const notice = surfaceEnvInvalidNotice('everything', r.surface, r.source);
+ expect(notice).toMatchObject({ code: 'surface_env_invalid', kind: 'info' });
+ expect(notice.why).toContain('use verbs, starter or full');
+ expect(notice.why).toContain("serves 'starter' (source: --surface)");
+ });
+
+ it('serve --http ignores GBRAIN_SURFACE and says so on stderr', async () => {
+ const { withEnv } = await import('./helpers/with-env.ts');
+ const { runServe } = await import('../src/commands/serve.ts');
+ const errors: string[] = [];
+ let served: string | undefined;
+ const origError = console.error;
+ console.error = (...args: unknown[]) => { errors.push(args.map(String).join(' ')); };
+ try {
+ await withEnv({ GBRAIN_SURFACE: 'verbs' }, () => runServe({ disconnect: async () => {} } as never, ['--http', '--surface', 'starter'], {
+ runServeHttp: async (_e: unknown, o: { surface?: string }) => { served = o.surface; },
+ exit: () => {}, log: () => {}, stallWatchdogMs: 0,
+ } as never));
+ } finally {
+ console.error = origError;
+ }
+ expect(served).toBe('starter');
+ expect(errors.join('\n')).toContain('GBRAIN_SURFACE is ignored with --http');
+ expect(errors.join('\n')).toContain('surface=starter (source: --surface)');
+ });
+
+ it('the stdio session surface widens one allow-set and never passes --access read-only', async () => {
+ const { createStdioSurfaceState } = await import('../src/mcp/surface.ts');
+ const changes: Array<{ from: string; to: string; added: string[] }> = [];
+ const session = createStdioSurfaceState(operations, { surface: 'starter', source: 'flag', readOnly: false, onWiden: c => changes.push(c) });
+ expect(session.allowedOps?.has('get_health')).toBe(false);
+ session.widen('full');
+ expect(session.surface).toBe('full');
+ expect(session.allowedOps).toBeUndefined();
+ expect(session.surfacedOps.some(op => op.name === 'get_health')).toBe(true);
+ expect(changes[0]?.added).toContain('get_health');
+ const ro = createStdioSurfaceState(operations, { surface: 'starter', source: 'flag', readOnly: true });
+ ro.widen('full');
+ expect(ro.allowedOps?.has('put_page')).toBe(false);
+ expect(ro.allowedOps?.has('get_timeline')).toBe(true);
+ });
+});
diff --git a/test/request-tools-stdio.test.ts b/test/request-tools-stdio.test.ts
new file mode 100644
index 0000000000..4f3ad85afd
--- /dev/null
+++ b/test/request-tools-stdio.test.ts
@@ -0,0 +1,162 @@
+/**
+ * Runtime widening on the owner's stdio pipe, and GBRAIN_SURFACE on stdio
+ * `serve`, over real MCP stdio sessions on a hermetic PGLite brain.
+ *
+ * Protects: `request_tools {surface}` widens this session's one allow-set
+ * (tools/list and dispatch both see it), sends tools/list_changed, returns
+ * the new tools' schemas so a client that ignores list_changed can call them
+ * by name, writes a `surface_widened` audit line, and persists nothing (a new
+ * session starts at the registered surface); `--access read-only` still caps
+ * it; `mcp.allow_session_widen=false` refuses with the persistent route;
+ * 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).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+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 { keylessBrainEnv } from './helpers/provider-env.ts';
+import { waitFor } from './helpers/wait-for.ts';
+import { CAPABILITIES_URI } from '../src/mcp/capabilities.ts';
+
+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' });
+}
+
+interface Session { client: Client; stderr: () => string; listChanged: () => number; close: () => Promise<void> }
+
+async function session(args: string[], extraEnv: Record<string, string> = {}): Promise<Session> {
+ const transport = new StdioClientTransport({
+ command: 'bun', args: ['--no-env-file', 'run', 'src/cli.ts', 'serve', ...args], cwd: process.cwd(), env: { ...env, ...extraEnv }, stderr: 'pipe',
+ });
+ let err = '';
+ transport.stderr?.on('data', (chunk: Buffer) => { err += chunk.toString('utf8'); });
+ const client = new Client({ name: 'gbrain-request-tools-stdio-test', version: '1.0.0' }, { capabilities: {} });
+ let changed = 0;
+ client.setNotificationHandler(ToolListChangedNotificationSchema, async () => { changed++; });
+ await client.connect(transport);
+ return { client, stderr: () => err, listChanged: () => changed, close: async () => { await client.close().catch(() => {}); await transport.close().catch(() => {}); } };
+}
+
+const names = async (s: Session) => (await s.client.listTools()).tools.map(t => t.name);
+const parsed = (r: unknown) => JSON.parse(((r as { content: Array<{ text: string }> }).content[0]).text) as Record<string, unknown>;
+const isError = (r: unknown) => (r as { isError?: boolean }).isError === true;
+
+beforeAll(() => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-request-tools-stdio-'));
+ env = keylessBrainEnv(process.env, home, { DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_REMOTE_CLIENT_SECRET: undefined, GBRAIN_SURFACE: undefined, GBRAIN_MCP_FORCE_SURFACE: undefined, GBRAIN_NO_ONBOARD_NUDGE: '1' });
+ delete env.GBRAIN_SOURCE;
+ expect(cli(['init', '--pglite', '--no-embedding', '--non-interactive']).status).toBe(0);
+}, 120_000);
+
+afterAll(() => { if (home) rmSync(home, { recursive: true, force: true }); });
+
+describe('request_tools {surface} on stdio', () => {
+ test('widens this session: list_changed, tools/list and dispatch agree, schemas returned, audit line, nothing persisted', async () => {
+ const s = await session(['--surface', 'starter']);
+ try {
+ expect(await names(s)).not.toContain('get_health');
+ const hidden = await s.client.callTool({ name: 'get_health', arguments: {} });
+ expect(isError(hidden)).toBe(true);
+ const hint = parsed(hidden) as { fix?: { mcp?: { tool: string; arguments: unknown }; next?: string } };
+ expect(hint.fix?.mcp).toEqual({ tool: 'request_tools', arguments: { surface: 'full' } });
+ expect(hint.fix?.next).toBe('run');
+
+ const widened = parsed(await s.client.callTool({ name: 'request_tools', arguments: { surface: 'full' } })) as {
+ persisted: boolean; scope: string; surface: string; previous: string; tools: Array<{ name: string }>; note: string;
+ };
+ expect(widened).toMatchObject({ persisted: false, scope: 'session', surface: 'full', previous: 'starter' });
+ expect(widened.tools.map(t => t.name)).toContain('get_health');
+ expect(widened.note).toContain('GBRAIN_SURFACE=full');
+
+ // A client that ignores list_changed calls the new tool by name.
+ 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');
+ expect(s.stderr()).toMatch(/surface_widened from=starter to=full op=request_tools/);
+
+ const who = parsed(await s.client.callTool({ name: 'whoami', arguments: {} }));
+ expect(who).toMatchObject({ transport: 'stdio', surface: 'full', surface_source: 'flag' });
+ } finally {
+ await s.close();
+ }
+ const next = await session(['--surface', 'starter']);
+ try {
+ expect(await names(next)).not.toContain('get_health');
+ } finally {
+ await next.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 {
+ expect(await names(s)).not.toContain('request_tools');
+ expect(isError(await s.client.callTool({ name: 'request_tools', arguments: { surface: 'full' } }))).toBe(true);
+ const put = parsed(await s.client.callTool({ name: 'put_page', arguments: { slug: 'notes/x', content: 'x' } })) as { fix?: { mcp?: unknown; next?: string } };
+ expect(put.fix?.mcp).toBeUndefined();
+ expect(put.fix?.next).toBe('tell_user_to_run');
+ } finally {
+ await s.close();
+ }
+ }, 60_000);
+
+ test('mcp.allow_session_widen=false refuses with the persistent route, and the hint names it', async () => {
+ expect(cli(['config', 'set', 'mcp.allow_session_widen', 'false']).status).toBe(0);
+ const s = await session(['--surface', 'starter']);
+ try {
+ const hint = parsed(await s.client.callTool({ name: 'get_health', arguments: {} })) as { suggestion: string; fix?: { mcp?: unknown; next?: string; user_message?: string } };
+ expect(hint.fix?.mcp).toBeUndefined();
+ expect(hint.fix?.next).toBe('tell_user_to_run');
+ expect(hint.suggestion).toContain('GBRAIN_SURFACE=full');
+ const refused = await s.client.callTool({ name: 'request_tools', arguments: { surface: 'full' } });
+ expect(isError(refused)).toBe(true);
+ const env = parsed(refused) as { code: string; suggestion: string };
+ expect(env.code).toBe('permission_denied');
+ expect(env.suggestion).toContain('GBRAIN_SURFACE=full');
+ expect(await names(s)).not.toContain('get_health');
+ } finally {
+ await s.close();
+ expect(cli(['config', 'set', 'mcp.allow_session_widen', 'true']).status).toBe(0);
+ }
+ }, 60_000);
+});
+
+describe('GBRAIN_SURFACE on stdio serve', () => {
+ test('the env wins over --surface, and whoami and capabilities report it', async () => {
+ const s = await session(['--surface', 'full'], { GBRAIN_SURFACE: 'verbs' });
+ try {
+ expect((await names(s)).length).toBe(7);
+ expect(s.stderr()).toContain('surface=verbs (source: env GBRAIN_SURFACE)');
+ const caps = JSON.parse(((await s.client.readResource({ uri: CAPABILITIES_URI })).contents[0] as { text: string }).text) as { surface: string; surface_source: string };
+ expect(caps).toMatchObject({ surface: 'verbs', surface_source: 'env' });
+ } finally {
+ await s.close();
+ }
+ }, 60_000);
+
+ test('an invalid value is ignored with a stderr line and one surface_env_invalid notice naming the served surface', async () => {
+ const s = await session(['--surface', 'starter'], { GBRAIN_SURFACE: 'everything' });
+ try {
+ expect(await names(s)).toContain('put_page');
+ expect(s.stderr()).toContain('ignoring GBRAIN_SURFACE="everything"');
+ const first = await s.client.callTool({ name: 'whoami', arguments: {} }) as { content: Array<{ text: string }>; _meta?: { gbrain_notices?: Array<{ code: string; why: string }> } };
+ const notice = first._meta?.gbrain_notices?.find(n => n.code === 'surface_env_invalid');
+ expect(notice?.why).toContain("serves 'starter' (source: --surface)");
+ expect(first.content.some(c => c.text.startsWith('[gbrain notice surface_env_invalid kind=info]'))).toBe(true);
+ const second = await s.client.callTool({ name: 'whoami', arguments: {} }) as { _meta?: { gbrain_notices?: Array<{ code: string }> } };
+ expect(second._meta?.gbrain_notices?.some(n => n.code === 'surface_env_invalid') ?? false).toBe(false);
+ } finally {
+ await s.close();
+ }
+ }, 60_000);
+});