Tool input callbacks receive runtimeContext instead of their tool context
Description
Tool input callbacks receive runtimeContext as their context, while execute correctly receives the tool-specific value from toolsContext.
The callbacks are typed using the tool's contextSchema. For example, if that schema requires prefix: z.string(), TypeScript accepts context.prefix.toUpperCase() in onInputAvailable, but it throws because context.prefix is actually undefined.
Expected: onInputStart, onInputDelta, and onInputAvailable receive the selected tool's context, consistent with their types and execute.
Actual: they receive the general runtime context instead. This affects generateText, streamText, ToolLoopAgent.generate, and ToolLoopAgent.stream in local tests. onInputDelta applies only to streaming.
The hook invocations in generate-text.ts and invoke-tool-callbacks-from-stream.ts explicitly use context: runtimeContext. A possible fix is to resolve and validate each tool's entry from toolsContext using the existing context-validation helper, then pass that to the input hooks. Per-step context overrides should also be covered.
I can send the failing regression tests or a small PR if useful.
Reproduction
No provider request or API key is needed. In an empty directory:
npm init -y
npm install [email protected] [email protected]
Save this as repro.mts, then run node repro.mts with Node 24:
import { generateText, tool } from 'ai';
import { MockLanguageModelV4 } from 'ai/test';
import { z } from 'zod';
const events: Array<{ hook: string; context: unknown }> = [];
const result = await generateText({
model: new MockLanguageModelV4({
doGenerate: {
content: [{ type: 'tool-call', toolCallId: 'call-1', toolName: 'echo', input: '{"value":"hello"}' }],
finishReason: { unified: 'tool-calls', raw: 'tool-calls' },
usage: {
inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 },
outputTokens: { total: 1, text: 1, reasoning: 0 },
},
warnings: [],
},
}),
prompt: 'Echo hello.',
runtimeContext: { scope: 'runtime-only' },
toolsContext: { echo: { prefix: 'tool-only' } },
tools: {
echo: tool({
inputSchema: z.object({ value: z.string() }),
contextSchema: z.object({ prefix: z.string() }),
onInputStart: ({ context }) => { events.push({ hook: 'onInputStart', context }); },
onInputAvailable: ({ context }) => {
const prefix: string = context.prefix; // Inferred as string, but actually undefined.
events.push({ hook: 'onInputAvailable', context });
console.log('Typed string prefix:', prefix);
},
execute: async ({ value }, { context }) => {
events.push({ hook: 'execute', context });
return `${context.prefix}: ${value}`;
},
}),
},
});
console.log(JSON.stringify({ events, output: result.toolResults[0].output }, null, 2));
Output:
Typed string prefix: undefined
{
"events": [
{
"hook": "onInputStart",
"context": {
"scope": "runtime-only"
}
},
{
"hook": "onInputAvailable",
"context": {
"scope": "runtime-only"
}
},
{
"hook": "execute",
"context": {
"prefix": "tool-only"
}
}
],
"output": "tool-only: hello"
}
All three callbacks should receive { prefix: 'tool-only' }. Replacing the prefix log with context.prefix.toUpperCase() makes the call fail before execution.
The reproduction passes strict application TypeScript checking. Eight local regression cases reproduce the context mismatch and callback failure across the four entry points above.
Prepared with AI assistance for investigation, reproduction code, and local verification.
AI SDK Version
ai: 7.0.101 (unmodified npm package)zod: 4.4.3- Node.js: 24.13.0, macOS arm64
- Also inspected main at
6dcd923799d2c663dff348927790c7967ce597dc: the relevant context assignments remain. Main was not built or runtime-tested.
Code of Conduct
- [x] I agree to follow this project's Code of Conduct
Identify issue type
Identified as Bug
Confidence: High
Rationale
This is a concrete mismatch between the SDK's typed callback contract and runtime behavior, with a reproducible failure in existing functionality.
Evidence
- Tool input callbacks receive
runtimeContexteven though their types andcontextSchemaindicate they should receive the selected tool'stoolsContextvalue. - The reproduction shows
onInputStartandonInputAvailablereceiving{ scope: 'runtime-only' }, whileexecutecorrectly receives{ prefix: 'tool-only' }. - Typed callback code such as
context.prefix.toUpperCase()can therefore throw at runtime despite passing strict TypeScript checks. - The issue reports the mismatch across
generateText,streamText,ToolLoopAgent.generate, andToolLoopAgent.stream.
Bug Reproduction - AI SDK 7
Bug was reproduced.
Branch: main
PR: successful reproduction pull request
Details
- Main (
ai7.0.105) reproduces thetyped/runtimecontext mismatch acrossgenerateText,streamText,ToolLoopAgent.generate, andToolLoopAgent.stream. - All 15 applicable input-hook invocations received
{ "scope": "runtime-only" }, while all sixexecuteinvocations correctly received the selected tool context. prepareStepoverride cases also failed: input hooks receivedruntimeContextinstead of the overridden{ "prefix": "step-only" }context.- The expected behavior is for
onInputStart,onInputDelta, andonInputAvailableto receive the tool-specific context inferred fromcontextSchema, preventing typed property access from evaluating toundefinedat runtime. - Runnable reproduction:
examples/ai-functions/src/reproduction/issue-20948-tool-input-context.ts.
Bugfix - AI SDK 7
Created bugfix and opened PR: #20956
Root Cause
The non-streaming and streaming callback paths explicitly assigned runtimeContext to callback context instead of resolving the selected entry from toolsContext; the reproduction confirmed this across generation, streaming, agents, and prepareStep overrides.
Summary
Input callbacks now receive the selected, schema-validated tool context for the current step. Added a patch changeset and removed reproduction-only artifacts.
Testing
Updated generateText, streamText, and stream callback tests to verify all input hooks receive prepareStep-overridden tool context rather than runtime context.
Bug Reproduction - AI SDK 5
Issue report appears invalid.
Target branch: release-v5.0
- Issue #20948 assumes AI SDK 7 APIs, but the target branch contains
ai5.0.260 according topackages/ai/package.json. - The reported
runtimeContext,toolsContext,contextSchema,ToolLoopAgent, andMockLanguageModelV4APIs are absent frompackages/aiandpackages/provider-utilson this branch. packages/provider-utils/src/types/tool.tsdefines callback context only as untypedexperimental_context?: unknown; tools have no tool-specificcontextSchemacontract.packages/ai/src/generate-text/generate-text.tspasses the sameexperimental_contextto input callbacks and tool execution, so the reported typedtool-context/runtime-contextmismatch cannot be expressed on release-v5.0.- Per-step tool-context overrides are also unavailable:
packages/ai/src/generate-text/prepare-step.tshas notoolsContext, whilepackages/ai/src/agent/index.tsexports onlyExperimental_Agentandpackages/ai/test/index.tsexports onlyMockLanguageModelV2.
Relevant Documentation
- https://v5.ai-sdk.dev/docs/migration-guides/versioning
- https://ai-sdk.dev/docs/reference/ai-sdk-core/tool-loop-agent
Bug Reproduction - AI SDK 6
Issue report appears invalid.
Target branch: release-v6.0
- Issue #20948 reports an AI SDK 7 typed tool-context contract in which input hooks should receive the selected
toolsContextentry; that contract is not available on the target branch. packages/ai/package.jsonidentifies the checked-out target as[email protected], while the report requires[email protected].packages/provider-utils/src/types/tool.tshas nocontextSchemaor typedcontext; AI SDK 6 exposes only the shared, untypedexperimental_contextoption.packages/ai/src/generate-text/generate-text.ts,packages/ai/src/generate-text/stream-text.ts, andpackages/ai/src/generate-text/execute-tool-call.tspass that sameexperimental_contextto input hooks and tool execution, so the reported runtime-versus-tool-context divergence cannot be expressed through this release's API.packages/ai/test/index.tsexportsMockLanguageModelV3and does not contain the reproduction's requiredMockLanguageModelV4export.- No reproduction artifact was created because installing AI SDK 7 APIs would test a different release line rather than
release-v6.0.
Relevant Documentation
- https://ai-sdk.dev/docs/reference/ai-sdk-core/tool
- https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling
- https://ai-sdk.dev/docs/migration-guides/migration-guide-6-0
Thanks to you and your agent to catch that 😅👍🏼