@ai-sdk/anthropic 4.0.98 → 4.0.99

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -562,13 +562,21 @@ schemas with open objects such as maps (`additionalProperties` set to a schema
562
562
  or `true`), which native structured outputs would return as `{}`.
563
563
  Likewise, a `required` or named `toolChoice` is downgraded to
564
564
  `auto` with a warning; instruct the model to use the tool in your prompt and
565
- verify that a tool call was made.
565
+ verify that a tool call was made. When a named choice falls back to `auto`,
566
+ inline tool additions must use the selected tool's name. Conflicting additions,
567
+ including definitions replayed from conversation history, cause an
568
+ `InvalidArgumentError` before the request is sent.
566
569
 
567
570
  The JSON-tool fallback limits which application tools are available:
568
571
  `toolChoice: 'none'` sends only the internal JSON response tool, and a named tool
569
572
  choice sends only that application tool alongside the JSON response tool. The
570
573
  fallback can produce a JSON response without calling the named application tool;
571
574
  verify the selected call if your application requires it.
575
+ These restrictions also apply to inline tool definitions: a named choice allows
576
+ only additions with the selected tool's name, and `toolChoice: 'none'` rejects
577
+ all inline additions. Conflicting definitions cause an `InvalidArgumentError`
578
+ before the request is sent. Tool changes on the initial system message remain
579
+ ignored with a warning.
572
580
 
573
581
  When the JSON tool cannot be forced (for example with manual thinking) and the
574
582
  model answers in text without calling it, the text of its final answer is
@@ -1079,6 +1087,9 @@ the selected tool is sent. This also applies when the top-level `reasoning`
1079
1087
  option enables manual thinking, including when structured output uses the
1080
1088
  internal JSON response tool. Tool use is no longer guaranteed: instruct the
1081
1089
  model to use the tool in your prompt and verify that a tool call was made.
1090
+ Inline tool additions must use the selected tool's name when a named choice
1091
+ falls back to `auto`. Conflicting additions, including definitions replayed from
1092
+ conversation history, cause an `InvalidArgumentError` before the request is sent.
1082
1093
 
1083
1094
  See [AI SDK UI: Chatbot](/docs/ai-sdk-ui/chatbot#reasoning) for more details
1084
1095
  on how to integrate reasoning into your chatbot.
@@ -1668,7 +1679,13 @@ return several actions in one turn, each as its own tool call.
1668
1679
  The API returns each action as a separate `tool_use` block with
1669
1680
  `toolset_name: 'computer'`. The AI SDK maps every action to the toolset tool and
1670
1681
  passes the action name as `action`, so `execute` receives the same input shape
1671
- as the older computer tools:
1682
+ as the older computer tools.
1683
+
1684
+ The SDK preserves the returned member name as `action` and rejects disabled or
1685
+ unavailable members before emitting tool calls, including during streaming.
1686
+ Disabled members are also rejected by the tool's local input schema.
1687
+
1688
+ For example:
1672
1689
 
1673
1690
  ```ts
1674
1691
  const computerTool = anthropic.tools.computerToolset_20260801({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/anthropic",
3
- "version": "4.0.98",
3
+ "version": "4.0.99",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "sideEffects": false,
@@ -35,8 +35,8 @@
35
35
  }
36
36
  },
37
37
  "dependencies": {
38
- "@ai-sdk/provider": "4.0.36",
39
- "@ai-sdk/provider-utils": "5.0.75"
38
+ "@ai-sdk/provider": "4.0.37",
39
+ "@ai-sdk/provider-utils": "5.0.76"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@ai-sdk/test-server": "2.0.4",
@@ -32,6 +32,7 @@ import {
32
32
  parseProviderOptions,
33
33
  postJsonToApi,
34
34
  resolve,
35
+ resolveProviderOptions,
35
36
  resolveProviderReference,
36
37
  secureJsonParse,
37
38
  serializeModelOptions,
@@ -80,6 +81,33 @@ import { CacheControlValidator } from './get-cache-control';
80
81
  import { mapAnthropicStopReason } from './map-anthropic-stop-reason';
81
82
  import { sanitizeJsonSchema } from './sanitize-json-schema';
82
83
  import { supportsNativeStructuredOutputSchema } from './supports-native-structured-output-schema';
84
+ import { computerToolset_20260801Members } from './tool/computer-toolset_20260801';
85
+
86
+ function validateToolsetMember({
87
+ toolsetName,
88
+ memberName,
89
+ tools,
90
+ }: {
91
+ toolsetName: string;
92
+ memberName: string;
93
+ tools: AnthropicTool[] | undefined;
94
+ }): void {
95
+ const toolset = tools?.find(
96
+ tool => 'type' in tool && tool.type === 'computer_toolset_20260801',
97
+ );
98
+
99
+ if (
100
+ toolsetName !== 'computer' ||
101
+ toolset == null ||
102
+ !computerToolset_20260801Members.some(member => member === memberName) ||
103
+ toolset.configs?.[memberName]?.enabled === false
104
+ ) {
105
+ throw new InvalidResponseDataError({
106
+ data: { toolsetName, memberName },
107
+ message: `Received an unavailable toolset member: ${toolsetName}.${memberName}.`,
108
+ });
109
+ }
110
+ }
83
111
 
84
112
  function createAnthropicStreamError(error: {
85
113
  message: string;
@@ -239,11 +267,16 @@ function toToolsetMemberInput({
239
267
  memberName: string;
240
268
  input: unknown;
241
269
  }): JSONObject {
270
+ if (typeof input !== 'object' || input === null || Array.isArray(input)) {
271
+ throw new InvalidResponseDataError({
272
+ data: input,
273
+ message: 'Invalid toolset member input: expected an object.',
274
+ });
275
+ }
276
+
242
277
  return {
278
+ ...(input as JSONObject),
243
279
  action: memberName,
244
- ...(typeof input === 'object' && input !== null && !Array.isArray(input)
245
- ? (input as JSONObject)
246
- : {}),
247
280
  };
248
281
  }
249
282
 
@@ -284,6 +317,16 @@ export type AnthropicLanguageModelConfig = {
284
317
  cacheControlProviderOptionsName?: string;
285
318
  };
286
319
 
320
+ /**
321
+ * Legacy names of custom providerOptions keys, read when the current key is
322
+ * absent.
323
+ */
324
+ const LEGACY_PROVIDER_OPTIONS_NAMES: Record<string, readonly string[]> = {
325
+ // The Google Vertex Anthropic provider was renamed from `vertex` to
326
+ // `googleVertex`, which silently changed its custom providerOptions key.
327
+ googleVertex: ['vertex'],
328
+ };
329
+
287
330
  const TEXT_OR_THINKING_BLOCK_TYPES = new Set<string>([
288
331
  'redacted_thinking',
289
332
  'text',
@@ -451,17 +494,32 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
451
494
  schema: anthropicLanguageModelOptions,
452
495
  });
453
496
 
454
- const customProviderOptions =
455
- providerOptionsName !== 'anthropic'
456
- ? await parseProviderOptions({
457
- provider: providerOptionsName,
458
- providerOptions,
459
- schema: anthropicLanguageModelOptions,
460
- })
461
- : null;
497
+ // The custom key and its legacy aliases are alternatives: the first
498
+ // present one is used.
499
+ const {
500
+ options: customProviderOptions,
501
+ namespaces: [customProviderOptionsName],
502
+ } = await resolveProviderOptions({
503
+ providerOptions,
504
+ namespaces:
505
+ providerOptionsName !== 'anthropic'
506
+ ? [
507
+ providerOptionsName,
508
+ ...(Object.hasOwn(
509
+ LEGACY_PROVIDER_OPTIONS_NAMES,
510
+ providerOptionsName,
511
+ )
512
+ ? LEGACY_PROVIDER_OPTIONS_NAMES[providerOptionsName]
513
+ : []),
514
+ ]
515
+ : [],
516
+ resolution: 'first',
517
+ schema: anthropicLanguageModelOptions,
518
+ });
462
519
 
463
520
  // Track if custom key was explicitly used
464
- const usedCustomProviderKey = customProviderOptions != null;
521
+ const usedCustomProviderKey =
522
+ customProviderOptionsName === providerOptionsName;
465
523
 
466
524
  // Merge options
467
525
  const anthropicOptions = Object.assign(
@@ -688,6 +746,10 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
688
746
  });
689
747
 
690
748
  const toolsetNames = getAnthropicToolsetNames(tools);
749
+ const inlineToolDefinitions: Array<{
750
+ sdkName: string;
751
+ definition: AnthropicTool;
752
+ }> = [];
691
753
 
692
754
  const { prompt: messagesPrompt, betas } = await convertToAnthropicPrompt({
693
755
  prompt,
@@ -713,6 +775,13 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
713
775
  // between streaming and non-streaming calls to keep the cache.
714
776
  });
715
777
 
778
+ if (definitions?.[0] != null) {
779
+ inlineToolDefinitions.push({
780
+ sdkName: tool.name,
781
+ definition: definitions[0],
782
+ });
783
+ }
784
+
716
785
  return {
717
786
  definition: definitions?.[0],
718
787
  warnings: toolWarnings,
@@ -1287,6 +1356,72 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
1287
1356
  },
1288
1357
  );
1289
1358
 
1359
+ // Forced-choice and JSON-tool fallbacks restrict the declared tools.
1360
+ // MCP connectors and inline definitions, including those replayed from
1361
+ // history, must not restore other tools before the provider executes the request.
1362
+ if (
1363
+ (toolChoice?.type === 'tool' &&
1364
+ (anthropicToolChoice?.type === 'auto' || jsonResponseTool != null)) ||
1365
+ (toolChoice?.type === 'none' && jsonResponseTool != null)
1366
+ ) {
1367
+ for (const server of baseArgs.mcp_servers ?? []) {
1368
+ server.tool_configuration = {
1369
+ allowed_tools: server.tool_configuration?.allowed_tools,
1370
+ enabled: false,
1371
+ };
1372
+ }
1373
+
1374
+ // Initial system tool changes are ignored by the prompt converter.
1375
+ // Validate only definitions that remain in the outgoing messages.
1376
+ const emittedInlineDefinitions = new Set(
1377
+ messagesPrompt.messages.flatMap(message =>
1378
+ message.role === 'system'
1379
+ ? message.content.flatMap(part =>
1380
+ part.type === 'tool_addition' &&
1381
+ part.tool.type === 'tool_definition'
1382
+ ? [part.tool.definition]
1383
+ : [],
1384
+ )
1385
+ : [],
1386
+ ),
1387
+ );
1388
+ const selectedSdkName =
1389
+ toolChoice.type === 'tool' ? toolChoice.toolName : undefined;
1390
+ const selectedTool = tools?.find(tool => tool.name === selectedSdkName);
1391
+ const selectedProviderName =
1392
+ jsonResponseTool != null &&
1393
+ selectedSdkName != null &&
1394
+ selectedTool?.type !== 'function'
1395
+ ? toolNameMapping.toProviderToolName(selectedSdkName)
1396
+ : selectedSdkName;
1397
+ const conflictingTool = inlineToolDefinitions.find(
1398
+ ({ sdkName, definition }) =>
1399
+ emittedInlineDefinitions.has(definition) &&
1400
+ (toolChoice.type === 'none' ||
1401
+ // The JSON-tool path filters application tools by SDK name before
1402
+ // conversion; the forced-choice fallback filters by provider name.
1403
+ (jsonResponseTool != null && sdkName !== selectedSdkName) ||
1404
+ !('name' in definition) ||
1405
+ definition.name !== selectedProviderName),
1406
+ );
1407
+ if (conflictingTool != null) {
1408
+ const toolName =
1409
+ 'name' in conflictingTool.definition
1410
+ ? conflictingTool.definition.name
1411
+ : conflictingTool.definition.type;
1412
+ const choice =
1413
+ toolChoice.type === 'tool'
1414
+ ? `named tool choice '${toolChoice.toolName}'`
1415
+ : `tool choice 'none'`;
1416
+ throw new InvalidArgumentError({
1417
+ argument: 'toolChoice',
1418
+ message:
1419
+ `Inline tool '${toolName}' conflicts with ${choice}. ` +
1420
+ 'Inline definitions must respect the tool choice when forced tool use falls back or the JSON response tool is used.',
1421
+ });
1422
+ }
1423
+ }
1424
+
1290
1425
  // Extract cache control warnings once at the end
1291
1426
  const cacheWarnings = cacheControlValidator.getWarnings();
1292
1427
 
@@ -1310,6 +1445,7 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
1310
1445
  usesJsonResponseTool: jsonResponseTool != null,
1311
1446
  includePings: stream === true && anthropicOptions?.includePings === true,
1312
1447
  toolNameMapping,
1448
+ preparedTools: anthropicTools,
1313
1449
  providerOptionsName,
1314
1450
  usedCustomProviderKey,
1315
1451
  };
@@ -1438,6 +1574,7 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
1438
1574
  usesJsonResponseTool,
1439
1575
  markCodeExecutionDynamic,
1440
1576
  toolNameMapping,
1577
+ preparedTools,
1441
1578
  providerOptionsName,
1442
1579
  usedCustomProviderKey,
1443
1580
  } = await this.getArgs({
@@ -1606,6 +1743,11 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
1606
1743
  text: JSON.stringify(part.input),
1607
1744
  });
1608
1745
  } else if (part.toolset_name != null) {
1746
+ validateToolsetMember({
1747
+ toolsetName: part.toolset_name,
1748
+ memberName: part.name,
1749
+ tools: preparedTools,
1750
+ });
1609
1751
  // toolset member calls (e.g. the computer toolset) are mapped to
1610
1752
  // the toolset tool with the member name as the `action`:
1611
1753
  content.push({
@@ -2104,6 +2246,7 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
2104
2246
  markCodeExecutionDynamic,
2105
2247
  includePings,
2106
2248
  toolNameMapping,
2249
+ preparedTools,
2107
2250
  providerOptionsName,
2108
2251
  usedCustomProviderKey,
2109
2252
  } = await this.getArgs({
@@ -2395,6 +2538,11 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
2395
2538
  id: String(value.index),
2396
2539
  });
2397
2540
  } else if (part.toolset_name != null) {
2541
+ validateToolsetMember({
2542
+ toolsetName: part.toolset_name,
2543
+ memberName: part.name,
2544
+ tools: preparedTools,
2545
+ });
2398
2546
  const callerInfo = getAnthropicCallerInfo(part.caller);
2399
2547
  const customToolName = toolNameMapping.toCustomToolName(
2400
2548
  part.toolset_name,
@@ -2918,19 +3066,18 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
2918
3066
  ? {}
2919
3067
  : secureJsonParse(contentBlock.input);
2920
3068
  } catch {
2921
- // ignore parse errors, fall back to the raw input
2922
- memberInput = undefined;
3069
+ throw new InvalidResponseDataError({
3070
+ data: contentBlock.input,
3071
+ message: 'Invalid toolset member input JSON.',
3072
+ });
2923
3073
  }
2924
3074
 
2925
- contentBlock.input =
2926
- memberInput === undefined
2927
- ? contentBlock.input
2928
- : JSON.stringify(
2929
- toToolsetMemberInput({
2930
- memberName: contentBlock.toolset.memberName,
2931
- input: memberInput,
2932
- }),
2933
- );
3075
+ contentBlock.input = JSON.stringify(
3076
+ toToolsetMemberInput({
3077
+ memberName: contentBlock.toolset.memberName,
3078
+ input: memberInput,
3079
+ }),
3080
+ );
2934
3081
 
2935
3082
  controller.enqueue({
2936
3083
  type: 'tool-input-delta',
@@ -33,30 +33,39 @@ export const computerToolset_20260801Members = [
33
33
  export type ComputerToolset_20260801Member =
34
34
  (typeof computerToolset_20260801Members)[number];
35
35
 
36
- const computerToolset_20260801InputSchema = lazySchema(() =>
37
- zodSchema(
38
- z.object({
39
- action: z.enum(computerToolset_20260801Members),
40
- coordinate: z.tuple([z.number().int(), z.number().int()]).optional(),
41
- duration: z.number().optional(),
42
- region: z
43
- .tuple([
44
- z.number().int(),
45
- z.number().int(),
46
- z.number().int(),
47
- z.number().int(),
48
- ])
49
- .optional(),
50
- repeat: z.number().int().optional(),
51
- scroll_amount: z.number().optional(),
52
- scroll_direction: z.enum(['up', 'down', 'left', 'right']).optional(),
53
- start_coordinate: z
54
- .tuple([z.number().int(), z.number().int()])
55
- .optional(),
56
- text: z.string().optional(),
57
- }),
58
- ),
59
- );
36
+ const computerToolset_20260801InputSchema = (
37
+ configs?: Partial<
38
+ Record<ComputerToolset_20260801Member, { enabled?: boolean }>
39
+ >,
40
+ ) =>
41
+ lazySchema(() =>
42
+ zodSchema(
43
+ z.object({
44
+ action: z.enum(
45
+ computerToolset_20260801Members.filter(
46
+ member => configs?.[member]?.enabled !== false,
47
+ ),
48
+ ),
49
+ coordinate: z.tuple([z.number().int(), z.number().int()]).optional(),
50
+ duration: z.number().optional(),
51
+ region: z
52
+ .tuple([
53
+ z.number().int(),
54
+ z.number().int(),
55
+ z.number().int(),
56
+ z.number().int(),
57
+ ])
58
+ .optional(),
59
+ repeat: z.number().int().optional(),
60
+ scroll_amount: z.number().optional(),
61
+ scroll_direction: z.enum(['up', 'down', 'left', 'right']).optional(),
62
+ start_coordinate: z
63
+ .tuple([z.number().int(), z.number().int()])
64
+ .optional(),
65
+ text: z.string().optional(),
66
+ }),
67
+ ),
68
+ );
60
69
 
61
70
  export const computerToolset_20260801ArgsSchema = lazySchema(() =>
62
71
  zodSchema(
@@ -74,7 +83,7 @@ export const computerToolset_20260801ArgsSchema = lazySchema(() =>
74
83
  ),
75
84
  );
76
85
 
77
- export const computerToolset_20260801 = createProviderDefinedToolFactory<
86
+ const factory = createProviderDefinedToolFactory<
78
87
  {
79
88
  /**
80
89
  * The member tool that Claude invoked. Each member is returned by the API
@@ -161,5 +170,10 @@ export const computerToolset_20260801 = createProviderDefinedToolFactory<
161
170
  }
162
171
  >({
163
172
  id: 'anthropic.computer_toolset_20260801',
164
- inputSchema: computerToolset_20260801InputSchema,
173
+ inputSchema: computerToolset_20260801InputSchema(),
174
+ });
175
+
176
+ export const computerToolset_20260801: typeof factory = args => ({
177
+ ...factory(args),
178
+ inputSchema: computerToolset_20260801InputSchema(args.configs),
165
179
  });