@ai-sdk/anthropic 3.0.137 → 3.0.139

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.
@@ -152,7 +152,7 @@ The following optional provider options are available for Anthropic models:
152
152
 
153
153
  - `"outputFormat"`: Use the `output_format` parameter to specify the structured output format.
154
154
  - `"jsonTool"`: Use a special `"json"` tool to specify the structured output format.
155
- - `"auto"`: Use `"outputFormat"` when supported, otherwise fall back to `"jsonTool"` (default).
155
+ - `"auto"`: Use `"outputFormat"` when the model and schema support it, otherwise fall back to `"jsonTool"` (default). Schemas with recursive references, open objects, or more than ten optional properties use the JSON-tool fallback to avoid rejected requests or lost data.
156
156
 
157
157
  - `metadata` _object_
158
158
 
@@ -203,7 +203,21 @@ schemas with open objects such as maps (`additionalProperties` set to a schema
203
203
  or `true`), which native structured outputs would return as `{}`.
204
204
  Likewise, a `required` or named `toolChoice` is downgraded to
205
205
  `auto` with a warning; instruct the model to use the tool in your prompt and
206
- verify that a tool call was made.
206
+ verify that a tool call was made. When a named choice falls back to `auto`,
207
+ inline tool additions must use the selected tool's name. Conflicting additions,
208
+ including definitions replayed from conversation history, cause an
209
+ `InvalidArgumentError` before the request is sent.
210
+
211
+ The JSON-tool fallback limits which application tools are available:
212
+ `toolChoice: 'none'` sends only the internal JSON response tool, and a named tool
213
+ choice sends only that application tool alongside the JSON response tool. The
214
+ fallback can produce a JSON response without calling the named application tool;
215
+ verify the selected call if your application requires it.
216
+ These restrictions also apply to inline tool definitions: a named choice allows
217
+ only additions with the selected tool's name, and `toolChoice: 'none'` rejects
218
+ all inline additions. Conflicting definitions cause an `InvalidArgumentError`
219
+ before the request is sent. Tool changes on the initial system message remain
220
+ ignored with a warning.
207
221
 
208
222
  When the JSON tool cannot be forced (for example with manual thinking) and the
209
223
  model answers in text without calling it, the text of its final answer is
@@ -712,6 +726,9 @@ the selected tool is sent. This also applies when the top-level `reasoning`
712
726
  option enables manual thinking, including when structured output uses the
713
727
  internal JSON response tool. Tool use is no longer guaranteed: instruct the
714
728
  model to use the tool in your prompt and verify that a tool call was made.
729
+ Inline tool additions must use the selected tool's name when a named choice
730
+ falls back to `auto`. Conflicting additions, including definitions replayed from
731
+ conversation history, cause an `InvalidArgumentError` before the request is sent.
715
732
 
716
733
  See [AI SDK UI: Chatbot](/docs/ai-sdk-ui/chatbot#reasoning) for more details
717
734
  on how to integrate reasoning into your chatbot.
@@ -1634,7 +1651,61 @@ const result = await generateText({
1634
1651
  });
1635
1652
  ```
1636
1653
 
1637
- To change a tool's definition, remove the old definition at the end of one request, then carry the conversation forward with the updated definition in `tools` on the next request.
1654
+ #### Defining Tools by Value
1655
+
1656
+ A `tool_addition` can also define the tool by value with `tool`, in the same shape as an entry of the `tools` option. The tool does not need to be declared in `tools` up front, which lets you introduce tools that did not exist when the conversation started, for example after an MCP server connects. Defining a tool under an existing name replaces the earlier definition from that point on, so this also changes a tool's schema mid-conversation. The required `inline-tools-2026-09-15` beta header is added automatically.
1657
+
1658
+ ```ts
1659
+ import { anthropic } from '@ai-sdk/anthropic';
1660
+ import { generateText } from 'ai';
1661
+
1662
+ const result = await generateText({
1663
+ model: anthropic('claude-opus-4-8'),
1664
+ // required for system messages inside `messages`:
1665
+ allowSystemInMessages: true,
1666
+ messages: [
1667
+ { role: 'user', content: 'What is the weather forecast for Paris?' },
1668
+ {
1669
+ role: 'system',
1670
+ content: '',
1671
+ providerOptions: {
1672
+ anthropic: {
1673
+ toolChanges: [
1674
+ {
1675
+ type: 'tool_addition',
1676
+ tool: {
1677
+ type: 'function',
1678
+ name: 'get_forecast',
1679
+ description: 'Get 5-day forecast',
1680
+ inputSchema: {
1681
+ type: 'object',
1682
+ properties: { city: { type: 'string' } },
1683
+ required: ['city'],
1684
+ },
1685
+ },
1686
+ },
1687
+ ],
1688
+ },
1689
+ },
1690
+ },
1691
+ ],
1692
+ });
1693
+ ```
1694
+
1695
+ <Note>
1696
+ A tool defined by value is only known to the model. It is not part of the
1697
+ `tools` option, so functions like `generateText` cannot execute its calls. Use
1698
+ it when you handle the tool calls yourself, or declare the tool in `tools` and
1699
+ add it by reference with `toolName` to have the AI SDK execute it.
1700
+ `inputSchema` is a plain JSON Schema object.
1701
+ </Note>
1702
+
1703
+ <Note>
1704
+ The computer use tools cannot be defined in a message. Declare them in `tools`
1705
+ and add them by reference with `toolName`. The AI SDK ignores such an addition
1706
+ and emits a warning. A `tool_removal` always references the tool by
1707
+ `toolName`.
1708
+ </Note>
1638
1709
 
1639
1710
  <Note>
1640
1711
  Tool changes are not supported on the initial system message. The AI SDK
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/anthropic",
3
- "version": "3.0.137",
3
+ "version": "3.0.139",
4
4
  "license": "Apache-2.0",
5
5
  "sideEffects": false,
6
6
  "main": "./dist/index.js",
@@ -37,7 +37,7 @@
37
37
  },
38
38
  "dependencies": {
39
39
  "@ai-sdk/provider": "3.0.19",
40
- "@ai-sdk/provider-utils": "4.0.63"
40
+ "@ai-sdk/provider-utils": "4.0.64"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@types/node": "20.17.24",
@@ -35,13 +35,26 @@ export interface AnthropicSystemMessage {
35
35
  * conversation's tool set without invalidating the prompt cache.
36
36
  *
37
37
  * Only valid inside system messages that appear in the `messages` array.
38
- * Requires the `mid-conversation-tool-changes-2026-07-01` beta.
38
+ * Changes by reference require the `mid-conversation-tool-changes-2026-07-01`
39
+ * beta. Additions by value (`tool_definition`) require the
40
+ * `inline-tools-2026-09-15` beta, which also covers changes by reference.
39
41
  */
40
- export interface AnthropicToolChangeContent {
41
- type: 'tool_addition' | 'tool_removal';
42
- tool: { type: 'tool_reference'; name: string };
43
- cache_control?: never;
44
- }
42
+ export type AnthropicToolChangeContent =
43
+ | {
44
+ type: 'tool_addition' | 'tool_removal';
45
+ tool: { type: 'tool_reference'; name: string };
46
+ cache_control?: never;
47
+ }
48
+ | {
49
+ type: 'tool_addition';
50
+ /**
51
+ * The tool definition, in the same shape as an entry of the top-level
52
+ * `tools` array. It replaces any earlier definition with the same name
53
+ * from this point on.
54
+ */
55
+ tool: { type: 'tool_definition'; definition: AnthropicTool };
56
+ cache_control?: never;
57
+ };
45
58
 
46
59
  export interface AnthropicUserMessage {
47
60
  role: 'user';
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  APICallError,
3
+ InvalidArgumentError,
3
4
  InvalidResponseDataError,
4
5
  type JSONObject,
5
6
  type LanguageModelV3,
@@ -58,6 +59,7 @@ import {
58
59
  } from './convert-anthropic-messages-usage';
59
60
  import {
60
61
  convertToAnthropicMessagesPrompt,
62
+ getInlineToolsFromPrompt,
61
63
  type AnthropicMediaPartConverter,
62
64
  } from './convert-to-anthropic-messages-prompt';
63
65
  import { CacheControlValidator } from './get-cache-control';
@@ -449,6 +451,11 @@ export class AnthropicMessagesLanguageModel implements LanguageModelV3 {
449
451
  (this.config.supportsNativeStructuredOutput ?? true) &&
450
452
  modelSupportsStructuredOutput;
451
453
 
454
+ const supportsResponseSchema =
455
+ responseFormat?.type !== 'json' ||
456
+ responseFormat.schema == null ||
457
+ supportsNativeStructuredOutputSchema(responseFormat.schema);
458
+
452
459
  const supportsStrictTools =
453
460
  (this.config.supportsStrictTools ?? true) &&
454
461
  modelSupportsStructuredOutput;
@@ -457,7 +464,9 @@ export class AnthropicMessagesLanguageModel implements LanguageModelV3 {
457
464
  anthropicOptions?.structuredOutputMode ?? 'auto';
458
465
  let useStructuredOutput =
459
466
  structureOutputMode === 'outputFormat' ||
460
- (structureOutputMode === 'auto' && supportsStructuredOutput);
467
+ (structureOutputMode === 'auto' &&
468
+ supportsStructuredOutput &&
469
+ supportsResponseSchema);
461
470
 
462
471
  // The JSON response tool relies on forced tool use, which some models
463
472
  // reject (e.g. Opus 5.5, Fable 5.1). Fall back to native structured
@@ -513,8 +522,34 @@ export class AnthropicMessagesLanguageModel implements LanguageModelV3 {
513
522
  this.config.cacheControlProviderOptionsName,
514
523
  );
515
524
 
525
+ const defaultEagerInputStreaming =
526
+ stream && (anthropicOptions?.toolStreaming ?? true);
527
+
528
+ // Tools that tool changes add by value are only known from the prompt.
529
+ const inlineTools = await getInlineToolsFromPrompt(prompt);
530
+
531
+ // function tools are not part of the name mapping, so an inline provider
532
+ // tool must not reuse the name of a declared function: references to that
533
+ // name would otherwise resolve to the provider tool.
534
+ const declaredFunctionToolNames = new Set(
535
+ (tools ?? []).flatMap(tool =>
536
+ tool.type === 'function' ? [tool.name] : [],
537
+ ),
538
+ );
539
+
516
540
  const toolNameMapping = createToolNameMapping({
517
- tools,
541
+ // later entries win when provider tool names collide, so the declared
542
+ // tools go last and an inline tool cannot take over their mapping:
543
+ tools: [
544
+ ...inlineTools.filter(
545
+ tool =>
546
+ !(
547
+ tool.type === 'provider' &&
548
+ declaredFunctionToolNames.has(tool.name)
549
+ ),
550
+ ),
551
+ ...(tools ?? []),
552
+ ],
518
553
  providerToolNames: {
519
554
  'anthropic.code_execution_20250522': 'code_execution',
520
555
  'anthropic.code_execution_20250825': 'code_execution',
@@ -541,6 +576,10 @@ export class AnthropicMessagesLanguageModel implements LanguageModelV3 {
541
576
  });
542
577
 
543
578
  const toolsetNames = getAnthropicToolsetNames(tools);
579
+ const inlineToolDefinitions: Array<{
580
+ sdkName: string;
581
+ definition: AnthropicTool;
582
+ }> = [];
544
583
 
545
584
  const { prompt: messagesPrompt, betas } =
546
585
  await convertToAnthropicMessagesPrompt({
@@ -551,6 +590,36 @@ export class AnthropicMessagesLanguageModel implements LanguageModelV3 {
551
590
  toolNameMapping,
552
591
  toolsetNames,
553
592
  convertMediaPart: this.config.convertMediaPart,
593
+ convertInlineTool: async tool => {
594
+ const {
595
+ tools: definitions,
596
+ toolWarnings,
597
+ betas,
598
+ } = await prepareTools({
599
+ tools: [tool],
600
+ toolChoice: undefined,
601
+ cacheControlValidator,
602
+ supportsStructuredOutput,
603
+ supportsStrictTools,
604
+ // no stream-dependent defaults (eager input streaming): the
605
+ // definition is replayed on every request and has to stay
606
+ // identical between streaming and non-streaming calls to keep
607
+ // the cache.
608
+ });
609
+
610
+ if (definitions?.[0] != null) {
611
+ inlineToolDefinitions.push({
612
+ sdkName: tool.name,
613
+ definition: definitions[0],
614
+ });
615
+ }
616
+
617
+ return {
618
+ definition: definitions?.[0],
619
+ warnings: toolWarnings,
620
+ betas,
621
+ };
622
+ },
554
623
  });
555
624
 
556
625
  // Some models always run adaptive thinking and reject `disabled` thinking
@@ -996,9 +1065,6 @@ export class AnthropicMessagesLanguageModel implements LanguageModelV3 {
996
1065
  betas.add('server-side-fallback-2026-06-01');
997
1066
  }
998
1067
 
999
- const defaultEagerInputStreaming =
1000
- stream && (anthropicOptions?.toolStreaming ?? true);
1001
-
1002
1068
  const {
1003
1069
  tools: anthropicTools,
1004
1070
  toolChoice: anthropicToolChoice,
@@ -1007,7 +1073,15 @@ export class AnthropicMessagesLanguageModel implements LanguageModelV3 {
1007
1073
  } = await prepareTools(
1008
1074
  jsonResponseTool != null
1009
1075
  ? {
1010
- tools: [...(tools ?? []), jsonResponseTool],
1076
+ tools: [
1077
+ ...(tools ?? []).filter(
1078
+ tool =>
1079
+ toolChoice?.type !== 'none' &&
1080
+ (toolChoice?.type !== 'tool' ||
1081
+ tool.name === toolChoice.toolName),
1082
+ ),
1083
+ jsonResponseTool,
1084
+ ],
1011
1085
  toolChoice: { type: 'required' },
1012
1086
  disableParallelToolUse: true,
1013
1087
  cacheControlValidator,
@@ -1020,6 +1094,9 @@ export class AnthropicMessagesLanguageModel implements LanguageModelV3 {
1020
1094
  : {
1021
1095
  tools: tools ?? [],
1022
1096
  toolChoice,
1097
+ // tool changes can add tools when `tools` is empty, so the tool
1098
+ // choice and parallel tool use settings still apply:
1099
+ hasInlineTools: inlineTools.length > 0,
1023
1100
  disableParallelToolUse: anthropicOptions?.disableParallelToolUse,
1024
1101
  cacheControlValidator,
1025
1102
  supportsStructuredOutput,
@@ -1030,6 +1107,65 @@ export class AnthropicMessagesLanguageModel implements LanguageModelV3 {
1030
1107
  },
1031
1108
  );
1032
1109
 
1110
+ // Forced-choice and JSON-tool fallbacks restrict the declared tools.
1111
+ // Inline definitions, including those replayed from history, must not
1112
+ // restore other tools before the provider executes the request.
1113
+ if (
1114
+ (toolChoice?.type === 'tool' &&
1115
+ (anthropicToolChoice?.type === 'auto' || jsonResponseTool != null)) ||
1116
+ (toolChoice?.type === 'none' && jsonResponseTool != null)
1117
+ ) {
1118
+ // Initial system tool changes are ignored by the prompt converter.
1119
+ // Validate only definitions that remain in the outgoing messages.
1120
+ const emittedInlineDefinitions = new Set(
1121
+ messagesPrompt.messages.flatMap(message =>
1122
+ message.role === 'system'
1123
+ ? message.content.flatMap(part =>
1124
+ part.type === 'tool_addition' &&
1125
+ part.tool.type === 'tool_definition'
1126
+ ? [part.tool.definition]
1127
+ : [],
1128
+ )
1129
+ : [],
1130
+ ),
1131
+ );
1132
+ const selectedSdkName =
1133
+ toolChoice.type === 'tool' ? toolChoice.toolName : undefined;
1134
+ const selectedTool = tools?.find(tool => tool.name === selectedSdkName);
1135
+ const selectedProviderName =
1136
+ jsonResponseTool != null &&
1137
+ selectedSdkName != null &&
1138
+ selectedTool?.type !== 'function'
1139
+ ? toolNameMapping.toProviderToolName(selectedSdkName)
1140
+ : selectedSdkName;
1141
+ const conflictingTool = inlineToolDefinitions.find(
1142
+ ({ sdkName, definition }) =>
1143
+ emittedInlineDefinitions.has(definition) &&
1144
+ (toolChoice.type === 'none' ||
1145
+ // The JSON-tool path filters application tools by SDK name before
1146
+ // conversion; the forced-choice fallback filters by provider name.
1147
+ (jsonResponseTool != null && sdkName !== selectedSdkName) ||
1148
+ !('name' in definition) ||
1149
+ definition.name !== selectedProviderName),
1150
+ );
1151
+ if (conflictingTool != null) {
1152
+ const toolName =
1153
+ 'name' in conflictingTool.definition
1154
+ ? conflictingTool.definition.name
1155
+ : conflictingTool.definition.type;
1156
+ const choice =
1157
+ toolChoice.type === 'tool'
1158
+ ? `named tool choice '${toolChoice.toolName}'`
1159
+ : `tool choice 'none'`;
1160
+ throw new InvalidArgumentError({
1161
+ argument: 'toolChoice',
1162
+ message:
1163
+ `Inline tool '${toolName}' conflicts with ${choice}. ` +
1164
+ 'Inline definitions must respect the tool choice when forced tool use falls back or the JSON response tool is used.',
1165
+ });
1166
+ }
1167
+ }
1168
+
1033
1169
  // Extract cache control warnings once at the end
1034
1170
  const cacheWarnings = cacheControlValidator.getWarnings();
1035
1171
 
@@ -104,18 +104,44 @@ export const anthropicSystemMessageProviderOptions = lazySchema(() =>
104
104
  * initial system prompt). A system message carrying tool changes must come
105
105
  * right before an assistant message or at the end of the messages.
106
106
  *
107
- * Tools referenced by a `tool_addition` must be declared in the `tools`
108
- * option (typically with `deferLoading: true` so they are not loaded until
109
- * the addition surfaces them). The required
110
- * `mid-conversation-tool-changes-2026-07-01` beta is added automatically.
107
+ * A `tool_addition` either references a tool by `toolName` or defines it
108
+ * by value with `tool`:
109
+ * - By reference: the tool must be declared in the `tools` option
110
+ * (typically with `deferLoading: true` so it is not loaded until the
111
+ * addition surfaces it). The required
112
+ * `mid-conversation-tool-changes-2026-07-01` beta is added
113
+ * automatically.
114
+ * - By value: `tool` is a function or provider tool, in the same shape as
115
+ * an entry of the `tools` option. The tool does not need to be declared
116
+ * in `tools`, and defining a tool under an existing name replaces it
117
+ * from that point on. The required `inline-tools-2026-09-15` beta is
118
+ * added automatically.
119
+ *
120
+ * A `tool_removal` always references the tool by `toolName`.
111
121
  */
112
122
  toolChanges: z
113
123
  .array(
114
- z.discriminatedUnion('type', [
124
+ z.union([
115
125
  z.object({
116
126
  type: z.literal('tool_addition'),
117
127
  toolName: z.string(),
118
128
  }),
129
+ z.object({
130
+ type: z.literal('tool_addition'),
131
+ tool: z.union([
132
+ z.looseObject({
133
+ type: z.literal('function'),
134
+ name: z.string(),
135
+ inputSchema: z.record(z.string(), z.unknown()),
136
+ }),
137
+ z.looseObject({
138
+ type: z.literal('provider'),
139
+ id: z.string(),
140
+ name: z.string(),
141
+ args: z.record(z.string(), z.unknown()),
142
+ }),
143
+ ]),
144
+ }),
119
145
  z.object({
120
146
  type: z.literal('tool_removal'),
121
147
  toolName: z.string(),
@@ -28,6 +28,7 @@ export interface AnthropicToolOptions {
28
28
  export async function prepareTools({
29
29
  tools,
30
30
  toolChoice,
31
+ hasInlineTools = false,
31
32
  disableParallelToolUse,
32
33
  cacheControlValidator,
33
34
  supportsStructuredOutput,
@@ -37,6 +38,13 @@ export async function prepareTools({
37
38
  }: {
38
39
  tools: LanguageModelV3CallOptions['tools'];
39
40
  toolChoice: LanguageModelV3CallOptions['toolChoice'] | undefined;
41
+
42
+ /**
43
+ * Whether tools are added by value in the prompt (mid-conversation tool
44
+ * changes). The model has tools even when `tools` is empty, so the tool
45
+ * choice and parallel tool use settings still need to be sent.
46
+ */
47
+ hasInlineTools?: boolean;
40
48
  disableParallelToolUse?: boolean;
41
49
  cacheControlValidator?: CacheControlValidator;
42
50
 
@@ -75,13 +83,13 @@ export async function prepareTools({
75
83
  const betas = new Set<string>();
76
84
  const validator = cacheControlValidator || new CacheControlValidator();
77
85
 
78
- if (tools == null) {
86
+ if (tools == null && !hasInlineTools) {
79
87
  return { tools: undefined, toolChoice: undefined, toolWarnings, betas };
80
88
  }
81
89
 
82
90
  const anthropicTools: AnthropicTool[] = [];
83
91
 
84
- for (const tool of tools) {
92
+ for (const tool of tools ?? []) {
85
93
  switch (tool.type) {
86
94
  case 'function': {
87
95
  const cacheControl = validator.getCacheControl(tool.providerOptions, {
@@ -424,9 +432,13 @@ export async function prepareTools({
424
432
  }
425
433
  }
426
434
 
435
+ // when the user passed no tools (they exist only in tool changes inside the
436
+ // messages), omit `tools` instead of sending an empty array
437
+ const declaredTools = tools == null ? undefined : anthropicTools;
438
+
427
439
  if (toolChoice == null) {
428
440
  return {
429
- tools: anthropicTools,
441
+ tools: declaredTools,
430
442
  toolChoice: disableParallelToolUse
431
443
  ? { type: 'auto', disable_parallel_tool_use: disableParallelToolUse }
432
444
  : undefined,
@@ -440,7 +452,7 @@ export async function prepareTools({
440
452
  switch (type) {
441
453
  case 'auto':
442
454
  return {
443
- tools: anthropicTools,
455
+ tools: declaredTools,
444
456
  toolChoice: {
445
457
  type: 'auto',
446
458
  disable_parallel_tool_use: disableParallelToolUse,
@@ -458,7 +470,7 @@ export async function prepareTools({
458
470
  `Using 'auto' instead. Instruct the model to use a tool in the prompt and verify that a tool call was made.`,
459
471
  });
460
472
  return {
461
- tools: anthropicTools,
473
+ tools: declaredTools,
462
474
  toolChoice: {
463
475
  type: 'auto',
464
476
  disable_parallel_tool_use: disableParallelToolUse,
@@ -468,7 +480,7 @@ export async function prepareTools({
468
480
  };
469
481
  }
470
482
  return {
471
- tools: anthropicTools,
483
+ tools: declaredTools,
472
484
  toolChoice: {
473
485
  type: 'any',
474
486
  disable_parallel_tool_use: disableParallelToolUse,
@@ -478,7 +490,7 @@ export async function prepareTools({
478
490
  };
479
491
  case 'none':
480
492
  return {
481
- tools: anthropicTools,
493
+ tools: declaredTools,
482
494
  toolChoice: { type: 'none' },
483
495
  toolWarnings,
484
496
  betas,
@@ -494,7 +506,7 @@ export async function prepareTools({
494
506
  `Instruct the model to use the tool in the prompt and verify that a tool call was made.`,
495
507
  });
496
508
  return {
497
- tools: anthropicTools.filter(
509
+ tools: declaredTools?.filter(
498
510
  tool => 'name' in tool && tool.name === toolChoice.toolName,
499
511
  ),
500
512
  toolChoice: {
@@ -506,7 +518,7 @@ export async function prepareTools({
506
518
  };
507
519
  }
508
520
  return {
509
- tools: anthropicTools,
521
+ tools: declaredTools,
510
522
  toolChoice: {
511
523
  type: 'tool',
512
524
  name: toolChoice.toolName,