Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(serve): serve --http operations see the DB-plane config (#6589)

time-attack31cec9726db6
diff --git a/docs/eval-capture.md b/docs/eval-capture.md
index 1fbe4d3a46..1623f8677b 100644
--- a/docs/eval-capture.md
+++ b/docs/eval-capture.md
@@ -9,6 +9,15 @@ replay captured real-world queries as a BrainBench-Real fixture.
## The pipeline
+HTTP MCP servers (`gbrain serve --http`, both the OAuth and the legacy bearer
+transport) honor DB-plane settings such as `eval.capture` and `eval.scrub_pii`
+from `gbrain config set`, with file and environment settings taking
+precedence, as the CLI does. The server reads that effective config once at
+startup, so restart serve after a DB-plane change (#6589). A server whose
+database is degraded at startup uses the file and environment settings only.
+Capture remains opt-in, and PII scrubbing remains enabled unless explicitly
+disabled.
+
```
MCP / CLI / subagent tool-bridge caller
│
diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsv
index b62bee1d4d..86ea1d7069 100644
--- a/scripts/serial-files.tsv
+++ b/scripts/serial-files.tsv
@@ -2,6 +2,7 @@
# class: R1 (process.env mutation) | R2 (mock.module) | global-state (other process-wide state) | exclusive (EXCLUSIVE_FILES in scripts/run-serial-tests.sh).
# Before adding a row, run: bash scripts/check-test-isolation.sh --as-parallel <file> (docs/TESTING.md#when-to-quarantine-instead-of-fix)
path class reason
+test/http-db-config.serial.test.ts global-state global-state: binds HTTP listeners; drains process-wide pending eval capture registry; withEnv scopes GBRAIN_HOME and GBRAIN_CONTRIBUTOR_MODE
test/admin-grant-outcome.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect; binds local servers/ports
test/advisor-backup-coverage.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_BACKUP_CHECK)
test/agent-error-surfaces.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.ts
index b0c20ada4b..26782d63f9 100644
--- a/src/commands/serve-http-mcp.ts
+++ b/src/commands/serve-http-mcp.ts
@@ -392,6 +392,7 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, reques
toolResult = await dispatchToolCall(engine, name, params as Record<string, unknown> | undefined, {
remote: true,
admissionOrigin: 'interactive',
+ config: ctx.config,
// WP1/D7: network transport — the dispatch-layer localOnly
// backstop keys off this marker.
transport: 'http',
diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.ts
index 5e0db3cdc5..c397660265 100644
--- a/src/commands/serve-http.ts
+++ b/src/commands/serve-http.ts
@@ -44,7 +44,8 @@ import type { McpSurface } from '../mcp/surface.ts';
import { bindResolveIpcForServe } from '../mcp/resolve-ipc-binding.ts';
import { createPersistenceIpcProvider, residentPersistenceConfig } from '../core/persistence/provider.ts';
import { resolveMcpStdioSourceScope } from '../mcp/server.ts';
-import { loadConfig, type GBrainConfig } from '../core/config.ts';
+import { loadConfig, loadConfigWithEngine, type GBrainConfig } from '../core/config.ts';
+import { isEngineDegraded } from '../core/degraded-marker.ts';
import { buildError } from '../core/errors.ts';
import * as db from '../core/db.ts';
import { sqlQueryForEngine, type SqlQuery } from '../core/sql-query.ts';
@@ -614,7 +615,12 @@ export async function buildServeHttpApp(app: express.Express, engine: BrainEngin
// a misconfiguration; we WARN to stderr at startup in that case rather
// than silently binding loopback only.
const bind = options.bind ?? '127.0.0.1';
- const config = loadConfig() || { engine: 'pglite' as const };
+ // #6589: CLI parity. Operations, resources and startup consumers see file + env over the DB plane
+ // (`gbrain config set`), read once here: a DB-plane change applies after a serve restart (D18). A degraded
+ // engine keeps the file plane, as the bearer transport does.
+ const fileConfig = loadConfig();
+ const config = (isEngineDegraded(engine) ? fileConfig : await loadConfigWithEngine(engine, fileConfig ?? { engine: engine.kind } as GBrainConfig))
+ || { engine: 'pglite' as const };
const skillStatus = await logServeHttpStartup(engine, options, config);
diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.ts
index cfc9c10e20..94ca2eee7e 100644
--- a/src/mcp/http-transport.ts
+++ b/src/mcp/http-transport.ts
@@ -45,7 +45,7 @@ import { GBRAIN_CLIENT_HEADER, isGbrainThinClient, resolveResultRowsMode, result
import { parseStrictParamsMode } from './validate-params.ts';
import { filterOpsForSurface, clampSurface, advertisedOps, resolveAdvertisedSurface, type McpSurface } from './surface.ts';
import { disabledOpsForPublishGates } from './publish-gates.ts';
-import { loadConfig } from '../core/config.ts';
+import { loadConfig, loadConfigWithEngine, type GBrainConfig } from '../core/config.ts';
import { buildDefaultLimiters, type RateLimiter } from './rate-limit.ts';
import { sqlQueryForEngine } from '../core/sql-query.ts';
import { degradedLastError, isEngineDegraded } from '../core/degraded-marker.ts';
@@ -220,6 +220,9 @@ export async function startHttpTransport(opts: HttpTransportOptions) {
// serve-http path re-reads dual-plane per request). Dispatch-side
// enforcement still resolves per call. mcp.advertised_surface (file plane) narrows the tool list only.
const fileConfig = loadConfig();
+ // #6589: operations see the CLI's effective config (file + env over the DB plane), read once at startup:
+ // a DB-plane change (`gbrain config set`) applies after a serve restart. A degraded engine keeps the file plane.
+ const operationConfig = isEngineDegraded(engine) ? fileConfig : await loadConfigWithEngine(engine, fileConfig ?? { engine: engine.kind } as GBrainConfig);
const strictParams = parseStrictParamsMode(fileConfig?.mcp?.strict_params) === 'reject';
const tools = buildToolDefs(advertisedOps(surfacedOps, surface, await resolveAdvertisedSurface(null, fileConfig)), { strictParams });
@@ -465,7 +468,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {
if (method === 'resources/list' || method === 'resources/read') {
const resources = createSkillResources(engine, async () => ({ remote: true, transport: 'http',
- auth: auth.auth!, sourceId: auth.sourceId ?? 'default', allowedOps: surfaceAllowedOps, surface, config: fileConfig ?? undefined }));
+ auth: auth.auth!, sourceId: auth.sourceId ?? 'default', allowedOps: surfaceAllowedOps, surface, config: operationConfig ?? undefined }));
try {
const result = method === 'resources/list'
? { resources: [{ uri: CAPABILITIES_URI, name: 'GBrain capabilities', mimeType: 'application/json' }, ...await resources.list()] }
@@ -537,6 +540,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {
const result = await dispatchToolCall(engine, toolName, args, {
remote: true,
admissionOrigin: 'interactive',
+ config: operationConfig ?? undefined,
// WP1/D7: network transport — the dispatch-layer localOnly
// backstop keys off this marker.
transport: 'http',
diff --git a/test/http-db-config.serial.test.ts b/test/http-db-config.serial.test.ts
new file mode 100644
index 0000000000..458001911c
--- /dev/null
+++ b/test/http-db-config.serial.test.ts
@@ -0,0 +1,88 @@
+/**
+ * #6589: DB-plane eval settings must reach actual HTTP operation dispatch.
+ * A file-only context loses capture opt-in and scrub opt-out. Config-loader
+ * unit tests do not exercise either transport. Real PGLite, authenticated
+ * HTTP and stored eval rows need no new production seam or provider calls.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import express from 'express';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { buildServeHttpApp } from '../src/commands/serve-http.ts';
+import { startHttpTransport } from '../src/mcp/http-transport.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { awaitPendingEvalCaptures } from '../src/core/eval-capture.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+afterAll(async () => {
+ await awaitPendingEvalCaptures();
+ await engine.disconnect();
+});
+
+for (const transport of ['oauth-app', 'bearer'] as const) {
+ describe(`${transport} operation config`, () => {
+ for (const scenario of ['db-enabled', 'file-disabled', 'db-disabled'] as const) {
+ test(scenario, async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-http-config-'));
+ mkdirSync(join(home, '.gbrain'));
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({
+ engine: 'pglite', ...(scenario === 'file-disabled' ? { eval: { capture: false } } : {}),
+ }));
+ try {
+ await withEnv({ GBRAIN_HOME: home, GBRAIN_CONTRIBUTOR_MODE: scenario === 'db-disabled' ? '1' : undefined }, async () => {
+ let close: (() => Promise<void>) | undefined;
+ try {
+ await engine.executeRaw('DELETE FROM eval_candidates');
+ await engine.setConfig('eval.capture', scenario === 'db-disabled' ? 'false' : 'true');
+ await engine.setConfig('eval.scrub_pii', 'false');
+ const { token } = await mintLegacyToken(engine, { name: 'http-config-fixture', scopes: ['read'], takesHolders: ['world'] });
+ let base: string;
+ if (transport === 'oauth-app') {
+ const app = express();
+ const server = app.listen(0, '127.0.0.1');
+ await new Promise<void>(resolve => server.once('listening', resolve));
+ const address = server.address();
+ if (!address || typeof address === 'string') throw new Error('TCP address missing');
+ base = `http://127.0.0.1:${address.port}`;
+ close = () => new Promise(resolve => { server.closeAllConnections(); server.close(() => resolve()); });
+ await buildServeHttpApp(app, engine, { port: address.port, tokenTtl: 3600, enableDcr: false, publicUrl: base });
+ } else {
+ const server = await startHttpTransport({ port: 0, engine });
+ base = `http://127.0.0.1:${server.port}`;
+ close = async () => { await server.stop(true); };
+ }
+ const query = '[email protected]';
+ const res = await fetch(`${base}/mcp`, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'search', arguments: { query } } }),
+ });
+ expect(res.status).toBe(200);
+ const text = await res.text();
+ const data = text.split('\n').find(line => line.startsWith('data:'));
+ const rpc = JSON.parse(data ? data.slice(5) : text);
+ expect(rpc.error).toBeUndefined();
+ expect(rpc.result.isError).not.toBe(true);
+ expect((await awaitPendingEvalCaptures()).unfinished).toBe(0);
+ const rows = await engine.executeRaw<{ query: string }>('SELECT query FROM eval_candidates');
+ expect(rows).toEqual(scenario === 'db-enabled' ? [{ query }] : []);
+ } finally {
+ await close?.();
+ await awaitPendingEvalCaptures();
+ }
+ });
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ }, 120_000);
+ }
+ });
+}
diff --git a/test/http-degraded-health.test.ts b/test/http-degraded-health.test.ts
index 828cf60be0..fe0f96f6e4 100644
--- a/test/http-degraded-health.test.ts
+++ b/test/http-degraded-health.test.ts
@@ -40,6 +40,8 @@ describe('/health while startup-degraded', () => {
const server = await startHttpTransport({ port: 0, engine });
stopServer = () => (server as { stop: (force?: boolean) => void }).stop(true);
+ // Startup config resolution must not consume the lazy recovery attempt.
+ expect(attempts).toBe(0);
const port = (server as { port: number }).port;
const res = await fetch(`http://127.0.0.1:${port}/health`);
diff --git a/test/serve-http-mcp-dispatch-context.serial.test.ts b/test/serve-http-mcp-dispatch-context.serial.test.ts
index 1a47317269..fd1c46c601 100644
--- a/test/serve-http-mcp-dispatch-context.serial.test.ts
+++ b/test/serve-http-mcp-dispatch-context.serial.test.ts
@@ -5,7 +5,7 @@
* Protects: the options object the HTTP transport hands to
* `dispatchToolCall`: remote: true, transport 'http', the fail-closed
* takesHoldersAllowList default, the token's sourceId, the verified
- * AuthInfo, metaHook, the per-request surface / surfaceCeiling / allowedOps,
+ * AuthInfo, effective config (#6589), metaHook, the per-request surface / surfaceCeiling / allowedOps,
* the request-level `_meta.session_id` as sessionId (CX2-11, as stdio threads
* it) and the stderr logger, with exactly today's key set.
* Fails when: the decomposed handler drops or renames a dispatch option,
@@ -46,6 +46,7 @@ beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
+ await engine.setConfig('eval.capture', 'false');
});
afterAll(async () => {
@@ -88,7 +89,7 @@ async function rpc(base: string, token: string, method: string, params?: unknown
return JSON.parse(dataLine ? dataLine.slice('data:'.length) : text).result;
}
-const FULL_SURFACE_KEYS = ['admissionOrigin', 'auth', 'isListed', 'logger', 'metaHook', 'noticeLedger', 'remote', 'resultRows', 'sourceId', 'surface', 'surfaceCeiling', 'takesHoldersAllowList', 'transport'];
+const FULL_SURFACE_KEYS = ['admissionOrigin', 'auth', 'config', 'isListed', 'logger', 'metaHook', 'noticeLedger', 'remote', 'resultRows', 'sourceId', 'surface', 'surfaceCeiling', 'takesHoldersAllowList', 'transport'];
describe('POST /mcp dispatch context', () => {
test('full surface: remote http dispatch with the verified auth and token source scope', async () => {
@@ -99,6 +100,7 @@ describe('POST /mcp dispatch context', () => {
const { opts } = calls[0];
expect(Object.keys(opts).sort()).toEqual(FULL_SURFACE_KEYS);
expect(opts.remote).toBe(true);
+ expect(opts.config?.eval?.capture).toBe(false);
// #6696 (A5): a remote MCP write is interactive, so the background pause line never refuses it.
expect(opts.admissionOrigin).toBe('interactive');
// C1: a client without the thin-client header gets the host default, lean rows.