Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

refactor(mcp-host): extract session route handlers to a testable factory (R1-M3)

Diego Zacarias62aaad2bd948
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 77a8287b5..8a33e7feb 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.226",
+ "version": "0.1.227",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.226",
+ "version": "0.1.227",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index 879770a09..5dba6d20e 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.226",
+ "version": "0.1.227",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts b/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts
index 1212ab3d4..67ef24f71 100644
--- a/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts
+++ b/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts
@@ -24,38 +24,10 @@ import { beforeEach, describe, expect, it } from 'vitest'
import express, { type NextFunction, type Request, type Response } from 'express'
import request from 'supertest'
import { ConversationManager } from '../../core/conversation/conversation'
-import type { Conversation } from '../../core/types'
-import { ConversationState } from '../../core/types'
-import { getDisplayName } from '../../progress/intentExtraction'
import { makeHandlers } from '../../server/__tests__/testHelpers'
import { handleSessionMessagesRoute, handleSessionsListRoute } from '../../server/routes'
-import {
- decodeSessionsCursor,
- paginateSessionSummaries,
- projectMessageWindowBounds,
-} from '../../server/wireProjections'
-
-// D.1 — mirrors main.ts `sessionStateView`: expose state/activeTaskId/pendingApproval.
-function stateView(conversation: Conversation) {
- const state =
- conversation.state === ConversationState.Processing
- ? ('processing' as const)
- : conversation.state === ConversationState.AwaitingApproval
- ? ('awaiting_approval' as const)
- : ('idle' as const)
- const pendingApproval =
- conversation.state === ConversationState.AwaitingApproval && conversation.pending_approval
- ? {
- requestId: conversation.pending_approval.request_id,
- displayName: getDisplayName(conversation.pending_approval.tool_name),
- }
- : undefined
- return {
- state,
- activeTaskId: state === 'idle' ? undefined : conversation.activeTaskId,
- pendingApproval,
- }
-}
+import { createSessionRouteHandlers } from '../../server/sessionRouteHandlers'
+import { decodeSessionsCursor, sessionsCursorScope } from '../../server/wireProjections'
function makeApp(convManager: ConversationManager) {
const app = express()
@@ -79,76 +51,17 @@ function makeApp(convManager: ConversationManager) {
next()
})
- // Closures mirror main.ts — same prefix filter, same mapping shape.
+ // Wire the REAL production handlers (createSessionRouteHandlers) over a real
+ // ConversationManager — no reimplemented pagination/mapping. `redactToolError`
+ // is a passthrough here (tool-error redaction has its own coverage and is not
+ // exercised by these transcripts).
+ const { handleSessionsList, handleSessionMessages } = createSessionRouteHandlers({
+ getConversationManager: () => convManager,
+ redactToolError: (_toolName, rawError) => rawError,
+ })
const handlers = makeHandlers({
- sessionsListHandler: (userSub: string, query) => {
- const cursor = decodeSessionsCursor(query.cursor)
- const entries = convManager
- .listSessionsForUser(`${userSub}:rpc:`)
- .map(entry => ({ ...entry, lastActivityAt: entry.conversation.updated_at }))
- .filter(
- entry =>
- !cursor ||
- entry.lastActivityAt.toISOString() < cursor.updatedAt ||
- (entry.lastActivityAt.toISOString() === cursor.updatedAt && entry.key > cursor.key)
- )
- .sort(
- (left, right) =>
- right.lastActivityAt.getTime() - left.lastActivityAt.getTime() ||
- (left.key < right.key ? -1 : left.key > right.key ? 1 : 0)
- )
- const { page, nextCursor } = paginateSessionSummaries(entries, query.limit)
- return {
- items: page.map(({ conversation, agent, chatId }) => ({
- agent,
- chatId,
- turnCount: conversation.turns.length,
- lastActivityAt: conversation.updated_at.toISOString(),
- ...stateView(conversation),
- })),
- ...(nextCursor ? { nextCursor } : {}),
- }
- },
- sessionMessagesHandler: (userSub: string, agentName: string, chatId: string, query) => {
- // Direct O(1) key lookup — mirrors the main.ts fix.
- const key = `${userSub}:rpc:${agentName}:${chatId}`
- const conversation = convManager.getSessionByKey(key)
- if (!conversation) return null
- const eligibleTurns =
- query.afterTurn !== undefined
- ? conversation.turns.filter(turn => turn.number > query.afterTurn!)
- : query.beforeTurn !== undefined
- ? conversation.turns.filter(turn => turn.number < query.beforeTurn!)
- : conversation.turns
- const turns =
- query.limit === undefined
- ? eligibleTurns
- : query.afterTurn !== undefined
- ? eligibleTurns.slice(0, query.limit)
- : eligibleTurns.slice(-query.limit)
- const windowBounds = projectMessageWindowBounds(
- turns,
- {
- firstTurnNumber: conversation.turns[0]?.number,
- lastTurnNumber: conversation.turns.at(-1)?.number,
- },
- query
- )
- return {
- agent: agentName,
- chatId,
- ...stateView(conversation),
- totalTurns: conversation.turns.length,
- ...windowBounds,
- turns: turns.map(t => ({
- number: t.number,
- user_input: t.user_input,
- response: t.response,
- started_at: t.started_at.toISOString(),
- completed_at: t.completed_at ? t.completed_at.toISOString() : undefined,
- })),
- }
- },
+ sessionsListHandler: handleSessionsList,
+ sessionMessagesHandler: handleSessionMessages,
})
app.get('/v1/runtime/sessions', async (req, res) => {
@@ -205,6 +118,9 @@ describe('Cross-device desktop sessions — integration regression guard', () =>
agent: 'agent-x',
chatId: 'chat-1',
turnCount: 1,
+ // 1 completed turn = 1 user + 1 assistant response = 2 visible messages.
+ // The real handler emits messageCount; the previous fake omitted it.
+ messageCount: 2,
})
expect(typeof listRes.body.items[0].lastActivityAt).toBe('string')
@@ -401,4 +317,38 @@ describe('Cross-device desktop sessions — integration regression guard', () =>
.expect(200)
expect(yRes.body.turns[0].user_input).toBe('y1')
})
+
+ it('paginates with a real decodable nextCursor that advances to the next page exactly once', async () => {
+ await seedConversation(convManager, 'user-A', 'agent-x', 'chat-1', 'q1', 'a1')
+ await seedConversation(convManager, 'user-A', 'agent-x', 'chat-2', 'q2', 'a2')
+
+ const firstPage = await request(app)
+ .get('/v1/runtime/sessions?limit=1')
+ .set('x-test-sub', 'user-A')
+ .expect(200)
+ expect(firstPage.body.items).toHaveLength(1)
+ expect(typeof firstPage.body.nextCursor).toBe('string')
+
+ // The token is a REAL, scope-bound cursor — decodable only with the same
+ // (user, no-agent) scope the handler encoded it under, and its stripped key
+ // is `${agent}:${chatId}` of the last item on the page.
+ const decoded = decodeSessionsCursor(
+ firstPage.body.nextCursor,
+ sessionsCursorScope('user-A', undefined)
+ )
+ expect(decoded).not.toBeNull()
+ expect(decoded!.key).toBe(`${firstPage.body.items[0].agent}:${firstPage.body.items[0].chatId}`)
+
+ const secondPage = await request(app)
+ .get(`/v1/runtime/sessions?limit=1&cursor=${encodeURIComponent(firstPage.body.nextCursor)}`)
+ .set('x-test-sub', 'user-A')
+ .expect(200)
+ expect(secondPage.body.items).toHaveLength(1)
+ // Catalog exhausted → no further cursor.
+ expect(secondPage.body.nextCursor).toBeUndefined()
+
+ // Exactly-once coverage across the two pages.
+ const seen = [firstPage.body.items[0].chatId, secondPage.body.items[0].chatId]
+ expect(new Set(seen)).toEqual(new Set(['chat-1', 'chat-2']))
+ })
})
diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.ts
index 13142d52c..8032ebbb9 100644
--- a/mcp-host/src/main.ts
+++ b/mcp-host/src/main.ts
@@ -33,10 +33,6 @@ import {
resolveSessionModel,
} from './config/modelResolution'
import { ContextMapperClient, getContextMapperClient } from './contextMapperClient'
-import type {
- ConversationSessionMessages,
- ConversationSessionSummary,
-} from './core/conversation/conversationStore'
import {
type ConversationStoreHandle,
SqliteColdStartLoader,
@@ -51,7 +47,7 @@ import { FsSpilloverResolver } from './core/spillover/fsResolver'
import { isInternalGeneratedArtifactAttachment } from './core/tools/generatedArtifactAttachments'
import { NativeToolRegistry } from './core/tools/nativeToolRegistry'
import { WorkflowResultTool } from './core/tools/workflow'
-import type { Attachment, Conversation } from './core/types'
+import type { Attachment } from './core/types'
import { ConversationState } from './core/types'
import { wireActivityEvents } from './eventWiring'
import { HostWatcher, getHost } from './k8sClient'
@@ -105,16 +101,8 @@ import {
WorkflowApprovalNotificationClaim,
WorkflowApprovalNotificationTerminal,
} from './server'
-import {
- decodeSessionsCursor,
- paginateSessionSummaries,
- projectContextBreakdown,
- projectMessageWindowBounds,
- projectSessionTokens,
- projectTurnTokens,
- projectTurnToolSteps,
- sessionsCursorScope,
-} from './server/wireProjections'
+import { createSessionRouteHandlers } from './server/sessionRouteHandlers'
+import { projectContextBreakdown } from './server/wireProjections'
import { SessionProcessor } from './session'
import { serializeSessionKey } from './session/types.js'
import { approxDecodedBytes } from './shared/encoding'
@@ -2111,39 +2099,11 @@ async function startRPCServer(): Promise<void> {
// LRU — or, under sqlite/dual, any session after a pod restart — still
// surface from SQLite. The sync RAM-only accessors would 404 persisted
// sessions, defeating the persistence feature. The route already awaits.
- // D.1 — view of session liveness shared by /sessions and /messages.
- // `state` lets the desktop paint sidebar badges; `activeTaskId` tells it
- // which task to re-subscribe to; `pendingApproval` lets it render the
- // approve button without waiting for the SSE. `displayName` is derived
- // server-side (the `tool_name` itself is NOT leaked over the wire — security
- // patch P1-1).
- const sessionStateView = (
- session: Conversation | ConversationSessionSummary | ConversationSessionMessages
- ) => {
- const state =
- session.state === ConversationState.Processing
- ? ('processing' as const)
- : session.state === ConversationState.AwaitingApproval
- ? ('awaiting_approval' as const)
- : ('idle' as const)
- const activeTaskId = state === 'idle' ? undefined : session.activeTaskId
- const approval =
- 'pendingApproval' in session
- ? session.pendingApproval
- : (session as Conversation).pending_approval
- const pendingApproval =
- session.state === ConversationState.AwaitingApproval && approval
- ? {
- requestId: approval.request_id,
- displayName: getDisplayName(approval.tool_name),
- }
- : undefined
- // Lifetime token totals — projected to the wire shape (omitted until the
- // session has had an LLM call; cache breakdown included only when the model
- // reports it). See `projectSessionTokens`.
- const tokens = projectSessionTokens(session)
- return { state, activeTaskId, pendingApproval, tokens }
- }
+ // D.1 — the shared session-liveness projection (`sessionStateView`) and the
+ // two session-read handlers now live in `createSessionRouteHandlers`
+ // (src/server/sessionRouteHandlers.ts) so they can be unit-tested against a
+ // real ConversationManager. `redactToolError` stays here (it closes over the
+ // operator secret list) and is injected into the factory below.
// #582: redact a persisted tool error before it reaches the `/messages` wire,
// mirroring the live SSE path exactly: `sanitizeOutput` scrubs secret values
@@ -2154,78 +2114,10 @@ async function startRPCServer(): Promise<void> {
const redactToolError = (toolName: string, rawError: string): string =>
sanitizeError(toolErrorSafety.sanitizeOutput(toolName, rawError).content)
- const handleSessionsList = async (
- userSub: string,
- query: { agent?: string; limit?: number; cursor?: string }
- ) => {
- const convManager = agent!.getConversationManager()
- const keyPrefix = query.agent ? `${userSub}:rpc:${query.agent}:` : `${userSub}:rpc:`
- const cursorScope = sessionsCursorScope(userSub, query.agent)
- const cursor = decodeSessionsCursor(query.cursor, cursorScope)
- const entries = await convManager.listSessionSummariesForUserAsync(keyPrefix, {
- limit: query.limit === undefined ? undefined : query.limit + 1,
- cursor: cursor
- ? { updatedAt: new Date(cursor.updatedAt), key: `${keyPrefix}${cursor.key}` }
- : undefined,
- agent: query.agent,
- })
- const { page, nextCursor } = paginateSessionSummaries(
- entries,
- query.limit,
- key => key.slice(keyPrefix.length),
- cursorScope
- )
- return {
- items: page.map(summary => ({
- agent: summary.agent,
- chatId: summary.chatId,
- turnCount: summary.turnCount,
- messageCount: summary.messageCount,
- lastActivityAt: summary.lastActivityAt.toISOString(),
- ...sessionStateView(summary),
- })),
- ...(nextCursor ? { nextCursor } : {}),
- }
- }
-
- const handleSessionMessages = async (
- userSub: string,
- agentName: string,
- chatId: string,
- query: { limit?: number; beforeTurn?: number; afterTurn?: number }
- ) => {
- const convManager = agent!.getConversationManager()
- // Direct O(1) key lookup — spec §2: `conversations.get(`${auth.sub}:rpc:${agent}:${chatId}`)`.
- const key = `${userSub}:rpc:${agentName}:${chatId}`
- const keyPrefix = `${userSub}:rpc:`
- const page = await convManager.getSessionMessagesByKeyAsync(key, keyPrefix, query)
- if (!page) return null
- const turns = page.turns
- const windowBounds = projectMessageWindowBounds(
- turns,
- {
- firstTurnNumber: page.firstTurnNumber,
- lastTurnNumber: page.lastTurnNumber,
- },
- query
- )
- return {
- agent: agentName,
- chatId,
- ...sessionStateView(page),
- totalTurns: page.totalTurns,
- ...windowBounds,
- turns: turns.map(t => ({
- number: t.number,
- user_input: t.user_input,
- response: t.response,
- started_at: t.started_at.toISOString(),
- completed_at: t.completed_at ? t.completed_at.toISOString() : undefined,
- tokens: projectTurnTokens(t),
- tool_steps: projectTurnToolSteps(t, redactToolError),
- })),
- }
- }
+ const { handleSessionsList, handleSessionMessages } = createSessionRouteHandlers({
+ getConversationManager: () => agent!.getConversationManager(),
+ redactToolError,
+ })
const handleContextBreakdown = async (userSub: string, agentName: string, chatId: string) => {
const convManager = agent!.getConversationManager()
diff --git a/mcp-host/src/server/sessionRouteHandlers.ts b/mcp-host/src/server/sessionRouteHandlers.ts
new file mode 100644
index 000000000..bc4112e6b
--- /dev/null
+++ b/mcp-host/src/server/sessionRouteHandlers.ts
@@ -0,0 +1,138 @@
+import type { ConversationManager } from '../core/conversation/conversation'
+import type {
+ ConversationSessionMessages,
+ ConversationSessionSummary,
+} from '../core/conversation/conversationStore'
+import { type Conversation, ConversationState } from '../core/types'
+import { getDisplayName } from '../progress/intentExtraction'
+import {
+ decodeSessionsCursor,
+ paginateSessionSummaries,
+ projectMessageWindowBounds,
+ projectSessionTokens,
+ projectTurnTokens,
+ projectTurnToolSteps,
+ sessionsCursorScope,
+} from './wireProjections'
+
+/**
+ * Dependencies for the session-read RPC handlers, injected so the handlers can
+ * be unit-tested against a real `ConversationManager` (see
+ * `sessionRouteHandlers.test.ts`) instead of only through the full `main.ts`
+ * wiring. `redactToolError` stays owned by `main.ts` (it closes over the
+ * operator secret list via `BasicSafety`).
+ */
+export interface SessionRouteHandlerDeps {
+ getConversationManager: () => ConversationManager
+ redactToolError: (toolName: string, rawError: string) => string
+}
+
+export function createSessionRouteHandlers(deps: SessionRouteHandlerDeps) {
+ const { getConversationManager, redactToolError } = deps
+
+ // Common projection: state + active task + pending approval + lifetime token
+ // totals, shared by the list and messages handlers (RPC token exposure
+ // patch P1-1).
+ const sessionStateView = (
+ session: Conversation | ConversationSessionSummary | ConversationSessionMessages
+ ) => {
+ const state =
+ session.state === ConversationState.Processing
+ ? ('processing' as const)
+ : session.state === ConversationState.AwaitingApproval
+ ? ('awaiting_approval' as const)
+ : ('idle' as const)
+ const activeTaskId = state === 'idle' ? undefined : session.activeTaskId
+ const approval =
+ 'pendingApproval' in session
+ ? session.pendingApproval
+ : (session as Conversation).pending_approval
+ const pendingApproval =
+ session.state === ConversationState.AwaitingApproval && approval
+ ? {
+ requestId: approval.request_id,
+ displayName: getDisplayName(approval.tool_name),
+ }
+ : undefined
+ // Lifetime token totals — projected to the wire shape (omitted until the
+ // session has had an LLM call; cache breakdown included only when the model
+ // reports it). See `projectSessionTokens`.
+ const tokens = projectSessionTokens(session)
+ return { state, activeTaskId, pendingApproval, tokens }
+ }
+
+ const handleSessionsList = async (
+ userSub: string,
+ query: { agent?: string; limit?: number; cursor?: string }
+ ) => {
+ const convManager = getConversationManager()
+ const keyPrefix = query.agent ? `${userSub}:rpc:${query.agent}:` : `${userSub}:rpc:`
+ const cursorScope = sessionsCursorScope(userSub, query.agent)
+ const cursor = decodeSessionsCursor(query.cursor, cursorScope)
+ const entries = await convManager.listSessionSummariesForUserAsync(keyPrefix, {
+ limit: query.limit === undefined ? undefined : query.limit + 1,
+ cursor: cursor
+ ? { updatedAt: new Date(cursor.updatedAt), key: `${keyPrefix}${cursor.key}` }
+ : undefined,
+ agent: query.agent,
+ })
+ const { page, nextCursor } = paginateSessionSummaries(
+ entries,
+ query.limit,
+ key => key.slice(keyPrefix.length),
+ cursorScope
+ )
+ return {
+ items: page.map(summary => ({
+ agent: summary.agent,
+ chatId: summary.chatId,
+ turnCount: summary.turnCount,
+ messageCount: summary.messageCount,
+ lastActivityAt: summary.lastActivityAt.toISOString(),
+ ...sessionStateView(summary),
+ })),
+ ...(nextCursor ? { nextCursor } : {}),
+ }
+ }
+
+ const handleSessionMessages = async (
+ userSub: string,
+ agentName: string,
+ chatId: string,
+ query: { limit?: number; beforeTurn?: number; afterTurn?: number }
+ ) => {
+ const convManager = getConversationManager()
+ // Direct O(1) key lookup — spec §2: `conversations.get(`${auth.sub}:rpc:${agent}:${chatId}`)`.
+ const key = `${userSub}:rpc:${agentName}:${chatId}`
+ const keyPrefix = `${userSub}:rpc:`
+ const page = await convManager.getSessionMessagesByKeyAsync(key, keyPrefix, query)
+ if (!page) return null
+ const turns = page.turns
+ const windowBounds = projectMessageWindowBounds(
+ turns,
+ {
+ firstTurnNumber: page.firstTurnNumber,
+ lastTurnNumber: page.lastTurnNumber,
+ },
+ query
+ )
+ return {
+ agent: agentName,
+ chatId,
+ ...sessionStateView(page),
+ totalTurns: page.totalTurns,
+ ...windowBounds,
+ turns: turns.map(t => ({
+ number: t.number,
+ user_input: t.user_input,
+ response: t.response,
+ started_at: t.started_at.toISOString(),
+ completed_at: t.completed_at ? t.completed_at.toISOString() : undefined,
+ tokens: projectTurnTokens(t),
+ tool_steps: projectTurnToolSteps(t, redactToolError),
+ })),
+ }
+ }
+
+ return { handleSessionsList, handleSessionMessages }
+}