Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(mcp-host): u5 reactive connect_required detection + durable suspension
Diego Zacariasb4582c912490
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 365674759..1b2cdbea5 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.232",+ "version": "0.1.233","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.232",+ "version": "0.1.233","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 92d6ef984..ec5770fb2 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.232",+ "version": "0.1.233","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/agent/__tests__/taskExecutor.test.ts b/mcp-host/src/agent/__tests__/taskExecutor.test.tsindex 9c9ed0d3f..a9d2ca72e 100644--- a/mcp-host/src/agent/__tests__/taskExecutor.test.ts+++ b/mcp-host/src/agent/__tests__/taskExecutor.test.ts@@ -863,6 +863,79 @@ describe('TaskExecutor', () => {expect(deps.onComplete).toHaveBeenCalledTimes(1)})+ it('U5: a 401 on resume re-suspends as connect_required, then re-executes on connect (no double approval)', async () => {+ vi.mocked(runToolUseLoop)+ // Round A — the LLM calls an oauth MCP tool → approval_required.+ .mockResolvedValueOnce({+ type: 'need_approval',+ approval: {+ request_id: 'req-approve',+ tool_name: 'monday__list_boards',+ parameters: { limit: 5 },+ description: 'MCP tool',+ tool_call_id: 'tc_1',+ context_snapshot: [+ { role: 'user', content: 'list boards' },+ {+ role: 'assistant',+ content: '',+ tool_calls: [{ id: 'tc_1', name: 'monday__list_boards', arguments: { limit: 5 } }],+ },+ ],+ },+ } as any)+ // Round C — after connect, the re-executed tool feeds the loop, which responds.+ .mockResolvedValueOnce({ type: 'response', content: 'Boards: A, B' } as any)++ vi.mocked(executeSingleTool)+ // First resume (user approved) → the live tool call 401s on the oauth server.+ .mockResolvedValueOnce({+ tool_call_id: 'tc_1',+ name: 'monday__list_boards',+ content: 'MCP server monday auth failed (401)',+ is_error: true,+ metadata: { connect_required: { mcpServerName: 'monday', provider: 'monday' } },+ })+ // Second resume (user connected) → the SAME tool now succeeds.+ .mockResolvedValueOnce({+ tool_call_id: 'tc_1',+ name: 'monday__list_boards',+ content: 'ok',+ is_error: false,+ })++ const deps = createDeps()+ const task = createTask('list boards')+ const executor = new TaskExecutor(task, deps)++ await executor.run()+ expect(executor.executorState).toBe('waiting_approval')++ // Round B — approve. The tool executes and 401s → durable re-suspension as+ // connect_required. The auth error is NOT fed back to the LLM.+ await executor.resumeAfterApproval(false)+ expect(executor.executorState).toBe('waiting_approval')+ const connectCall = vi.mocked(deps.onApprovalNeeded).mock.calls.at(-1)+ expect(connectCall?.[2]).toMatchObject({+ reason: 'connect_required',+ mcpServerName: 'monday',+ provider: 'monday',+ tool_name: 'monday__list_boards',+ tool_call_id: 'tc_1',+ })+ // No 2nd loop yet — round B suspended instead of continuing.+ expect(runToolUseLoop).toHaveBeenCalledTimes(1)+ expect(executeSingleTool).toHaveBeenCalledTimes(1)++ // Round C — connect. The SAME tool re-executes directly (no fresh approval+ // gate — resumeAfterApproval bypasses beforeTool), then the loop completes.+ await executor.resumeAfterApproval(false)+ expect(executeSingleTool).toHaveBeenCalledTimes(2)+ expect(runToolUseLoop).toHaveBeenCalledTimes(2)+ expect(executor.executorState).toBe('completed')+ expect(deps.onComplete).toHaveBeenCalledTimes(1)+ })+it.each(['openai', 'claude', 'zai', 'bailian'] as const)('injects text+image contentParts for %s provider',async providerType => {diff --git a/mcp-host/src/agent/taskExecutor.ts b/mcp-host/src/agent/taskExecutor.tsindex b959eaf83..2a29be921 100644--- a/mcp-host/src/agent/taskExecutor.ts+++ b/mcp-host/src/agent/taskExecutor.ts@@ -17,7 +17,11 @@ import { LlmError, LlmErrorCode } from '../core/errors'import { ApprovalController } from '../core/extensions/approvalController'import type { ApprovalConfig } from '../core/extensions/approvalTypes'import { PressureContextManager } from '../core/extensions/contextManager'-import { UnifiedApprovalGateController } from '../core/extensions/mcpApprovalGateController'+import {+ UnifiedApprovalGateController,+ buildConnectRequiredApproval,+ extractConnectRequiredMarker,+} from '../core/extensions/mcpApprovalGateController'import type { AgentEventEmitter, LlmPort, LoopController, ToolRegistry } from '../core/interfaces'import { DeferrableToolController } from '../core/orchestration/deferrableToolController'import type { SimpleEventEmitter } from '../core/orchestration/eventEmitter'@@ -591,6 +595,39 @@ export class TaskExecutor {})}+ // U5 — the re-executed tool surfaced a 401 on an oauth mcp-server. Suspend+ // durably for reactive OAuth consent INSTEAD of feeding the auth error to+ // the LLM. The connect suspension inherits the SAME tool coordinates+ // (via `suspendedCall`) + the frozen `context_snapshot`/`completed_results`+ // so the NEXT resume (after the user connects) re-executes the SAME tool.+ // The failed connect `toolResult` is intentionally dropped — it never+ // enters the reconstructed message history. No machine loop: each resume is+ // human-gated (approve/connect), and the client already exhausted its+ // single 401 refresh-retry before throwing (McpAuthError).+ const connectMarker = extractConnectRequiredMarker(toolResult.metadata)+ if (connectMarker) {+ const connectApproval = buildConnectRequiredApproval(suspendedCall, connectMarker)+ connectApproval.context_snapshot = approval.context_snapshot+ connectApproval.completed_results = approval.completed_results+ connectApproval.intent_summary = approval.intent_summary+ connectApproval.attachments = approval.attachments+ connectApproval.traceContext = approval.traceContext ?? this.task.traceContext ?? null+ await this.handleLoopResult({ type: 'need_approval', approval: connectApproval })+ if (+ (this.state as ExecutorState) !== 'waiting_approval' &&+ !this.abortController.signal.aborted+ ) {+ this.state = 'completed'+ this.turnTiming?.emit(this.taskId)+ this.deps.onComplete(this.task)+ this.resolveCompletion?.()+ } else if (this.abortController.signal.aborted) {+ console.log(`[TaskExecutor:${this.taskId}] Cancelled`)+ this.resolveCompletion?.()+ }+ return+ }+// Reconstruct messages using the resolved completed_results.// `resolvedCompletedResults` is `approval.completed_results` with any// spillover refs swapped in for their blob bodies (invariant #2).@@ -918,9 +955,17 @@ export class TaskExecutor {}const reporter = progressReporterRegistry.get(this.taskId)if (reporter) {+ // U5 — carry the reason (+ mcpServerName/provider for connect_required)+ // so the desktop distinguishes an OAuth-consent suspension from the+ // default HITL gate. Absent reason → 'approval_required' (back-compat).reporter.emitSuspended(getDisplayName(result.approval.tool_name),- result.approval.request_id+ result.approval.request_id,+ {+ reason: result.approval.reason ?? 'approval_required',+ mcpServerName: result.approval.mcpServerName,+ provider: result.approval.provider,+ })}this.state = 'waiting_approval'diff --git a/mcp-host/src/core/adapters/__tests__/toolRegistryAdapter.test.ts b/mcp-host/src/core/adapters/__tests__/toolRegistryAdapter.test.tsindex 31541097b..7a2131149 100644--- a/mcp-host/src/core/adapters/__tests__/toolRegistryAdapter.test.ts+++ b/mcp-host/src/core/adapters/__tests__/toolRegistryAdapter.test.ts@@ -134,6 +134,62 @@ describe('McpToolRegistryAdapter', () => {})})+ it('maps the connect_required marker to metadata.connect_required on the success path (U5)', async () => {+ const mockManager = {+ getAllTools: () => [+ {+ name: 'monday-server__list_boards',+ description: 'List boards',+ inputSchema: { type: 'object' },+ serverName: 'monday-server',+ },+ ],+ // manager.callTool returns the TYPED marker (never a flattened opaque error)+ // when a live 401 hit an oauth server.+ callTool: vi.fn(async () => ({+ toolName: 'monday-server__list_boards',+ result: { error: 'MCP server monday-server auth failed (401)' },+ isError: true,+ connectRequired: { mcpServerName: 'monday-server', provider: 'monday' },+ })),+ } as any++ const registry = new McpToolRegistryAdapter(mockManager)+ const tool = registry.get('monday-server__list_boards')+ expect(tool).not.toBeNull()++ const output = await tool!.execute({})+ // The consumer observes the typed metadata marker, not an opaque error.+ expect(output.metadata).toEqual({+ connect_required: { mcpServerName: 'monday-server', provider: 'monday' },+ })+ expect(output.is_error).toBe(true)+ })++ it('does not attach connect_required metadata for a plain (non-oauth) error result', async () => {+ const mockManager = {+ getAllTools: () => [+ {+ name: 'airtable-server__list',+ description: 'List',+ inputSchema: { type: 'object' },+ serverName: 'airtable-server',+ },+ ],+ callTool: vi.fn(async () => ({+ toolName: 'airtable-server__list',+ result: { error: 'boom' },+ isError: true,+ // no connectRequired marker+ })),+ } as any++ const registry = new McpToolRegistryAdapter(mockManager)+ const tool = registry.get('airtable-server__list')+ const output = await tool!.execute({})+ expect(output.metadata).toBeUndefined()+ })+it('uses a text summary when MCP content contains only images', async () => {const mockManager = {getAllTools: () => [diff --git a/mcp-host/src/core/adapters/toolRegistryAdapter.ts b/mcp-host/src/core/adapters/toolRegistryAdapter.tsindex 597cb675a..ed846c185 100644--- a/mcp-host/src/core/adapters/toolRegistryAdapter.ts+++ b/mcp-host/src/core/adapters/toolRegistryAdapter.ts@@ -127,6 +127,18 @@ class McpToolAdapter implements Tool {duration_ms: Date.now() - startTime,is_error: result.isError,attachments: attachments.length > 0 ? attachments : undefined,+ // U5 — map the typed reactive-consent marker to `metadata.connect_required`+ // on the SUCCESS path (the manager never lets the McpAuthError throw reach+ // the catch below — that route would be dead code). The tool-use loop and+ // resume path read this to raise a durable `connect_required` suspension.+ metadata: result.connectRequired+ ? {+ connect_required: {+ mcpServerName: result.connectRequired.mcpServerName,+ provider: result.connectRequired.provider,+ },+ }+ : undefined,}} catch (err) {return {diff --git a/mcp-host/src/core/conversation/persistence/__tests__/reconstructConnectRequired.test.ts b/mcp-host/src/core/conversation/persistence/__tests__/reconstructConnectRequired.test.tsnew file mode 100644index 000000000..c316a59ca--- /dev/null+++ b/mcp-host/src/core/conversation/persistence/__tests__/reconstructConnectRequired.test.ts@@ -0,0 +1,101 @@+/**+ * U5 — durable round-trip of a `connect_required` suspension.+ *+ * A reactive OAuth-consent suspension must survive a cold restart WITHOUT+ * degrading into a generic approval. This drives a REAL in-memory SQLite DB+ * through every migration (incl. 013), inserts a connect_required row via the+ * real prepared statement, reads it back via the real select, and reconstructs+ * the PendingApproval — asserting reason/mcpServerName/provider are preserved.+ *+ * The row shape is `PendingApprovalRow`, the exact interface `persistSuspend`+ * fills (T1: no ad-hoc fixture standing in for another layer — the DB schema and+ * statements under test are the real ones).+ */+import { describe, expect, it } from 'vitest'+import Database from 'better-sqlite3'+import { migrations } from '../../../../db/migrations'+import { prepareStatements } from '../../../../db/statements'+import type { PendingApprovalRow } from '../../../../db/worker/protocol'+import { reconstructPendingApproval } from '../reconstruct'++function freshDb(): Database.Database {+ const db = new Database(':memory:')+ for (const migration of migrations) migration.up(db)+ return db+}++function connectRow(): PendingApprovalRow {+ return {+ request_id: 'req-connect-1',+ session_id: 'session-1',+ task_id: 'task-1',+ tool_name: 'monday__list_boards',+ tool_call_id: 'call-1',+ parameters: '{}',+ description: 'Connect monday to continue',+ context_snapshot: '[]',+ completed_results: null,+ intent_summary: 'Using monday...',+ source_message: null,+ registered_at: 0,+ expires_at: 9999999999,+ trace_context: null,+ reason: 'connect_required',+ mcp_server_name: 'monday',+ provider: 'monday',+ }+}++describe('U5 — connect_required durable round-trip', () => {+ it('preserves reason/mcpServerName/provider through insert → select → reconstruct', () => {+ const db = freshDb()+ const s = prepareStatements(db)++ db.prepare(+ `INSERT INTO sessions (id, session_key, source, started_at, state, active_task_id)+ VALUES (?, ?, 'rpc', 0, 'awaiting_approval', ?)`+ ).run('session-1', 'user:rpc:agent:chat', 'task-1')++ s.insertPendingApproval.run(connectRow())++ const row = s.selectPendingApprovalBySession.get('session-1') as PendingApprovalRow+ const approval = reconstructPendingApproval(row)++ // Observable: the rehydrated suspension is a connect_required, not a generic+ // approval, and it still names the oauth server + provider.+ expect(approval.reason).toBe('connect_required')+ expect(approval.mcpServerName).toBe('monday')+ expect(approval.provider).toBe('monday')+ expect(approval.tool_name).toBe('monday__list_boards')+ db.close()+ })++ it('a legacy/approval row rehydrates as a generic approval (reason undefined)', () => {+ const db = freshDb()+ const s = prepareStatements(db)++ db.prepare(+ `INSERT INTO sessions (id, session_key, source, started_at, state, active_task_id)+ VALUES (?, ?, 'rpc', 0, 'awaiting_approval', ?)`+ ).run('session-2', 'user:rpc:agent:chat', 'task-2')++ const legacy: PendingApprovalRow = {+ ...connectRow(),+ request_id: 'req-approval-1',+ session_id: 'session-2',+ task_id: 'task-2',+ reason: null,+ mcp_server_name: null,+ provider: null,+ }+ s.insertPendingApproval.run(legacy)++ const row = s.selectPendingApprovalBySession.get('session-2') as PendingApprovalRow+ const approval = reconstructPendingApproval(row)++ expect(approval.reason).toBeUndefined()+ expect(approval.mcpServerName).toBeUndefined()+ expect(approval.provider).toBeUndefined()+ db.close()+ })+})diff --git a/mcp-host/src/core/conversation/persistence/reconstruct.ts b/mcp-host/src/core/conversation/persistence/reconstruct.tsindex e04e54064..f84b5194a 100644--- a/mcp-host/src/core/conversation/persistence/reconstruct.ts+++ b/mcp-host/src/core/conversation/persistence/reconstruct.ts@@ -131,6 +131,12 @@ export function reconstructPendingApproval(row: PendingApprovalRow): PendingApprcompleted_results: deserializeCompletedResults(row.completed_results),intent_summary: row.intent_summary ?? undefined,traceContext: parseTraceContext(row.trace_context),+ // U5 — rehydrate the connect_required discriminator so a cold restart does+ // NOT degrade a reactive-consent suspension into a generic approval. Only the+ // two known reasons survive; any other/legacy value reads as the default gate.+ reason: row.reason === 'connect_required' ? 'connect_required' : undefined,+ mcpServerName: row.mcp_server_name ?? undefined,+ provider: row.provider ?? undefined,}}diff --git a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.tsindex bbb6d8cbb..0eba43fc7 100644--- a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts+++ b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts@@ -1005,6 +1005,12 @@ export class SqliteConversationStore implements ConversationStore {expires_at:(now + (this.opts.pendingApprovalTtlMs ?? DEFAULT_PENDING_APPROVAL_TTL_MS)) / 1000,trace_context: approval.traceContext ? JSON.stringify(approval.traceContext) : null,+ // U5 — durable connect_required discriminator + oauth server/provider, so a+ // cold restart rehydrates the reactive-consent suspension (never a generic+ // approval). NULL for the default HITL gate.+ reason: approval.reason ?? null,+ mcp_server_name: approval.mcpServerName ?? null,+ provider: approval.provider ?? null,}await this.persistQueue.enqueueSync({ kind: 'insert_pending_approval', payload: row },diff --git a/mcp-host/src/core/extensions/__tests__/connectRequiredApproval.test.ts b/mcp-host/src/core/extensions/__tests__/connectRequiredApproval.test.tsnew file mode 100644index 000000000..fc59ef5f1--- /dev/null+++ b/mcp-host/src/core/extensions/__tests__/connectRequiredApproval.test.ts@@ -0,0 +1,51 @@+/**+ * U5 — connect_required marker extraction + suspension builder.+ */+import { describe, expect, it } from 'vitest'+import {+ buildConnectRequiredApproval,+ extractConnectRequiredMarker,+} from '../mcpApprovalGateController'++describe('extractConnectRequiredMarker', () => {+ it('reads a well-formed marker', () => {+ expect(+ extractConnectRequiredMarker({+ connect_required: { mcpServerName: 'monday', provider: 'monday' },+ })+ ).toEqual({ mcpServerName: 'monday', provider: 'monday' })+ })++ it('provider is optional', () => {+ expect(+ extractConnectRequiredMarker({ connect_required: { mcpServerName: 'clickup' } })+ ).toEqual({ mcpServerName: 'clickup', provider: undefined })+ })++ it('returns null for absent/malformed markers (no server → no suspension)', () => {+ expect(extractConnectRequiredMarker(undefined)).toBeNull()+ expect(extractConnectRequiredMarker({})).toBeNull()+ expect(extractConnectRequiredMarker({ connect_required: null })).toBeNull()+ expect(extractConnectRequiredMarker({ connect_required: {} })).toBeNull()+ expect(extractConnectRequiredMarker({ connect_required: { provider: 'monday' } })).toBeNull()+ expect(extractConnectRequiredMarker({ connect_required: [] })).toBeNull()+ })+})++describe('buildConnectRequiredApproval', () => {+ it('builds a connect_required PendingApproval carrying the tool coordinates', () => {+ const approval = buildConnectRequiredApproval(+ { id: 'call-1', name: 'monday__list_boards', arguments: { limit: 5 } },+ { mcpServerName: 'monday', provider: 'monday' }+ )+ expect(approval.reason).toBe('connect_required')+ expect(approval.mcpServerName).toBe('monday')+ expect(approval.provider).toBe('monday')+ expect(approval.tool_name).toBe('monday__list_boards')+ expect(approval.tool_call_id).toBe('call-1')+ expect(approval.parameters).toEqual({ limit: 5 })+ expect(approval.tool_kind).toBe('mcp_server_tool')+ expect(approval.tool_source_ref).toBe('monday')+ expect(typeof approval.request_id).toBe('string')+ })+})diff --git a/mcp-host/src/core/extensions/mcpApprovalGateController.ts b/mcp-host/src/core/extensions/mcpApprovalGateController.tsindex 9c24b6afc..f5e65e0f4 100644--- a/mcp-host/src/core/extensions/mcpApprovalGateController.ts+++ b/mcp-host/src/core/extensions/mcpApprovalGateController.ts@@ -40,6 +40,62 @@ export function getMcpServerPrefix(toolName: string): string | null {return idx >= 0 ? toolName.substring(0, idx) : null}+// ─── U5 · Reactive OAuth-consent suspension ──────────────────────────────────++/** Typed `connect_required` marker carried on a tool result's metadata. */+export interface ConnectRequiredMarker {+ mcpServerName: string+ provider?: string+}++/**+ * Read the typed `connect_required` marker off a tool result's `metadata`+ * (set by `toolRegistryAdapter` when `manager.callTool` surfaced a 401 on an+ * oauth mcp-server). Returns null for any other result — a plain error, a 403+ * (terminal, never marked), or a non-oauth tool. Defensive against a malformed+ * marker (missing mcpServerName → null) so a suspension is never raised without+ * a server to connect.+ */+export function extractConnectRequiredMarker(+ metadata: Record<string, unknown> | undefined+): ConnectRequiredMarker | null {+ const raw = metadata?.connect_required+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null+ const marker = raw as Record<string, unknown>+ const mcpServerName = typeof marker.mcpServerName === 'string' ? marker.mcpServerName : undefined+ if (!mcpServerName) return null+ const provider = typeof marker.provider === 'string' ? marker.provider : undefined+ return { mcpServerName, provider }+}++/**+ * Build a durable `connect_required` suspension for a tool call whose live+ * execution surfaced a 401 on an oauth mcp-server (spec §U5). Reuses the SAME+ * `PendingApproval` machinery as the HITL gate; `reason='connect_required'` ++ * `mcpServerName`/`provider` steer the desktop connect UI and are persisted so a+ * cold restart never degrades this into a generic approval. The caller fills in+ * `context_snapshot`/`completed_results`/`intent_summary` so the resume path+ * re-executes the SAME tool once the user connects.+ */+export function buildConnectRequiredApproval(+ call: { id: string; name: string; arguments: Record<string, unknown> },+ marker: ConnectRequiredMarker+): PendingApproval {+ return {+ request_id: randomUUID(),+ tool_name: call.name,+ tool_kind: 'mcp_server_tool',+ tool_source_ref: getMcpServerPrefix(call.name),+ parameters: call.arguments,+ description: `Connect ${marker.mcpServerName} to continue`,+ tool_call_id: call.id,+ context_snapshot: [],+ reason: 'connect_required',+ mcpServerName: marker.mcpServerName,+ provider: marker.provider,+ }+}+/*** Cron×stateless approval prompt (product decision): creating or enabling a* schedule on a stateless host keeps the pod running indefinitely (an activediff --git a/mcp-host/src/core/orchestration/__tests__/toolCallBridge.test.ts b/mcp-host/src/core/orchestration/__tests__/toolCallBridge.test.tsindex 3b31ea632..7a190acb5 100644--- a/mcp-host/src/core/orchestration/__tests__/toolCallBridge.test.ts+++ b/mcp-host/src/core/orchestration/__tests__/toolCallBridge.test.ts@@ -68,6 +68,7 @@ interface BuildConfigOpts {// Validation hook to exercise inner-arg validation against the real schema.beforeExecution?: (name: string, params: Record<string, unknown>) => booleaninvalidNames?: Set<string>+ progressReporter?: LoopConfig['progressReporter']}function makeConfig(opts: BuildConfigOpts): LoopConfig {@@ -99,9 +100,28 @@ function makeConfig(opts: BuildConfigOpts): LoopConfig {toolTimeout: 5000,toolProgressInterval: 0,bridge: opts.bridge,+ progressReporter: opts.progressReporter,}}+/** Records the ordered stream of tool-card lifecycle events (start/complete). */+function recordingReporter(): {+ reporter: LoopConfig['progressReporter']+ events: Array<{ kind: 'start' | 'complete'; toolCallId: string; isError?: boolean }>+} {+ const events: Array<{ kind: 'start' | 'complete'; toolCallId: string; isError?: boolean }> = []+ const reporter = {+ reportToolStart: (e: { toolCallId: string }) =>+ events.push({ kind: 'start', toolCallId: e.toolCallId }),+ reportToolComplete: (e: { toolCallId: string; isError: boolean }) =>+ events.push({ kind: 'complete', toolCallId: e.toolCallId, isError: e.isError }),+ reportToolProgress: () => {},+ reportThinking: () => {},+ reportLlmInProgress: () => {},+ } as unknown as LoopConfig['progressReporter']+ return { reporter, events }+}+function bridgeContext(nativeNames: string[], deferrable: string[]): LoopConfig['bridge'] {return {nativeNames: new Set(nativeNames),@@ -115,8 +135,108 @@ function bridgeCall(id: string, name: string, args: Record<string, unknown>): Toreturn { id, name: 'clerum__tool_call', arguments: { name, arguments: args } }}+/** A tool whose execute() returns a connect_required marker (as toolRegistryAdapter would). */+class ConnectRequiredTool implements Tool {+ constructor(private readonly _name: string) {}+ name(): string {+ return this._name+ }+ description(): string {+ return `${this._name} desc`+ }+ parametersSchema(): Record<string, unknown> {+ return { type: 'object', properties: {} }+ }+ requiresSanitization(): boolean {+ return false+ }+ requiresApproval(): boolean {+ return false+ }+ async execute(): Promise<ToolOutput> {+ return {+ content: 'MCP server monday auth failed (401)',+ duration_ms: 1,+ is_error: true,+ metadata: { connect_required: { mcpServerName: 'monday', provider: 'monday' } },+ }+ }+}+// ── Tests ────────────────────────────────────────────────────────────────────+describe('U5 — connect_required inline suspension (auto-approved / cron path)', () => {+ it('turns a connect_required tool result into a durable connect suspension', async () => {+ const config = makeConfig({+ tools: { monday__list_boards: new ConnectRequiredTool('monday__list_boards') },+ })+ const { toolResults, pendingApproval } = await executeToolCalls(+ [{ id: 'call-1', name: 'monday__list_boards', arguments: { limit: 5 } }],+ config,+ 0,+ [{ role: 'user', content: 'list boards' }]+ )++ // A connect_required suspension is raised (not fed to the LLM as an error).+ expect(pendingApproval).toBeDefined()+ expect(pendingApproval).toMatchObject({+ reason: 'connect_required',+ mcpServerName: 'monday',+ provider: 'monday',+ tool_name: 'monday__list_boards',+ tool_call_id: 'call-1',+ })+ // The failed connect result is NOT pushed (the tool re-executes fresh on resume).+ expect(toolResults.find(r => r.tool_call_id === 'call-1')).toBeUndefined()+ })++ it('closes the tool card (start→complete) before suspending — no dangling "running" step', async () => {+ const { reporter, events } = recordingReporter()+ const config = makeConfig({+ tools: { monday__list_boards: new ConnectRequiredTool('monday__list_boards') },+ progressReporter: reporter,+ })+ const { pendingApproval } = await executeToolCalls(+ [{ id: 'call-1', name: 'monday__list_boards', arguments: {} }],+ config,+ 0,+ [{ role: 'user', content: 'list boards' }]+ )++ expect(pendingApproval?.reason).toBe('connect_required')+ // Observable event sequence: the start is closed by a matching complete+ // BEFORE the (later) suspended event — no step card left "running". This+ // mirrors the resume path (taskExecutor emits reportToolComplete before its+ // own connect check).+ expect(events).toEqual([+ { kind: 'start', toolCallId: 'call-1' },+ { kind: 'complete', toolCallId: 'call-1', isError: true },+ ])+ })++ it('leaves following batch calls unexecuted with a synthetic not-executed result', async () => {+ const config = makeConfig({+ tools: {+ monday__list_boards: new ConnectRequiredTool('monday__list_boards'),+ server__other: new StubTool('server__other'),+ },+ })+ const { toolResults, pendingApproval } = await executeToolCalls(+ [+ { id: 'call-1', name: 'monday__list_boards', arguments: {} },+ { id: 'call-2', name: 'server__other', arguments: {} },+ ],+ config,+ 0,+ [{ role: 'user', content: 'do both' }]+ )+ expect(pendingApproval?.reason).toBe('connect_required')+ const other = toolResults.find(r => r.tool_call_id === 'call-2')+ expect(other?.is_error).toBe(true)+ expect(other?.content).toContain('Not executed')+ })+})+describe('clerum__tool_call bridge intercept', () => {it('unwraps to the real tool, preserving call.id on the result', async () => {const real = new StubTool('server__do_thing')diff --git a/mcp-host/src/core/orchestration/toolUseLoopToolBatch.ts b/mcp-host/src/core/orchestration/toolUseLoopToolBatch.tsindex 01f636e20..428a95599 100644--- a/mcp-host/src/core/orchestration/toolUseLoopToolBatch.ts+++ b/mcp-host/src/core/orchestration/toolUseLoopToolBatch.ts@@ -1,4 +1,8 @@import { extractToolIntent, getDisplayName } from '../../progress/intentExtraction.js'+import {+ buildConnectRequiredApproval,+ extractConnectRequiredMarker,+} from '../extensions/mcpApprovalGateController'import type { ChatMessage, PendingApproval, TokenUsage, ToolCall, ToolResult } from '../types'import type { LoopConfig } from './loopConfig'import { executeSingleTool, reportToolComplete, reportToolStart } from './toolUseLoopSingleTool'@@ -253,12 +257,71 @@ export async function executeToolCalls(const progressStart = reportToolStart(config, call, iteration, i, calls.length, llmTextContent)const toolResult = await executeSingleTool(call, config, iteration)- toolResults.push(toolResult)if (config.abortSignal?.aborted) {+ toolResults.push(toolResult)return { toolResults, cancelled: true }}+ // U5 — reactive OAuth consent on the inline (auto-approved / cron / no-snapshot+ // resume) path: a live 401 on an oauth mcp-server surfaces a typed+ // connect_required marker. Suspend durably instead of feeding the auth error+ // to the LLM. Mirrors the approval-gate suspend block: the failed connect+ // `toolResult` is NOT pushed (the same tool re-executes fresh on resume),+ // remaining batch calls get synthetic not-executed results, and the frozen+ // context travels on the approval so resume can rebuild the history.+ const connectMarker = extractConnectRequiredMarker(toolResult.metadata)+ if (connectMarker) {+ // Close the tool card BEFORE suspending. `reportToolStart` already fired at+ // the top of this call (the tool HAD to execute to surface the 401), so+ // returning without a complete would strand the step card as "running"+ // until the suspended event lands. This matches the resume path+ // (taskExecutor emits reportToolComplete before its own connect-marker+ // check) — both connect paths emit start→complete→suspended. The+ // approval-gate suspend leaves no start only because it returns BEFORE+ // execution (a different timing, not an inconsistency).+ reportToolComplete(+ config,+ call,+ toolResult,+ progressStart,+ iteration,+ i,+ calls.length,+ usageEmitted ? undefined : usage+ )+ usageEmitted = true+ const approval = buildConnectRequiredApproval(call, connectMarker)+ approval.intent_summary =+ extractToolIntent(llmTextContent ?? null, call.name) ??+ `Using ${getDisplayName(call.name)}...`+ for (let k = i + 1; k < calls.length; k++) {+ toolResults.push({+ tool_call_id: calls[k].id,+ name: calls[k].name,+ content: `Not executed — ${call.name} requires connection. Re-request if needed.`,+ is_error: true,+ })+ }+ if (priorMessages) {+ approval.context_snapshot = [...priorMessages]+ approval.completed_results = [...toolResults]+ }+ events.emit({+ type: 'tool:approval_needed',+ data: {+ toolName: call.name,+ requestId: approval.request_id,+ parameters: call.arguments,+ iteration,+ },+ timestamp: new Date(),+ })+ return { toolResults, pendingApproval: approval }+ }++ toolResults.push(toolResult)+reportToolComplete(config,call,diff --git a/mcp-host/src/core/types.ts b/mcp-host/src/core/types.tsindex 199aa4f1e..9b80da099 100644--- a/mcp-host/src/core/types.ts+++ b/mcp-host/src/core/types.ts@@ -494,6 +494,18 @@ export interface PendingApproval {intent_summary?: string/** Exact active-turn context retained while this approval is pending. */traceContext?: TraceContextV1 | null+ /**+ * U5 — suspension reason. Absent / 'approval_required' is the default HITL+ * gate (back-compat). 'connect_required' is a REACTIVE OAuth-consent+ * suspension: the live tool call surfaced a 401 on an oauth mcp-server and the+ * user must (re)connect before the tool can run. Persisted durably so a cold+ * restart rehydrates the right kind of suspension — never a generic approval.+ */+ reason?: 'approval_required' | 'connect_required'+ /** U5 — the oauth mcp-server to connect. Set iff reason==='connect_required'. */+ mcpServerName?: string+ /** U5 — the OAuth provider (enum) for the connect UI. Set iff reason==='connect_required'. */+ provider?: string}// ─── Loop Types ─────────────────────────────────────────────diff --git a/mcp-host/src/db/migrations/013-pending-approval-connect.ts b/mcp-host/src/db/migrations/013-pending-approval-connect.tsnew file mode 100644index 000000000..2c0d28a0d--- /dev/null+++ b/mcp-host/src/db/migrations/013-pending-approval-connect.ts@@ -0,0 +1,44 @@+/**+ * Migration 013 — durable `connect_required` suspension fields (spec §U5).+ *+ * A reactive OAuth-consent suspension (`reason='connect_required'`) must survive+ * a cold restart WITHOUT degrading into a generic approval. These nullable+ * columns carry the discriminator + the oauth server/provider so+ * `reconstructPendingApproval` rebuilds the right kind of suspension. NULL for+ * every existing/legacy row and for the default HITL gate (absent reason ⇒+ * 'approval_required').+ */+import type { Database } from 'better-sqlite3'++export const name = '013-pending-approval-connect'++function hasColumn(db: Database, column: string): boolean {+ const columns = db.prepare('PRAGMA table_info(pending_approvals)').all() as Array<{+ name: string+ }>+ return columns.some(entry => entry.name === column)+}++export function up(db: Database): void {+ if (!hasColumn(db, 'reason')) {+ db.exec('ALTER TABLE pending_approvals ADD COLUMN reason TEXT;')+ }+ if (!hasColumn(db, 'mcp_server_name')) {+ db.exec('ALTER TABLE pending_approvals ADD COLUMN mcp_server_name TEXT;')+ }+ if (!hasColumn(db, 'provider')) {+ db.exec('ALTER TABLE pending_approvals ADD COLUMN provider TEXT;')+ }+}++export function down(db: Database): void {+ if (hasColumn(db, 'provider')) {+ db.exec('ALTER TABLE pending_approvals DROP COLUMN provider;')+ }+ if (hasColumn(db, 'mcp_server_name')) {+ db.exec('ALTER TABLE pending_approvals DROP COLUMN mcp_server_name;')+ }+ if (hasColumn(db, 'reason')) {+ db.exec('ALTER TABLE pending_approvals DROP COLUMN reason;')+ }+}diff --git a/mcp-host/src/db/migrations/__tests__/008-active-trace-context.test.ts b/mcp-host/src/db/migrations/__tests__/008-active-trace-context.test.tsindex df6e53464..5d45ca4b7 100644--- a/mcp-host/src/db/migrations/__tests__/008-active-trace-context.test.ts+++ b/mcp-host/src/db/migrations/__tests__/008-active-trace-context.test.ts@@ -74,6 +74,7 @@ describe('migration 008 — active trace context', () => {'010-materialized-session-summaries','011-session-summary-user-activity-index','012-session-ownership-backfill',+ '013-pending-approval-connect',],pending: [],})diff --git a/mcp-host/src/db/migrations/index.ts b/mcp-host/src/db/migrations/index.tsindex a489bf081..5b788294e 100644--- a/mcp-host/src/db/migrations/index.ts+++ b/mcp-host/src/db/migrations/index.ts@@ -10,6 +10,7 @@ import * as sessionSummaryIndexes from './009-session-summary-indexes'import * as materializedSessionSummaries from './010-materialized-session-summaries'import * as sessionSummaryUserActivityIndex from './011-session-summary-user-activity-index'import * as sessionOwnershipBackfill from './012-session-ownership-backfill'+import * as pendingApprovalConnect from './013-pending-approval-connect'/*** Ordered list of migrations. New migrations append; never reorder or rename.@@ -33,4 +34,5 @@ export const migrations: Array<{materializedSessionSummaries,sessionSummaryUserActivityIndex,sessionOwnershipBackfill,+ pendingApprovalConnect,]diff --git a/mcp-host/src/db/statements.ts b/mcp-host/src/db/statements.tsindex a2ce30c07..81c6d812a 100644--- a/mcp-host/src/db/statements.ts+++ b/mcp-host/src/db/statements.ts@@ -385,11 +385,13 @@ export function prepareStatements(db: Database): PreparedStatements {INSERT INTO pending_approvals (request_id, session_id, task_id, tool_name, tool_call_id,parameters, description, context_snapshot, completed_results,- intent_summary, source_message, registered_at, expires_at, trace_context+ intent_summary, source_message, registered_at, expires_at, trace_context,+ reason, mcp_server_name, provider) VALUES (@request_id, @session_id, @task_id, @tool_name, @tool_call_id,@parameters, @description, @context_snapshot, @completed_results,- @intent_summary, @source_message, @registered_at, @expires_at, @trace_context+ @intent_summary, @source_message, @registered_at, @expires_at, @trace_context,+ @reason, @mcp_server_name, @provider)ON CONFLICT(request_id) DO UPDATE SETtask_id = excluded.task_id,diff --git a/mcp-host/src/db/worker/__tests__/dispatcher.test.ts b/mcp-host/src/db/worker/__tests__/dispatcher.test.tsindex 62cc624d6..d2571a51b 100644--- a/mcp-host/src/db/worker/__tests__/dispatcher.test.ts+++ b/mcp-host/src/db/worker/__tests__/dispatcher.test.ts@@ -631,6 +631,9 @@ describe('dbWorker dispatcher', () => {registered_at: Date.now() / 1000,expires_at: Date.now() / 1000 + 3600,trace_context: null,+ reason: null,+ mcp_server_name: null,+ provider: null,}await dispatch({ kind: 'insert_pending_approval', payload: approvalRow }, deps)const rows = (await dispatch({ kind: 'load_all_pending_approvals' }, deps)) as Array<{@@ -673,6 +676,9 @@ describe('dbWorker dispatcher', () => {registered_at: registeredAt,expires_at: 100,trace_context: null,+ reason: null,+ mcp_server_name: null,+ provider: null,},},deps@@ -725,6 +731,9 @@ describe('dbWorker dispatcher', () => {registered_at: now / 1000,expires_at: now / 1000 + 3600,trace_context: null,+ reason: null,+ mcp_server_name: null,+ provider: null,},},depsdiff --git a/mcp-host/src/db/worker/protocol.ts b/mcp-host/src/db/worker/protocol.tsindex 361f0a390..852596dd4 100644--- a/mcp-host/src/db/worker/protocol.ts+++ b/mcp-host/src/db/worker/protocol.ts@@ -96,6 +96,14 @@ export interface PendingApprovalRow {registered_at: numberexpires_at: numbertrace_context: string | null+ /** U5 (migration 013) — suspension discriminator. NULL / 'approval_required'+ * is the default HITL gate; 'connect_required' is a reactive OAuth-consent+ * suspension. Preserved so a cold restart rehydrates the right kind. */+ reason: string | null+ /** U5 (migration 013) — oauth mcp-server to connect (reason='connect_required'). */+ mcp_server_name: string | null+ /** U5 (migration 013) — OAuth provider for the connect UI (reason='connect_required'). */+ provider: string | null}export interface SessionCountersUpdate {diff --git a/mcp-host/src/mcp/__tests__/managerConnectRequired.test.ts b/mcp-host/src/mcp/__tests__/managerConnectRequired.test.tsnew file mode 100644index 000000000..5786e44ce--- /dev/null+++ b/mcp-host/src/mcp/__tests__/managerConnectRequired.test.ts@@ -0,0 +1,128 @@+/**+ * U5 seam — reactive OAuth-consent classification in `manager.callTool`.+ *+ * Invariants pinned here (spec §U5 must-fix):+ * - 401 on an oauth server → typed `connectRequired` marker (mcpServerName ++ * provider), NOT a flattened opaque error.+ * - 403 on an oauth server → TERMINAL: plain error, NO connectRequired marker.+ * - 401 on a static (non-oauth) server → NO connectRequired marker (only oauth+ * has a consent flow).+ * - No infinite loop: McpAuthError is thrown only AFTER the client's single+ * forced-refresh retry, so a persistent 401 is terminal-after-retry.+ */+import { beforeEach, describe, expect, it, vi } from 'vitest'+import type { McpServerInfo } from '../../types'+import type { McpPrincipal, McpTokenProviderFactory } from '../manager'+import { McpManager } from '../manager'++// ─── SDK mocks: callTool pulls from a queue so the test scripts 401/403/ok ─────++const state: { callToolQueue: Array<() => Promise<unknown>> } = { callToolQueue: [] }++vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({+ Client: class MockClient {+ connect = vi.fn().mockResolvedValue(undefined)+ close = vi.fn().mockResolvedValue(undefined)+ listTools = vi.fn().mockResolvedValue({+ tools: [{ name: 'do', description: 'demo', inputSchema: { type: 'object' } }],+ })+ callTool = vi.fn(async () => {+ const next = state.callToolQueue.shift()+ if (!next) throw new Error('unexpected extra callTool')+ return next()+ })+ },+}))++vi.mock('@modelcontextprotocol/sdk/client/streamableHttp.js', () => ({+ StreamableHTTPClientTransport: class {+ close = vi.fn().mockResolvedValue(undefined)+ constructor(_url: URL, _opts?: unknown) {}+ },+}))++vi.mock('@modelcontextprotocol/sdk/client/sse.js', () => ({+ SSEClientTransport: class {+ close = vi.fn().mockResolvedValue(undefined)+ },+}))++function httpError(status: number): () => Promise<never> {+ return () => {+ const err = new Error(`http ${status}`) as Error & { code: number }+ err.code = status+ return Promise.reject(err)+ }+}++function oauthUserServer(name = 'monday', provider = 'monday'): McpServerInfo {+ return {+ name,+ contextRef: 'ctx-1',+ transport: { type: 'streamableHttp', url: `http://${name}/mcp` },+ auth: { type: 'oauth' },+ oauth: { grantScope: 'user', provider },+ enabled: true,+ status: { deployed: true, ready: true },+ }+}++function staticServer(name = 'airtable'): McpServerInfo {+ return {+ name,+ contextRef: 'ctx-1',+ transport: { type: 'streamableHttp', url: `http://${name}/mcp` },+ auth: { type: 'none' },+ enabled: true,+ status: { deployed: true, ready: true },+ }+}++/** Always hands out a token, so the connection has a Bearer and the 401 is real. */+function tokenFactory(): McpTokenProviderFactory {+ return (_server: McpServerInfo, principal: McpPrincipal) => ({+ resolve: async () => (principal.kind === 'user' ? `tok-${principal.userId}` : undefined),+ refresh: async () => (principal.kind === 'user' ? `tok-${principal.userId}` : undefined),+ })+}++beforeEach(() => {+ state.callToolQueue = []+})++describe('manager.callTool — U5 reactive consent classification', () => {+ it('401 on an oauth server → typed connect_required marker (mcpServerName + provider)', async () => {+ const manager = new McpManager(undefined, undefined, tokenFactory())+ await manager.addServer(oauthUserServer('monday', 'monday'))++ // Two 401s: initial + the client's single forced-refresh retry → McpAuthError(401).+ state.callToolQueue = [httpError(401), httpError(401)]+ const result = await manager.callTool('monday__do', {}, { userId: 'alice' })++ expect(result.isError).toBe(true)+ expect(result.connectRequired).toEqual({ mcpServerName: 'monday', provider: 'monday' })+ })++ it('403 on an oauth server → terminal, NO connect_required marker', async () => {+ const manager = new McpManager(undefined, undefined, tokenFactory())+ await manager.addServer(oauthUserServer('monday', 'monday'))++ // 403 is terminal immediately in the client — no refresh/retry.+ state.callToolQueue = [httpError(403)]+ const result = await manager.callTool('monday__do', {}, { userId: 'alice' })++ expect(result.isError).toBe(true)+ expect(result.connectRequired).toBeUndefined()+ })++ it('401 on a static (non-oauth) server → NO connect_required marker', async () => {+ const manager = new McpManager(undefined, undefined, tokenFactory())+ await manager.addServer(staticServer('airtable'))++ state.callToolQueue = [httpError(401), httpError(401)]+ const result = await manager.callTool('airtable__do', {})++ expect(result.isError).toBe(true)+ expect(result.connectRequired).toBeUndefined()+ })+})diff --git a/mcp-host/src/mcp/manager.ts b/mcp-host/src/mcp/manager.tsindex 0c5c3f3c2..1c21b98a9 100644--- a/mcp-host/src/mcp/manager.ts+++ b/mcp-host/src/mcp/manager.ts@@ -826,6 +826,23 @@ export class McpManager {// Terminal auth failure — evict the per-user partition so a later call// (e.g. after the user reconnects) re-admits fresh. Static/shared exempt.if (isOauthUser) this.evictPartition(key)+ // U5 reactive-consent marker: a live 401 on an oauth server (surfaced+ // only AFTER the client's single forced-refresh retry, so already+ // terminal-after-retry — no loop) means the user must (re)connect. Gate+ // strictly on `auth.type==='oauth'` (covers BOTH per-user and shared+ // grantScope='context' — the shared flavor bootstraps on its first user)+ // AND `status===401`. A 403 (insufficient scope) is TERMINAL: no marker,+ // no connect flow. static (secretRef) has no consent flow → excluded by+ // the oauth type check. The marker is attached as a typed field so the+ // caller sees it (NOT flattened into the opaque error).+ if (info?.auth?.type === 'oauth' && error.status === 401) {+ return {+ toolName: fullToolName,+ result: { error: error.message },+ isError: true,+ connectRequired: { mcpServerName: serverName, provider: info.oauth?.provider },+ }+ }return {toolName: fullToolName,result: { error: error.message },diff --git a/mcp-host/src/progress/__tests__/sseProgressReporter.test.ts b/mcp-host/src/progress/__tests__/sseProgressReporter.test.tsindex ccbee1085..34f835cd2 100644--- a/mcp-host/src/progress/__tests__/sseProgressReporter.test.ts+++ b/mcp-host/src/progress/__tests__/sseProgressReporter.test.ts@@ -151,6 +151,49 @@ describe('SseProgressReporter', () => {})})+ it('U5: emitSuspended with connect_required carries reason + mcpServerName + provider', () => {+ const reporter = new SseProgressReporter('task-1', undefined, NoopSafety)+ const received: ProgressEvent[] = []+ reporter.subscribe(e => received.push(e))++ reporter.emitSuspended('Monday', 'req-connect', {+ reason: 'connect_required',+ mcpServerName: 'monday',+ provider: 'monday',+ })++ expect(received).toHaveLength(1)+ expect(received[0]).toEqual({+ type: 'suspended',+ data: {+ taskId: 'task-1',+ requestId: 'req-connect',+ displayName: 'Monday',+ reason: 'connect_required',+ mcpServerName: 'monday',+ provider: 'monday',+ },+ })+ })++ it('U5: omitting options keeps the legacy approval_required shape (back-compat)', () => {+ const reporter = new SseProgressReporter('task-1', undefined, NoopSafety)+ const received: ProgressEvent[] = []+ reporter.subscribe(e => received.push(e))++ reporter.emitSuspended('Shell', 'req-42', { reason: 'approval_required' })++ expect(received[0].data).toEqual({+ taskId: 'task-1',+ requestId: 'req-42',+ displayName: 'Shell',+ reason: 'approval_required',+ })+ // connect-only fields are absent for the default gate.+ expect('mcpServerName' in received[0].data).toBe(false)+ expect('provider' in received[0].data).toBe(false)+ })+it('P1-1: the suspended event never carries the raw tool_name', () => {const reporter = new SseProgressReporter('task-1', undefined, NoopSafety)const received: ProgressEvent[] = []diff --git a/mcp-host/src/progress/sseProgressReporter.ts b/mcp-host/src/progress/sseProgressReporter.tsindex c214ec17c..d74b32b5e 100644--- a/mcp-host/src/progress/sseProgressReporter.ts+++ b/mcp-host/src/progress/sseProgressReporter.ts@@ -7,6 +7,7 @@ import type {OutputPreview,ProgressEvent,ProgressReporter,+ SuspendedEvent,TerminalEvent,ThinkingEvent,ToolCompleteEvent,@@ -156,12 +157,26 @@ export class SseProgressReporter implements ProgressReporter {}// P1-1: takes only the server-derived displayName (not the raw tool_name).- emitSuspended(displayName: string, requestId: string): void {+ // U5: `options` is ADDITIVE — absent → the legacy 'approval_required' gate,+ // byte-identical to before. reason==='connect_required' carries the oauth+ // mcpServerName/provider so the desktop can open the connect flow.+ emitSuspended(+ displayName: string,+ requestId: string,+ options?: {+ reason?: 'approval_required' | 'connect_required'+ mcpServerName?: string+ provider?: string+ }+ ): void {if (this.completed) return- const event: ProgressEvent = {- type: 'suspended',- data: { taskId: this.taskId, requestId, displayName, reason: 'approval_required' },+ const reason = options?.reason ?? 'approval_required'+ const data: SuspendedEvent = { taskId: this.taskId, requestId, displayName, reason }+ if (reason === 'connect_required') {+ if (options?.mcpServerName) data.mcpServerName = options.mcpServerName+ if (options?.provider) data.provider = options.provider}+ const event: ProgressEvent = { type: 'suspended', data }// P1: store the exact redacted payload we publish live so late/re-connected// subscribers can replay it (see subscribe). displayName is already the// server-derived name from getDisplayName — never the raw tool_name/args.diff --git a/mcp-host/src/progress/types.ts b/mcp-host/src/progress/types.tsindex 0a50433ce..5700f8f1d 100644--- a/mcp-host/src/progress/types.ts+++ b/mcp-host/src/progress/types.ts@@ -101,7 +101,13 @@ export interface SuspendedEvent {// endpoint still exposes raw tool_name in `pendingApprovals[]` — separate// channel, tracked as a follow-up.displayName: string- reason: 'approval_required'+ // U5 — 'connect_required' is a reactive OAuth-consent suspension; the default+ // HITL gate stays 'approval_required'.+ reason: 'approval_required' | 'connect_required'+ /** Set iff reason==='connect_required' — the oauth mcp-server to connect. */+ mcpServerName?: string+ /** Set iff reason==='connect_required' — the OAuth provider for the connect UI. */+ provider?: string}/**diff --git a/mcp-host/src/types.ts b/mcp-host/src/types.tsindex f812880ec..e9eceda6b 100644--- a/mcp-host/src/types.ts+++ b/mcp-host/src/types.ts@@ -212,4 +212,19 @@ export interface ToolCallResult {toolName: stringresult: unknownisError: boolean+ /**+ * U5 reactive-consent marker. Present iff `manager.callTool` caught an+ * `McpAuthError` with `status===401` on a server whose `auth.type==='oauth'`+ * (both per-user and shared grantScope='context'): a live tool call surfaced a+ * real 401 after the client's single forced-refresh retry, so the user must+ * (re)connect. NEVER set for 403 (insufficient scope — terminal) nor for+ * static/non-oauth servers. `toolRegistryAdapter` maps it to+ * `metadata.connect_required`, which the tool-use loop turns into a durable+ * `connect_required` suspension (spec §U5). Kept as a typed field so the marker+ * is NOT flattened into an opaque error.+ */+ connectRequired?: {+ mcpServerName: string+ provider?: string+ }}