@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.
@@ -1136,9 +1136,15 @@ declare const anthropicTools: {
1136
1136
  }[]>;
1137
1137
  };
1138
1138
 
1139
- declare function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheControlValidator, supportsStructuredOutput, supportsStrictTools, defaultEagerInputStreaming, rejectsForcedToolUse, }: {
1139
+ declare function prepareTools({ tools, toolChoice, hasInlineTools, disableParallelToolUse, cacheControlValidator, supportsStructuredOutput, supportsStrictTools, defaultEagerInputStreaming, rejectsForcedToolUse, }: {
1140
1140
  tools: LanguageModelV3CallOptions['tools'];
1141
1141
  toolChoice: LanguageModelV3CallOptions['toolChoice'] | undefined;
1142
+ /**
1143
+ * Whether tools are added by value in the prompt (mid-conversation tool
1144
+ * changes). The model has tools even when `tools` is empty, so the tool
1145
+ * choice and parallel tool use settings still need to be sent.
1146
+ */
1147
+ hasInlineTools?: boolean;
1142
1148
  disableParallelToolUse?: boolean;
1143
1149
  cacheControlValidator?: CacheControlValidator;
1144
1150
  /**
@@ -1136,9 +1136,15 @@ declare const anthropicTools: {
1136
1136
  }[]>;
1137
1137
  };
1138
1138
 
1139
- declare function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheControlValidator, supportsStructuredOutput, supportsStrictTools, defaultEagerInputStreaming, rejectsForcedToolUse, }: {
1139
+ declare function prepareTools({ tools, toolChoice, hasInlineTools, disableParallelToolUse, cacheControlValidator, supportsStructuredOutput, supportsStrictTools, defaultEagerInputStreaming, rejectsForcedToolUse, }: {
1140
1140
  tools: LanguageModelV3CallOptions['tools'];
1141
1141
  toolChoice: LanguageModelV3CallOptions['toolChoice'] | undefined;
1142
+ /**
1143
+ * Whether tools are added by value in the prompt (mid-conversation tool
1144
+ * changes). The model has tools even when `tools` is empty, so the tool
1145
+ * choice and parallel tool use settings still need to be sent.
1146
+ */
1147
+ hasInlineTools?: boolean;
1142
1148
  disableParallelToolUse?: boolean;
1143
1149
  cacheControlValidator?: CacheControlValidator;
1144
1150
  /**
@@ -920,17 +920,43 @@ var anthropicSystemMessageProviderOptions = (0, import_provider_utils3.lazySchem
920
920
  * initial system prompt). A system message carrying tool changes must come
921
921
  * right before an assistant message or at the end of the messages.
922
922
  *
923
- * Tools referenced by a `tool_addition` must be declared in the `tools`
924
- * option (typically with `deferLoading: true` so they are not loaded until
925
- * the addition surfaces them). The required
926
- * `mid-conversation-tool-changes-2026-07-01` beta is added automatically.
923
+ * A `tool_addition` either references a tool by `toolName` or defines it
924
+ * by value with `tool`:
925
+ * - By reference: the tool must be declared in the `tools` option
926
+ * (typically with `deferLoading: true` so it is not loaded until the
927
+ * addition surfaces it). The required
928
+ * `mid-conversation-tool-changes-2026-07-01` beta is added
929
+ * automatically.
930
+ * - By value: `tool` is a function or provider tool, in the same shape as
931
+ * an entry of the `tools` option. The tool does not need to be declared
932
+ * in `tools`, and defining a tool under an existing name replaces it
933
+ * from that point on. The required `inline-tools-2026-09-15` beta is
934
+ * added automatically.
935
+ *
936
+ * A `tool_removal` always references the tool by `toolName`.
927
937
  */
928
938
  toolChanges: import_v43.z.array(
929
- import_v43.z.discriminatedUnion("type", [
939
+ import_v43.z.union([
930
940
  import_v43.z.object({
931
941
  type: import_v43.z.literal("tool_addition"),
932
942
  toolName: import_v43.z.string()
933
943
  }),
944
+ import_v43.z.object({
945
+ type: import_v43.z.literal("tool_addition"),
946
+ tool: import_v43.z.union([
947
+ import_v43.z.looseObject({
948
+ type: import_v43.z.literal("function"),
949
+ name: import_v43.z.string(),
950
+ inputSchema: import_v43.z.record(import_v43.z.string(), import_v43.z.unknown())
951
+ }),
952
+ import_v43.z.looseObject({
953
+ type: import_v43.z.literal("provider"),
954
+ id: import_v43.z.string(),
955
+ name: import_v43.z.string(),
956
+ args: import_v43.z.record(import_v43.z.string(), import_v43.z.unknown())
957
+ })
958
+ ])
959
+ }),
934
960
  import_v43.z.object({
935
961
  type: import_v43.z.literal("tool_removal"),
936
962
  toolName: import_v43.z.string()
@@ -1628,6 +1654,7 @@ var import_provider_utils11 = require("@ai-sdk/provider-utils");
1628
1654
  async function prepareTools({
1629
1655
  tools,
1630
1656
  toolChoice,
1657
+ hasInlineTools = false,
1631
1658
  disableParallelToolUse,
1632
1659
  cacheControlValidator,
1633
1660
  supportsStructuredOutput,
@@ -1640,11 +1667,11 @@ async function prepareTools({
1640
1667
  const toolWarnings = [];
1641
1668
  const betas = /* @__PURE__ */ new Set();
1642
1669
  const validator = cacheControlValidator || new CacheControlValidator();
1643
- if (tools == null) {
1670
+ if (tools == null && !hasInlineTools) {
1644
1671
  return { tools: void 0, toolChoice: void 0, toolWarnings, betas };
1645
1672
  }
1646
1673
  const anthropicTools2 = [];
1647
- for (const tool of tools) {
1674
+ for (const tool of tools != null ? tools : []) {
1648
1675
  switch (tool.type) {
1649
1676
  case "function": {
1650
1677
  const cacheControl = validator.getCacheControl(tool.providerOptions, {
@@ -1956,9 +1983,10 @@ async function prepareTools({
1956
1983
  }
1957
1984
  }
1958
1985
  }
1986
+ const declaredTools = tools == null ? void 0 : anthropicTools2;
1959
1987
  if (toolChoice == null) {
1960
1988
  return {
1961
- tools: anthropicTools2,
1989
+ tools: declaredTools,
1962
1990
  toolChoice: disableParallelToolUse ? { type: "auto", disable_parallel_tool_use: disableParallelToolUse } : void 0,
1963
1991
  toolWarnings,
1964
1992
  betas
@@ -1968,7 +1996,7 @@ async function prepareTools({
1968
1996
  switch (type) {
1969
1997
  case "auto":
1970
1998
  return {
1971
- tools: anthropicTools2,
1999
+ tools: declaredTools,
1972
2000
  toolChoice: {
1973
2001
  type: "auto",
1974
2002
  disable_parallel_tool_use: disableParallelToolUse
@@ -1984,7 +2012,7 @@ async function prepareTools({
1984
2012
  details: `toolChoice 'required' is not supported with this model or thinking configuration. Using 'auto' instead. Instruct the model to use a tool in the prompt and verify that a tool call was made.`
1985
2013
  });
1986
2014
  return {
1987
- tools: anthropicTools2,
2015
+ tools: declaredTools,
1988
2016
  toolChoice: {
1989
2017
  type: "auto",
1990
2018
  disable_parallel_tool_use: disableParallelToolUse
@@ -1994,7 +2022,7 @@ async function prepareTools({
1994
2022
  };
1995
2023
  }
1996
2024
  return {
1997
- tools: anthropicTools2,
2025
+ tools: declaredTools,
1998
2026
  toolChoice: {
1999
2027
  type: "any",
2000
2028
  disable_parallel_tool_use: disableParallelToolUse
@@ -2004,7 +2032,7 @@ async function prepareTools({
2004
2032
  };
2005
2033
  case "none":
2006
2034
  return {
2007
- tools: anthropicTools2,
2035
+ tools: declaredTools,
2008
2036
  toolChoice: { type: "none" },
2009
2037
  toolWarnings,
2010
2038
  betas
@@ -2017,7 +2045,7 @@ async function prepareTools({
2017
2045
  details: `toolChoice 'tool' is not supported with this model or thinking configuration. Only the '${toolChoice.toolName}' tool is sent with 'auto' tool choice. Instruct the model to use the tool in the prompt and verify that a tool call was made.`
2018
2046
  });
2019
2047
  return {
2020
- tools: anthropicTools2.filter(
2048
+ tools: declaredTools == null ? void 0 : declaredTools.filter(
2021
2049
  (tool) => "name" in tool && tool.name === toolChoice.toolName
2022
2050
  ),
2023
2051
  toolChoice: {
@@ -2029,7 +2057,7 @@ async function prepareTools({
2029
2057
  };
2030
2058
  }
2031
2059
  return {
2032
- tools: anthropicTools2,
2060
+ tools: declaredTools,
2033
2061
  toolChoice: {
2034
2062
  type: "tool",
2035
2063
  name: toolChoice.toolName,
@@ -2449,6 +2477,32 @@ async function extractErrorValue(value) {
2449
2477
  }
2450
2478
  return {};
2451
2479
  }
2480
+ function isComputerTool(tool) {
2481
+ return tool.type === "provider" && tool.id.startsWith("anthropic.computer_");
2482
+ }
2483
+ async function getInlineToolsFromPrompt(prompt) {
2484
+ var _a;
2485
+ const inlineTools = [];
2486
+ for (const message of prompt) {
2487
+ if (message.role !== "system" || message.providerOptions == null) {
2488
+ continue;
2489
+ }
2490
+ const options = await (0, import_provider_utils16.parseProviderOptions)({
2491
+ provider: "anthropic",
2492
+ providerOptions: message.providerOptions,
2493
+ schema: anthropicSystemMessageProviderOptions
2494
+ });
2495
+ for (const toolChange of (_a = options == null ? void 0 : options.toolChanges) != null ? _a : []) {
2496
+ if ("tool" in toolChange) {
2497
+ const tool = toolChange.tool;
2498
+ if (!isComputerTool(tool)) {
2499
+ inlineTools.push(tool);
2500
+ }
2501
+ }
2502
+ }
2503
+ }
2504
+ return inlineTools;
2505
+ }
2452
2506
  async function convertToAnthropicMessagesPrompt({
2453
2507
  prompt,
2454
2508
  sendReasoning,
@@ -2456,7 +2510,8 @@ async function convertToAnthropicMessagesPrompt({
2456
2510
  cacheControlValidator,
2457
2511
  toolNameMapping,
2458
2512
  toolsetNames = {},
2459
- convertMediaPart
2513
+ convertMediaPart,
2514
+ convertInlineTool
2460
2515
  }) {
2461
2516
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v;
2462
2517
  const betas = /* @__PURE__ */ new Set();
@@ -2493,6 +2548,7 @@ async function convertToAnthropicMessagesPrompt({
2493
2548
  case "system": {
2494
2549
  const systemMessages = [];
2495
2550
  let toolChangeCount = 0;
2551
+ let hasInlineToolDefinition = false;
2496
2552
  let hasMidConversationOptions = false;
2497
2553
  for (const { content: text, providerOptions } of block.messages) {
2498
2554
  const systemMessageOptions = await (0, import_provider_utils16.parseProviderOptions)({
@@ -2515,6 +2571,40 @@ async function convertToAnthropicMessagesPrompt({
2515
2571
  });
2516
2572
  }
2517
2573
  for (const toolChange of toolChanges) {
2574
+ if ("tool" in toolChange) {
2575
+ if (convertInlineTool == null) {
2576
+ throw new import_provider2.UnsupportedFunctionalityError({
2577
+ functionality: "tool additions by value in mid-conversation tool changes"
2578
+ });
2579
+ }
2580
+ const tool = toolChange.tool;
2581
+ if (isComputerTool(tool)) {
2582
+ warnings.push({
2583
+ type: "other",
2584
+ message: `The tool '${tool.name}' cannot be added by value in a tool change. Declare it in the tools option and add it by reference with toolName. The tool change has been ignored.`
2585
+ });
2586
+ continue;
2587
+ }
2588
+ const {
2589
+ definition,
2590
+ warnings: toolWarnings,
2591
+ betas: toolBetas
2592
+ } = await convertInlineTool(tool);
2593
+ warnings.push(...toolWarnings);
2594
+ for (const beta of toolBetas) {
2595
+ betas.add(beta);
2596
+ }
2597
+ if (definition == null) {
2598
+ continue;
2599
+ }
2600
+ content.push({
2601
+ type: "tool_addition",
2602
+ tool: { type: "tool_definition", definition }
2603
+ });
2604
+ toolChangeCount++;
2605
+ hasInlineToolDefinition = true;
2606
+ continue;
2607
+ }
2518
2608
  toolChangeCount++;
2519
2609
  content.push({
2520
2610
  type: toolChange.type,
@@ -2524,6 +2614,9 @@ async function convertToAnthropicMessagesPrompt({
2524
2614
  }
2525
2615
  });
2526
2616
  }
2617
+ if (content.length === 0 && clearAt == null && effort == null) {
2618
+ continue;
2619
+ }
2527
2620
  hasMidConversationOptions || (hasMidConversationOptions = clearAt != null || effort != null);
2528
2621
  systemMessages.push({
2529
2622
  role: "system",
@@ -2558,7 +2651,9 @@ async function convertToAnthropicMessagesPrompt({
2558
2651
  } else {
2559
2652
  messages.push(...systemMessages);
2560
2653
  betas.add("mid-conversation-system-2026-04-07");
2561
- if (toolChangeCount > 0) {
2654
+ if (hasInlineToolDefinition) {
2655
+ betas.add("inline-tools-2026-09-15");
2656
+ } else if (toolChangeCount > 0) {
2562
2657
  betas.add("mid-conversation-tool-changes-2026-07-01");
2563
2658
  }
2564
2659
  if (systemMessages.some((message) => message.clear_at != null)) {
@@ -4019,7 +4114,7 @@ var AnthropicMessagesLanguageModel = class {
4019
4114
  providerOptions,
4020
4115
  stream
4021
4116
  }) {
4022
- var _a, _b, _c, _d, _e, _f, _g, _h;
4117
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
4023
4118
  const warnings = [];
4024
4119
  if (frequencyPenalty != null) {
4025
4120
  warnings.push({ type: "unsupported", feature: "frequencyPenalty" });
@@ -4148,8 +4243,22 @@ var AnthropicMessagesLanguageModel = class {
4148
4243
  const cacheControlValidator = new CacheControlValidator(
4149
4244
  this.config.cacheControlProviderOptionsName
4150
4245
  );
4246
+ const defaultEagerInputStreaming = stream && ((_e = anthropicOptions == null ? void 0 : anthropicOptions.toolStreaming) != null ? _e : true);
4247
+ const inlineTools = await getInlineToolsFromPrompt(prompt);
4248
+ const declaredFunctionToolNames = new Set(
4249
+ (tools != null ? tools : []).flatMap(
4250
+ (tool) => tool.type === "function" ? [tool.name] : []
4251
+ )
4252
+ );
4151
4253
  const toolNameMapping = (0, import_provider_utils17.createToolNameMapping)({
4152
- tools,
4254
+ // later entries win when provider tool names collide, so the declared
4255
+ // tools go last and an inline tool cannot take over their mapping:
4256
+ tools: [
4257
+ ...inlineTools.filter(
4258
+ (tool) => !(tool.type === "provider" && declaredFunctionToolNames.has(tool.name))
4259
+ ),
4260
+ ...tools != null ? tools : []
4261
+ ],
4153
4262
  providerToolNames: {
4154
4263
  "anthropic.code_execution_20250522": "code_execution",
4155
4264
  "anthropic.code_execution_20250825": "code_execution",
@@ -4175,14 +4284,43 @@ var AnthropicMessagesLanguageModel = class {
4175
4284
  }
4176
4285
  });
4177
4286
  const toolsetNames = getAnthropicToolsetNames(tools);
4287
+ const inlineToolDefinitions = [];
4178
4288
  const { prompt: messagesPrompt, betas } = await convertToAnthropicMessagesPrompt({
4179
4289
  prompt,
4180
- sendReasoning: (_e = anthropicOptions == null ? void 0 : anthropicOptions.sendReasoning) != null ? _e : true,
4290
+ sendReasoning: (_f = anthropicOptions == null ? void 0 : anthropicOptions.sendReasoning) != null ? _f : true,
4181
4291
  warnings,
4182
4292
  cacheControlValidator,
4183
4293
  toolNameMapping,
4184
4294
  toolsetNames,
4185
- convertMediaPart: this.config.convertMediaPart
4295
+ convertMediaPart: this.config.convertMediaPart,
4296
+ convertInlineTool: async (tool) => {
4297
+ const {
4298
+ tools: definitions,
4299
+ toolWarnings: toolWarnings2,
4300
+ betas: betas2
4301
+ } = await prepareTools({
4302
+ tools: [tool],
4303
+ toolChoice: void 0,
4304
+ cacheControlValidator,
4305
+ supportsStructuredOutput,
4306
+ supportsStrictTools
4307
+ // no stream-dependent defaults (eager input streaming): the
4308
+ // definition is replayed on every request and has to stay
4309
+ // identical between streaming and non-streaming calls to keep
4310
+ // the cache.
4311
+ });
4312
+ if ((definitions == null ? void 0 : definitions[0]) != null) {
4313
+ inlineToolDefinitions.push({
4314
+ sdkName: tool.name,
4315
+ definition: definitions[0]
4316
+ });
4317
+ }
4318
+ return {
4319
+ definition: definitions == null ? void 0 : definitions[0],
4320
+ warnings: toolWarnings2,
4321
+ betas: betas2
4322
+ };
4323
+ }
4186
4324
  });
4187
4325
  if (rejectsThinkingDisabled && (anthropicOptions == null ? void 0 : anthropicOptions.thinking) != null) {
4188
4326
  const requestedThinking = anthropicOptions.thinking;
@@ -4292,7 +4430,7 @@ var AnthropicMessagesLanguageModel = class {
4292
4430
  ...(anthropicOptions == null ? void 0 : anthropicOptions.cacheControl) && {
4293
4431
  cache_control: anthropicOptions.cacheControl
4294
4432
  },
4295
- ...((_f = anthropicOptions == null ? void 0 : anthropicOptions.metadata) == null ? void 0 : _f.userId) != null && {
4433
+ ...((_g = anthropicOptions == null ? void 0 : anthropicOptions.metadata) == null ? void 0 : _g.userId) != null && {
4296
4434
  metadata: { user_id: anthropicOptions.metadata.userId }
4297
4435
  },
4298
4436
  // mcp servers:
@@ -4487,7 +4625,6 @@ var AnthropicMessagesLanguageModel = class {
4487
4625
  } else if ((anthropicOptions == null ? void 0 : anthropicOptions.fallbacks) && anthropicOptions.fallbacks.length > 0) {
4488
4626
  betas.add("server-side-fallback-2026-06-01");
4489
4627
  }
4490
- const defaultEagerInputStreaming = stream && ((_g = anthropicOptions == null ? void 0 : anthropicOptions.toolStreaming) != null ? _g : true);
4491
4628
  const {
4492
4629
  tools: anthropicTools2,
4493
4630
  toolChoice: anthropicToolChoice,
@@ -4511,6 +4648,9 @@ var AnthropicMessagesLanguageModel = class {
4511
4648
  } : {
4512
4649
  tools: tools != null ? tools : [],
4513
4650
  toolChoice,
4651
+ // tool changes can add tools when `tools` is empty, so the tool
4652
+ // choice and parallel tool use settings still apply:
4653
+ hasInlineTools: inlineTools.length > 0,
4514
4654
  disableParallelToolUse: anthropicOptions == null ? void 0 : anthropicOptions.disableParallelToolUse,
4515
4655
  cacheControlValidator,
4516
4656
  supportsStructuredOutput,
@@ -4519,6 +4659,37 @@ var AnthropicMessagesLanguageModel = class {
4519
4659
  rejectsForcedToolUse: rejectsForcedToolUse || thinkingType === "enabled"
4520
4660
  }
4521
4661
  );
4662
+ if ((toolChoice == null ? void 0 : toolChoice.type) === "tool" && ((anthropicToolChoice == null ? void 0 : anthropicToolChoice.type) === "auto" || jsonResponseTool != null) || (toolChoice == null ? void 0 : toolChoice.type) === "none" && jsonResponseTool != null) {
4663
+ for (const server of (_h = baseArgs.mcp_servers) != null ? _h : []) {
4664
+ server.tool_configuration = {
4665
+ allowed_tools: (_i = server.tool_configuration) == null ? void 0 : _i.allowed_tools,
4666
+ enabled: false
4667
+ };
4668
+ }
4669
+ const emittedInlineDefinitions = new Set(
4670
+ messagesPrompt.messages.flatMap(
4671
+ (message) => message.role === "system" ? message.content.flatMap(
4672
+ (part) => part.type === "tool_addition" && part.tool.type === "tool_definition" ? [part.tool.definition] : []
4673
+ ) : []
4674
+ )
4675
+ );
4676
+ const selectedSdkName = toolChoice.type === "tool" ? toolChoice.toolName : void 0;
4677
+ const selectedTool = tools == null ? void 0 : tools.find((tool) => tool.name === selectedSdkName);
4678
+ const selectedProviderName = jsonResponseTool != null && selectedSdkName != null && (selectedTool == null ? void 0 : selectedTool.type) !== "function" ? toolNameMapping.toProviderToolName(selectedSdkName) : selectedSdkName;
4679
+ const conflictingTool = inlineToolDefinitions.find(
4680
+ ({ sdkName, definition }) => emittedInlineDefinitions.has(definition) && (toolChoice.type === "none" || // The JSON-tool path filters application tools by SDK name before
4681
+ // conversion; the forced-choice fallback filters by provider name.
4682
+ jsonResponseTool != null && sdkName !== selectedSdkName || !("name" in definition) || definition.name !== selectedProviderName)
4683
+ );
4684
+ if (conflictingTool != null) {
4685
+ const toolName = "name" in conflictingTool.definition ? conflictingTool.definition.name : conflictingTool.definition.type;
4686
+ const choice = toolChoice.type === "tool" ? `named tool choice '${toolChoice.toolName}'` : `tool choice 'none'`;
4687
+ throw new import_provider3.InvalidArgumentError({
4688
+ argument: "toolChoice",
4689
+ message: `Inline tool '${toolName}' conflicts with ${choice}. Inline definitions must respect the tool choice when forced tool use falls back or the JSON response tool is used.`
4690
+ });
4691
+ }
4692
+ }
4522
4693
  const cacheWarnings = cacheControlValidator.getWarnings();
4523
4694
  return {
4524
4695
  args: {
@@ -4533,7 +4704,7 @@ var AnthropicMessagesLanguageModel = class {
4533
4704
  ...betas,
4534
4705
  ...toolsBetas,
4535
4706
  ...userSuppliedBetas,
4536
- ...(_h = anthropicOptions == null ? void 0 : anthropicOptions.anthropicBeta) != null ? _h : []
4707
+ ...(_j = anthropicOptions == null ? void 0 : anthropicOptions.anthropicBeta) != null ? _j : []
4537
4708
  ]),
4538
4709
  usesJsonResponseTool: jsonResponseTool != null,
4539
4710
  toolNameMapping,