Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
serve --http applies the rate-limit and body-size settings to /mcp
garrytanf628415ad3c7
diff --git a/SECURITY.md b/SECURITY.mdindex 8cb7869e74..9a1f5208eb 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -513,6 +513,11 @@ window):On exhaustion the server returns `429 Too Many Requests` with a`Retry-After` header.+`gbrain serve --http` applies each bucket only when its env var is set+(`GBRAIN_HTTP_RATE_LIMIT_IP=30 GBRAIN_HTTP_RATE_LIMIT_TOKEN=60` gives the+defaults above); with neither set it does not rate-limit `/mcp`. The legacy+bearer transport always applies the defaults.+**Caveat for tunneled deployments (ngrok, Tailscale Funnel, CloudflareTunnel):** all requests share one egress IP, so the pre-auth IP bucketbecomes effectively shared by all clients on that tunnel. The@@ -569,8 +574,9 @@ forwarded-for headers and using the socket peer address.### Body size cap-Default 1 MiB, stream-counted (chunked transfers without-`Content-Length` are still capped). Override:+Default 4 MiB on `gbrain serve --http` and 1 MiB on the legacy bearer+transport, stream-counted (chunked transfers without `Content-Length` are+still capped). `GBRAIN_HTTP_MAX_BODY_BYTES` overrides both:```bashGBRAIN_HTTP_MAX_BODY_BYTES=2097152 gbrain serve --http # 2 MiBdiff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.mdindex ffa43382dc..f2d8e67e9f 100644--- a/docs/guides/memory-boundaries.md+++ b/docs/guides/memory-boundaries.md@@ -297,7 +297,7 @@ wrong with the page.| Markdown import and sync (`gbrain import`, `gbrain sync`, the managed sync blob read) | the page ceiling: 256 MiB on Postgres, 128 MiB on PGLite (24 MiB while segmented storage is off); above 24 MiB on a source backed by files, only from the file's own place in the checkout | — || CLI stdin (`gbrain put`, `gbrain capture --stdin`) | 24 MiB (was 5 MB) | `gbrain import` the file || MCP stdio (local agents, `gbrain serve`) | 64 MiB per JSON-RPC message (the MCP SDK default of 10 MiB is raised), so a JSON-escaped page at the ceiling fits | — |-| MCP over HTTP (`gbrain serve --http`) | 4 MiB request body (the MCP SDK default) | an [upload session](#adding-to-a-large-page), or sync or the CLI on the brain host |+| MCP over HTTP (`gbrain serve --http`) | 4 MiB request body (the MCP SDK default; `GBRAIN_HTTP_MAX_BODY_BYTES` overrides it) | an [upload session](#adding-to-a-large-page), or sync or the CLI on the brain host || Legacy HTTP transport | 1 MiB (`GBRAIN_HTTP_MAX_BODY_BYTES`) | the same || `put_pages` batch | 8 MiB per batch | send large pages one per `put_page`, or by file || Persistence journal | 64 MiB of outstanding JSON-escaped write intent per principal (was 32 MiB), 256 MiB per brain | nothing: a second large write waits for the first |diff --git a/docs/guides/remote-mcp.md b/docs/guides/remote-mcp.mdindex 13f6223618..ca18254672 100644--- a/docs/guides/remote-mcp.md+++ b/docs/guides/remote-mcp.md@@ -418,8 +418,8 @@ put_pages with one request_id per batch and wait_ms 25000."*immediately and by meaning once its embedding effect finishes.- **Request size.** HTTP carries less than the 24 MiB page ceiling:`gbrain serve --http` reads at most 4 MiB per request (the MCP SDK- default), and the simpler HTTP transport caps a request at- `GBRAIN_HTTP_MAX_BODY_BYTES`. A batch goes in smaller `put_pages` calls; a+ default) and the simpler HTTP transport 1 MiB; `GBRAIN_HTTP_MAX_BODY_BYTES`+ sets either cap. A batch goes in smaller `put_pages` calls; apage over the transport limit goes by file on the brain host (sync,`gbrain import` or `gbrain put`), never split by hand. Every limit is in[limits per entry point](memory-boundaries.md#large-page-limits).diff --git a/llms-full.txt b/llms-full.txtindex b8356e3356..cb65124674 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -431,8 +431,8 @@ put_pages with one request_id per batch and wait_ms 25000."*immediately and by meaning once its embedding effect finishes.- **Request size.** HTTP carries less than the 24 MiB page ceiling:`gbrain serve --http` reads at most 4 MiB per request (the MCP SDK- default), and the simpler HTTP transport caps a request at- `GBRAIN_HTTP_MAX_BODY_BYTES`. A batch goes in smaller `put_pages` calls; a+ default) and the simpler HTTP transport 1 MiB; `GBRAIN_HTTP_MAX_BODY_BYTES`+ sets either cap. A batch goes in smaller `put_pages` calls; apage over the transport limit goes by file on the brain host (sync,`gbrain import` or `gbrain put`), never split by hand. Every limit is in[limits per entry point](memory-boundaries.md#large-page-limits).diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.tsindex d4f0eeab7c..7d096bbaf8 100644--- a/src/commands/serve-http-mcp.ts+++ b/src/commands/serve-http-mcp.ts@@ -5,7 +5,8 @@* through the shared dispatcher, request logging and the admin SSE feed.*/import { createHash } from 'node:crypto';-import type { Express, Request, Response } from 'express';+import type { Express, NextFunction, Request, Response } from 'express';+import { buildDefaultLimiters, type RateLimiter } from '../mcp/rate-limit.ts';import { Server } from '@modelcontextprotocol/sdk/server/index.js';import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';import { DEFAULT_MAX_REQUEST_BODY_SIZE } from '@modelcontextprotocol/sdk/server/requestBody.js';@@ -143,9 +144,15 @@ export function mountMcp(app: Express, ctx: ServeHttpContext): void {// #5277: hint every scope a connector may need. Clients that request exactly// the hinted scope and never step up (claude.ai connectors) otherwise stay// read-only; grantScopes still caps each grant to the client row's scope.- app.post('/mcp', withBearerScopeHint(+ // GBRA-431: the rate limits SECURITY.md documents for /mcp, applied when the operator sets them: the IP bucket before+ // the token lookup, the token bucket after it. Unset, serve --http keeps its unlimited default.+ const limiters = buildDefaultLimiters();+ const ipLimit = rateLimitStep('GBRAIN_HTTP_RATE_LIMIT_IP', limiters.ip, req => req.ip ?? req.socket.remoteAddress ?? 'unknown', 'Too many requests');+ const tokenLimit = rateLimitStep('GBRAIN_HTTP_RATE_LIMIT_TOKEN', limiters.token,+ req => createHash('sha256').update(((req as any).auth as AuthInfo).token).digest('hex'), 'Too many requests for this token');+ app.post('/mcp', ipLimit, withBearerScopeHint(requireBearerAuth({ verifier: resourceVerifier, resourceMetadataUrl }), ['read', 'write'],- ), (req: Request, res: Response) => withEngineScope(engine, () => withRequestConfigSnapshot(engine, () => handleMcpPost(req, res))));+ ), tokenLimit, (req: Request, res: Response) => withEngineScope(engine, () => withRequestConfigSnapshot(engine, () => handleMcpPost(req, res))));// #6721: one config snapshot serves every config read of one POST /mcp (the// surface, row-shape and writeback reads below, tools/list and a read op's@@ -442,7 +449,7 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, reques// WP1/D7: network transport — the dispatch-layer localOnly// backstop keys off this marker.transport: 'http',- inboundFrameBytes: DEFAULT_MAX_REQUEST_BODY_SIZE,+ inboundFrameBytes: mcpBodyCap(),...(sessionId ? { sessionId } : {}),...(hotMemoryOffIn(request.params) ? { hotMemoryOff: true } : {}),onBehalfOf: { header: state.onBehalfOfHeader, requestMeta: (request.params as { _meta?: unknown })._meta },@@ -663,6 +670,28 @@ async function recordMcpToolResult(return toolResult;}+/** A positive integer env var, or undefined when unset or not one. */+function positiveEnvInt(name: string): number | undefined {+ const n = Number.parseInt(process.env[name] ?? '', 10);+ return Number.isFinite(n) && n > 0 ? n : undefined;+}++/** GBRA-431: the POST /mcp body cap, GBRAIN_HTTP_MAX_BODY_BYTES when the operator sets it, else the SDK's 4 MiB. Over it the SDK answers 413 before the body is read. */+function mcpBodyCap(): number {+ return positiveEnvInt('GBRAIN_HTTP_MAX_BODY_BYTES') ?? DEFAULT_MAX_REQUEST_BODY_SIZE;+}++/** One rate-limit bucket as an Express step: a no-op while `envName` is unset, else 429 with Retry-After once the key's bucket is empty. */+function rateLimitStep(envName: string, limiter: RateLimiter, key: (req: Request) => string, message: string) {+ const enabled = positiveEnvInt(envName) !== undefined;+ return (req: Request, res: Response, next: NextFunction) => {+ if (!enabled) return next();+ const check = limiter.check(key(req));+ if (check.allowed) return next();+ res.set('Retry-After', String(check.retryAfter ?? 60)).status(429).json({ error: 'rate_limited', message });+ };+}+async function serveMcpRequest(server: Server, req: Request, res: Response): Promise<void> {// F14: wrap transport setup + handleRequest in try/catch. Without this,// an SDK-level throw (e.g., schema parse failure on a malformed request)@@ -671,7 +700,7 @@ async function serveMcpRequest(server: Server, req: Request, res: Response): Pro// !res.headersSent we emit a minimal JSON 500 so the client at least// gets parseable JSON back.try {- const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined as any });+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined as any, maxRequestBodySize: mcpBodyCap() });// #2844: per-request teardown (SDK stateless pattern) — without it every POST /mcp leaks the transport+Server pair (~3GB/day RSS). Registered BEFORE connect/handleRequest so early disconnects and handleRequest throws still clean up; best-effort catches so cleanup never surfaces an unhandledRejection.res.on('close', () => { transport.close().catch(() => {}); server.close().catch(() => {}); });await server.connect(transport);diff --git a/test/fixtures/goldens/serve-http/routes-runtime.json b/test/fixtures/goldens/serve-http/routes-runtime.jsonindex dabcb5f177..a36dbe8d72 100644--- a/test/fixtures/goldens/serve-http/routes-runtime.json+++ b/test/fixtures/goldens/serve-http/routes-runtime.json@@ -657,6 +657,8 @@},{"handlers": [+ "<anonymous>",+ "<anonymous>","<anonymous>","<anonymous>"],@@ -1381,6 +1383,8 @@},{"handlers": [+ "<anonymous>",+ "<anonymous>","<anonymous>","<anonymous>"],diff --git a/test/fixtures/goldens/serve-http/routes.json b/test/fixtures/goldens/serve-http/routes.jsonindex ce46c0055d..0d5138ca69 100644--- a/test/fixtures/goldens/serve-http/routes.json+++ b/test/fixtures/goldens/serve-http/routes.json@@ -523,7 +523,9 @@},{"handlers": [+ "ipLimit","withBearerScopeHint(requireBearerAuth({ verifier : resourceVerifier , resourceMetadataUrl }), [ 'read' , 'write' ])",+ "tokenLimit","<inline>"],"method": "post",diff --git a/test/serve-http-mcp-limits.test.ts b/test/serve-http-mcp-limits.test.tsnew file mode 100644index 0000000000..0b2d7e4300--- /dev/null+++ b/test/serve-http-mcp-limits.test.ts@@ -0,0 +1,84 @@+/**+ * GBRA-431: the /mcp rate limits and body cap SECURITY.md documents are enforced by `gbrain serve --http`.+ *+ * 1. Protects: with GBRAIN_HTTP_RATE_LIMIT_IP set, POST /mcp answers 429 with Retry-After once an address spends its+ * bucket, before any token lookup; with GBRAIN_HTTP_RATE_LIMIT_TOKEN set, an authenticated token is throttled the+ * same way; GBRAIN_HTTP_MAX_BODY_BYTES caps the request body (413). With none set the server keeps its unlimited+ * rate and 4 MiB body default.+ * 2. Fails when: a set limit is ignored (the settings only reached the legacy transport, which no command starts), or+ * an unset one starts throttling.+ * 3. Existing coverage: test/rate-limit.test.ts pins the limiter itself; the legacy transport's tests pin its use there.+ * 4. Real seams: the production serve-http app on a loopback port over a repo-less PGLite brain, real fetch.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { legacyToken, rpc, startServeHttp } from './helpers/live-mcp-servers.ts';+import { withEnv } from './helpers/with-env.ts';++const UNSET = { GBRAIN_HTTP_RATE_LIMIT_IP: undefined, GBRAIN_HTTP_RATE_LIMIT_TOKEN: undefined, GBRAIN_HTTP_MAX_BODY_BYTES: undefined };++describe('serve --http enforces the /mcp limits the operator sets', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); }, 120_000);+ afterAll(async () => { await engine.disconnect(); }, 60_000);++ const post = (base: string, body: string, token?: string) => fetch(`${base}/mcp`, {+ method: 'POST', body,+ headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', ...(token ? { Authorization: `Bearer ${token}` } : {}) },+ });+ const listTools = JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' });++ test('GBRAIN_HTTP_RATE_LIMIT_IP throttles an address before the token lookup', async () => {+ await withEnv({ ...UNSET, GBRAIN_HTTP_RATE_LIMIT_IP: '5' }, async () => {+ const app = await startServeHttp(engine);+ try {+ const statuses: number[] = [];+ for (let i = 0; i < 8; i++) statuses.push((await post(app.base, listTools)).status);+ expect(statuses).toEqual([401, 401, 401, 401, 401, 429, 429, 429]);+ const limited = await post(app.base, listTools);+ expect({ status: limited.status, retryAfter: Number(limited.headers.get('retry-after')) > 0, body: await limited.json() })+ .toEqual({ status: 429, retryAfter: true, body: { error: 'rate_limited', message: 'Too many requests' } });+ } finally { await app.close(); }+ });+ }, 120_000);++ test('GBRAIN_HTTP_RATE_LIMIT_TOKEN throttles one token and leaves another alone', async () => {+ await withEnv({ ...UNSET, GBRAIN_HTTP_RATE_LIMIT_TOKEN: '5' }, async () => {+ const app = await startServeHttp(engine);+ try {+ const [busy, quiet] = [await legacyToken(engine, ['read']), await legacyToken(engine, ['read'])];+ const statuses: number[] = [];+ for (let i = 0; i < 7; i++) statuses.push((await rpc(app.base, busy, 'tools/list')).status);+ expect(statuses).toEqual([200, 200, 200, 200, 200, 429, 429]);+ expect((await rpc(app.base, quiet, 'tools/list')).status).toBe(200);+ } finally { await app.close(); }+ });+ }, 120_000);++ test('GBRAIN_HTTP_MAX_BODY_BYTES caps the request body', async () => {+ await withEnv({ ...UNSET, GBRAIN_HTTP_MAX_BODY_BYTES: String(1024 * 1024) }, async () => {+ const app = await startServeHttp(engine);+ try {+ const token = await legacyToken(engine, ['read']);+ const big = JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'search', arguments: { query: 'x'.repeat(1536 * 1024) } } });+ expect((await post(app.base, big, token)).status).toBe(413);+ expect((await rpc(app.base, token, 'tools/list')).status).toBe(200);+ } finally { await app.close(); }+ });+ }, 120_000);++ test('with no limit set, serve --http keeps its unlimited rate and 4 MiB body default', async () => {+ await withEnv(UNSET, async () => {+ const app = await startServeHttp(engine);+ try {+ const token = await legacyToken(engine, ['read']);+ const statuses = new Set<number>();+ for (let i = 0; i < 70; i++) statuses.add((await rpc(app.base, token, 'tools/list')).status);+ for (let i = 0; i < 40; i++) statuses.add((await post(app.base, listTools)).status);+ expect([...statuses].sort()).toEqual([200, 401]);+ const mid = JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'search', arguments: { query: 'x'.repeat(1536 * 1024) } } });+ expect((await post(app.base, mid, token)).status).not.toBe(413);+ } finally { await app.close(); }+ });+ }, 180_000);+});diff --git a/test/serve-http-route-runtime-golden.test.ts b/test/serve-http-route-runtime-golden.test.tsindex 22d8f1292c..93cd1461bd 100644--- a/test/serve-http-route-runtime-golden.test.ts+++ b/test/serve-http-route-runtime-golden.test.ts@@ -163,7 +163,7 @@ const AST_TO_RUNTIME: Array<[RegExp, string]> = [[/^requireAdmin$/, 'requireAdmin'],[/^(ccRateLimiter|adminLimits\.(total|failures|consent)|ingestRateLimiter|githubWebhookLimiter)$/, 'rateLimit'],[/^authRouter$/, 'router'],- [/^(<inline>|mountOAuthCorsGate\(.*|metricsTrackingMiddleware\(.*|withBearerScopeHint\(.*|requireBearerAuth\(.*)$/, '<anonymous>'],+ [/^(<inline>|ipLimit|tokenLimit|mountOAuthCorsGate\(.*|metricsTrackingMiddleware\(.*|withBearerScopeHint\(.*|requireBearerAuth\(.*)$/, '<anonymous>'],];function runtimeBase(astIdentity: string): string {