ai icon indicating copy to clipboard operation
ai copied to clipboard

Tool input callbacks receive runtimeContext instead of their tool context

Open brennanbutler01 opened this issue 2 months ago • 6 comments

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

brennanbutler01 avatar Sep 17 '26 08:09 brennanbutler01

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 runtimeContext even though their types and contextSchema indicate they should receive the selected tool's toolsContext value.
  • The reproduction shows onInputStart and onInputAvailable receiving { scope: 'runtime-only' }, while execute correctly 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, and ToolLoopAgent.stream.

ai-sdk-factory[bot] avatar Sep 17 '26 08:09 ai-sdk-factory[bot]

Bug Reproduction - AI SDK 7

Bug was reproduced.

Branch: main PR: successful reproduction pull request

Details

  • Main (ai 7.0.105) reproduces the typed/runtime context mismatch across generateText, streamText, ToolLoopAgent.generate, and ToolLoopAgent.stream.
  • All 15 applicable input-hook invocations received { "scope": "runtime-only" }, while all six execute invocations correctly received the selected tool context.
  • prepareStep override cases also failed: input hooks received runtimeContext instead of the overridden { "prefix": "step-only" } context.
  • The expected behavior is for onInputStart, onInputDelta, and onInputAvailable to receive the tool-specific context inferred from contextSchema, preventing typed property access from evaluating to undefined at runtime.
  • Runnable reproduction: examples/ai-functions/src/reproduction/issue-20948-tool-input-context.ts.

ai-sdk-factory[bot] avatar Sep 17 '26 08:09 ai-sdk-factory[bot]

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.

ai-sdk-factory[bot] avatar Sep 17 '26 10:09 ai-sdk-factory[bot]

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 ai 5.0.260 according to packages/ai/package.json.
  • The reported runtimeContext, toolsContext, contextSchema, ToolLoopAgent, and MockLanguageModelV4 APIs are absent from packages/ai and packages/provider-utils on this branch.
  • packages/provider-utils/src/types/tool.ts defines callback context only as untyped experimental_context?: unknown; tools have no tool-specific contextSchema contract.
  • packages/ai/src/generate-text/generate-text.ts passes the same experimental_context to input callbacks and tool execution, so the reported typed tool-context/runtime-context mismatch cannot be expressed on release-v5.0.
  • Per-step tool-context overrides are also unavailable: packages/ai/src/generate-text/prepare-step.ts has no toolsContext, while packages/ai/src/agent/index.ts exports only Experimental_Agent and packages/ai/test/index.ts exports only MockLanguageModelV2.

Relevant Documentation

  • https://v5.ai-sdk.dev/docs/migration-guides/versioning
  • https://ai-sdk.dev/docs/reference/ai-sdk-core/tool-loop-agent

ai-sdk-factory[bot] avatar Sep 18 '26 21:09 ai-sdk-factory[bot]

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 toolsContext entry; that contract is not available on the target branch.
  • packages/ai/package.json identifies the checked-out target as [email protected], while the report requires [email protected].
  • packages/provider-utils/src/types/tool.ts has no contextSchema or typed context; AI SDK 6 exposes only the shared, untyped experimental_context option.
  • packages/ai/src/generate-text/generate-text.ts, packages/ai/src/generate-text/stream-text.ts, and packages/ai/src/generate-text/execute-tool-call.ts pass that same experimental_context to 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.ts exports MockLanguageModelV3 and does not contain the reproduction's required MockLanguageModelV4 export.
  • 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

ai-sdk-factory[bot] avatar Sep 18 '26 21:09 ai-sdk-factory[bot]

Thanks to you and your agent to catch that 😅👍🏼

gr2m avatar Sep 18 '26 21:09 gr2m