Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-156: _meta.hot_memory "off" drops the brain_hot_memory block for one call; docs say when it appears and which source it reads

garrytan8e9cd64d654c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 76090e04ef..fd10aab7d2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,7 @@ identifiers and attribution are available in the pre-removal Git revision
| `context_pack`, `delta` and writes | world-only | world-only, for every caller |
| `--private-pages none` | | hides them again on the next request |
| `gbrain auth list`, `auth clients`, `auth rescope`, the `serve --http` dashboard API key list and `whoami` | | show the setting; `gbrain auth list --json` is new |
+| A harness answering a channel or other shared session | every successful tool call could carry `_meta.brain_hot_memory`, which holds recent facts from the connection's write source (a member token's own private source), and there was no way to turn it off for one call | `_meta.hot_memory: "off"`, on the request or inside the arguments, drops the block for that call. Without it, nothing changes. `docs/protocol/MCP_META_CHANNELS.md`, `docs/mcp/README.md` and the install guide now say when the block appears and which source it reads |
### What to watch for after you upgrade
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md
index ed160199f3..4cf45313d8 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -624,6 +624,24 @@ to register. Ask the user which integrations they want (email, calendar, voice,
Verify: `gbrain integrations doctor` (after at least one is configured)
+### A bot that answers in channels or shared sessions
+
+Every successful MCP tool call except `recall`, `extract_facts` and
+`forget_fact` can carry a `_meta.brain_hot_memory` block. It holds recent
+facts from the connection's own source: a token's write source (the first id
+of its source grant), a stdio server's resolved source, or `default`. For a
+member token whose first source is that member's private source, the block
+holds that member's own facts, such as preferences from a direct message. The
+grant still holds: the block never draws on a source the connection can't
+read. But the harness may put it into its context, so the member's facts can
+reach a channel reply other people read.
+
+A harness running a channel or other shared session should set
+`_meta.hot_memory: "off"` on each tool call, on the MCP request beside
+`arguments` or inside the arguments. That call then carries no block. One
+member's direct-message session can keep it. Details:
+[MCP_META_CHANNELS.md](docs/protocol/MCP_META_CHANNELS.md#brain_hot_memory-when-it-appears-and-how-to-turn-it-off).
+
## Step 9: Verify
For memory-only installs, run the install check from the
diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.md
index dbf2461939..1afe253233 100644
--- a/docs/architecture/key-files/mcp.md
+++ b/docs/architecture/key-files/mcp.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)` (a read op (`mutating === false`) runs inside `withRequestConfigSnapshot`, a write op under `withoutRequestConfigSnapshot`; `src/core/config-snapshot.ts`), `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts`; for a read op on a live engine it runs beside the handler instead of after it (GBRA-156), and reads its withdrawal watermark and trust generation in one round trip — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash + eligibility + the `sessionOnly` scope (a session with no facts of its own falls back to the source's newest 24h facts unless the caller passes `sessionOnly`, which the IPC handlers do when `context.hot_memory.session_only` is on; MCP callers never pass it), so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served, the key folds the effective read eligibility and each hit revalidates the trust policy generation (`src/core/eligibility/generation.ts`, migration v230: deferred triggers bump `trust_policy_state` on tier changes, quarantine transitions, read floor and `trust.%` config changes, purges and `needs_rederive`), read before the rows; an unreadable generation delivers nothing; facts read through the `hot_memory` proactive eligibility and `partitionForActivation`, carry `trust_tier` and `origin`, and the payload's `suppressed` counts what activation control withheld), each producer isolated so one failure never drops another's key; A successful result's content[0] is compact `JSON.stringify(result)` (error envelopes stay indented); `opts.resultRows` threads the transport's row-shape choice into `OperationContext.resultRows`. empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. `retrievalNoticeBlocks` caps the saved-facts block at 1,500 characters and the other-names block at 400 (header included) with whole items only: the first item always shows, later items that would cross the ceiling are counted in a `(+N more…)` marker (pinned by `test/mcp-notice-ceilings.test.ts`). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `accepted_pending` (a `write_pending` with an admitted non-terminal receipt, kept out of the admin error rate; `acceptedPendingReceipt` returns its receipt so serve-http logs the opaque `write_request_id`) / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`. Agent contract v1: every failure (unknown tool, source guard, validation, strict params, missing source scope, handler throws) goes through `errorResult` → `toAgentError` → exactly one content block; handlers emit advice through `ctx.emitNotice` and the empty-retrieval, unknown-param and backup-coverage blocks ride that channel (prefixed `[gbrain notice <code> kind=<kind>]` blocks + `_meta.gbrain_notices`), filtered by the notice ledger (`opts.noticeLedger` on HTTP). `dispatchRenderContext` binds `isCallable` for fixes; `unknownToolEnvelope(name, opts, 'unknown_operation')` keeps serve-http's frozen value; `localCallErrorEnvelope` is `gbrain call`'s envelope. `sessionSafetyNotices` adds the one-time `behavior_changes` disclosure (stdio: once per brain; HTTP: once per authenticated client, remote view) and, on stdio only, the queued `chat_fallback_hop` notice, on success and failure results alike. `requestMetaSessionId(request.params)` is the one reader of the request-level `_meta.session_id` (beside `arguments`); stdio (`server.ts`) and HTTP (`serve-http-mcp.ts`) both pass it as `opts.sessionId`, which wins over an arguments-level `_meta` and is clamped to `SESSION_ID_MAX_CHARS` (256). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero. `retrievalNoticeBlocks` also appends the rate line for a rateable answer (`_meta.retrieval.answer_id` with `feedback.rateable`): `Rate after use: rate_answer { answer_id, rating: 1-5 }`, or the fuller wording when `how_to_rate` fired, capped at `RATE_LINE_MAX_CHARS` = 160 (#6192; `test/mcp-feedback-visible-answer-id.test.ts`). Large pages: after a read's result is assembled (notices and `_meta` included), `frameOverCap` measures the final encoded frame against the connection's cap and replaces an oversized read with `result_too_large` (writes are never replaced); `DispatchOpts.thinClient` (from `X-Gbrain-Client` on both HTTP transports) reaches `OperationContext.thinClient`, a default-body-mode hint, never authority. GBRA-156: a remote non-mutating op runs inside `withPrivateReadableSources(auth.privatePages.sources)`; writes, local calls and `context_pack` / `delta` (`WORLD_ONLY_PACK_OPS`) run with an empty set.
+- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)` (a read op (`mutating === false`) runs inside `withRequestConfigSnapshot`, a write op under `withoutRequestConfigSnapshot`; `src/core/config-snapshot.ts`), `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts`; for a read op on a live engine it runs beside the handler instead of after it (GBRA-156), and reads its withdrawal watermark and trust generation in one round trip — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash + eligibility + the `sessionOnly` scope (a session with no facts of its own falls back to the source's newest 24h facts unless the caller passes `sessionOnly`, which the IPC handlers do when `context.hot_memory.session_only` is on; MCP callers never pass it), so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served, the key folds the effective read eligibility and each hit revalidates the trust policy generation (`src/core/eligibility/generation.ts`, migration v230: deferred triggers bump `trust_policy_state` on tier changes, quarantine transitions, read floor and `trust.%` config changes, purges and `needs_rederive`), read before the rows; an unreadable generation delivers nothing; facts read through the `hot_memory` proactive eligibility and `partitionForActivation`, carry `trust_tier` and `origin`, and the payload's `suppressed` counts what activation control withheld), each producer isolated so one failure never drops another's key; A successful result's content[0] is compact `JSON.stringify(result)` (error envelopes stay indented); `opts.resultRows` threads the transport's row-shape choice into `OperationContext.resultRows`. empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. `retrievalNoticeBlocks` caps the saved-facts block at 1,500 characters and the other-names block at 400 (header included) with whole items only: the first item always shows, later items that would cross the ceiling are counted in a `(+N more…)` marker (pinned by `test/mcp-notice-ceilings.test.ts`). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `accepted_pending` (a `write_pending` with an admitted non-terminal receipt, kept out of the admin error rate; `acceptedPendingReceipt` returns its receipt so serve-http logs the opaque `write_request_id`) / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`. Agent contract v1: every failure (unknown tool, source guard, validation, strict params, missing source scope, handler throws) goes through `errorResult` → `toAgentError` → exactly one content block; handlers emit advice through `ctx.emitNotice` and the empty-retrieval, unknown-param and backup-coverage blocks ride that channel (prefixed `[gbrain notice <code> kind=<kind>]` blocks + `_meta.gbrain_notices`), filtered by the notice ledger (`opts.noticeLedger` on HTTP). `dispatchRenderContext` binds `isCallable` for fixes; `unknownToolEnvelope(name, opts, 'unknown_operation')` keeps serve-http's frozen value; `localCallErrorEnvelope` is `gbrain call`'s envelope. `sessionSafetyNotices` adds the one-time `behavior_changes` disclosure (stdio: once per brain; HTTP: once per authenticated client, remote view) and, on stdio only, the queued `chat_fallback_hop` notice, on success and failure results alike. `requestMetaSessionId(request.params)` is the one reader of the request-level `_meta.session_id` (beside `arguments`); stdio (`server.ts`) and HTTP (`serve-http-mcp.ts`) both pass it as `opts.sessionId`, which wins over an arguments-level `_meta` and is clamped to `SESSION_ID_MAX_CHARS` (256). GBRA-156: `hotMemoryOffIn(params)` reads `_meta.hot_memory: "off"`. Both transports pass the request-level value as `opts.hotMemoryOff`, and dispatch also reads it from the arguments' `_meta`. Either one skips the `metaHook` for that call, so the response carries no `brain_hot_memory` (`test/mcp-hot-memory-opt-out.test.ts`). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero. `retrievalNoticeBlocks` also appends the rate line for a rateable answer (`_meta.retrieval.answer_id` with `feedback.rateable`): `Rate after use: rate_answer { answer_id, rating: 1-5 }`, or the fuller wording when `how_to_rate` fired, capped at `RATE_LINE_MAX_CHARS` = 160 (#6192; `test/mcp-feedback-visible-answer-id.test.ts`). Large pages: after a read's result is assembled (notices and `_meta` included), `frameOverCap` measures the final encoded frame against the connection's cap and replaces an oversized read with `result_too_large` (writes are never replaced); `DispatchOpts.thinClient` (from `X-Gbrain-Client` on both HTTP transports) reaches `OperationContext.thinClient`, a default-body-mode hint, never authority. GBRA-156: a remote non-mutating op runs inside `withPrivateReadableSources(auth.privatePages.sources)`; writes, local calls and `context_pack` / `delta` (`WORLD_ONLY_PACK_OPS`) run with an empty set.
- `src/core/egress-budget.ts` — the per-connection result cap: `resultByteCap` (Infinity for the trusted local CLI; else `mcp.max_result_bytes_stdio` 4 MiB / `mcp.max_result_bytes_http` 1 MiB, DB plane then file plane, clamped to 256 KiB–9 MiB), `encodedFrameBytes` (the complete JSON-RPC frame plus a framing reserve), and the dispatcher backstop pair `frameOverCap` / `resultTooLargeError`.
- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract, compile-time source text (no runtime filesystem dependency) shared by the stdio SDK server, the OAuth HTTP SDK server and the legacy raw HTTP initialize path. `buildMcpInstructions({writeback?, tools?})` GENERATES the contract from the caller's callable set (`tools.callable`, the tools/list predicate): a clause naming a tool (search/query/get_page, skills catalog, put_page, whoami, join/sync skills, put/delete skill, the memory loop's `context_pack`/`volunteer_context`/`remember`/`forget`) appears only when that tool is listed, so every tool named is in that surface's tools/list (`test/mcp-initialize-instructions.test.ts`). When callable tools are left out of the listed set (`hiddenCallable`) and `request_tools` is callable, the hidden-tool sentence leads the contract, inside the 2,048 characters capped harnesses read (D1). It always carries the error protocol (follow `fix.next`, then `fix.verify`) and the notice prefix, then the optional status-only line (F4), the opt-in ambient-writeback section (`src/core/facts/writeback-instructions.ts`) and the readiness tail (top two `missing`/`degraded` gaps among embeddings, chat_llm, migrations, worker — never a by-choice state). With no `tools` and no writeback it equals `GBRAIN_MCP_INSTRUCTIONS` (the every-tool rendering bootstrap writes to GBRAIN-INSTRUCTIONS.md). `resolveMcpInstructions(config, env?, opts)` appends the operator-set deployment identity LAST under `Deployment identity:` (`GBRAIN_MCP_INSTRUCTIONS` env when non-blank, else file-plane `mcp.instructions`). `installInstructionsResolver(server, compute)` swaps the SDK Server's initialize handler so the stdio and OAuth servers compute the contract (callable set + readiness tail via `src/mcp/initialize-context.ts`) when the client initializes; the constructor value stays the fallback on a throw. The legacy bearer transport builds it inline per initialize. Transport tests compare against the contract for that connection's own tools/list (`test/helpers/instructions-parity.ts`): `test/serve-stdio-roundtrip.test.ts`, `test/http-transport.test.ts`, `test/connect-bearer.test.ts`, `test/mcp-instructions-writeback.test.ts`; identity composition in `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`. #6170: `contractClauses(c, writeback)` puts the short `Ambient writeback is ON (<mode>)` line (with `visibility "private"` under a private posture) in the memory clause when writeback is on, follows the data-not-instructions clause with the shortened error protocol and moves the forget caveat after the scope clause, so the writeback line, `Follow \`fix.next\``, `[gbrain notice`, `context_pack`, `put_page REPLACES` and `Writing:` end inside the first 2,048 characters on every surface (pinned per surface × mode × extract_facts × visibility in `test/mcp-initialize-instructions.test.ts`); the full writeback section stays appended last. Cat 40's measured "Answering from the brain" clause is verbatim; the change needs the D12 Cat 40 smoke before merge. The brief clause puts the `referenced_by` walk on the single-name `entity` card and names only the fields compact `names` rows carry on the brain (`references: {namesRow, records}`, read at every per-initialize call site by `readInstructionContent` from `src/core/entity-references-config.ts`; the static contract is the defaults rendering; `test/mcp-instructions-references.test.ts`). Instruction 7's governing rule (`mcp.instructions_governing_rule`: `in_effect` default, `newest` the earlier recency sentence) leads the answering clause so it ends inside the first 2,048 characters (`test/mcp-instructions-governing-rule.test.ts` records its offset per surface).
diff --git a/docs/mcp/README.md b/docs/mcp/README.md
index dc7990d7c7..c4d29260c4 100644
--- a/docs/mcp/README.md
+++ b/docs/mcp/README.md
@@ -140,3 +140,15 @@ pass it to `get_page`.
```
`search.query_facts_arm=false` turns fact rows off.
+
+## Recent facts in `_meta.brain_hot_memory`
+
+Most successful tool calls carry `_meta.brain_hot_memory`: up to 10 recent
+facts from the connection's own source. For a token, that is its write source,
+the first id of its source grant. For a member token whose first source is the
+member's private source, the block holds that member's own facts. A harness
+that answers a channel or other shared session should send
+`_meta.hot_memory: "off"` with each call, on the request beside `arguments`
+or inside the arguments, so those facts can't ride into a reply other people
+read. Without it, the block is unchanged. When it appears and which facts it
+holds: [MCP_META_CHANNELS.md](../protocol/MCP_META_CHANNELS.md#brain_hot_memory-when-it-appears-and-how-to-turn-it-off).
diff --git a/docs/protocol/MCP_META_CHANNELS.md b/docs/protocol/MCP_META_CHANNELS.md
index 0e4f0bb0b2..f901fa3a25 100644
--- a/docs/protocol/MCP_META_CHANNELS.md
+++ b/docs/protocol/MCP_META_CHANNELS.md
@@ -41,3 +41,41 @@ lives in JSON BODIES of eval commands — a third, unrelated plane. Ambient
recall rides content/hooks, not `_meta`.
Adding a key: register it in the table above, one producer, additive-forever.
+
+## `brain_hot_memory`: when it appears and how to turn it off
+
+**When.** On every successful tool call over stdio (`gbrain serve`) and
+HTTP (`gbrain serve --http`), except `recall`, `extract_facts` and
+`forget_fact`, whenever the source below has facts to show. Errors never carry
+it.
+
+**Which facts.** Up to 10 recent facts from one source: the connection's own
+source. Over HTTP that is the token's or client's write source (the first id
+of its source grant), or `default` with no grant. Over stdio it is the source
+the server resolved (`GBRAIN_SOURCE`, `.gbrain-source`, then `default`). With
+a `_meta.session_id`, the block holds that session's facts. Without one, or
+when the session has none, it holds the source's facts from the last 24 hours,
+unless the host set `context.hot_memory.session_only`. A remote caller only
+ever gets facts with `visibility: world`, and never a fact from a source its
+grant can't read.
+
+**Why it matters for shared sessions.** A member token whose first source is
+that member's private source (`private-alice-example`) gets that member's own
+recent facts in the block, such as preferences from a direct message. That is
+correct for the member's own session. A harness that answers several people in
+a channel and puts the block into the model's context can carry those facts
+into a reply everyone reads.
+
+**Turning it off for one call.** Set `_meta.hot_memory: "off"` on the request,
+beside `arguments` (MCP request-level `_meta`), or inside the tool arguments
+(`{"query": "…", "_meta": {"hot_memory": "off"}}`) for clients that fold
+`_meta` into the arguments. That call's response carries no
+`brain_hot_memory`. Other values, or no value, leave the block as it is. A
+channel or shared session should send it on every call. A member's own
+direct-message session can leave it out.
+
+```json
+{"jsonrpc": "2.0", "id": 7, "method": "tools/call",
+ "params": {"name": "search", "arguments": {"query": "standup time"},
+ "_meta": {"session_id": "channel-a", "hot_memory": "off"}}}
+```
diff --git a/llms-full.txt b/llms-full.txt
index b1fc2b4a4a..3d1563f19e 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -3276,6 +3276,24 @@ to register. Ask the user which integrations they want (email, calendar, voice,
Verify: `gbrain integrations doctor` (after at least one is configured)
+### A bot that answers in channels or shared sessions
+
+Every successful MCP tool call except `recall`, `extract_facts` and
+`forget_fact` can carry a `_meta.brain_hot_memory` block. It holds recent
+facts from the connection's own source: a token's write source (the first id
+of its source grant), a stdio server's resolved source, or `default`. For a
+member token whose first source is that member's private source, the block
+holds that member's own facts, such as preferences from a direct message. The
+grant still holds: the block never draws on a source the connection can't
+read. But the harness may put it into its context, so the member's facts can
+reach a channel reply other people read.
+
+A harness running a channel or other shared session should set
+`_meta.hot_memory: "off"` on each tool call, on the MCP request beside
+`arguments` or inside the arguments. That call then carries no block. One
+member's direct-message session can keep it. Details:
+[MCP_META_CHANNELS.md](docs/protocol/MCP_META_CHANNELS.md#brain_hot_memory-when-it-appears-and-how-to-turn-it-off).
+
## Step 9: Verify
For memory-only installs, run the install check from the
diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.ts
index d760c179a6..b28dfde4cb 100644
--- a/src/commands/serve-http-mcp.ts
+++ b/src/commands/serve-http-mcp.ts
@@ -22,7 +22,7 @@ import { createSkillResources } from '../mcp/skill-resources.ts';
import { resolveAuthCapabilities } from '../core/harness/capabilities.ts';
import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback-config.ts';
import { hasScope, operationScopesAllowed } from '../core/scope.ts';
-import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult, requestMetaSessionId, acceptedPendingReceipt, unknownToolEnvelope, errorResult, dispatchRenderContext, grantBlockedNotices, admitNotices, type ToolResult } from '../mcp/dispatch.ts';
+import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult, requestMetaSessionId, hotMemoryOffIn, acceptedPendingReceipt, unknownToolEnvelope, errorResult, dispatchRenderContext, grantBlockedNotices, admitNotices, type ToolResult } from '../mcp/dispatch.ts';
import { toAgentError } from '../core/agent-output.ts';
import { STATUS_TOOL_NAME, statusModeOf, statusToolResult } from '../mcp/status-mode.ts';
import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';
@@ -405,6 +405,7 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, reques
transport: 'http',
inboundFrameBytes: DEFAULT_MAX_REQUEST_BODY_SIZE,
...(sessionId ? { sessionId } : {}),
+ ...(hotMemoryOffIn(request.params) ? { hotMemoryOff: true } : {}),
takesHoldersAllowList: tokenAllowList,
sourceId: tokenSourceId,
...(localFederated ? { localFederatedSourceIds: localFederated } : {}),
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index 35eb23b62f..b681058237 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -230,6 +230,13 @@ export interface DispatchOpts {
* it there). Cache/telemetry identity only — never a trust surface.
*/
sessionId?: string;
+ /**
+ * GBRA-156: the request asked for no `_meta.brain_hot_memory` block (MCP request-level
+ * `_meta.hot_memory: "off"`, resolved by the transport). The same value inside the tool
+ * arguments' `_meta` works too. A channel or shared session sets it so a requester's own
+ * facts never ride into a reply other people read.
+ */
+ hotMemoryOff?: boolean;
/**
* v0.31 (eD3): hook called by the dispatcher AFTER op.handler succeeds
* to compute `_meta.brain_hot_memory` for the response. Wrapped in its
@@ -806,6 +813,11 @@ export function requestMetaSessionId(requestParams: unknown): string | undefined
return typeof raw === 'string' && raw.length > 0 ? raw : undefined;
}
+/** GBRA-156: `_meta.hot_memory: "off"` on the request (pass `request.params`) or inside the tool arguments (pass the arguments). */
+export function hotMemoryOffIn(params: unknown): boolean {
+ return (params as { _meta?: { hot_memory?: unknown } } | undefined)?._meta?.hot_memory === 'off';
+}
+
/**
* Read `_meta.session_id` out of the tool arguments when present. The MCP
* spec carries `_meta` as a sibling of `arguments`, but several clients (and
@@ -884,7 +896,8 @@ export async function dispatchToolCall(
// context_pack and delta stay world-only for every caller unless a trusted local one passes include_private, so no grant widens them.
const readOnly = operations.find(o => o.name === name)?.mutating === false;
const privateSources = readOnly && opts.remote !== false && !WORLD_ONLY_PACK_OPS.has(name) ? opts.auth?.privatePages?.sources : undefined;
- const run = () => withPrivateReadableSources(privateSources, () => withRequestIdentityMemo(() => dispatchResolvedCall(engine, name, params, opts)));
+ const resolved = opts.metaHook && (opts.hotMemoryOff === true || hotMemoryOffIn(params)) ? { ...opts, metaHook: undefined } : opts;
+ const run = () => withPrivateReadableSources(privateSources, () => withRequestIdentityMemo(() => dispatchResolvedCall(engine, name, params, resolved)));
if (name === 'search' || name === 'query') return withSearchConnectionBudget(() => withRequestConfigSnapshot(engine, run));
return readOnly
? withRequestConfigSnapshot(engine, run)
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index dda7e3b742..2446f2def4 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -444,7 +444,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// shape and cast through `any` (the SDK accepts it via the ServerResult union).
server.setRequestHandler(CallToolRequestSchema, async (request: any): Promise<any> => trackStdioRpc(() => withRequestConfigSnapshot(engine, async () => {
const { name, arguments: params } = request.params;
- const [{ dispatchToolCall, dispatchRenderContext, requestMetaSessionId }, { getBrainHotMemoryMeta }] = await gate.awaitCall();
+ const [{ dispatchToolCall, dispatchRenderContext, requestMetaSessionId, hotMemoryOffIn }, { getBrainHotMemoryMeta }] = await gate.awaitCall();
// F4: status-only mode answers gbrain_status and refuses the rest until
// a tool call's re-probe finds the brain openable (then dispatch normally).
if (statusMode) {
@@ -484,7 +484,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// stdio stays remote/untrusted.
transport: 'stdio', inboundFrameBytes: MCP_STDIO_MAX_MESSAGE_BYTES,
takesHoldersAllowList: ['world'],
- ...(sessionId ? { sessionId } : {}),
+ ...(sessionId ? { sessionId } : {}), ...(hotMemoryOffIn(request.params) ? { hotMemoryOff: true } : {}),
sourceId: sourceScope.sourceId,
...(sourceScope.localFederatedSourceIds
? { localFederatedSourceIds: sourceScope.localFederatedSourceIds }
diff --git a/test/mcp-hot-memory-opt-out.test.ts b/test/mcp-hot-memory-opt-out.test.ts
new file mode 100644
index 0000000000..13c0f599fe
--- /dev/null
+++ b/test/mcp-hot-memory-opt-out.test.ts
@@ -0,0 +1,101 @@
+/**
+ * GBRA-156: a per-request opt-out for `_meta.brain_hot_memory`.
+ *
+ * 1. Protects: under a member token, every successful tool call carries
+ * `_meta.brain_hot_memory` with recent facts from the token's write source
+ * (a member's private source). A channel or shared session asks for none
+ * with `_meta.hot_memory: "off"`, set on the MCP request (beside
+ * `arguments`) or inside the tool arguments, and gets no block. Without
+ * the opt-out the block is unchanged.
+ * 2. Fails when: an opted-out call still carries the block, or a call
+ * without the opt-out (or with another value) loses it.
+ * 3. Existing coverage (facts-context-injection, serve-http-meta) pins that
+ * the block appears and its visibility filter; nothing could turn it off
+ * per request.
+ * 4. No production seam: the production serve-http app, a real legacy token
+ * granted two sources, and dispatch with the options stdio passes.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { dispatchToolCall, hotMemoryOffIn } from '../src/mcp/dispatch.ts';
+import { getBrainHotMemoryMeta, __resetHotMemoryCacheForTests } from '../src/core/facts/meta-hook.ts';
+import { callTool, rpc, startServeHttp, type LiveServeHttp, type ToolResultWire } from './helpers/live-mcp-servers.ts';
+
+const MEMBER_SOURCE = 'hm-private-alice-example';
+const CHANNEL_SOURCE = 'hm-channel-a';
+const FACT = 'alice-example prefers async standups';
+
+let engine: PGLiteEngine;
+let app: LiveServeHttp;
+let token: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite' } as never);
+ await engine.initSchema();
+ for (const id of [MEMBER_SOURCE, CHANNEL_SOURCE]) await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [id]);
+ await engine.insertFact({ fact: FACT, kind: 'preference', entity_slug: 'people/alice-example', visibility: 'world', source: 'test' }, { source_id: MEMBER_SOURCE });
+ token = (await mintLegacyToken(engine, { name: 'hm-member-alice', scopes: ['read'], takesHolders: ['world'], sourceGrant: [MEMBER_SOURCE, CHANNEL_SOURCE] })).token;
+ app = await startServeHttp(engine);
+});
+
+afterAll(async () => {
+ await app?.close();
+ await engine?.disconnect();
+});
+
+function hotFacts(r: ToolResultWire): string[] | null {
+ const block = r._meta?.brain_hot_memory as { source_id: string; facts: Array<{ fact: string }> } | undefined;
+ if (!block) return null;
+ expect(block.source_id).toBe(MEMBER_SOURCE);
+ return block.facts.map(f => f.fact);
+}
+
+async function callWithRequestMeta(meta: Record<string, unknown>): Promise<ToolResultWire> {
+ const r = await rpc(app.base, token, 'tools/call', { name: 'search', arguments: { query: 'standups' }, _meta: meta });
+ expect(r.status).toBe(200);
+ return r.body.result as ToolResultWire;
+}
+
+describe('_meta.brain_hot_memory per-request opt-out (serve-http, member token)', () => {
+ test('by default the block carries the member source\'s recent facts', async () => {
+ __resetHotMemoryCacheForTests();
+ expect(hotFacts(await callTool(app.base, token, 'search', { query: 'standups' }))).toContain(FACT);
+ expect(hotFacts(await callTool(app.base, token, 'list_pages', {}))).toContain(FACT);
+ });
+
+ test('request-level _meta.hot_memory "off" drops the block', async () => {
+ const r = await callWithRequestMeta({ hot_memory: 'off', session_id: 'channel-session' });
+ expect(r.isError).toBeFalsy();
+ expect(hotFacts(r)).toBeNull();
+ });
+
+ test('_meta.hot_memory "off" inside the tool arguments drops the block', async () => {
+ const r = await callTool(app.base, token, 'search', { query: 'standups', _meta: { hot_memory: 'off' } });
+ expect(r.isError).toBeFalsy();
+ expect(hotFacts(r)).toBeNull();
+ });
+
+ test('any other value keeps the default', async () => {
+ expect(hotFacts(await callWithRequestMeta({ hot_memory: 'on' }))).toContain(FACT);
+ expect(hotFacts(await callWithRequestMeta({ hot_memory: false }))).toContain(FACT);
+ });
+});
+
+describe('dispatch honours hotMemoryOff from the transport (stdio options)', () => {
+ const opts = { remote: true, transport: 'stdio' as const, sourceId: MEMBER_SOURCE, takesHoldersAllowList: ['world'], metaHook: getBrainHotMemoryMeta };
+
+ test('without the opt-out the block is present; with it, absent', async () => {
+ __resetHotMemoryCacheForTests();
+ expect(((await dispatchToolCall(engine, 'get_stats', {}, opts))._meta as any)?.brain_hot_memory).toBeDefined();
+ const off = await dispatchToolCall(engine, 'get_stats', {}, { ...opts, hotMemoryOff: true });
+ expect(off.isError).toBeFalsy();
+ expect((off._meta as any)?.brain_hot_memory).toBeUndefined();
+ });
+
+ test('hotMemoryOffIn reads only the exact "off" value', () => {
+ expect(hotMemoryOffIn({ _meta: { hot_memory: 'off' } })).toBe(true);
+ for (const v of [undefined, {}, { _meta: null }, { _meta: { hot_memory: 'OFF' } }, { _meta: { hot_memory: false } }]) expect(hotMemoryOffIn(v)).toBe(false);
+ });
+});