Successful tool returns containing BigInt or cycles crash toJSONValue with TypeError
Description
When a tool executes successfully and returns an object containing a BigInt (e.g. database ID, Ethereum/blockchain integer, snowflake ID) or a cyclic structure, createToolModelOutput crashes with TypeError: Do not know how to serialize a BigInt or TypeError: Converting circular structure to JSON.
In #22796 / #22882, getErrorMessage was safeguarded against BigInt and cycles when a tool throws an error. However, when a tool succeeds, its return value is normalized through toJSONValue(output), which calls JSON.stringify(value) without safeguards. This unhandled exception crashes generateText and aborts streamText.
Reproduction
Save and run as an ES module (uses synthetic model and tool only, no credentials needed):
import assert from 'node:assert/strict';
import { generateText, tool, jsonSchema } from 'ai';
import { MockLanguageModelV4 } from 'ai/test';
const model = new MockLanguageModelV4({
async doGenerate() {
return {
content: [
{
type: 'tool-call',
toolCallId: 'call_1',
toolName: 'getUserData',
input: '{}',
},
],
warnings: [],
finishReason: { unified: 'tool-calls', raw: 'tool_calls' },
usage: { inputTokens: { total: 1 }, outputTokens: { total: 1 } },
};
},
});
const getUserDataTool = tool({
description: 'Fetch user data',
inputSchema: jsonSchema({ type: 'object' }),
execute: async () => ({
userId: 9007199254740993n, // BigInt exceeding Number.MAX_SAFE_INTEGER
name: 'Alice',
}),
});
try {
await generateText({
model,
prompt: 'Get user info',
tools: { getUserData: getUserDataTool },
});
} catch (error) {
console.log('Caught error:', error.name, error.message);
assert.equal(error.name, 'TypeError');
assert.equal(error.message, 'Do not know how to serialize a BigInt');
}
Expected Behavior
Successful tool executions containing BigInt values should serialize safely (e.g., converting BigInt to a string or numeric string in JSON) without throwing an unhandled serialization TypeError that aborts the generation.
Root Cause and Affected Source
In packages/ai/src/prompt/create-tool-model-output.ts lines 47–54:
function toJSONValue(value: unknown): JSONValue {
if (value === undefined) {
return null;
}
const serialized = JSON.stringify(value);
return serialized === undefined ? null : JSON.parse(serialized);
}
JSON.stringify(value) is called without a replacer or error guard. While the docstring notes that the value is in-process and safe from prototype poisoning, JSON.stringify still throws synchronously for BigInt and circular references.
Proposed Fix
- Pass a replacer to
JSON.stringifyintoJSONValuethat serializestypeof val === 'bigint'toval.toString(). - Wrap in a fallback guard so circular structures or throwing formatters degrade gracefully rather than throwing a replacement
TypeError.
AI SDK Version
- ai: 7.0.152 (main @ 682e2dd)
- Node.js: 22.x / 24.x
Identify issue type
Identified as Bug
Confidence: High
Rationale
This reports a concrete unhandled failure in existing successful tool execution behavior, with reproducible inputs and an identified source location. The proposed safeguards do not change that the primary issue is a crash.
Evidence
- A successful tool result containing a BigInt causes
createToolModelOutput/toJSONValueto throwTypeError: Do not know how to serialize a BigInt. - Cyclic tool results similarly throw during
JSON.stringify, abortinggenerateTextorstreamText. - The issue includes a credential-free reproduction, identifies the current serialization path, and states the expected non-crashing behavior.
Identify bug discovery
Discovery source: discovery:audit (medium confidence).
The report appears to originate from source-code inspection followed by a synthetic test, with no evidence that the bug was encountered in a production application.
- The author identifies the exact implementation and line range in
packages/ai/src/prompt/create-tool-model-output.ts. - The report compares the successful-result path with safeguards introduced in earlier issues and explains the unguarded
JSON.stringifyroot cause. - The reproduction deliberately uses
MockLanguageModelV4, a synthetic tool, and no credentials rather than describing a real application or production incident. - No original-author clarification about discovery source was provided.
If you find bugs through an agent audit, please share the prompts you used instead. Please see our updated guidelines at https://github.com/vercel/ai/issues/17243. If you have any questions, comment on #24118.