Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(mcp): allow X-Gbrain-Agent-Label in both CORS preflights
garrytane412e119fd15
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9facf17979..ae62e9016c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,12 +12,14 @@ identifiers and attribution are available in the pre-removal Git revision## [0.60.587.0] - 2026-11-06-**An HTTP MCP caller can now say which AI made a write, and attribution reads show it.** Send `X-Gbrain-Agent-Label: Claude Code` (or `Codex`, or a job name) on a request, and every write that request makes shows `agent_label` in `gbrain attribution` / `get_write_attribution` and in `get_versions` for admin and local readers. This answers "which of my AIs wrote this?" when several share one OAuth client or token. The label is text the caller declares and gbrain does not verify. The principal is still who was authorized, and no grant, access rule or trust tier reads it. A request without the header is recorded exactly as before, so nothing changes until a caller sends it. Contributed by @JamisonMercurio (#8664).+**An HTTP MCP caller can now say which AI made a write, and attribution reads show it.** Send `X-Gbrain-Agent-Label: Claude Code` (or `Codex`, or a job name) on a request, and the writes that request makes itself show `agent_label` in `gbrain attribution` / `get_write_attribution` and in `get_versions` for admin and local readers. This answers "which of my AIs wrote this?" when several share one OAuth client or token. The label is text the caller declares and gbrain does not verify. The principal is still who was authorized, and no grant, access rule or trust tier reads it. A request without the header is recorded exactly as before, so nothing changes until a caller sends it. Contributed by @JamisonMercurio (#8664).### Itemized changes- Both HTTP transports (the OAuth `serve --http` mount and the legacy bearer transport) read the header. Admission stores it on the request's existing `authority` record as `agentLabel`, so there's no new column or migration, and repo-less brains record it too. Stdio MCP and the local CLI have no request headers and record no label.- A label is 1 to 120 printable ASCII characters after trimming. Anything else (control, bidi, zero-width or non-ASCII characters, or a longer value) is dropped, never refused.+- Jobs a labelled request queues (`submit_job` remote jobs and agent jobs) run under their own authority and record no label.+- Both transports' CORS preflight now allows the header, so a browser client on an origin in `GBRAIN_HTTP_CORS_ORIGIN` can send it without its whole MCP call being blocked.- `test/write-agent-label.test.ts` covers both transports, a repo-less brain, the parser bounds, a stored authority that is otherwise identical with and without a label, and a read-only token that is still refused. The export-surface golden gains the optional `agentLabel` and `agent_label` fields.## [0.60.586.0] - 2026-11-06diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex cd17cdcf68..1ba88af301 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -584,7 +584,9 @@ agent_label?, origin }`. Branch on `origin`:app calling for Claude Code and Codex, say). An HTTP MCP caller can name the AIon each request with the `X-Gbrain-Agent-Label` header, for example`X-Gbrain-Agent-Label: Claude Code`. Writes from that request show it as-`agent_label`. It is a label the caller declares and gbrain does not verify:+`agent_label`; jobs the request queues run under their own authority and record+no label. Browser callers on an origin in `GBRAIN_HTTP_CORS_ORIGIN` may send it,+since both transports' CORS preflight allows it. It is a label the caller declares and gbrain does not verify:the principal is still who was authorized, and no grant, access rule or trusttier reads the label. Any token may send it, and it lands only on that token'sown write requests. A value that is not 1 to 120 printable ASCII characters isdiff --git a/src/commands/serve-http-oauth.ts b/src/commands/serve-http-oauth.tsindex 7e5600f968..1de7c17673 100644--- a/src/commands/serve-http-oauth.ts+++ b/src/commands/serve-http-oauth.ts@@ -17,6 +17,7 @@ import { scopesSupportedForDiscovery } from '../core/scope.ts';import { GRANT_PROFILES } from '../core/grants/model.ts';import { publicHarnessMetadata } from '../core/harness/registry.ts';import { mcpAdministrationGuidance } from '../mcp/capabilities.ts';+import { AGENT_LABEL_HEADER } from '../core/persistence/attribution.ts';import { VERSION } from '../version.ts';import type { ServeHttpContext } from './serve-http.ts';@@ -129,7 +130,7 @@ export function mountOAuth(app: Express, ctx: ServeHttpContext): void {origin: resolveCorsOrigin(corsAllowlistOAuth),credentials: false,methods: ['GET', 'POST', 'OPTIONS'],- allowedHeaders: ['Content-Type', 'Authorization', 'Accept'],+ allowedHeaders: ['Content-Type', 'Authorization', 'Accept', AGENT_LABEL_HEADER],};app.use('/mcp', cors(corsOAuthOptions));app.use('/authorize', cors(corsOAuthOptions));diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.tsindex de76448dfb..f133cfa2d7 100644--- a/src/mcp/http-transport.ts+++ b/src/mcp/http-transport.ts@@ -279,7 +279,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {headers['Vary'] = 'Origin';if (preflight) {headers['Access-Control-Allow-Methods'] = 'POST, OPTIONS';- headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, Accept';+ headers['Access-Control-Allow-Headers'] = `Content-Type, Authorization, Accept, ${AGENT_LABEL_HEADER}`;}}return headers;diff --git a/test/write-agent-label.test.ts b/test/write-agent-label.test.tsindex 76729673ab..1c9a4e0ea1 100644--- a/test/write-agent-label.test.ts+++ b/test/write-agent-label.test.ts@@ -7,7 +7,7 @@* admission records it, on a managed-worktree brain and on a repo-less brain; an unlabelled write is unchanged; a* label is unverified text that never changes what the request may do (the stored authority is otherwise identical,* and a read-only token is still refused); a label that is not 1-120 printable ASCII characters is dropped, never- * stored or refused.+ * stored or refused; an allowlisted browser origin's CORS preflight on either transport allows the header.* Fails when: the header is dropped before admission, invented at read time, read by authorization, or a value that is* unsafe to render (controls, bidi or zero-width characters, non-ASCII bytes) reaches the record.* Seams: the mounted SDK transport and the legacy Bun transport over real sockets with real bearer tokens, and the@@ -34,6 +34,8 @@ import { claimWorktree } from '../src/core/persistence/ownership.ts';import { registerLocalWriter } from '../src/core/persistence/identity.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { AGENT_LABEL_HEADER, parseAgentLabel } from '../src/core/persistence/attribution.ts';+import { buildServeHttpApp } from '../src/commands/serve-http.ts';+import { withEnv } from './helpers/with-env.ts';const CONFIG = { engine: 'pglite', embedding_disabled: true } as const;const content = (title: string) => '---\ntype: note\ntitle: ' + title + '\n---\n\n# ' + title + '\n\nA synthetic page.\n';@@ -127,9 +129,13 @@ describe('OAuth serve --http mount, managed worktree brain', () => {}, 240_000);test('a label is never authority: the stored authority is otherwise identical and a read-only token is still refused', async () => {+ const slug = 'notes/authority-check';+ await put(engine, url, TOKEN, slug, 'Authority by Claude', 'Claude Code');+ await put(engine, url, TOKEN, slug, 'Authority by Codex', 'Codex');+ await put(engine, url, TOKEN, slug, 'Authority unlabelled');const rows = await engine.executeRaw<{ label: string | null; rest: Record<string, unknown> }>(- "SELECT authority->>'agentLabel' AS label, authority - 'agentLabel' AS rest FROM persistence_requests WHERE slug=$1 ORDER BY created_at", [SLUG]);- expect(rows.map(r => r.label)).toEqual(['Claude Code', 'Codex', null, null]);+ "SELECT authority->>'agentLabel' AS label, authority - 'agentLabel' AS rest FROM persistence_requests WHERE slug=$1 ORDER BY created_at", [slug]);+ expect(rows.map(r => r.label)).toEqual(['Claude Code', 'Codex', null]);const rest = rows.map(r => typeof r.rest === 'string' ? JSON.parse(r.rest) : r.rest);for (const other of rest.slice(1)) expect(other).toEqual(rest[0]);@@ -177,3 +183,50 @@ describe('legacy bearer transport, repo-less brain', () => {expect(after.created.agent_label).toBe('Claude Code');}, 240_000);});++describe('a browser caller on an allowlisted origin may send the header', () => {+ const ORIGIN = 'https://allowed.example';+ let engine: BrainEngine;+ let http: Server;+ let legacy: { port: number; stop: (force?: boolean) => unknown };++ beforeAll(async () => {+ const db = new PGLiteEngine();+ await db.connect({});+ await db.initSchema();+ engine = db;+ await withEnv({ GBRAIN_HTTP_CORS_ORIGIN: ORIGIN }, async () => {+ const app = express();+ http = await new Promise(resolve => { const listener = app.listen(0, '127.0.0.1', () => resolve(listener)); });+ const port = (http.address() as AddressInfo).port;+ await buildServeHttpApp(app, engine, { port, tokenTtl: 3600, enableDcr: false, publicUrl: 'http://127.0.0.1:' + port });+ legacy = await startHttpTransport({ port: 0, engine, surface: 'full', limiters: {+ ip: new RateLimiter({ limit: 10_000, windowMs: 60_000, lruCap: 100 }),+ token: new RateLimiter({ limit: 10_000, windowMs: 60_000, lruCap: 100 }),+ } }) as unknown as { port: number; stop: (force?: boolean) => unknown };+ });+ }, 120_000);++ afterAll(async () => {+ await legacy?.stop(true);+ if (http) await new Promise<void>(resolve => { http.closeAllConnections?.(); http.close(() => resolve()); });+ await engine.disconnect();+ });++ const preflight = async (port: number) => await fetch('http://127.0.0.1:' + port + '/mcp', { method: 'OPTIONS', headers: {+ Origin: ORIGIN, 'Access-Control-Request-Method': 'POST', 'Access-Control-Request-Headers': 'authorization, content-type, x-gbrain-agent-label' } });+ const allowsLabel = (response: Response) => (response.headers.get('access-control-allow-headers') ?? '').toLowerCase().split(/\s*,\s*/).includes(AGENT_LABEL_HEADER.toLowerCase());++ test('the OAuth serve --http mount allows the header in its preflight', async () => {+ const response = await preflight((http.address() as AddressInfo).port);+ expect(response.headers.get('access-control-allow-origin')).toBe(ORIGIN);+ expect(allowsLabel(response)).toBe(true);+ });++ test('the legacy bearer transport allows the header in its preflight', async () => {+ const response = await preflight(legacy.port);+ expect(response.headers.get('access-control-allow-origin')).toBe(ORIGIN);+ expect(allowsLabel(response)).toBe(true);+ });+});+