Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(serve-http): thread the request-level _meta.session_id into dispatch, as stdio does (#6087)
time-attack032cb4d61475
diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.tsindex 9e6faee606..1fcc048e73 100644--- a/src/commands/serve-http-mcp.ts+++ b/src/commands/serve-http-mcp.ts@@ -21,7 +21,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, acceptedPendingReceipt, unknownToolEnvelope, errorResult, dispatchRenderContext, type ToolResult } from '../mcp/dispatch.ts';+import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult, requestMetaSessionId, acceptedPendingReceipt, unknownToolEnvelope, errorResult, dispatchRenderContext, 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';@@ -370,6 +370,11 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, requeslet argsDigest = 'none';try { argsDigest = createHash('sha256').update(JSON.stringify(params ?? null)).digest('hex').slice(0, 16); } catch { /* unserializable */ }process.stderr.write(`[gbrain-serve] dispatch op=${name} args_sha256=${argsDigest}\n`);+ // CX2-11 parity with stdio: the request-level `_meta.session_id` (a sibling+ // of `arguments`) becomes OperationContext.sessionId, so the hot-memory+ // metaHook and every other session consumer key per remote session. Identity+ // only, never a trust surface.+ const sessionId = requestMetaSessionId(request.params);let toolResult: Awaited<ReturnType<typeof dispatchToolCall>>;try {toolResult = await dispatchToolCall(engine, name, params as Record<string, unknown> | undefined, {@@ -377,6 +382,7 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, reques// WP1/D7: network transport — the dispatch-layer localOnly// backstop keys off this marker.transport: 'http',+ ...(sessionId ? { sessionId } : {}),takesHoldersAllowList: tokenAllowList,sourceId: tokenSourceId,...(localFederated ? { localFederatedSourceIds: localFederated } : {}),diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex f5f678ec67..375cdb12b0 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -630,6 +630,16 @@ const stderrLogger: OperationContext['logger'] = {/** CX2-11: clamp an opaque session id to 256 chars (cache-key hygiene). */const SESSION_ID_MAX_CHARS = 256;+/**+ * CX2-11: the request-level session — MCP carries `_meta.session_id` as a sibling of `arguments` in+ * `request.params`. Every transport threads it the same way, so a fact `remember`s the session over+ * HTTP exactly as over stdio. Non-string / empty values are ignored; dispatch clamps the length.+ */+export function requestMetaSessionId(requestParams: unknown): string | undefined {+ const raw = (requestParams as { _meta?: { session_id?: unknown } } | undefined)?._meta?.session_id;+ return typeof raw === 'string' && raw.length > 0 ? raw : undefined;+}+/*** Read `_meta.session_id` out of the tool arguments when present. The MCP* spec carries `_meta` as a sibling of `arguments`, but several clients (anddiff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 927049f32d..cac4aa1e6b 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -7,7 +7,7 @@ import { operations, opError, OperationError } from '../core/operations.ts';import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';import { VERSION } from '../version.ts';import { buildToolDefs } from './tool-defs.ts';-import { dispatchToolCall, buildOperationContext, dispatchRenderContext, type ToolResult } from './dispatch.ts';+import { dispatchToolCall, buildOperationContext, dispatchRenderContext, requestMetaSessionId, type ToolResult } from './dispatch.ts';import { findInvalidParam, schemaInvalidParams, parseStrictParamsMode } from './validate-params.ts';import { clampSurface, createStdioSurfaceState, sessionWidenAllowed, surfaceEnvInvalidNotice, type McpAccess, type McpSurface, type SurfaceSource } from './surface.ts';import { startOnboardingRefresher } from '../core/onboard/mcp-onboarding.ts';@@ -389,10 +389,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS// request.params. Thread it (clamped in dispatch) into the typed// OperationContext.sessionId so the hot-memory metaHook's cache keys per// session instead of collapsing every caller onto the null-session key.- const rawMetaSession = (request.params as { _meta?: { session_id?: unknown } })?._meta?.session_id;- const sessionId = typeof rawMetaSession === 'string' && rawMetaSession.length > 0- ? rawMetaSession- : undefined;+ const sessionId = requestMetaSessionId(request.params);// #4583 rework: warn (once per process) when a MUTATING call's RESOLVED// source scope actually lands in 'default' (tier seed_default) on a// bulk-non-default brain. Keyed on the already-computed resolution tier —diff --git a/test/remember-session.test.ts b/test/remember-session.test.tsindex 05e7de8696..e4aa1c4d74 100644--- a/test/remember-session.test.ts+++ b/test/remember-session.test.ts@@ -58,6 +58,20 @@ describe('remember records the MCP session', () => {expect(byTransport.facts.map((f: { fact_id: string }) => f.fact_id)).toContain(id);});+ test('an overlong transport session is clamped to 256 characters before it is stored', async () => {+ const res = await dispatchToolCall(+ engine,+ 'remember',+ { fact: 'the vault opens at nine', provenance: 'test' },+ { ...STDIO, sessionId: 's'.repeat(1000) },+ );+ expect(res.isError ?? false).toBe(false);+ const rows = await engine.executeRaw<{ source_session: string | null }>(+ `SELECT source_session FROM facts WHERE fact = 'the vault opens at nine'`,+ );+ expect(rows).toEqual([{ source_session: 's'.repeat(256) }]);+ });+test('a fact remembered with no session has none', async () => {const res = await dispatchToolCall(engine, 'remember', { fact: 'payroll runs monthly', provenance: 'test' }, { ...STDIO });const { id } = parsed(res);diff --git a/test/request-meta-session.test.ts b/test/request-meta-session.test.tsnew file mode 100644index 0000000000..695bba3b41--- /dev/null+++ b/test/request-meta-session.test.ts@@ -0,0 +1,65 @@+/**+ * CX2-11: `requestMetaSessionId` — the one reader of the request-level+ * `_meta.session_id` that both MCP transports (stdio and HTTP) thread into+ * dispatch.+ *+ * Protects: the session is read from beside `arguments` in `request.params`;+ * absent, empty and non-string values yield no session.+ * Fails when: the helper reads the wrong field or lets an empty or non-string+ * value through as a session.+ * Why new: the HTTP threading is pinned through the real transport in+ * serve-http-mcp-dispatch-context.serial.test.ts; these input edge cases are+ * not worth an HTTP round-trip each.+ */++import { afterEach, describe, expect, test } from 'bun:test';+import { requestMetaSessionId } from '../src/mcp/dispatch.ts';+import {+ HOT_MEMORY_CACHE_MAX_ENTRIES,+ __hotMemoryCacheForTests,+ __resetHotMemoryCacheForTests,+ getBrainHotMemoryMeta,+} from '../src/core/facts/meta-hook.ts';+import type { OperationContext } from '../src/core/operations.ts';++describe('requestMetaSessionId', () => {+ test('reads the session beside the arguments', () => {+ expect(requestMetaSessionId({ name: 'remember', arguments: {}, _meta: { session_id: 'sess-1' } })).toBe('sess-1');+ });++ test('absent, empty or non-string is no session', () => {+ expect(requestMetaSessionId({ name: 'remember', arguments: {} })).toBeUndefined();+ expect(requestMetaSessionId({ _meta: { session_id: '' } })).toBeUndefined();+ expect(requestMetaSessionId({ _meta: { session_id: 7 } })).toBeUndefined();+ expect(requestMetaSessionId(undefined)).toBeUndefined();+ });++ test('reads only the request level; arguments-level _meta stays the dispatch fallback', () => {+ expect(requestMetaSessionId({ name: 'remember', arguments: { _meta: { session_id: 'in-args' } } })).toBeUndefined();+ });+});++// FM17: the session id is client-controlled over both transports, and the+// hot-memory cache folds it into its key. The cache's own bound must hold when+// a remote client mints a fresh id on every call. Coverage-only: the bound+// predates request-level session threading; this pins it under remote ids.+describe('per-session hot-memory cache stays bounded under remote session ids', () => {+ afterEach(() => __resetHotMemoryCacheForTests());++ test('2000 random remote session ids leave at most HOT_MEMORY_CACHE_MAX_ENTRIES entries', async () => {+ __resetHotMemoryCacheForTests();+ const engine = {+ executeRaw: async () => [{ n: 0, at: null }],+ listFactsBySession: async () => [],+ listFactsSince: async () => [],+ };+ for (let i = 0; i < 2000; i++) {+ const sessionId = requestMetaSessionId({ name: 'search', arguments: {}, _meta: { session_id: crypto.randomUUID() } });+ expect(sessionId).toBeDefined();+ const ctx = { engine, remote: true, sourceId: 'default', sessionId } as unknown as OperationContext;+ await getBrainHotMemoryMeta('search', ctx);+ }+ expect(HOT_MEMORY_CACHE_MAX_ENTRIES).toBe(1000);+ expect(__hotMemoryCacheForTests().size).toBe(HOT_MEMORY_CACHE_MAX_ENTRIES);+ });+});diff --git a/test/serve-http-mcp-dispatch-context.serial.test.ts b/test/serve-http-mcp-dispatch-context.serial.test.tsindex 1ab661b337..c5f280281d 100644--- a/test/serve-http-mcp-dispatch-context.serial.test.ts+++ b/test/serve-http-mcp-dispatch-context.serial.test.ts@@ -5,10 +5,11 @@* 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- * and the stderr logger, with exactly today's key set.+ * AuthInfo, 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,- * passes a stale surface, or widens allowedOps.+ * passes a stale surface, widens allowedOps, or drops the request's session.* Why new: outcome tests show remote/auth/surface indirectly; nothing pinned* the literal dispatch context the handler builds.*@@ -130,6 +131,22 @@ describe('POST /mcp dispatch context', () => {expect(stderrLines.join('')).not.toContain('synthetic private phrase');});+ // CX2-11: MCP carries `_meta.session_id` beside `arguments`. Stdio threads it+ // into dispatch; over HTTP it was dropped, so a remote `remember` stored no+ // session and `recall({ session_id })` could not find the fact.+ test('the request-level _meta.session_id reaches dispatch as sessionId; without it there is none', async () => {+ const { base, token } = await start(undefined, 'session');+ calls.length = 0;+ await rpc(base, token, 'tools/call', { name: 'whoami', arguments: {}, _meta: { session_id: 'sess-http' } });+ await rpc(base, token, 'tools/call', { name: 'whoami', arguments: {} });+ expect(calls.map(c => c.name)).toEqual(['whoami', 'whoami']);+ const [withSession, withoutSession] = calls.map(c => c.opts);+ expect(withSession.sessionId).toBe('sess-http');+ expect(Object.keys(withSession).sort()).toEqual([...FULL_SURFACE_KEYS, 'sessionId'].sort());+ expect(withoutSession.sessionId).toBeUndefined();+ expect(Object.keys(withoutSession).sort()).toEqual(FULL_SURFACE_KEYS);+ });+test('starter ceiling: allowedOps is the surface-filtered remote catalog and the surface is threaded', async () => {const { base, token } = await start('starter');const listed = (await rpc(base, token, 'tools/list')).tools.map((t: { name: string }) => t.name);