ai 7.0.179 → 7.0.180

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.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
- import { $ as convertToLanguageModelPrompt, A as toolSearch, At as UnsupportedModelVersionError, B as setAbortTimeout, C as resolveToolApproval, Ct as asLanguageModelV4, D as convertToReasoningOutputs, Dt as RetryError, E as DefaultGenerateTextResult, Et as logWarnings, F as resolveGeneratedFileData, Ft as ToolCallNotFoundForApprovalError, G as addLanguageModelUsage, H as mergeAbortSignals, I as DefaultGeneratedFile, It as InvalidToolInputError, J as standardizePrompt, K as asLanguageModelUsage, L as DefaultGeneratedFileWithType, Lt as InvalidToolApprovalSignatureError, M as prepareToolsForToolCallers, Mt as NoSuchToolError, N as resolveToolCallerConfiguration, Nt as NoOutputGeneratedError, O as validateToolContext, Ot as InvalidMessageRoleError, P as convertLanguageModelContent, Pt as MissingToolResultsError, Q as createToolModelOutput, R as collectToolApprovals, Rt as InvalidToolApprovalError, S as filterIncludedContext, St as asVideoModelV4, T as getToolCallInputSchemaInput, Tt as asEmbeddingModelV4, U as getOwn, V as prepareRetries, W as addImageModelUsage, X as prepareToolChoice, Y as prepareTools, Z as prepareLanguageModelCallOptions, _ as createTelemetryDispatcher, _t as resolveSpeechModel, a as createAsyncIterableStream, at as convertDataContentToUint8Array, b as AI_SDK_TELEMETRY_TRACING_CHANNEL, bt as resolveVideoModel, c as validateApprovedToolApprovals, ct as download, dt as resolveDecisionModel, f as hashCanonical, ft as resolveEmbeddingModel, g as DefaultStepResult, gt as resolveRerankingModel, h as createRestrictedTelemetryDispatcher$4, ht as resolveLanguageModel, i as asAsyncIterableStream, it as convertDataContentToBase64String, j as appendToolCallerMessages, jt as ToolCallRepairError, k as createToolSearchState, kt as InvalidDataContentError, l as maybeSignApproval, lt as VERSION, m as isDeepEqualData, mt as resolveImageModel, nt as convertToLanguageModelV4FilePart, o as mapWithConcurrency, ot as mergeObjects, p as toResponseMessages, pt as resolveExtractionModel, q as createNullLanguageModelUsage, r as isOutputChunk$1, rt as splitDataUrl, s as prepareToolCallConcurrency, t as createDefaultStopCondition, ut as asEvaluationModel, v as getGlobalTelemetryIntegrations, vt as resolveSpeechTranslationModel, w as parseToolCall, wt as asImageModelV4, x as mergeCallbacks, xt as asProviderV4, y as registerTelemetry, yt as resolveTranscriptionModel, z as calculateTokensPerSecond, zt as InvalidArgumentError } from "./default-stop-condition-wtuJTiTo.js";
2
+ import { $ as convertToLanguageModelPrompt, A as toolSearch, At as UnsupportedModelVersionError, B as setAbortTimeout, C as resolveToolApproval, Ct as asLanguageModelV4, D as convertToReasoningOutputs, Dt as RetryError, E as DefaultGenerateTextResult, Et as logWarnings, F as resolveGeneratedFileData, Ft as ToolCallNotFoundForApprovalError, G as addLanguageModelUsage, H as mergeAbortSignals, I as DefaultGeneratedFile, It as InvalidToolInputError, J as standardizePrompt, K as asLanguageModelUsage, L as DefaultGeneratedFileWithType, Lt as InvalidToolApprovalSignatureError, M as prepareToolsForToolCallers, Mt as NoSuchToolError, N as resolveToolCallerConfiguration, Nt as NoOutputGeneratedError, O as validateToolContext, Ot as InvalidMessageRoleError, P as convertLanguageModelContent, Pt as MissingToolResultsError, Q as createToolModelOutput, R as collectToolApprovals, Rt as InvalidToolApprovalError, S as filterIncludedContext, St as asVideoModelV4, T as getToolCallInputSchemaInput, Tt as asEmbeddingModelV4, U as getOwn, V as prepareRetries, W as addImageModelUsage, X as prepareToolChoice, Y as prepareTools, Z as prepareLanguageModelCallOptions, _ as createTelemetryDispatcher, _t as resolveSpeechModel, a as createAsyncIterableStream, at as convertDataContentToUint8Array, b as AI_SDK_TELEMETRY_TRACING_CHANNEL, bt as resolveVideoModel, c as validateApprovedToolApprovals, ct as download, dt as resolveDecisionModel, f as hashCanonical, ft as resolveEmbeddingModel, g as DefaultStepResult, gt as resolveRerankingModel, h as createRestrictedTelemetryDispatcher$4, ht as resolveLanguageModel, i as asAsyncIterableStream, it as convertDataContentToBase64String, j as appendToolCallerMessages, jt as ToolCallRepairError, k as createToolSearchState, kt as InvalidDataContentError, l as maybeSignApproval, lt as VERSION, m as isDeepEqualData, mt as resolveImageModel, nt as convertToLanguageModelV4FilePart, o as mapWithConcurrency, ot as mergeObjects, p as toResponseMessages, pt as resolveExtractionModel, q as createNullLanguageModelUsage, r as isOutputChunk$1, rt as splitDataUrl, s as prepareToolCallConcurrency, t as createDefaultStopCondition, ut as asEvaluationModel, v as getGlobalTelemetryIntegrations, vt as resolveSpeechTranslationModel, w as parseToolCall, wt as asImageModelV4, x as mergeCallbacks, xt as asProviderV4, y as registerTelemetry, yt as resolveTranscriptionModel, z as calculateTokensPerSecond, zt as InvalidArgumentError } from "./default-stop-condition-vtYEJcnz.js";
3
3
  import { t as simulateReadableStream } from "./simulate-readable-stream-Bi5kQKbv.js";
4
4
  import { GatewayAuthenticationError, createGateway, gateway, gateway as gateway$1 } from "@ai-sdk/gateway";
5
5
  import { DelayedPromise, DownloadError, DownloadError as DownloadError$1, EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER, asArray, asSchema, asSchema as asSchema$1, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertUint8ArrayToBase64, createIdGenerator, createIdGenerator as createIdGenerator$1, delay, detectMediaType, dynamicTool, executeTool, experimental_toolCaller, filterNullable, generateId, generateId as generateId$1, getErrorMessage, getRuntimeEnvironmentUserAgent, getTopLevelMediaType, getWebSocketConstructor, isAbortError, isArrayBuffer, isBuffer, isExecutableTool, isFullMediaType, isNonNullable, isProviderReference, isProviderStreamError, isUint8Array, jsonSchema, lazySchema, normalizeHeaders, parseJsonEventStream, parseJsonEventStream as parseJsonEventStream$1, readWebSocketMessageText, resolve, safeParseJSON, safeValidateTypes, toWebSocketUrl, tool, validateTypes, waitForWebSocketBufferDrain, withUserAgentSuffix, zodSchema, zodSchema as zodSchema$1 } from "@ai-sdk/provider-utils";
@@ -1,3 +1,3 @@
1
- import { $ as convertToLanguageModelPrompt, B as setAbortTimeout, C as resolveToolApproval, E as DefaultGenerateTextResult, Et as logWarnings, G as addLanguageModelUsage, H as mergeAbortSignals, J as standardizePrompt, K as asLanguageModelUsage, O as validateToolContext, P as convertLanguageModelContent, Q as createToolModelOutput, R as collectToolApprovals, S as filterIncludedContext, V as prepareRetries, X as prepareToolChoice, Y as prepareTools, Z as prepareLanguageModelCallOptions, _ as createTelemetryDispatcher, a as createAsyncIterableStream, c as validateApprovedToolApprovals, d as verifyToolApprovalSignature, et as downloadAssets, g as DefaultStepResult, h as createRestrictedTelemetryDispatcher, ht as resolveLanguageModel, k as createToolSearchState, n as logDefaultStopConditionWarning, o as mapWithConcurrency, ot as mergeObjects, p as toResponseMessages, q as createNullLanguageModelUsage, r as isOutputChunk, s as prepareToolCallConcurrency, st as createDefaultDownloadFunction, tt as mapToolResultOutput, u as signToolApproval, w as parseToolCall, x as mergeCallbacks, z as calculateTokensPerSecond } from "../default-stop-condition-wtuJTiTo.js";
1
+ import { $ as convertToLanguageModelPrompt, B as setAbortTimeout, C as resolveToolApproval, E as DefaultGenerateTextResult, Et as logWarnings, G as addLanguageModelUsage, H as mergeAbortSignals, J as standardizePrompt, K as asLanguageModelUsage, O as validateToolContext, P as convertLanguageModelContent, Q as createToolModelOutput, R as collectToolApprovals, S as filterIncludedContext, V as prepareRetries, X as prepareToolChoice, Y as prepareTools, Z as prepareLanguageModelCallOptions, _ as createTelemetryDispatcher, a as createAsyncIterableStream, c as validateApprovedToolApprovals, d as verifyToolApprovalSignature, et as downloadAssets, g as DefaultStepResult, h as createRestrictedTelemetryDispatcher, ht as resolveLanguageModel, k as createToolSearchState, n as logDefaultStopConditionWarning, o as mapWithConcurrency, ot as mergeObjects, p as toResponseMessages, q as createNullLanguageModelUsage, r as isOutputChunk, s as prepareToolCallConcurrency, st as createDefaultDownloadFunction, tt as mapToolResultOutput, u as signToolApproval, w as parseToolCall, x as mergeCallbacks, z as calculateTokensPerSecond } from "../default-stop-condition-vtYEJcnz.js";
2
2
  import { convertAsyncIteratorToReadableStream } from "@ai-sdk/provider-utils";
3
3
  export { DefaultGenerateTextResult, DefaultStepResult, addLanguageModelUsage, asLanguageModelUsage, calculateTokensPerSecond, collectToolApprovals, convertAsyncIteratorToReadableStream, convertLanguageModelContent, convertToLanguageModelPrompt, createAsyncIterableStream, createDefaultDownloadFunction, createNullLanguageModelUsage, createRestrictedTelemetryDispatcher, createTelemetryDispatcher, createToolModelOutput, createToolSearchState, downloadAssets, filterIncludedContext, isOutputChunk, logDefaultStopConditionWarning, logWarnings, mapToolResultOutput, mapWithConcurrency, mergeAbortSignals, mergeCallbacks, mergeObjects, parseToolCall, prepareLanguageModelCallOptions as prepareCallSettings, prepareLanguageModelCallOptions, prepareRetries, prepareToolCallConcurrency, prepareToolChoice, prepareTools, resolveLanguageModel, resolveToolApproval, setAbortTimeout, signToolApproval, standardizePrompt, toResponseMessages, validateApprovedToolApprovals, validateToolContext, verifyToolApprovalSignature };
@@ -71,14 +71,15 @@ A model can return several tool calls in one response. `generateText`, `streamTe
71
71
  `opaPolicy` therefore evaluates every tool call after the first one of a response twice, unless the first evaluation already denies it:
72
72
 
73
73
  1. With `messages` as they were sent to the model.
74
- 2. With the earlier tool calls of the same response appended as an assistant message. Tool calls that the policy denied are followed by a tool message with their `execution-denied` result. The other tool calls have no result yet.
74
+ 2. With the earlier tool calls of the same response appended as an assistant message. Tool calls that are denied are followed by a tool message with their `execution-denied` result. The other tool calls have no result yet.
75
75
 
76
76
  The more restrictive decision applies: `deny` before `requires-approval`, before no matching rule, before `allow`.
77
77
 
78
78
  - A limit such as a budget, a quota, or "only one delete per conversation" counts the earlier tool calls of the same response.
79
79
  - A rule that allows a tool call only after another one, such as "deploy only after the tests ran", is not satisfied by a tool call of the same response, because that call has not run yet.
80
+ - Check a prerequisite through the earlier tool's result in history, not through the presence of its tool call. A tool call does not prove that the tool ran or succeeded. This also matters when an approved tool call is evaluated again before it runs: the history then contains the response with the tool calls, but not their results.
80
81
  - Base a limit that must hold within one response on tool calls, not on tool results. The earlier tool calls of a response have no results when the policy is evaluated.
81
- - OPA receives two queries for such a tool call, so it appears twice in OPA decision logs. A custom `toInput` is called twice as well. When it returns the same input both times, for example because it does not use `messages`, the policy is evaluated once.
82
+ - OPA receives two queries for such a tool call, so it appears twice in OPA decision logs. A custom `toInput` is called twice as well. When it returns the same input both times, for example because it does not use `messages`, the policy is evaluated once. With `wrapMcpTools` in hard allowlist mode (`default: 'denied'`), a tool call whose first evaluation is `not-applicable` is treated as denied by the fallback and evaluated once.
82
83
  - `opaPolicy` recognizes the tool calls of one response by the `messages` array they are evaluated with. `generateText`, `streamText`, and `ToolLoopAgent` pass the same array for all tool calls of a response and a new array for every response. When a caller passes a separate array for each tool call, `opaPolicy` evaluates each tool call once, with `messages` as passed. A caller must not pass one array for several responses: the tool calls of the earlier responses would count as earlier tool calls of the later ones.
83
84
 
84
85
  ### Tool calls that a user approved
@@ -350,6 +351,8 @@ Defaults for uncovered tools:
350
351
  - `'denied'`: hard allowlist mode. The policy enumerates what is allowed; everything else is rejected.
351
352
  - `'approved'`: allow. Only when the discovery source is fully trusted.
352
353
 
354
+ When the approval is an `opaPolicy` approval, the fallback is applied to each policy evaluation for a tool call, before the evaluations are compared. This holds when you pass `opaPolicy(...)` or `shadow(opaPolicy(...))` directly. A custom wrapper function around it hides the fallback from the policy, so the fallback then applies to the combined decision only.
355
+
353
356
  Despite the name, it works on any `Record<string, Tool>`.
354
357
 
355
358
  ## Allow-all when no policy is configured
@@ -218,6 +218,65 @@ const mcpClient = await createMCPClient({
218
218
 
219
219
  You can also bring your own transport by implementing the `MCPTransport` interface for specific requirements not covered by the standard transports.
220
220
 
221
+ ### WebMCP Transport
222
+
223
+ `Experimental_WebMCPTransport` (aliased below as `WebMCPTransport`) adapts tools
224
+ registered with the browser's
225
+ [`document.modelContext`](https://webmachinelearning.github.io/webmcp/) to the
226
+ existing MCP client:
227
+
228
+ ```ts
229
+ import {
230
+ createMCPClient,
231
+ Experimental_WebMCPTransport as WebMCPTransport,
232
+ } from '@ai-sdk/mcp';
233
+
234
+ // Run in a browser with WebMCP enabled, after checking API availability.
235
+ const client = await createMCPClient({
236
+ transport: new WebMCPTransport({ modelContext: document.modelContext }),
237
+ });
238
+
239
+ const tools = await client.tools();
240
+ ```
241
+
242
+ The required `modelContext` provides WebMCP's `getTools` and `executeTool`
243
+ methods. The optional `fromOrigins: string[]` constructor option discovers tools
244
+ exposed by additional frame origins, subject to browser permissions. The package
245
+ exports structural `Experimental_WebMCPModelContext` and
246
+ `Experimental_WebMCPTool` types; use browser API
247
+ typings such as `webmcp-types` to declare `document.modelContext`.
248
+
249
+ Use the tool names returned by `listTools` or `tools`: duplicate names across
250
+ frames receive stable aliases such as `getCart_2`. Results include text `content`
251
+ and parsed `structuredContent`. WebMCP `OperationError` failures become tool
252
+ results with `isError: true`; other failures reject the request.
253
+
254
+ WebMCP is an experimental browser API, not an HTTP MCP endpoint. Tool discovery
255
+ and execution happen in the page. To keep model inference on your backend, send
256
+ tool definitions to your API route, then execute the returned calls in
257
+ [`useChat.onToolCall`](/docs/ai-sdk-ui/chatbot-tool-usage) and return results with
258
+ `addToolOutput`. On the backend,
259
+ [`createMCPTools`](/docs/reference/ai-sdk-core/create-mcp-tools) validates and
260
+ converts those definitions into model-facing tools without `execute` functions:
261
+
262
+ ```ts
263
+ import { createMCPTools } from '@ai-sdk/mcp';
264
+
265
+ const { messages, tools: definitions } = await request.json();
266
+ const tools = createMCPTools(definitions);
267
+ ```
268
+
269
+ Pass `tools` to `streamText` and to `convertToModelMessages(messages, { tools })`
270
+ so returned MCP results are converted to model content. The
271
+ [shopping cart example](https://github.com/vercel/ai/tree/main/examples/ai-e2e-next/app/chat/webmcp)
272
+ demonstrates this flow with live page state. Follow the
273
+ [WebMCP shopping cart recipe](/cookbook/next/webmcp-tools) to build it.
274
+
275
+ Tool lists are snapshots. List tools again when the page's available tools change,
276
+ and close the client when the consuming component or browser connection is
277
+ disposed. Cancellation is forwarded to tool execution. Closing the client aborts
278
+ pending calls without unregistering the page's tools.
279
+
221
280
  <Note>
222
281
  The client returned by the `createMCPClient` function is a
223
282
  lightweight client intended for use in tool conversion. It currently does not
@@ -0,0 +1,65 @@
1
+ ---
2
+ title: createMCPTools
3
+ description: Convert MCP tool definitions into AI SDK tools without a connection.
4
+ ---
5
+
6
+ # `createMCPTools()`
7
+
8
+ Converts an array of MCP tool definitions into AI SDK dynamic tools without
9
+ `execute` functions. Use it when the model runs on your backend and tools execute
10
+ elsewhere, such as in a browser using
11
+ [`Experimental_WebMCPTransport`](/docs/ai-sdk-core/mcp-tools#webmcp-transport).
12
+
13
+ ```ts
14
+ import { createMCPTools } from '@ai-sdk/mcp';
15
+ import { convertToModelMessages, streamText } from 'ai';
16
+
17
+ // In your API route, after applying application-specific request policies:
18
+ const { messages, tools: definitions } = await request.json();
19
+ const tools = createMCPTools(definitions);
20
+
21
+ const result = streamText({
22
+ model,
23
+ messages: await convertToModelMessages(messages, { tools }),
24
+ tools,
25
+ });
26
+ ```
27
+
28
+ The browser obtains the definitions using `const { tools } = await client.listTools()`
29
+ and sends that array with the chat request. It handles returned calls through
30
+ `useChat.onToolCall` and submits results with `addToolOutput`. The helper does not
31
+ connect to a browser or create an MCP client.
32
+
33
+ ## Parameters
34
+
35
+ - **`definitions: unknown`** (required): an array in the format of
36
+ `listTools().tools`. Each item must contain `name` and `inputSchema` and can
37
+ include MCP fields such as `description`, `title`, `annotations`, and `_meta`.
38
+ Deserialized request data can be passed directly.
39
+
40
+ ## Returns
41
+
42
+ A record of tool names to AI SDK dynamic tools. The helper:
43
+
44
+ - Validates the MCP definition structure and rejects duplicate names.
45
+ - Converts input schemas using the same automatic schema conversion as
46
+ `client.tools()`, including defaulting `properties` to `{}` and setting
47
+ `additionalProperties: false`.
48
+ - Preserves titles, standard MCP annotations, MCP App metadata, and `_meta`.
49
+ - Adds `toModelOutput` to convert returned MCP text and image content into model
50
+ content. Pass `{ tools }` to `convertToModelMessages` to use this conversion
51
+ for browser tool results in chat history.
52
+ - Leaves `execute` unset. The application forwards calls and returns results.
53
+
54
+ As with `client.tools()` in automatic schema mode, declared MCP output schemas
55
+ are not used to validate results.
56
+
57
+ ## Errors
58
+
59
+ Throws `MCPClientError` for malformed definitions or duplicate names. API routes
60
+ can catch it and return HTTP 400. Validation checks the MCP definition structure;
61
+ it does not establish trust, enforce application limits, or fully validate JSON
62
+ Schema documents. Apply your own authentication and tool policies to requests.
63
+
64
+ To execute tools over an MCP connection in the same runtime as the model, use
65
+ [`client.tools()`](/docs/reference/ai-sdk-core/create-mcp-client) instead.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai",
3
- "version": "7.0.179",
3
+ "version": "7.0.180",
4
4
  "type": "module",
5
5
  "description": "AI SDK by Vercel - build apps like ChatGPT, Claude, Gemini, and more with a single interface for any model using the Vercel AI Gateway or go direct to OpenAI, Anthropic, Google, or any other model provider.",
6
6
  "license": "Apache-2.0",
@@ -43,7 +43,7 @@
43
43
  }
44
44
  },
45
45
  "dependencies": {
46
- "@ai-sdk/gateway": "4.0.152",
46
+ "@ai-sdk/gateway": "4.0.153",
47
47
  "@ai-sdk/provider": "4.0.39",
48
48
  "@ai-sdk/provider-utils": "5.0.83"
49
49
  },