Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(mcp): harness and bot grants list the memory verbs over HTTP (surface_set_by install)

garrytan9339dd229eda
diff --git a/docs/architecture/thin-client.md b/docs/architecture/thin-client.md
index ec01048ff2..5653cffbdb 100644
--- a/docs/architecture/thin-client.md
+++ b/docs/architecture/thin-client.md
@@ -18,7 +18,7 @@ The generic `gbrain call` dispatcher is host-only and refuses before opening a
local engine; use the named CLI command or an authorized MCP tool instead.
**Surface posture:** thin CLI clients use the full MCP surface for remote
-command compatibility. Bootstrap pins `--surface full`; managed thin CLI grants
+command compatibility. Bootstrap pins `--surface full` (listing the memory verbs, `--advertise verbs`); managed thin CLI grants
for OpenClaw, Grok Bot, and Muse also select `full`. Surface visibility does not
grant authority: profiles, token scopes, operation snapshots, sources, and write
fences still restrict requests. A `memory-writer` thin client gains neither
diff --git a/docs/guides/hosted-harness-access.md b/docs/guides/hosted-harness-access.md
index 233e265122..403c3a7969 100644
--- a/docs/guides/hosted-harness-access.md
+++ b/docs/guides/hosted-harness-access.md
@@ -110,14 +110,14 @@ are one principal. See [shared brain skills](shared-brain-skills.md).
| Profile | Access | Native MCP surface |
| --- | --- | --- |
-| `memory-reader` | Read selected memory | Full |
-| `memory-writer` | Read and write selected memory | Full |
-| `coding-agent` | Isolated project writes and explicit project reads | Full |
+| `memory-reader` | Read selected memory | Full, listing the memory verbs |
+| `memory-writer` | Read and write selected memory | Full, listing the memory verbs |
+| `coding-agent` | Isolated project writes and explicit project reads | Full, listing the memory verbs |
| `operator` | Read, write, and eligible brain administration operations | Full |
| `delegating-agent` | Memory plus explicitly bound delegation | Starter |
| `full` | All eligible remote capabilities at grant time, including bound delegation | Full |
-A **profile grants authority**. A **surface selects visible tools**. Full surface does not bypass a grant, and `admin` does not imply delegation, the named shared-skill scopes, or owner dashboard/client-management authority. Starter includes authorized skill discovery and membership; the exact seven-tool `verbs` surface is memory-only. Thin CLI adapters use the full surface while retaining their source, operation, and write restrictions. Direct local CLI access is trusted access to the local computer; OAuth profiles do not confine a local shell.
+A **profile grants authority**. A **surface selects visible tools**. Full surface does not bypass a grant, and `admin` does not imply delegation, the named shared-skill scopes, or owner dashboard/client-management authority. Starter includes authorized skill discovery and membership; the exact seven-tool `verbs` surface is memory-only. A new memory or coding grant lists only the seven memory verbs and `request_tools` in `tools/list` while every operation its grant allows stays callable; `request_tools` returns any other tool's schema, and `gbrain auth rescope-client <client_id> --surface full` lists everything. Thin CLI adapters use the full surface while retaining their source, operation, and write restrictions. Direct local CLI access is trusted access to the local computer; OAuth profiles do not confine a local shell.
Clients granted a memory profile before the full-surface default keep their stored `starter` surface; no migration or repair widens it, and only an explicit `--profile` application regrants it. New grants snapshot operation names and source access. A later server upgrade does not silently give a snapshot-bound client new operations. The connection's own `whoami` reports `grant_diagnosis`: which blocker applies (scope, operation snapshot, client pin or server ceiling) and how many operations it hides, without naming them; `gbrain doctor` on the host reports the same as `grant_new_ops_available` with the commands. The connection is also told once per session, in band, by the `grant_blocked_operations` notice (same blockers and counts, the owner's preview-then-apply command as `fix`, `next: tell_user_to_run`; once per grant revision for stateless HTTP calls), and a read that left out takes a hidden tool serves carries `hidden_tool_content` with the next step that connection can actually take ([connection notices](repair.md#connection-notices)). Neither notice changes what the connection can call. A grant written before snapshots recorded their operation catalog says "original intent unknown" rather than claiming it predates the operations. Explicitly regrant to include them: `gbrain auth rescope --client <client_id> --operations <op,...> --surface full --dry-run` (then without `--dry-run`; `--surface full` only when the stored surface also blocks) for OAuth clients, or `gbrain auth rescope-token <name> --refresh-operations` (preview) then `--add <op,...>` for legacy tokens ([grants that cannot reach new operations](../mcp/ADMIN.md#grants-that-cannot-reach-new-operations)). `gbrain auth rescope --client <client_id> --operations all` (alias: `gbrain auth rescope-client <client_id> --allowed-operations all`) stores no snapshot and clears the profile instead, so the scopes and the surface alone decide, including operations later upgrades add. `gbrain auth clients` marks such a client `operations: "all"` with `includes_future_operations: true` and the command that re-pins it. A `bootstrap harness` re-run carries the replaced token's grants and does not widen its snapshot ([legacy token grants](../mcp/ADMIN.md#legacy-token-grants)). Archived sources are excluded. Legacy clients with a `NULL` operation snapshot retain their prior operation behavior.
diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.md
index 71d442d1c2..dbfcd21f54 100644
--- a/docs/mcp/ADMIN.md
+++ b/docs/mcp/ADMIN.md
@@ -236,11 +236,16 @@ security boundary; a request's `source_ids` can only narrow inside it. See
Access is per source, never per page, so lay sources out by who may read them
([guide](../guides/multi-source-brains.md#lay-out-sources-by-who-may-read-them)).
-New `memory-reader`, `memory-writer` and `coding-agent` grants are callable and
-listed on the full surface; their operation snapshot is still the ceiling, so a
-reader still has no write operation. `delegating-agent` grants keep the starter
-surface. Clients granted before this keep their stored surface: no migration or
-repair changes it, and only an explicit `--profile` application regrants it.
+New `memory-reader`, `memory-writer` and `coding-agent` grants are callable on
+the full surface and list the seven memory verbs plus `request_tools`, which
+returns any other tool's schema (`gbrain auth clients` shows the surface as
+`full (set by install)`); `gbrain agent register` daily-driver and coding-agent
+clients without `--surface` do the same. Their operation snapshot is still the
+ceiling, so a reader still has no write operation. To list every tool, pin the
+surface: `gbrain auth rescope-client <client_id> --surface full`.
+`delegating-agent` grants keep the starter surface. Clients granted before this
+keep their stored surface and listing: no migration or repair changes it, and
+re-applying a profile to an operator-pinned client keeps its full listing.
### Grants that cannot reach new operations
diff --git a/docs/mcp/DEPLOY.md b/docs/mcp/DEPLOY.md
index eaca4d8c4d..aed4dadbc0 100644
--- a/docs/mcp/DEPLOY.md
+++ b/docs/mcp/DEPLOY.md
@@ -59,13 +59,15 @@ the OAuth request when issuing my owner login link."*
### Local stdio (zero setup)
```bash
-gbrain serve --surface full # full operation catalog (what registrations pin; also the bare-serve default)
+gbrain serve --surface full --advertise verbs # what registrations write: every operation callable, the memory verbs and request_tools listed
```
Works with Claude Code, Cursor, Windsurf, and any MCP client that supports stdio.
On Claude Code, `gbrain setup claude-code` writes and verifies this registration
for you ([setup guide](../guides/setup.md)). No server, no tunnel, no token needed. Works on both PGLite and Postgres engines.
-`--surface full` serves every operation. For a client that cannot hold the full
+`--surface full` serves every operation; `--advertise verbs` lists only the seven
+memory verbs and `request_tools` in tools/list, and `request_tools` returns any
+other tool's schema. A bare `gbrain serve` lists everything. For a client that cannot hold the full
catalog, `--surface verbs` exposes exactly the seven-verb memory protocol
(`recall`, `remember`, `entity`, `synthesize`, `forget`, `context_pack`,
`delta` — [MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md)) and `--surface
diff --git a/docs/operations/mcp-surface-runbook.md b/docs/operations/mcp-surface-runbook.md
index b15bf54189..1b6c3b0c69 100644
--- a/docs/operations/mcp-surface-runbook.md
+++ b/docs/operations/mcp-surface-runbook.md
@@ -110,6 +110,11 @@ Usage counts only successful calls (`success` / `success_with_warnings`) —
a client flooding denials or errors shows zero usage, so denied traffic can
never argue its way into a wider surface or the starter derivation.
+A memory or coding grant from `gbrain mcp provision` or a `gbrain agent register`
+preset stores `full` with `surface_set_by = install`: it calls the full surface
+but lists only the memory verbs and `request_tools`. An operator rescope (any
+surface) lists that surface in full.
+
**Expected outcomes:**
- The client's NEXT request resolves the new surface (per-request
ceiling-bounded resolution: `min(server --surface ceiling, client row)`)
diff --git a/docs/protocol/AGENT_OPERATOR_v1.md b/docs/protocol/AGENT_OPERATOR_v1.md
index 2fd96466b5..97ef4180b3 100644
--- a/docs/protocol/AGENT_OPERATOR_v1.md
+++ b/docs/protocol/AGENT_OPERATOR_v1.md
@@ -361,7 +361,7 @@ stdout (`--json`):
"options": [
{
"id": "wire",
- "label": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "label": "Register `<absolute path to gbrain> serve --surface full --advertise verbs` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
{
"id": "skip",
diff --git a/llms-full.txt b/llms-full.txt
index c35f682407..e12b4040a9 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -1530,14 +1530,14 @@ are one principal. See [shared brain skills](shared-brain-skills.md).
| Profile | Access | Native MCP surface |
| --- | --- | --- |
-| `memory-reader` | Read selected memory | Full |
-| `memory-writer` | Read and write selected memory | Full |
-| `coding-agent` | Isolated project writes and explicit project reads | Full |
+| `memory-reader` | Read selected memory | Full, listing the memory verbs |
+| `memory-writer` | Read and write selected memory | Full, listing the memory verbs |
+| `coding-agent` | Isolated project writes and explicit project reads | Full, listing the memory verbs |
| `operator` | Read, write, and eligible brain administration operations | Full |
| `delegating-agent` | Memory plus explicitly bound delegation | Starter |
| `full` | All eligible remote capabilities at grant time, including bound delegation | Full |
-A **profile grants authority**. A **surface selects visible tools**. Full surface does not bypass a grant, and `admin` does not imply delegation, the named shared-skill scopes, or owner dashboard/client-management authority. Starter includes authorized skill discovery and membership; the exact seven-tool `verbs` surface is memory-only. Thin CLI adapters use the full surface while retaining their source, operation, and write restrictions. Direct local CLI access is trusted access to the local computer; OAuth profiles do not confine a local shell.
+A **profile grants authority**. A **surface selects visible tools**. Full surface does not bypass a grant, and `admin` does not imply delegation, the named shared-skill scopes, or owner dashboard/client-management authority. Starter includes authorized skill discovery and membership; the exact seven-tool `verbs` surface is memory-only. A new memory or coding grant lists only the seven memory verbs and `request_tools` in `tools/list` while every operation its grant allows stays callable; `request_tools` returns any other tool's schema, and `gbrain auth rescope-client <client_id> --surface full` lists everything. Thin CLI adapters use the full surface while retaining their source, operation, and write restrictions. Direct local CLI access is trusted access to the local computer; OAuth profiles do not confine a local shell.
Clients granted a memory profile before the full-surface default keep their stored `starter` surface; no migration or repair widens it, and only an explicit `--profile` application regrants it. New grants snapshot operation names and source access. A later server upgrade does not silently give a snapshot-bound client new operations. The connection's own `whoami` reports `grant_diagnosis`: which blocker applies (scope, operation snapshot, client pin or server ceiling) and how many operations it hides, without naming them; `gbrain doctor` on the host reports the same as `grant_new_ops_available` with the commands. The connection is also told once per session, in band, by the `grant_blocked_operations` notice (same blockers and counts, the owner's preview-then-apply command as `fix`, `next: tell_user_to_run`; once per grant revision for stateless HTTP calls), and a read that left out takes a hidden tool serves carries `hidden_tool_content` with the next step that connection can actually take ([connection notices](repair.md#connection-notices)). Neither notice changes what the connection can call. A grant written before snapshots recorded their operation catalog says "original intent unknown" rather than claiming it predates the operations. Explicitly regrant to include them: `gbrain auth rescope --client <client_id> --operations <op,...> --surface full --dry-run` (then without `--dry-run`; `--surface full` only when the stored surface also blocks) for OAuth clients, or `gbrain auth rescope-token <name> --refresh-operations` (preview) then `--add <op,...>` for legacy tokens ([grants that cannot reach new operations](../mcp/ADMIN.md#grants-that-cannot-reach-new-operations)). `gbrain auth rescope --client <client_id> --operations all` (alias: `gbrain auth rescope-client <client_id> --allowed-operations all`) stores no snapshot and clears the profile instead, so the scopes and the surface alone decide, including operations later upgrades add. `gbrain auth clients` marks such a client `operations: "all"` with `includes_future_operations: true` and the command that re-pins it. A `bootstrap harness` re-run carries the replaced token's grants and does not widen its snapshot ([legacy token grants](../mcp/ADMIN.md#legacy-token-grants)). Archived sources are excluded. Legacy clients with a `NULL` operation snapshot retain their prior operation behavior.
@@ -3845,7 +3845,7 @@ stdout (`--json`):
"options": [
{
"id": "wire",
- "label": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "label": "Register `<absolute path to gbrain> serve --surface full --advertise verbs` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
{
"id": "skip",
diff --git a/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md b/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md
index 98b8739441..8a1650e0d3 100644
--- a/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md
+++ b/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md
@@ -363,7 +363,7 @@ stdout (`--json`):
"options": [
{
"id": "wire",
- "label": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "label": "Register `<absolute path to gbrain> serve --surface full --advertise verbs` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
{
"id": "skip",
diff --git a/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md b/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md
index 98b8739441..8a1650e0d3 100644
--- a/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md
+++ b/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md
@@ -363,7 +363,7 @@ stdout (`--json`):
"options": [
{
"id": "wire",
- "label": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "label": "Register `<absolute path to gbrain> serve --surface full --advertise verbs` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
{
"id": "skip",
diff --git a/plugin/skills/conventions/agent-operator-protocol.md b/plugin/skills/conventions/agent-operator-protocol.md
index 98b8739441..8a1650e0d3 100644
--- a/plugin/skills/conventions/agent-operator-protocol.md
+++ b/plugin/skills/conventions/agent-operator-protocol.md
@@ -363,7 +363,7 @@ stdout (`--json`):
"options": [
{
"id": "wire",
- "label": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "label": "Register `<absolute path to gbrain> serve --surface full --advertise verbs` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
{
"id": "skip",
diff --git a/skills/conventions/agent-operator-protocol.md b/skills/conventions/agent-operator-protocol.md
index 98b8739441..8a1650e0d3 100644
--- a/skills/conventions/agent-operator-protocol.md
+++ b/skills/conventions/agent-operator-protocol.md
@@ -363,7 +363,7 @@ stdout (`--json`):
"options": [
{
"id": "wire",
- "label": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "label": "Register `<absolute path to gbrain> serve --surface full --advertise verbs` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
{
"id": "skip",
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 237b9054c5..c0ffc995db 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -44,7 +44,7 @@
"concept-synthesis/routing-eval.jsonl": "96dbd7d9c1b606e9e06262d0c06282399741e2bccb8eeb7b9ca88c20f44cda0e",
"context-audit/SKILL.md": "6d786629d40544ddaab4f4e6e333569d270bcb8b581589dc16fb9f8bcb4f6207",
"context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab",
- "conventions/agent-operator-protocol.md": "b42b19223aa9dffbe783ce7c5c681d762377c740f3c609cbc555b9a60a035235",
+ "conventions/agent-operator-protocol.md": "5fb107f916e48c690d193ccf3479b54e87e71344131546d77a90d4ba386f3e2b",
"conventions/brain-first.md": "e0e4d7c4b760213325dffd286baf934720816a0b6aac5338538a0463e8fe77d2",
"conventions/brain-routing.md": "392998d9a109b330c9225af4ca5c8798b0ff02eba4d441c93fdb7c263687d0c6",
"conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198",
diff --git a/src/commands/agent-register.ts b/src/commands/agent-register.ts
index dd982f590e..5173dcb853 100644
--- a/src/commands/agent-register.ts
+++ b/src/commands/agent-register.ts
@@ -52,6 +52,7 @@ import { GBRAIN_REMOTE_TOKEN_ENV } from '../core/bootstrap/opencode-json.ts';
import { renderCodexHttpServerBlock } from '../core/bootstrap/codex-toml.ts';
import { probeServeHealth, isServeOlderThanScopes, SCOPES_MIN_SERVE_VERSION } from '../core/bootstrap/serve-health.ts';
import { writeSurfaceChangeAudit } from '../core/surface-audit.ts';
+import { INSTALL_SURFACE_SET_BY } from '../mcp/surface.ts';
import {
registerScopedClient,
preflightOauthClientColumns,
@@ -280,10 +281,15 @@ export interface ResolvedPreset {
/** 'snapshot' = all non-archived sources at registration time. */
federatedRead: string[] | 'snapshot';
surface?: 'verbs' | 'starter' | 'full';
+ /** INSTALL_SURFACE_SET_BY when the preset chose `surface` (no --surface): the client lists the memory verbs. */
+ surfaceSetBy?: typeof INSTALL_SURFACE_SET_BY;
/** The write source is the derived `<name>-workspace` (auto-creatable). */
workspaceDerived: boolean;
}
+/** GBRA-199: a preset's own full surface lists the memory verbs and request_tools; an explicit --surface lists that surface in full. */
+const presetListing = (flags: AgentRegisterArgs): Pick<ResolvedPreset, 'surfaceSetBy'> => (flags.surface === undefined ? { surfaceSetBy: INSTALL_SURFACE_SET_BY } : {});
+
export function resolvePreset(flags: AgentRegisterArgs): ResolvedPreset {
const name = flags.name ?? '';
const explicit = <T>(v: T | undefined, fallback: T): T => (v !== undefined ? v : fallback);
@@ -295,6 +301,7 @@ export function resolvePreset(flags: AgentRegisterArgs): ResolvedPreset {
federatedRead: flags.federatedRead ?? 'snapshot',
// S0/D4: no narrowing on any install path; pass --surface starter for a capped harness.
surface: explicit(flags.surface, 'full'),
+ ...presetListing(flags),
workspaceDerived: false,
};
case 'coding-agent': {
@@ -322,6 +329,7 @@ export function resolvePreset(flags: AgentRegisterArgs): ResolvedPreset {
// source-scoped for remote callers (readPolicyOpts / routeCodeIntelScope),
// so full no longer reaches past the client's grant.
surface: explicit(flags.surface, 'full'),
+ ...presetListing(flags),
workspaceDerived,
};
}
@@ -367,6 +375,8 @@ interface RegisterOutput {
write_source: string;
federated_read: string[];
surface: string | null;
+ /** The surface tools/list shows when narrower than `surface` (an install-default surface lists the verbs). */
+ listed: string | null;
token_ttl: number | null;
};
serveWarning: string | null;
@@ -550,6 +560,7 @@ export async function runAgentRegister(engine: BrainEngine | null, args: string[
registered = await registerScopedClient(txSql, name, registerArgs, {
tokenTtlSeconds: ttl,
surface: preset.surface,
+ surfaceSetBy: preset.surfaceSetBy,
columns,
});
});
@@ -577,6 +588,7 @@ export async function runAgentRegister(engine: BrainEngine | null, args: string[
write_source: preset.writeSource,
federated_read: federated,
surface: registered.surface ?? null,
+ listed: registered.surface && preset.surfaceSetBy ? 'verbs' : null,
token_ttl: registered.tokenTtl ?? null,
});
printOutput(flags, out);
@@ -789,6 +801,7 @@ async function runReissue(
write_source: registered.sourceId,
federated_read: registered.federatedRead,
surface: null,
+ listed: null,
token_ttl: registered.tokenTtl ?? null,
});
out.probeNote = `${out.probeNote ?? ''}${out.probeNote ? ' ' : ''}Secret ROTATED: the old secret no longer mints tokens; outstanding access tokens stay valid until expiry — revoke the client to kill them now.`;
@@ -917,7 +930,9 @@ function printOutput(flags: AgentRegisterArgs, out: RegisterOutput): void {
console.log(` Write source: ${out.presetResolved.write_source}${r.created.source ? ' (created)' : ''}`);
console.log(` Federated reads: ${out.presetResolved.federated_read.join(', ')}`);
if (out.presetResolved.surface) {
- console.log(` Surface tier: ${out.presetResolved.surface} (widen: gbrain auth rescope-client "${r.clientId}" --surface full)`);
+ console.log(out.presetResolved.listed
+ ? ` Surface tier: ${out.presetResolved.surface}, listing the memory verbs and request_tools (list everything: gbrain auth rescope-client "${r.clientId}" --surface full)`
+ : ` Surface tier: ${out.presetResolved.surface} (widen: gbrain auth rescope-client "${r.clientId}" --surface full)`);
}
if (out.presetResolved.token_ttl) {
console.log(` Token TTL: ${out.presetResolved.token_ttl}s`);
diff --git a/src/commands/auth.ts b/src/commands/auth.ts
index a44bbe6141..450134fe80 100644
--- a/src/commands/auth.ts
+++ b/src/commands/auth.ts
@@ -34,6 +34,7 @@ import { readClientGrant, rescopeClientGrant, resolveGrantProfile, type GrantPat
import { parseClientRescopeArgs, parseRescopeGrantArgs, splitRescopeTarget, type RescopeGrantArgs } from '../core/grants/cli.ts';
import { GRANT_PROFILES, GrantError, TOKEN_TTL_MAX_SECONDS, TOKEN_TTL_MIN_SECONDS, grantFromClient, type ClientGrant } from '../core/grants/model.ts';
import { cliRenderContext, renderAction, type RenderedAction } from '../core/agent-output.ts';
+import type { INSTALL_SURFACE_SET_BY } from '../mcp/surface.ts';
import { migrateLegacyTokens, parseRescopeTokenArgs, renderLegacyGrantAxis, rescopeLegacyToken, resolveRescopeTarget, type MigrateLegacyResult, type RescopeTokenResult } from '../core/grants/legacy-token.ts';
function hashToken(token: string): string {
@@ -586,6 +587,8 @@ export interface RegisterScopedClientOpts {
* ONLY surface-column writer (sets surface_set_by='operator', the lock
* request_tools cannot override). Never a raw column UPDATE. */
surface?: 'verbs' | 'starter' | 'full';
+ /** INSTALL_SURFACE_SET_BY when `surface` is an install default (the client lists the memory verbs). */
+ surfaceSetBy?: 'operator' | typeof INSTALL_SURFACE_SET_BY;
/** Result of preflightOauthClientColumns — decides which optional-column
* writes are attempted. Absent → attempt everything (caller owns errors). */
columns?: Set<string>;
@@ -679,7 +682,7 @@ export async function registerScopedClient(
if (opts.columns && !opts.columns.has('surface')) {
surfaceSkipped = true;
} else {
- const rescoped = await provider.rescopeClient(clientId, { surface: opts.surface });
+ const rescoped = await provider.rescopeClient(clientId, { surface: opts.surface, surfaceSetBy: opts.surfaceSetBy });
surfaceApplied = opts.surface;
surfaceOld = rescoped.surfaceOld ?? null;
}
diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.ts
index e4c752622c..3a5a3ad69b 100644
--- a/src/commands/serve-http-mcp.ts
+++ b/src/commands/serve-http-mcp.ts
@@ -33,7 +33,7 @@ import { buildToolDefs } from '../mcp/tool-defs.ts';
import {
filterOpsForSurface,
advertisedOps,
- resolveAdvertisedSurface,
+ clientAdvertisedSurface,
clampSurface,
minSurface,
resolveClientRowSurface,
@@ -246,7 +246,7 @@ async function listMcpTools(ctx: ServeHttpContext, state: McpRequestState) {
const [gateDisabled, strictParamsMode, advertised] = await Promise.all([
disabledOpsForPublishGates(engine, config),
resolveStrictParamsMode(engine, config),
- resolveAdvertisedSurface(engine, config, ctx.advertise ?? null),
+ clientAdvertisedSurface(authInfo, engine, config, ctx.advertise ?? null),
]);
// FOV-4: `agent` deliberately implies only itself, which would strand
// agent-only tokens with ZERO discovery — ops flagged `agentCallable`
@@ -268,7 +268,7 @@ async function listMcpTools(ctx: ServeHttpContext, state: McpRequestState) {
const strictParams = strictParamsMode === 'reject';
// mcp.advertised_surface narrows the list only; dispatch below keeps the callable set (request_tools reaches the rest).
// A client that chose its own surface (request_tools {surface}, an operator rescope) gets that surface listed in full.
- const tools = buildToolDefs(authInfo.surface ? visibleOps : advertisedOps(visibleOps, surface, advertised), { strictParams });
+ const tools = buildToolDefs(advertisedOps(visibleOps, surface, advertised), { strictParams });
// v0.28.10: log every JSON-RPC method, not just successful tools/call.
// Pre-fix, /admin/api/requests showed nothing for clients that only
// ever called tools/list, and the v0.26.3 persistence regression test
@@ -416,7 +416,7 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, reques
// WP4 (D2): request_tools bounds its catalog + persist by this.
surfaceCeiling,
// D2: a callable tool the advertised surface leaves out of tools/list (same rule as listMcpTools).
- isListed: async op => !!authInfo.surface || advertisedOps([op], surface, await resolveAdvertisedSurface(engine, ctx.config, ctx.advertise ?? null)).length > 0,
+ isListed: async op => advertisedOps([op], surface, await clientAdvertisedSurface(authInfo, engine, ctx.config, ctx.advertise ?? null)).length > 0,
resultRows,
...(thinClient ? { thinClient: true } : {}),
// v0.31 follow-up fix: thread auth so the whoami op (and any
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 9e68e60586..a1953d7180 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1268,7 +1268,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.452.0', id: 'starter_tools_list_params_gbra156', text: 'The starter MCP tool list is about 27% smaller: it leaves out parameters MCP callers cannot use (local-only, server-set provenance) and rarely needed ones (legacy, admin, versioned skill catalog, image and code search, tuning and recovery knobs with safe defaults). Every left-out parameter is still accepted, and `request_tools {tools: [names]}` now returns each tool\'s full schema with every optional parameter, also on a server capped at starter. Memory verb descriptions no longer start with `MEMORY VERB (v1):`. The verbs and full surfaces list every parameter as before.' },
{ since: '0.60.452.0', id: 'sources_not_readable_gbra156', text: 'An unscoped `search`, `query`, `recall` or `list_pages` from a token or agent connection with no source grant that comes back empty, while every source it can read holds no page and other sources do, now carries a `sources_not_readable` notice (kind degraded). It says the empty result is not proof of absence, never names a hidden source, and its fix is `gbrain sources federate <source>` on the brain host, or a grant for the token. Granted tokens and OAuth clients never get it.' },
// GBRA-199. since: 'TBD' is stamped at the merge slot.
- { since: 'TBD', id: 'registration_lists_verbs_gbra199', text: 'New MCP registrations gbrain writes now list only the seven memory verbs (`recall`, `remember`, `entity`, …) and `request_tools` in tools/list: `gbrain setup claude-code|codex`, `gbrain bootstrap hooks`, the readiness and `gbrain init` registration lines (`serve --surface full --advertise verbs`) and `gbrain mcp expose` (its `serve --http` runs with `--advertise verbs`, so clients without their own surface see that list). Every operation stays callable, `request_tools` lists the rest and returns any tool\'s full schema, and a tool it describes joins the session\'s list. The initialize instructions follow the listed tools, so they point agents at `recall` instead of `search`. Existing registrations and exposures keep their listing, and an explicit `--surface full` (or starter, or verbs) lists that whole surface. New `gbrain serve --advertise <verbs|starter|full>` sets the listing per server and wins over config `mcp.advertised_surface`; a listing narrower than the callable set now always includes `request_tools`. Plugin manifests, a bare `serve` and grant-profile clients (whose surface is pinned) are unchanged.' },
+ { since: 'TBD', id: 'registration_lists_verbs_gbra199', text: 'New MCP registrations gbrain writes now list only the seven memory verbs (`recall`, `remember`, `entity`, …) and `request_tools` in tools/list: `gbrain setup claude-code|codex`, `gbrain bootstrap hooks`, the readiness and `gbrain init` registration lines (`serve --surface full --advertise verbs`) and `gbrain mcp expose` (its `serve --http` runs with `--advertise verbs`, so clients without their own surface see that list). Every operation stays callable, `request_tools` lists the rest and returns any tool\'s full schema, and a tool it describes joins the session\'s list. The initialize instructions follow the listed tools, so they point agents at `recall` instead of `search`. Existing registrations and exposures keep their listing, and an explicit `--surface full` (or starter, or verbs) lists that whole surface. New `gbrain serve --advertise <verbs|starter|full>` sets the listing per server and wins over config `mcp.advertised_surface`; a listing narrower than the callable set now always includes `request_tools`. Remote harness and bot clients get the same listing: a new `gbrain mcp provision` grant with the memory-reader, memory-writer or coding-agent profile and a new `gbrain agent register` daily-driver or coding-agent client keep the full callable surface but list the verbs and `request_tools` (`auth list-clients` shows `full (set by install)`); `gbrain auth rescope-client <id> --surface full` lists everything, and clients the operator pinned before keep their listing. Plugin manifests and a bare `serve` are unchanged.' },
{ since: '0.60.452.0', id: 'sources_add_federation_warning_gbra156', text: '`gbrain sources add` without `--federated` or `--no-federated` now warns on stderr that the new source is not federated, so a remote token or agent connection with no source grant cannot read its pages, and names `gbrain sources federate <id>` and `gbrain auth rescope --token <name> --sources <id>`. The stored default is still non-federated.' },
];
diff --git a/src/core/grants/profiles.ts b/src/core/grants/profiles.ts
index 56ca3b4ed4..9d14abad2a 100644
--- a/src/core/grants/profiles.ts
+++ b/src/core/grants/profiles.ts
@@ -4,8 +4,12 @@ import { operationScopesAllowed } from '../scope.ts';
import { opAllowedForBoundClient } from '../ops/context.ts';
import { GrantError, type ClientGrant, type GrantPatch, type GrantProfileId, type GrantValidationContext } from './model.ts';
import { VERSION } from '../../version.ts';
+import { INSTALL_SURFACE_SET_BY } from '../../mcp/surface.ts';
export const RENEWABLE_GRANT_TTL_SECONDS = 3600;
+
+/** Harness and bot profiles: a new grant calls the full surface and lists the memory verbs (INSTALL_SURFACE_SET_BY). */
+const VERBS_LISTED_PROFILES: ReadonlySet<GrantProfileId> = new Set(['memory-reader', 'memory-writer', 'coding-agent']);
export const STATIC_GRANT_TTL_SECONDS = 30 * 24 * 3600;
export function grantCatalog(): Pick<GrantValidationContext, 'operationNames' | 'delegateToolNames'> {
@@ -58,7 +62,9 @@ export function resolveGrantProfile(opts: {
profile: opts.profile, scopes, sourceId: opts.sourceId,
federatedRead: opts.federatedRead ?? opts.existing?.federatedRead ?? [opts.sourceId],
boundSlugPrefixes: directPrefixes, allowedOperations,
- surface: opts.profile === 'delegating-agent' ? 'starter' : 'full', surfaceSetBy: 'operator',
+ surface: opts.profile === 'delegating-agent' ? 'starter' : 'full',
+ surfaceSetBy: VERBS_LISTED_PROFILES.has(opts.profile) && (!opts.existing || opts.existing.surfaceSetBy === INSTALL_SURFACE_SET_BY)
+ ? INSTALL_SURFACE_SET_BY : 'operator',
boundTools: delegated ? opts.boundTools ?? opts.existing?.boundTools ?? null : null,
boundSourceId: delegated ? opts.sourceId : null,
boundBrainId: null,
diff --git a/src/core/grants/rescope.ts b/src/core/grants/rescope.ts
index 9429bbbd45..0c6f22929c 100644
--- a/src/core/grants/rescope.ts
+++ b/src/core/grants/rescope.ts
@@ -4,6 +4,7 @@ import { isUndefinedColumnError } from '../utils.ts';
import { assertValidSlugPrefixes, pgArray } from './encoding.ts';
import { rescopeClientGrantInTransaction } from './service.ts';
import type { GrantPatch, GrantProfileId } from './model.ts';
+import type { INSTALL_SURFACE_SET_BY } from '../../mcp/surface.ts';
export interface RescopeClientOptions {
sourceId?: string;
@@ -16,6 +17,8 @@ export interface RescopeClientOptions {
* (the operator lock: request_tools persist cannot override it).
*/
surface?: 'verbs' | 'starter' | 'full' | null;
+ /** Who set a non-null surface; default 'operator'. INSTALL_SURFACE_SET_BY marks an install default. */
+ surfaceSetBy?: 'operator' | typeof INSTALL_SURFACE_SET_BY;
scopes?: string[];
allowedOperations?: string[] | null;
boundTools?: string[] | null;
@@ -36,7 +39,7 @@ export type RescopeClientResult = { clientId: string; clientName: string; source
export async function rescopeOAuthClient(sql: SqlQuery, clientId: string, opts: RescopeClientOptions): Promise<RescopeClientResult> {
const { sourceId, federatedRead, boundSlugPrefixes, surface } = opts;
- if (sourceId === undefined && federatedRead === undefined && boundSlugPrefixes === undefined && surface === undefined && !Object.entries(opts).some(([key, value]) => !['actor', 'expectedRevision', 'dryRun', 'repair'].includes(key) && value !== undefined)) {
+ if (sourceId === undefined && federatedRead === undefined && boundSlugPrefixes === undefined && surface === undefined && !Object.entries(opts).some(([key, value]) => !['actor', 'expectedRevision', 'dryRun', 'repair', 'surfaceSetBy'].includes(key) && value !== undefined)) {
throw new Error('rescope-client requires --source, --federated-read, --bound-slug-prefixes, and/or --surface');
}
if (sourceId !== undefined) assertValidSourceId(sourceId);
@@ -70,8 +73,8 @@ export async function rescopeOAuthClient(sql: SqlQuery, clientId: string, opts:
WHERE table_schema = current_schema() AND table_name = 'oauth_clients'
AND column_name IN ('grant_revision', 'allowed_operations', 'delegated_slug_prefixes', 'delegated_namespace', 'grant_profile', 'grant_repair_reasons', 'surface', 'surface_set_by', 'token_ttl', 'source_id', 'federated_read', 'bound_slug_prefixes', 'bound_tools', 'bound_source_id', 'bound_brain_id', 'bound_max_concurrent', 'budget_usd_per_day')`;
if (schema.length === 17) {
- const { expectedRevision, actor, repair, dryRun, ...patch } = opts;
- if (surface !== undefined) (patch as GrantPatch).surfaceSetBy = surface === null ? null : 'operator';
+ const { expectedRevision, actor, repair, dryRun, surfaceSetBy, ...patch } = opts;
+ if (surface !== undefined) (patch as GrantPatch).surfaceSetBy = surface === null ? null : surfaceSetBy ?? 'operator';
if (sourceId !== undefined) {
const found = await sql`SELECT id FROM sources WHERE id = ${sourceId}`;
if (!found.length) throw new Error(`Source "${sourceId}" does not exist. Create it first: gbrain sources add ${sourceId} ...`);
@@ -82,7 +85,7 @@ export async function rescopeOAuthClient(sql: SqlQuery, clientId: string, opts:
...(boundSlugPrefixes !== undefined ? { boundSlugPrefixes: result.after.boundSlugPrefixes } : {}),
...(surface !== undefined ? { surface: result.after.surface, surfaceOld: result.before.surface } : {}) };
}
- if (Object.entries(opts).some(([key, value]) => !['sourceId', 'federatedRead', 'boundSlugPrefixes', 'surface'].includes(key) && value !== undefined)) {
+ if (Object.entries(opts).some(([key, value]) => !['sourceId', 'federatedRead', 'boundSlugPrefixes', 'surface', 'surfaceSetBy'].includes(key) && value !== undefined)) {
throw new Error('Client grant changes require an up-to-date OAuth schema; run gbrain apply-migrations --yes');
}
let rows: Record<string, unknown>[];
@@ -101,7 +104,7 @@ export async function rescopeOAuthClient(sql: SqlQuery, clientId: string, opts:
// `rescope-client --source wiki` fail on a brain that has the v60/v61
// OAuth columns but not v85's bound_* set (or v127's surface set) — a
// regression on an axis the caller never asked about.
- const surfaceSetBy = surface === null ? null : 'operator';
+ const surfaceSetBy = surface === null ? null : opts.surfaceSetBy ?? 'operator';
if (boundSlugPrefixes === undefined && surface === undefined) {
rows = await sql`
UPDATE oauth_clients
diff --git a/src/mcp/initialize-context.ts b/src/mcp/initialize-context.ts
index afa60dfbbb..5709d8e9ad 100644
--- a/src/mcp/initialize-context.ts
+++ b/src/mcp/initialize-context.ts
@@ -14,7 +14,7 @@ import { configReadiness, probedReadiness, readinessHttpView, readinessTail, typ
import { isEngineDegraded } from '../core/degraded-marker.ts';
import { disabledOpsForPublishGates } from './publish-gates.ts';
import type { InstructionTools } from './instructions.ts';
-import { advertisedOps, resolveAdvertisedSurface } from './surface.ts';
+import { advertisedOps, clientAdvertisedSurface } from './surface.ts';
/** Readiness entries the instructions tail may name, most limiting first. */
const TAIL_PRIORITY = ['embeddings', 'chat_llm', 'migrations', 'worker', 'facts_drain', 'local_transcripts'] as const;
@@ -45,7 +45,7 @@ export async function httpInstructionTools(
isCallable(op, { transport: 'http', surface: opts.surface, scopes: opts.auth.scopes, publishGates, allowedOps: opts.allowedOps })
&& opAllowedForBoundClient(opts.auth, op)).map(op => op.name));
const callable = opts.ops.filter(op => names.has(op.name));
- const listed = opts.auth.surface ? callable : advertisedOps(callable, opts.surface, await resolveAdvertisedSurface(engine, config, opts.advertise ?? null));
+ const listed = advertisedOps(callable, opts.surface, await clientAdvertisedSurface(opts.auth, engine, config, opts.advertise ?? null));
const listedNames = new Set(listed.map(op => op.name));
return { callable: n => listedNames.has(n), readiness: await instructionReadiness(engine, config, 'http', opts.cache), hiddenCallable: callable.length - listed.length };
}
diff --git a/src/mcp/surface.ts b/src/mcp/surface.ts
index a9eb4ac966..4135295e2c 100644
--- a/src/mcp/surface.ts
+++ b/src/mcp/surface.ts
@@ -372,6 +372,28 @@ export async function resolveAdvertisedSurface(engine: BrainEngine | null, confi
return isMcpSurface(fileVal) ? fileVal : null;
}
+/**
+ * `oauth_clients.surface_set_by` for a surface an install default wrote (the
+ * `gbrain agent register` presets and the harness grant profiles), not an
+ * operator: the client calls that surface but lists only the memory verbs and
+ * `request_tools`, like a stdio registration with `--advertise verbs`.
+ */
+export const INSTALL_SURFACE_SET_BY = 'install';
+
+/**
+ * The advertised surface for one HTTP client. A client without its own
+ * surface gets the server's (`--advertise`, `mcp.advertised_surface`); one
+ * whose surface an install default wrote lists the verbs; one that chose its
+ * surface (an operator rescope, `request_tools {surface}`) lists it in full.
+ */
+export async function clientAdvertisedSurface(
+ auth: { surface?: unknown; surfaceSetBy?: string | null },
+ engine: BrainEngine | null, config: GBrainConfig | null | undefined, flag: McpSurface | null = null,
+): Promise<McpSurface | null> {
+ if (auth.surface) return auth.surfaceSetBy === INSTALL_SURFACE_SET_BY ? 'verbs' : null;
+ return resolveAdvertisedSurface(engine, config, flag);
+}
+
/**
* The tools to list: the callable set narrowed to the advertised surface
* (never wider). A narrowed list always keeps request_tools when it is
diff --git a/test/agent-register.test.ts b/test/agent-register.test.ts
index 6974516f80..00748847d0 100644
--- a/test/agent-register.test.ts
+++ b/test/agent-register.test.ts
@@ -171,13 +171,14 @@ describe('resolvePreset', () => {
const flags = (over: Record<string, unknown>) =>
({ showToken: false, json: false, name: 'aurora', harness: 'claude-code', ...over }) as any;
- test('daily-driver: snapshot grant, default write source, full surface (S0/D4)', () => {
+ test('daily-driver: snapshot grant, default write source, full surface listing the verbs (S0/D4, GBRA-199)', () => {
const r = resolvePreset(flags({ preset: 'daily-driver' }));
expect(r).toEqual({
scopes: 'read write',
writeSource: 'default',
federatedRead: 'snapshot',
surface: 'full',
+ surfaceSetBy: 'install',
workspaceDerived: false,
});
});
diff --git a/test/client-grants.test.ts b/test/client-grants.test.ts
index 975bce87e7..be581660d7 100644
--- a/test/client-grants.test.ts
+++ b/test/client-grants.test.ts
@@ -80,7 +80,7 @@ describe('client capability grants', () => {
const created = await memoryClient('provenance-audit-example');
const grant = await readClientGrant(engine, created.clientId);
expect(grant.surface).toBe('full');
- expect(grant.surfaceSetBy).toBe('operator');
+ expect(grant.surfaceSetBy).toBe('install');
const [row] = await engine.executeRaw('SELECT after_grant FROM oauth_grant_audit WHERE client_id = $1', [created.clientId]);
const audit = row.after_grant as { allowedOperations: string[]; catalogProvenance: { version: number; operations: string[] } };
expect(audit.catalogProvenance.version).toBe(1);
diff --git a/test/fixtures/agent-contract/v1/journey/init-first-run.json b/test/fixtures/agent-contract/v1/journey/init-first-run.json
index 19b1fe35a3..07c9a5fd17 100644
--- a/test/fixtures/agent-contract/v1/journey/init-first-run.json
+++ b/test/fixtures/agent-contract/v1/journey/init-first-run.json
@@ -119,7 +119,7 @@
"options": [
{
"id": "wire",
- "label": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "label": "Register `<absolute path to gbrain> serve --surface full --advertise verbs` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
{
"id": "skip",
diff --git a/test/grant-profiles-surface.test.ts b/test/grant-profiles-surface.test.ts
index 138eda74c8..3897fc2771 100644
--- a/test/grant-profiles-surface.test.ts
+++ b/test/grant-profiles-surface.test.ts
@@ -50,12 +50,12 @@ async function capabilities(auth: AuthInfo) {
}
describe('profile surface defaults', () => {
- test('memory-writer and coding-agent resolve to an operator-set full surface with put_pages in the snapshot', () => {
+ test('memory-writer and coding-agent resolve to an install-default full surface (listing the verbs, GBRA-199) with put_pages in the snapshot', () => {
const writer = resolveGrantProfile({ profile: 'memory-writer', sourceId: 'default' });
const coding = resolveGrantProfile({ profile: 'coding-agent', sourceId: 'default', boundSlugPrefixes: ['agents/example/'] });
for (const grant of [writer, coding]) {
expect(grant.surface).toBe('full');
- expect(grant.surfaceSetBy).toBe('operator');
+ expect(grant.surfaceSetBy).toBe('install');
expect(grant.allowedOperations).toContain('put_pages');
}
});
@@ -98,7 +98,7 @@ describe('existing grants widen only through an explicit profile application', (
async function preD4Writer(name: string) {
// The shape every pre-D4 memory-writer was minted with: operator-pinned starter.
const created = await provider.registerClientManual(name, ['client_credentials'], 'read write', [], 'default', undefined, undefined, undefined,
- { ...resolveGrantProfile({ profile: 'memory-writer', sourceId: 'default' }), surface: 'starter' });
+ { ...resolveGrantProfile({ profile: 'memory-writer', sourceId: 'default' }), surface: 'starter', surfaceSetBy: 'operator' });
return { created, grant: await readClientGrant(engine, created.clientId) };
}
diff --git a/test/mcp-install-listing-http.test.ts b/test/mcp-install-listing-http.test.ts
new file mode 100644
index 0000000000..510c965343
--- /dev/null
+++ b/test/mcp-install-listing-http.test.ts
@@ -0,0 +1,120 @@
+/**
+ * GBRA-199: a harness or bot grant a gbrain install path mints (`gbrain mcp
+ * provision` profiles, `gbrain agent register` presets) calls the full
+ * surface but lists only the memory verbs and request_tools over HTTP, like a
+ * stdio registration with `--advertise verbs`. An operator's explicit surface
+ * lists that surface in full, and a grant that was operator-pinned before
+ * keeps its listing when a profile is applied again.
+ *
+ * Fails when: a provisioned client lists the whole catalog, an unlisted tool
+ * stops being callable, or an operator pin is narrowed to the verbs.
+ * PGLite in-memory, the production app from buildServeHttpApp over real HTTP.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { Server } from 'node:http';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import express from 'express';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { readClientGrant, resolveGrantProfile } from '../src/core/grants/service.ts';
+import { provisionHarnessGrant } from '../src/commands/mcp-provision.ts';
+import { buildServeHttpApp } from '../src/commands/serve-http.ts';
+import { resolvePreset } from '../src/commands/agent-register.ts';
+import { operations } from '../src/core/operations.ts';
+import { filterOpsForSurface, INSTALL_SURFACE_SET_BY } from '../src/mcp/surface.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+let provider: GBrainOAuthProvider;
+let home: string;
+let server: Server;
+let base: string;
+
+beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-install-listing-'));
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.setConfig('eval.capture', 'false');
+ provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const app = express();
+ server = await new Promise(resolve => { const s = app.listen(0, '127.0.0.1', () => resolve(s)); });
+ const address = server.address();
+ if (!address || typeof address === 'string') throw new Error('expected a TCP address');
+ base = `http://127.0.0.1:${address.port}`;
+ await buildServeHttpApp(app, engine, { port: address.port, tokenTtl: 3600, enableDcr: false, publicUrl: base });
+}, 120_000);
+
+afterAll(async () => {
+ await new Promise<void>(resolve => { server?.closeAllConnections?.(); server?.close(() => resolve()); });
+ await engine?.disconnect();
+ rmSync(home, { recursive: true, force: true });
+}, 30_000);
+
+async function token(clientId: string, secret: string): Promise<string> {
+ const res = await fetch(`${base}/token`, {
+ method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: new URLSearchParams({ grant_type: 'client_credentials', client_id: clientId, client_secret: secret, scope: 'read write' }),
+ });
+ expect(res.status).toBe(200);
+ return (await res.json() as { access_token: string }).access_token;
+}
+
+async function rpc(bearer: string, method: string, params?: unknown): Promise<any> {
+ const res = await fetch(`${base}/mcp`, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${bearer}`, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, ...(params ? { params } : {}) }),
+ });
+ expect(res.status).toBe(200);
+ const text = await res.text();
+ const data = text.split('\n').find(l => l.startsWith('data:'));
+ return JSON.parse(data ? data.slice('data:'.length) : text).result;
+}
+
+const listed = async (bearer: string) => (await rpc(bearer, 'tools/list')).tools.map((t: { name: string }) => t.name).sort();
+const VERBS_LISTING = [...filterOpsForSurface(operations, 'verbs').map(o => o.name), 'request_tools'].sort();
+
+describe('install-default grants list the memory verbs over HTTP', () => {
+ test('a provisioned memory-writer lists the verbs and request_tools, and an unlisted write stays callable', async () => {
+ const created = await withEnv({ GBRAIN_HOME: home }, () => provisionHarnessGrant(engine,
+ { name: 'listing-writer-example', harness: 'generic', url: `${base}/mcp`, profile: 'memory-writer' }, 'test'));
+ expect(created.grant.surface).toBe('full');
+ expect(created.grant.surfaceSetBy).toBe(INSTALL_SURFACE_SET_BY);
+ const bearer = await token(created.grant.clientId, created.credentials!.client_secret!);
+ expect(await listed(bearer)).toEqual(VERBS_LISTING);
+ const put = await rpc(bearer, 'tools/call', { name: 'put_page', arguments: { slug: 'notes/install-listing', content: '---\ntype: note\ntitle: Install listing\n---\nCallable while unlisted.\n' } });
+ expect(put.isError, put.content?.[0]?.text).toBeFalsy();
+ const described = await rpc(bearer, 'tools/call', { name: 'request_tools', arguments: { tools: ['put_page'] } });
+ expect(JSON.parse(described.content[0].text).tools.map((t: { name: string }) => t.name)).toEqual(['put_page']);
+ }, 60_000);
+
+ test('an operator rescope to --surface full lists the whole surface', async () => {
+ const created = await withEnv({ GBRAIN_HOME: home }, () => provisionHarnessGrant(engine,
+ { name: 'listing-operator-example', harness: 'generic', url: `${base}/mcp`, profile: 'memory-writer' }, 'test'));
+ await provider.rescopeClient(created.grant.clientId, { surface: 'full' });
+ expect((await readClientGrant(engine, created.grant.clientId)).surfaceSetBy).toBe('operator');
+ const names = await listed(await token(created.grant.clientId, created.credentials!.client_secret!));
+ expect(names).toContain('put_page');
+ expect(names.length).toBeGreaterThan(VERBS_LISTING.length);
+ }, 60_000);
+
+ test('a grant pinned by the operator before keeps its full listing when a profile is applied again', async () => {
+ const pinned = { ...resolveGrantProfile({ profile: 'memory-writer', sourceId: 'default' }), surfaceSetBy: 'operator' };
+ const created = await provider.registerClientManual('listing-pinned-example', ['client_credentials'], 'read write', [], 'default',
+ undefined, undefined, undefined, pinned);
+ const existing = await readClientGrant(engine, created.clientId);
+ expect(resolveGrantProfile({ profile: 'memory-writer', sourceId: 'default', existing }).surfaceSetBy).toBe('operator');
+ expect(await listed(await token(created.clientId, created.clientSecret!))).toContain('put_page');
+ }, 60_000);
+
+ test('agent register presets mark their own full surface; an explicit --surface is an operator pin', () => {
+ const base = { name: 'preset-example', federatedRead: ['proj-example'] } as const;
+ expect(resolvePreset({ ...base, preset: 'daily-driver' } as any).surfaceSetBy).toBe(INSTALL_SURFACE_SET_BY);
+ expect(resolvePreset({ ...base, preset: 'coding-agent' } as any).surfaceSetBy).toBe(INSTALL_SURFACE_SET_BY);
+ expect(resolvePreset({ ...base, preset: 'daily-driver', surface: 'full' } as any).surfaceSetBy).toBeUndefined();
+ });
+});