@ai-sdk/anthropic 3.0.138 → 3.0.140

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.
@@ -203,13 +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.
207
210
 
208
211
  The JSON-tool fallback limits which application tools are available:
209
212
  `toolChoice: 'none'` sends only the internal JSON response tool, and a named tool
210
213
  choice sends only that application tool alongside the JSON response tool. The
211
214
  fallback can produce a JSON response without calling the named application tool;
212
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.
213
221
 
214
222
  When the JSON tool cannot be forced (for example with manual thinking) and the
215
223
  model answers in text without calling it, the text of its final answer is
@@ -718,6 +726,9 @@ the selected tool is sent. This also applies when the top-level `reasoning`
718
726
  option enables manual thinking, including when structured output uses the
719
727
  internal JSON response tool. Tool use is no longer guaranteed: instruct the
720
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.
721
732
 
722
733
  See [AI SDK UI: Chatbot](/docs/ai-sdk-ui/chatbot#reasoning) for more details
723
734
  on how to integrate reasoning into your chatbot.
@@ -1640,7 +1651,61 @@ const result = await generateText({
1640
1651
  });
1641
1652
  ```
1642
1653
 
1643
- 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>
1644
1709
 
1645
1710
  <Note>
1646
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.138",
3
+ "version": "3.0.140",
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.64"
40
+ "@ai-sdk/provider-utils": "4.0.65"
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';
@@ -520,8 +522,34 @@ export class AnthropicMessagesLanguageModel implements LanguageModelV3 {
520
522
  this.config.cacheControlProviderOptionsName,
521
523
  );
522
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
+
523
540
  const toolNameMapping = createToolNameMapping({
524
- 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
+ ],
525
553
  providerToolNames: {
526
554
  'anthropic.code_execution_20250522': 'code_execution',
527
555
  'anthropic.code_execution_20250825': 'code_execution',
@@ -548,6 +576,10 @@ export class AnthropicMessagesLanguageModel implements LanguageModelV3 {
548
576
  });
549
577
 
550
578
  const toolsetNames = getAnthropicToolsetNames(tools);
579
+ const inlineToolDefinitions: Array<{
580
+ sdkName: string;
581
+ definition: AnthropicTool;
582
+ }> = [];
551
583
 
552
584
  const { prompt: messagesPrompt, betas } =
553
585
  await convertToAnthropicMessagesPrompt({
@@ -558,6 +590,36 @@ export class AnthropicMessagesLanguageModel implements LanguageModelV3 {
558
590
  toolNameMapping,
559
591
  toolsetNames,
560
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
+ },
561
623
  });
562
624
 
563
625
  // Some models always run adaptive thinking and reject `disabled` thinking
@@ -1003,9 +1065,6 @@ export class AnthropicMessagesLanguageModel implements LanguageModelV3 {
1003
1065
  betas.add('server-side-fallback-2026-06-01');
1004
1066
  }
1005
1067
 
1006
- const defaultEagerInputStreaming =
1007
- stream && (anthropicOptions?.toolStreaming ?? true);
1008
-
1009
1068
  const {
1010
1069
  tools: anthropicTools,
1011
1070
  toolChoice: anthropicToolChoice,
@@ -1035,6 +1094,9 @@ export class AnthropicMessagesLanguageModel implements LanguageModelV3 {
1035
1094
  : {
1036
1095
  tools: tools ?? [],
1037
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,
1038
1100
  disableParallelToolUse: anthropicOptions?.disableParallelToolUse,
1039
1101
  cacheControlValidator,
1040
1102
  supportsStructuredOutput,
@@ -1045,6 +1107,72 @@ export class AnthropicMessagesLanguageModel implements LanguageModelV3 {
1045
1107
  },
1046
1108
  );
1047
1109
 
1110
+ // Forced-choice and JSON-tool fallbacks restrict the declared tools.
1111
+ // MCP connectors and inline definitions, including those replayed from
1112
+ // history, must not 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
+ for (const server of baseArgs.mcp_servers ?? []) {
1119
+ server.tool_configuration = {
1120
+ allowed_tools: server.tool_configuration?.allowed_tools,
1121
+ enabled: false,
1122
+ };
1123
+ }
1124
+
1125
+ // Initial system tool changes are ignored by the prompt converter.
1126
+ // Validate only definitions that remain in the outgoing messages.
1127
+ const emittedInlineDefinitions = new Set(
1128
+ messagesPrompt.messages.flatMap(message =>
1129
+ message.role === 'system'
1130
+ ? message.content.flatMap(part =>
1131
+ part.type === 'tool_addition' &&
1132
+ part.tool.type === 'tool_definition'
1133
+ ? [part.tool.definition]
1134
+ : [],
1135
+ )
1136
+ : [],
1137
+ ),
1138
+ );
1139
+ const selectedSdkName =
1140
+ toolChoice.type === 'tool' ? toolChoice.toolName : undefined;
1141
+ const selectedTool = tools?.find(tool => tool.name === selectedSdkName);
1142
+ const selectedProviderName =
1143
+ jsonResponseTool != null &&
1144
+ selectedSdkName != null &&
1145
+ selectedTool?.type !== 'function'
1146
+ ? toolNameMapping.toProviderToolName(selectedSdkName)
1147
+ : selectedSdkName;
1148
+ const conflictingTool = inlineToolDefinitions.find(
1149
+ ({ sdkName, definition }) =>
1150
+ emittedInlineDefinitions.has(definition) &&
1151
+ (toolChoice.type === 'none' ||
1152
+ // The JSON-tool path filters application tools by SDK name before
1153
+ // conversion; the forced-choice fallback filters by provider name.
1154
+ (jsonResponseTool != null && sdkName !== selectedSdkName) ||
1155
+ !('name' in definition) ||
1156
+ definition.name !== selectedProviderName),
1157
+ );
1158
+ if (conflictingTool != null) {
1159
+ const toolName =
1160
+ 'name' in conflictingTool.definition
1161
+ ? conflictingTool.definition.name
1162
+ : conflictingTool.definition.type;
1163
+ const choice =
1164
+ toolChoice.type === 'tool'
1165
+ ? `named tool choice '${toolChoice.toolName}'`
1166
+ : `tool choice 'none'`;
1167
+ throw new InvalidArgumentError({
1168
+ argument: 'toolChoice',
1169
+ message:
1170
+ `Inline tool '${toolName}' conflicts with ${choice}. ` +
1171
+ 'Inline definitions must respect the tool choice when forced tool use falls back or the JSON response tool is used.',
1172
+ });
1173
+ }
1174
+ }
1175
+
1048
1176
  // Extract cache control warnings once at the end
1049
1177
  const cacheWarnings = cacheControlValidator.getWarnings();
1050
1178
 
@@ -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,
@@ -3,8 +3,10 @@ import {
3
3
  type SharedV3Warning,
4
4
  type LanguageModelV3DataContent,
5
5
  type LanguageModelV3FilePart,
6
+ type LanguageModelV3FunctionTool,
6
7
  type LanguageModelV3Message,
7
8
  type LanguageModelV3Prompt,
9
+ type LanguageModelV3ProviderTool,
8
10
  type SharedV3ProviderMetadata,
9
11
  } from '@ai-sdk/provider';
10
12
  import {
@@ -25,6 +27,7 @@ import {
25
27
  type AnthropicMessagesPrompt,
26
28
  type AnthropicSystemMessage,
27
29
  type AnthropicTextContent,
30
+ type AnthropicTool,
28
31
  type AnthropicToolChangeContent,
29
32
  type AnthropicToolCallCaller,
30
33
  type AnthropicToolResultContent,
@@ -121,6 +124,66 @@ export type AnthropicMediaPartConverter = (
121
124
  | undefined
122
125
  >;
123
126
 
127
+ // The computer use tools cannot be defined in a message (the API rejects
128
+ // them), they must be declared in `tools` and added by reference.
129
+ function isComputerTool(
130
+ tool: LanguageModelV3FunctionTool | LanguageModelV3ProviderTool,
131
+ ): boolean {
132
+ return tool.type === 'provider' && tool.id.startsWith('anthropic.computer_');
133
+ }
134
+
135
+ /**
136
+ * Collects the tools that mid-conversation tool changes add by value, so they
137
+ * can take part in tool name mapping like the tools of the `tools` option.
138
+ * Tools that cannot be added by value are left out because they are ignored.
139
+ */
140
+ export async function getInlineToolsFromPrompt(
141
+ prompt: LanguageModelV3Prompt,
142
+ ): Promise<Array<LanguageModelV3FunctionTool | LanguageModelV3ProviderTool>> {
143
+ const inlineTools: Array<
144
+ LanguageModelV3FunctionTool | LanguageModelV3ProviderTool
145
+ > = [];
146
+
147
+ for (const message of prompt) {
148
+ if (message.role !== 'system' || message.providerOptions == null) {
149
+ continue;
150
+ }
151
+
152
+ const options = await parseProviderOptions({
153
+ provider: 'anthropic',
154
+ providerOptions: message.providerOptions,
155
+ schema: anthropicSystemMessageProviderOptions,
156
+ });
157
+
158
+ for (const toolChange of options?.toolChanges ?? []) {
159
+ if ('tool' in toolChange) {
160
+ const tool = toolChange.tool as
161
+ | LanguageModelV3FunctionTool
162
+ | LanguageModelV3ProviderTool;
163
+
164
+ if (!isComputerTool(tool)) {
165
+ inlineTools.push(tool);
166
+ }
167
+ }
168
+ }
169
+ }
170
+
171
+ return inlineTools;
172
+ }
173
+
174
+ /**
175
+ * Converts a tool that is defined by value in a mid-conversation tool change
176
+ * into the Anthropic tool definition, the same way entries of the top-level
177
+ * `tools` option are converted.
178
+ */
179
+ export type AnthropicInlineToolConverter = (
180
+ tool: LanguageModelV3FunctionTool | LanguageModelV3ProviderTool,
181
+ ) => Promise<{
182
+ definition: AnthropicTool | undefined;
183
+ warnings: SharedV3Warning[];
184
+ betas: Set<string>;
185
+ }>;
186
+
124
187
  export async function convertToAnthropicMessagesPrompt({
125
188
  prompt,
126
189
  sendReasoning,
@@ -129,6 +192,7 @@ export async function convertToAnthropicMessagesPrompt({
129
192
  toolNameMapping,
130
193
  toolsetNames = {},
131
194
  convertMediaPart,
195
+ convertInlineTool,
132
196
  }: {
133
197
  prompt: LanguageModelV3Prompt;
134
198
  sendReasoning: boolean;
@@ -137,6 +201,12 @@ export async function convertToAnthropicMessagesPrompt({
137
201
  toolNameMapping: ToolNameMapping;
138
202
  convertMediaPart?: AnthropicMediaPartConverter;
139
203
 
204
+ /**
205
+ * Converts tools that mid-conversation tool changes add by value. Required
206
+ * when the prompt contains such tool changes.
207
+ */
208
+ convertInlineTool?: AnthropicInlineToolConverter;
209
+
140
210
  /**
141
211
  * Maps custom tool names of toolset tools (e.g. the computer toolset) to
142
212
  * the Anthropic `toolset_name`. Tool calls and results of these tools are
@@ -191,6 +261,7 @@ export async function convertToAnthropicMessagesPrompt({
191
261
  case 'system': {
192
262
  const systemMessages: AnthropicSystemMessage[] = [];
193
263
  let toolChangeCount = 0;
264
+ let hasInlineToolDefinition = false;
194
265
  let hasMidConversationOptions = false;
195
266
 
196
267
  for (const { content: text, providerOptions } of block.messages) {
@@ -221,6 +292,52 @@ export async function convertToAnthropicMessagesPrompt({
221
292
  }
222
293
 
223
294
  for (const toolChange of toolChanges) {
295
+ if ('tool' in toolChange) {
296
+ if (convertInlineTool == null) {
297
+ throw new UnsupportedFunctionalityError({
298
+ functionality:
299
+ 'tool additions by value in mid-conversation tool changes',
300
+ });
301
+ }
302
+
303
+ const tool = toolChange.tool as
304
+ | LanguageModelV3FunctionTool
305
+ | LanguageModelV3ProviderTool;
306
+
307
+ if (isComputerTool(tool)) {
308
+ warnings.push({
309
+ type: 'other',
310
+ message:
311
+ `The tool '${tool.name}' cannot be added by value in a tool change. ` +
312
+ 'Declare it in the tools option and add it by reference with toolName. ' +
313
+ 'The tool change has been ignored.',
314
+ });
315
+ continue;
316
+ }
317
+
318
+ const {
319
+ definition,
320
+ warnings: toolWarnings,
321
+ betas: toolBetas,
322
+ } = await convertInlineTool(tool);
323
+ warnings.push(...toolWarnings);
324
+ for (const beta of toolBetas) {
325
+ betas.add(beta);
326
+ }
327
+
328
+ if (definition == null) {
329
+ continue;
330
+ }
331
+
332
+ content.push({
333
+ type: 'tool_addition',
334
+ tool: { type: 'tool_definition', definition },
335
+ } satisfies AnthropicToolChangeContent);
336
+ toolChangeCount++;
337
+ hasInlineToolDefinition = true;
338
+ continue;
339
+ }
340
+
224
341
  toolChangeCount++;
225
342
  content.push({
226
343
  type: toolChange.type,
@@ -231,6 +348,11 @@ export async function convertToAnthropicMessagesPrompt({
231
348
  } satisfies AnthropicToolChangeContent);
232
349
  }
233
350
 
351
+ // Every change was ignored and nothing else is left to send.
352
+ if (content.length === 0 && clearAt == null && effort == null) {
353
+ continue;
354
+ }
355
+
234
356
  hasMidConversationOptions ||= clearAt != null || effort != null;
235
357
 
236
358
  systemMessages.push({
@@ -293,7 +415,10 @@ export async function convertToAnthropicMessagesPrompt({
293
415
  } else {
294
416
  messages.push(...systemMessages);
295
417
  betas.add('mid-conversation-system-2026-04-07');
296
- if (toolChangeCount > 0) {
418
+ // The inline tools beta also covers changes by reference.
419
+ if (hasInlineToolDefinition) {
420
+ betas.add('inline-tools-2026-09-15');
421
+ } else if (toolChangeCount > 0) {
297
422
  betas.add('mid-conversation-tool-changes-2026-07-01');
298
423
  }
299
424
  if (systemMessages.some(message => message.clear_at != null)) {