onFinish callback for streamText is missing tool information
Description
For calls of streamText, the onFinish callback context does not contain information on tool calls and results, even though tool steps were executed.
In my example, I connected the Linear MCP server and tried to fetch my issues. The tool is executed and the LLM responds with the results in the second step. The onStepFinish callback is executed as well and contains information on the tool call. The finish callback is only contains information on which steps were executed, but the dedicated properties for tool calls and results are empty.
My use case is to save the tool results to the database. Using the onStepFinish callback is a workaround, but it results in way more database queries and complicates logic, which I'd like to avoid.
Below is a snippet of my route implementation as well as the value of the context.
Context (with omitted request and response properties)
{
"finishReason": "stop",
"totalUsage": {
"inputTokens": 7813,
"outputTokens": 595,
"totalTokens": 8408,
"reasoningTokens": 0,
"cachedInputTokens": 0
},
"usage": {
"inputTokens": 5734,
"outputTokens": 572,
"totalTokens": 6306,
"reasoningTokens": 0,
"cachedInputTokens": 0
},
"content": [
{
"type": "text",
"text": "Here are your 5 latest Linear issues: ... (omitted for brevity)"
}
],
"text": "Here are your 5 latest Linear issues: ... (omitted for brevity)",
"reasoning": [],
"files": [],
"sources": [],
"toolCalls": [],
"staticToolCalls": [],
"dynamicToolCalls": [],
"toolResults": [],
"staticToolResults": [],
"dynamicToolResults": [],
"warnings": [],
"providerMetadata": {
"openai": {
"acceptedPredictionTokens": 0,
"rejectedPredictionTokens": 0
}
},
"steps": [
{
"content": [
{
"type": "tool-call",
"toolCallId": "call_bQ9ImRPvwXQZIIB1XARkfgZ8",
"toolName": "list_my_issues",
"input": {
"limit": 5,
"orderBy": "updatedAt"
},
"dynamic": true
},
{
"type": "tool-result",
"toolCallId": "call_bQ9ImRPvwXQZIIB1XARkfgZ8",
"toolName": "list_my_issues",
"input": {
"limit": 5,
"orderBy": "updatedAt"
},
"dynamic": true,
"output": {
"content": [
{
"type": "text",
"text": ""
}
],
"isError": false
}
}
],
"finishReason": "tool-calls",
"usage": {
"inputTokens": 2079,
"outputTokens": 23,
"totalTokens": 2102,
"reasoningTokens": 0,
"cachedInputTokens": 0
},
"warnings": [],
"providerMetadata": {
"openai": {
"acceptedPredictionTokens": 0,
"rejectedPredictionTokens": 0
}
}
},
{
"content": [
{
"type": "text",
"text": "Here are your 5 latest Linear issues: ..."
}
],
"finishReason": "stop",
"usage": {
"inputTokens": 5734,
"outputTokens": 572,
"totalTokens": 6306,
"reasoningTokens": 0,
"cachedInputTokens": 0
},
"warnings": [],
"providerMetadata": {
"openai": {
"acceptedPredictionTokens": 0,
"rejectedPredictionTokens": 0
}
}
}
]
}
route.ts snippet:
return createUIMessageStreamResponse({
stream: createUIMessageStream({
execute: async ({
writer
}: {
writer: UIMessageStreamWriter<ChatMessage>
}) => {
const processedMessagesWithApproval = await processToolCalls(
{
messages: processedMessages,
writer,
tools
},
executeFunctions
)
const result = streamText({
model,
messages: convertToModelMessages(processedMessagesWithApproval),
system: prompt,
topP: assistant.topP,
temperature: assistant.temperature,
maxOutputTokens: assistant.maxTokens || undefined,
stopWhen: stepCountIs(10),
tools: {
...tools,
...(hasCanvasEnabled
? {
createDocument: createDocument({
writer,
model,
chatId: id,
messages: processedMessagesWithApproval,
assistant
}),
updateDocument: updateDocument({
writer,
model,
chatId: id,
messages: processedMessagesWithApproval,
assistant
})
}
: {}),
...(hasWebSearchEnabled
? {
searchWeb: getSearchWebTool(writer)
}
: {})
},
toolChoice: 'auto',
experimental_transform: smoothStream({ chunking: 'word' }),
onFinish: async context =>
finishHandler(
context,
numberOfPages,
id,
userId,
title,
assistant,
processedMessagesWithApproval,
clients
)
})
result.consumeStream()
return writer.merge(result.toUIMessageStream({ sendReasoning: true }))
},
onError: (error: any) =>
errorHandler({
error,
mcpClients: clients,
userId,
chatId: id,
title,
locale
})
})
})
AI SDK Version
"ai": "5.0.40", "@ai-sdk/azure": "^2.0.28", "@ai-sdk/deepseek": "^1.0.8", "@ai-sdk/google": "^2.0.6", "@ai-sdk/google-vertex": "^3.0.9", "@ai-sdk/mistral": "^2.0.5", "@ai-sdk/openai": "^2.0.28", "@ai-sdk/react": "^2.0.40"
Code of Conduct
- [x] I agree to follow this project's Code of Conduct
@gr2m we're also seeing missing toolCalls on streamText for 5.0.81 with sonnet 4.5, sonnet 4, and gpt-4-1 on all providers (anthropic, vertex, bedrock)
For what it's worth. Claude found a simple workaround for this.
const steps = await streamResult.steps;
const allToolCalls = steps.flatMap((step) => step.toolCalls);
Here's the full explanation for context, and hopefully to aid in fixing this issue:
I found it. Look at line 5999-6000:
if (part.type === "start-step") { recordedContent = []; // <-- Content is RESET for each step!And then look at how
toolCallsis resolved (line 6792-6793):get toolCalls() { return this.finalStep.then((step) => step.toolCalls); }The issue:
toolCallsreturnsfinalStep.toolCalls- the tool calls from the LAST step only.Looking at your
messagesdata, there are 3 steps:
- Step 1: Assistant with reasoning + text +
tool-call- Step 2: Tool role with
tool-result- Step 3: Assistant with final text
The
finalStepis Step 3 - which has no tool calls, just the final text response. The tool calls are in Step 1, buttoolCallsonly looks at the last step!Let me verify by checking if there's a way to get all steps:
[1 tool called]
Root cause confirmed:
streamResult.toolCallsreturnsfinalStep.toolCalls- only the last step's tool calls, not all tool calls across the entire multi-step generation.Your flow has 3 steps.
The SDK provides
streamResult.stepsto access all steps. The proper fix:[2 tools called]
The fix uses
streamResult.stepsto get all steps, then extracts tool calls from each step withsteps.flatMap((step) => step.toolCalls).Summary of the issue:
- The AI SDK's
streamResult.toolCallsonly returns tool calls fromfinalStep(the last step)- In multi-step tool execution, the tool calls happen in earlier steps, not the final one
- The final step is just the text response after tool execution, which has no tool calls
- Using
streamResult.stepsgives access to all steps, allowing you to collect tool calls from the entire conversation
You should extract the information from the steps as described above.
Identify issue type
{
"evidence": [
"Reporter states `streamText` `onFinish` context has empty `toolCalls` and `toolResults` even though tool steps executed and `onStepFinish` contains the tool call.",
"Provided `onFinish` context shows tool-call and tool-result entries inside `steps`, while top-level `toolCalls`, `dynamicToolCalls`, `toolResults`, and related arrays are empty.",
"Another user reports the same missing `toolCalls` behavior across AI SDK 5.0.81 and multiple providers/models.",
"A later comment identifies that `toolCalls` resolves from the final step only, so multi-step tool calls from earlier steps are omitted from the top-level result."
],
"rationale": "The issue reports a concrete incorrect/missing result in current `streamText` `onFinish` behavior for tool calls in multi-step generations. Although comments mention a workaround via `steps`, the primary report is about missing tool information from existing callback fields.",
"type": "bug",
"confidence": "high"
}
Bug Reproduction
Bug could not be reproduced.
Target branch: main
- The current checkout uses
ai7.0.26; the issue was reported against 5.0.40. - Created
examples/ai-functions/src/reproduction/issue-8578-stream-text-on-finish-tool-information.tswith a dynamic toolcall/resultin the first step and a text-only final step. - The final step had zero tool calls and results, but
onFinish.toolCallsandonFinish.toolResultseach containedcall-list-my-issues; the reported empty top-level arrays did not occur.
Relevant Documentation
- https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text
- https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling
Closed PR: cannot-reproduce investigation pull request
Bug Reproduction
Bug was reproduced.
Branch: release-v5.0
PR: successful reproduction pull request
Details
- Added runnable reproduction at
examples/ai-functions/src/reproduction/issue-8578-stream-text-on-finish-tool-information.tsagainst AI SDK 5.0.212. - A two-step dynamic tool flow executed
call-list-my-issuesand produced its result in the first step, followed by a text-only final step. onFinish.stepscontained the tool call and result, while top-leveltoolCalls,dynamicToolCalls,toolResults, anddynamicToolResultswere all empty.- The expected issue behavior was observed: the dedicated top-level
onFinishfields omitted tool information executed during an earlier step.
Relevant Documentation
- https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text
- https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling
Bug Reproduction
Bug was reproduced.
Branch: release-v6.0
PR: successful reproduction pull request
Details
- Added runnable reproduction at
examples/ai-functions/src/reproduction/issue-8578-stream-text-on-finish-tool-information.tsagainst AI SDK 6.0.225. - The two-step flow recorded
call-list-my-issuesand its result inonFinish.steps, followed by a text-only final step. - Top-level
onFinish.toolCalls,dynamicToolCalls,toolResults, anddynamicToolResultswere empty instead of exposing the completed tool information, reproducing the reported persistence-impacting behavior.
Relevant Documentation
- https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text
- https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling
Please use const allToolCalls = steps.flatMap((step) => step.toolCalls); to get all tool calls. In AI SDK 7 the distinction is clearer.
Bug Reproduction - AI SDK 6
Bug was reproduced.
Branch: release-v6.0
PR: successful reproduction pull request
Details
- Updated
examples/ai-functions/src/reproduction/issue-8578-stream-text-on-finish-tool-information.tsto verify the completed dynamic tool call and result are available through bothonStepFinishandonFinish.steps. - Against AI SDK 6.0.261, the final text-only step completes successfully, but
onFinish.toolCalls,dynamicToolCalls,toolResults, anddynamicToolResultsall omitcall-list-my-issues. - The expected behavior is for the top-level
onFinishtool fields to expose completed tool information from all steps, allowing one callback to persist the results.
Relevant Documentation
- https://v6.ai-sdk.dev/docs/reference/ai-sdk-core/stream-text
- https://v6.ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling