Skip to content

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

TypeScript

fix(mcp-host): preserve zai reasoning across tools

Alfredo Lopeza76743e29c72
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 3988e441b..5223dec4b 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.464",
+ "version": "0.1.465",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.464",
+ "version": "0.1.465",
"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 2a5711a66..3ba364fb1 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.464",
+ "version": "0.1.465",
"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__/providers/zai.test.ts b/mcp-host/src/__tests__/providers/zai.test.ts
index e24933353..73b3a2516 100644
--- a/mcp-host/src/__tests__/providers/zai.test.ts
+++ b/mcp-host/src/__tests__/providers/zai.test.ts
@@ -44,6 +44,7 @@ function toolCallResponse(toolName = 'search') {
message: {
role: 'assistant',
content: null,
+ reasoning_content: 'Keep this reasoning across the tool call',
tool_calls: [
{
id: 'tc1',
@@ -120,6 +121,42 @@ describe("ZaiProvider (OpenAICompatibleProvider, id='zai')", () => {
expect(result.tool_calls![0].name).toBe('web_search')
})
+ it('preserves GLM reasoning_content on the assistant tool-call round trip', async () => {
+ const provider = makeZai('glm-5.3')
+ const mockClient = createMockOpenAIClient()
+ mockClient.chat.completions.create.mockResolvedValue(toolCallResponse('shell_exec'))
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ ;(provider as any)['client'] = mockClient
+
+ const result = await provider.completeSingleTurnWithTools(
+ [
+ { role: 'user', content: 'Run the probe' },
+ {
+ role: 'assistant',
+ content: '',
+ reasoning_content: 'Prior GLM reasoning',
+ tool_calls: [
+ {
+ id: 'previous-call',
+ name: 'shell_exec',
+ arguments: { command: 'printf prior' },
+ },
+ ],
+ },
+ { role: 'tool', tool_call_id: 'previous-call', content: 'prior' },
+ ],
+ []
+ )
+
+ expect(result.reasoning_content).toBe('Keep this reasoning across the tool call')
+ const request = mockClient.chat.completions.create.mock.calls[0][0]
+ const assistant = request.messages.find(
+ (message: { role: string; tool_calls?: unknown }) =>
+ message.role === 'assistant' && message.tool_calls
+ )
+ expect(assistant.reasoning_content).toBe('Prior GLM reasoning')
+ })
+
it('propagates API errors from the underlying client', async () => {
const provider = makeZai()
const mockClient = createMockOpenAIClient()
diff --git a/mcp-host/src/core/orchestration/__tests__/toolUseLoop.test.ts b/mcp-host/src/core/orchestration/__tests__/toolUseLoop.test.ts
index 6a3aa6ee4..bf58520d0 100644
--- a/mcp-host/src/core/orchestration/__tests__/toolUseLoop.test.ts
+++ b/mcp-host/src/core/orchestration/__tests__/toolUseLoop.test.ts
@@ -8,8 +8,11 @@ import { VisualInputBudget } from '../../../visualInput/policy'
import { makeFakeConversation } from '../../conversation/__testing__/makeFakeConversation'
import { LlmError, LlmErrorCode } from '../../errors'
import type { ReasoningPort, Tool, ToolRegistry } from '../../interfaces'
+import { DefaultReasoningPort } from '../../reasoning/port'
+import { DefaultPromptBuilder } from '../../reasoning/promptBuilder'
import { BasicSafety } from '../../safety/safety'
-import type { Attachment, RespondResult, ToolOutput } from '../../types'
+import type { Attachment, ChatMessage, RespondResult, ToolOutput } from '../../types'
+import { FinishReason } from '../../types'
import { SimpleEventEmitter } from '../eventEmitter'
import { buildLoopConfig } from '../loopConfig'
import {
@@ -153,6 +156,47 @@ describe('runToolUseLoop — loop control', () => {
}
})
+ it('preserves provider reasoning_content from ReasoningPort through the next tool continuation', async () => {
+ const completeWithTools = vi
+ .fn()
+ .mockResolvedValueOnce({
+ content: null,
+ tool_calls: [{ id: 'tc_reason', name: 'noop', arguments: {} }],
+ reasoning_content: 'GLM reasoning must survive the tool boundary',
+ usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15 },
+ finish_reason: FinishReason.ToolUse,
+ })
+ .mockResolvedValueOnce({
+ content: 'done after reasoning',
+ tool_calls: null,
+ usage: { input_tokens: 11, output_tokens: 2, total_tokens: 13 },
+ finish_reason: FinishReason.Stop,
+ })
+ const reasoning = new DefaultReasoningPort(
+ { complete: vi.fn(), completeWithTools, modelName: () => 'glm-5.3' },
+ new DefaultPromptBuilder()
+ )
+
+ const config = buildLoopConfig({
+ reasoning,
+ toolRegistry: createMockRegistry([createMockTool('noop')]),
+ safety: new BasicSafety(),
+ events: new SimpleEventEmitter(),
+ conversation: makeFakeConversation(),
+ })
+
+ const result = await runToolUseLoop(config, [{ role: 'user', content: 'Use the tool' }])
+
+ expect(result.type).toBe('response')
+ expect(completeWithTools).toHaveBeenCalledTimes(2)
+ const continuation = completeWithTools.mock.calls[1]?.[0]
+ const assistant = continuation?.messages.find(
+ (message: ChatMessage) =>
+ message.role === 'assistant' && (message.tool_calls?.length ?? 0) > 0
+ )
+ expect(assistant?.reasoning_content).toBe('GLM reasoning must survive the tool boundary')
+ })
+
it('should stop at maxIterations when reasoning always returns tool_calls (Risk 4.5a)', async () => {
const toolCalls = {
type: 'tool_calls' as const,
diff --git a/mcp-host/src/core/orchestration/toolUseLoop.ts b/mcp-host/src/core/orchestration/toolUseLoop.ts
index b8926fb5e..772bf375f 100644
--- a/mcp-host/src/core/orchestration/toolUseLoop.ts
+++ b/mcp-host/src/core/orchestration/toolUseLoop.ts
@@ -333,6 +333,7 @@ export async function runToolUseLoop(
role: 'assistant',
content: result.content ?? '',
tool_calls: result.calls,
+ reasoning_content: result.reasoning_content,
})
for (const message of messages) {
diff --git a/mcp-host/src/core/reasoning/port.ts b/mcp-host/src/core/reasoning/port.ts
index d80a7a26b..6b0cf14e6 100644
--- a/mcp-host/src/core/reasoning/port.ts
+++ b/mcp-host/src/core/reasoning/port.ts
@@ -205,6 +205,7 @@ export class DefaultReasoningPort implements ReasoningPort {
type: 'tool_calls',
calls: response.tool_calls,
content: response.content ?? undefined,
+ reasoning_content: response.reasoning_content,
usage: response.usage,
}
}
diff --git a/mcp-host/src/core/types.ts b/mcp-host/src/core/types.ts
index 2311f58ad..2046329a3 100644
--- a/mcp-host/src/core/types.ts
+++ b/mcp-host/src/core/types.ts
@@ -61,6 +61,13 @@ export interface ChatMessage {
tool_call_id?: string
name?: string
tool_calls?: ToolCall[] | null
+ /**
+ * Provider reasoning that must accompany the assistant tool call on the next
+ * OpenAI-compatible request. ZAI GLM reasoning models require this field to
+ * remain on the same tool-call message; it is absent for providers that do
+ * not return reasoning.
+ */
+ reasoning_content?: string | null
/**
* IronClaw invariant #2 (P.3, Opción D): lateral field that points at a
* spillover blob written by T1.5. `content` always stays a string (a rich
@@ -226,6 +233,7 @@ export interface ToolCompletionRequest {
export interface ToolCompletionResponse {
content: string | null
tool_calls: ToolCall[] | null
+ reasoning_content?: string | null
usage: TokenUsage
/** True only when the provider response carried authoritative token counters. */
usage_reported?: boolean
@@ -245,7 +253,13 @@ export interface ReasoningContext {
export type RespondResult =
| { type: 'text'; content: string }
- | { type: 'tool_calls'; calls: ToolCall[]; content?: string; usage?: TokenUsage }
+ | {
+ type: 'tool_calls'
+ calls: ToolCall[]
+ content?: string
+ reasoning_content?: string | null
+ usage?: TokenUsage
+ }
| { type: 'need_approval'; approval: PendingApproval }
| { type: 'error'; error: Error }
diff --git a/mcp-host/src/llm/__tests__/openai.singleTurn.test.ts b/mcp-host/src/llm/__tests__/openai.singleTurn.test.ts
index 7827e34ed..a8a65c2dd 100644
--- a/mcp-host/src/llm/__tests__/openai.singleTurn.test.ts
+++ b/mcp-host/src/llm/__tests__/openai.singleTurn.test.ts
@@ -209,6 +209,30 @@ describe('OpenAI message conversion', () => {
expect(assistantMsg.tool_calls[0].function.arguments).toBe('{"query":"X"}')
expect(typeof assistantMsg.tool_calls[0].function.arguments).toBe('string')
})
+
+ it('should omit ZAI reasoning_content from native OpenAI requests', async () => {
+ const mockClient = createMockOpenAIClient()
+ mockClient.chat.completions.create.mockResolvedValue(openAITextResponse('Done'))
+ const provider = new OpenAIProvider(mockClient as any, 'gpt-4o')
+
+ const messages: ChatMessage[] = [
+ { role: 'user', content: 'Continue after a ZAI fallback' },
+ {
+ role: 'assistant',
+ content: '',
+ reasoning_content: 'Prior ZAI reasoning',
+ tool_calls: [{ id: 'tc_zai', name: 'search', arguments: { query: 'fallback' } }],
+ },
+ { role: 'tool', content: 'result', tool_call_id: 'tc_zai' },
+ ]
+
+ await provider.completeSingleTurnWithTools(messages, [])
+
+ const callArgs = mockClient.chat.completions.create.mock.calls[0][0]
+ const assistantMsg = callArgs.messages.find((m: any) => m.role === 'assistant' && m.tool_calls)
+ expect(assistantMsg).toBeDefined()
+ expect(assistantMsg).not.toHaveProperty('reasoning_content')
+ })
})
describe('OpenAI contentParts in user messages (screenshot images)', () => {
diff --git a/mcp-host/src/llm/openai.ts b/mcp-host/src/llm/openai.ts
index 365907059..e51817736 100644
--- a/mcp-host/src/llm/openai.ts
+++ b/mcp-host/src/llm/openai.ts
@@ -47,6 +47,15 @@ export class OpenAIProvider implements SingleTurnProvider {
return /^(?:gpt-5(?:[.-]|$)|o[1-9](?:[.-]|$))/i.test(this.defaultModel)
}
+ /**
+ * ZAI requires reasoning to remain on assistant tool-call messages across a
+ * tool turn. Native OpenAI and Azure keep the standard message shape, so a
+ * provider-specific field from prior ZAI history must not leak during failover.
+ */
+ protected supportsReasoningContent(): boolean {
+ return false
+ }
+
private tokenLimitOptions(maxTokens: number | undefined): {
max_tokens?: number
max_completion_tokens?: number
@@ -149,6 +158,7 @@ export class OpenAIProvider implements SingleTurnProvider {
name: tc.function.name,
arguments: this.parseArguments(tc.function.arguments),
})) ?? null
+ const reasoningContent = (message as { reasoning_content?: unknown }).reasoning_content
const usageReported =
response.usage != null &&
@@ -159,6 +169,7 @@ export class OpenAIProvider implements SingleTurnProvider {
return {
content: message.content,
tool_calls: toolCalls && toolCalls.length > 0 ? toolCalls : null,
+ reasoning_content: typeof reasoningContent === 'string' ? reasoningContent : null,
usage: {
input_tokens: response.usage?.prompt_tokens ?? 0,
output_tokens: response.usage?.completion_tokens ?? 0,
@@ -197,7 +208,7 @@ export class OpenAIProvider implements SingleTurnProvider {
}
if (m.role === 'assistant') {
if (m.tool_calls) {
- return {
+ const assistantMessage = {
role: 'assistant' as const,
content: m.content || null,
tool_calls: m.tool_calls.map(tc => ({
@@ -208,7 +219,11 @@ export class OpenAIProvider implements SingleTurnProvider {
arguments: JSON.stringify(tc.arguments),
},
})),
+ } as Record<string, unknown>
+ if (m.reasoning_content && this.supportsReasoningContent()) {
+ assistantMessage.reasoning_content = m.reasoning_content
}
+ return assistantMessage as unknown as OpenAI.ChatCompletionAssistantMessageParam
}
return { role: 'assistant' as const, content: m.content }
}
diff --git a/mcp-host/src/llm/openaiCompatible.ts b/mcp-host/src/llm/openaiCompatible.ts
index 975d0bddc..9a63d0c23 100644
--- a/mcp-host/src/llm/openaiCompatible.ts
+++ b/mcp-host/src/llm/openaiCompatible.ts
@@ -152,6 +152,10 @@ export class OpenAICompatibleProvider extends OpenAIProvider {
return false
}
+ protected override supportsReasoningContent(): boolean {
+ return this.cfg.id === 'zai'
+ }
+
override completeSingleTurn(
messages: CoreChatMessage[],
options?: { max_tokens?: number; temperature?: number; signal?: AbortSignal }