AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(server-utils): port the piece's web-search builder into aiUtils (#15487)
Abdulf5118ef789cb
diff --git a/brain/knowledge/ai-intelligence/ai-providers.md b/brain/knowledge/ai-intelligence/ai-providers.mdindex f1342cf4db2..3238acb824d 100644--- a/brain/knowledge/ai-intelligence/ai-providers.md+++ b/brain/knowledge/ai-intelligence/ai-providers.md@@ -54,6 +54,10 @@ renders and preserves every real price; the cheapest in the set is 0.01.- **The catalog object must be published before the code that reads it ships.** There is no bundled copy, so until a `workflow_dispatch` run puts it on the CDN, every install — including local dev — shows no metadata at all.- **A fresh Cloud platform cannot connect any AI provider, and the UI says nothing about why.** The admin page at `/platform/setup/ai` sets `allowWrite = platform.plan.aiProvidersEnabled`, and that column defaults to **false** on the `free` plan (migration `1776…AddDefaultToAiProvidersEnabled`), so the connect button is simply absent rather than disabled-with-a-reason. On Cloud the flag is owned by Autumn (`autumn-utils.ts` lists it among the synced features), so there is nothing to configure locally and no `DEV_ENTERPRISE_PLAN` escape hatch on main. For local Cloud testing, flip it directly: `UPDATE platform_plan SET "aiProvidersEnabled" = true`. Then connect a **BYO key**, not the managed `ACTIVEPIECES` provider — per *Provider visibility* above, the managed row is hidden whenever `OPENROUTER_PROVISION_KEY` is unset, which is the normal local state, and a hidden provider makes `getChatProvider()` return null. Anything gated on a chat provider (chat itself, personalization research) stays silently disabled until a BYO row exists.+- **`getEffectiveProviderAndModel` exists for one provider, and skipping it makes Cloudflare Gateway fall off the end of any per-provider switch.** It looks like generic provider resolution; it is not. It returns its input untouched for everything except `CLOUDFLARE_GATEWAY`, where it splits the model id and maps the submodel prefix (`anthropic`, `openai`, `google-ai-studio`, `google-vertex-ai`) back to the real provider. So a gateway model of `anthropic/claude-…` only reaches an Anthropic-keyed branch if you called it first. Any table or lookup keyed on `AIProviderName` — the web-search tool table, capability checks — has no `CLOUDFLARE_GATEWAY` entry and returns nothing for one that skipped the call: no tool, no error, no log. The AI piece calls it at the top of `buildWebSearchConfig`; server-side code that dispatches per provider needs the same call or the same resolution built in.++- **The Agent and the Direct AI steps disagree about whether OpenAI does web search, and both are right.** `WEB_SEARCH_MODE_BY_PROVIDER` has no `OPENAI` entry, so `supportsWebSearch(OPENAI)` is `false` — the Agent asks that question before offering the tool and therefore has never had OpenAI web search (deliberately: it needs the Responses API, which breaks legacy BYOK models). Ask AI never asks it; it builds the tool straight from its own props and has had OpenAI web search all along. So `supportsWebSearch` is the *agent's* policy, not a statement of fact about the provider — reusing it as a general gate silently removes a capability Ask AI users have today. Whoever unifies the two paths has to keep the OpenAI branch reachable without routing it through that gate. The two paths also disagree about the unsupported tail: the piece's `webSearch` prop is a plain checkbox with no provider gating, and `createWebSearchTool` ends in `default: throw new Error('Provider X is not supported for web search')` — so ticking it on Azure, Mistral, xAI, or a Cloudflare Gateway model whose submodel prefix is not one of the four in `CF_GATEWAY_SUBMODEL_TO_PROVIDER` **fails the step**. The server's `buildWebSearchTools` returns `{}` for the same input, because the agent gates before calling it. The builder cannot simply be made to throw: `supportsWebSearch` is true for the `plugin` providers (`openrouter`, `activepieces`), the agent calls the builder for them, and there is no native entry for either because the plugin rides on the model settings instead — so `{}` is the correct answer there. The piece has the same shape, returning early for OpenRouter before the switch that throws. Hence two entry points: `buildWebSearchTools` stays total for callers that gate first, `buildWebSearchToolsOrThrow` reproduces the piece's error for callers that do not.+- **`aiProviderModule` is registered unconditionally, `agentModule` is not.** In `app.ts`, `aiProviderModule` sits outside the edition switch, while `agentModule` appears only in the `CLOUD` and `ENTERPRISE` arms — so an AI route hung off the provider module is on Community for free, and the same route hung off the agent module 404s there. That asymmetry is the cheapest way to satisfy [000036](../decisions/000036-the-worker-side-ai-path-is-community-edition-core.md): pick the module and there is no edition branch left to get wrong.- **Multi-key resolution is deterministic, not configurable.** When several keys of one provider are eligible for a project, `resolveEligibleRow` picks by most specific `projectScope` (`selected` > `except` > `all`), newest `created` breaking ties — there is no priority/default field (decision: [providers-redesign-before-routing](../decisions/providers-redesign-before-routing.md)). The ACTIVEPIECES provider stays a singleton — `create()` rejects it (`aiProvider.activepiecesIsManaged`). That ranking is the *fallback*: a step or agent may also pin a key outright (decision: [000030](../decisions/000030-a-step-may-pin-an-ai-provider-key-and-omitting-one-can-only-narrow.md)), in which case `resolveRowForScope` serves that row after checking it is eligible for the caller's project.diff --git a/brain/knowledge/pieces-engine/pieces.md b/brain/knowledge/pieces-engine/pieces.mdindex 88a8f132fca..5efe3a8e381 100644--- a/brain/knowledge/pieces-engine/pieces.md+++ b/brain/knowledge/pieces-engine/pieces.md@@ -40,6 +40,8 @@ The metadata catalog of automation integrations ("pieces") — each a named inte- **Editing `matchPieceName`: the ≥3-character guard is asymmetric on purpose — naming tokens only, never `wholeNameTyped` coverage.** Applying it to both drops every piece with a two-letter name word (`Bland AI`, `Hume AI`, `Microsoft Power BI` — 29 queries regressed in one measured pass), because a two-letter token like `ai` must still count as covering the name word `AI` even though it is too short to *name* a piece on its own. The guard exists only to stop short tokens naming pieces they have nothing to do with. Related, and **not worth fixing**: `tokenizeSearchQuery` splits the query on whitespace while display names split on non-alphanumerics, so a literally-typed `quickbooks online (sandbox) find` leaves the token `(sandbox)`, fails full-name coverage and drops the piece. Only 6 pieces have parentheses (two of them `(Legacy)`/`(Deprecated)`), and every query a human actually types — `quickbooks find`, `quickbooks sandbox find`, `http send`, `approval wait` — finds them at rank 1-3. It surfaces only in generated corpora that build queries by lowercasing display names; do not mistake it for a real defect the way one sweep here did.- **Five frontend surfaces still render the whole ~700-piece catalogue into the DOM, and `usePieces({})` with no `searchQuery` hands them all of it.** The virtualization primitives exist (`VirtualizedScrollArea` in the builder's `pieces-card-list`, `VirtualizedList` in the MCP pieces tab, `virtualizeRows` on `DataTable`) — these just do not use them: the MCP-server `PiecesShowcase` tiles every piece into two masked rows on page load, `NewConnectionDialog` grids every piece that has `auth` as 150x150 cards, project-settings Pieces passes `hidePagination` to a `DataTable` **without** `virtualizeRows` (which defaults to `false`, unlike the platform-admin pieces tables), and both the connections piece filter (`DataTableSelectPopover`) and the piece-selector customization dialog mount every piece as a `CommandItem` — cmdk then rescores all of them per keystroke. Separately, the builder's Explore tab is non-virtualized *and correct in production* (it only ever holds Popular + Highlights), but `getExploreTabContent` has `metadata: environment === ApEnvironment.DEVELOPMENT ? queryResult : []` — so locally Popular **is** the entire catalogue. That is why the Explore tab feels sluggish in dev and fine on cloud; do not chase it as a production regression.+- **Deleting a piece's source is safe for pinned flows; deleting the server route that source calls is not.** A step pinned to an older piece version runs that version's *published bundle*, which carries its own compiled copy of everything it imports — so removing a file from the repo cannot break it, and a refactor may delete what it replaces in the same PR. A server API route those older bundles call at run time is the opposite: it has live callers until a flow migration has moved every pinned step forward, and closing it early fails them with nothing in the repo to explain why. So the two halves of "remove the old path" sequence differently — source with the change, route after the migration promotes. One exception on the source side: anything re-exported from the piece's `index.ts` is public surface, so check the breaking-change rules before removing it.+- **`piece-upgrade-register.json` has two consumers, not one.** The upgrade/downgrade dialog is the obvious one; the other is `migrate-v23`, which sits in the flow migration chain — so the register rewrites `pieceVersion` on every flow-version read, not only when someone clicks something. That makes regenerating it a live change to running flows. It also means a migration that pins a version can be undone by a later one in the same `apply()` pass: `migrate-v22` hands off at schemaVersion 23 and `migrate-v23`'s `targetSchemaVersion` is 23, so both run in one pass. Harmless only because the register's highest AI entry is `0.4.4` — add entries and v23 starts upgrading what v22 just pinned. **Pin versions in a migration of your own, appended last; leave the register alone.**- **`ctx.files.write()` returns a URL served as `application/octet-stream`, so a vendor that sniffs Content-Type will reject it.** The signed read URL (`v1/files/{id}?token=`) carries no file extension, and on S3/R2 storage it 307-redirects to presigned storage where the real filename rides only on `response-content-disposition`. WhatsScale's `/make/prepareFile` refuses it outright — `"URL did not return an image, video, document, or audio file. Got content-type: application/octet-stream" (400)` — unless an explicit `mediaType` is passed alongside the URL. Any piece that hands an AP-hosted file URL to a third party has to tell that API the media type out-of-band; do not assume the URL is self-describing. Verified live 2026-08-24 on the WhatsScale piece: identical URL, 400 without `mediaType`, delivered correctly with it.diff --git a/packages/server/utils/src/ai-utils.ts b/packages/server/utils/src/ai-utils.tsindex 5b5ef09e582..02e2a2927aa 100644--- a/packages/server/utils/src/ai-utils.ts+++ b/packages/server/utils/src/ai-utils.ts@@ -1,6 +1,6 @@import { AIProviderName, isNil, observedProviderFetch, ProviderOutcomeReporter, spreadIfDefined } from '@activepieces/core-utils';import { createLanguageModel } from '@activepieces/ai-providers';-import { AI_PROVIDER_CAPABILITIES, AIWebSearchMode, BaseAIProviderAuthConfig, CloudflareGatewayProviderConfig, splitCloudflareGatewayModelId } from '@activepieces/shared';+import { AI_PROVIDER_CAPABILITIES, AIWebSearchMode, BaseAIProviderAuthConfig, CloudflareGatewayProviderConfig, getEffectiveProviderAndModel, splitCloudflareGatewayModelId } from '@activepieces/shared';import { createAnthropic } from '@ai-sdk/anthropic'import { createAzure } from '@ai-sdk/azure'import { createGoogleGenerativeAI } from '@ai-sdk/google'@@ -10,44 +10,120 @@ import { SharedV3ProviderOptions } from '@ai-sdk/provider'import { createOpenRouter, OpenRouterChatSettings } from '@openrouter/ai-sdk-provider'import { EmbeddingModel, LanguageModel, ToolSet } from 'ai'-const MAX_WEB_SEARCH_RESULTS = 5-// OpenAI is absent on purpose: its web search needs the Responses API, which breaks legacy BYOK models.+const DEFAULT_WEB_SEARCH_RESULTS = 5+const MIN_OPENROUTER_WEB_SEARCH_RESULTS = 1+const MAX_OPENROUTER_WEB_SEARCH_RESULTS = 10+// Which providers support web search (and how) is declared in AI_PROVIDER_CAPABILITIES; the native-// tool builders below stay here because they need the provider SDKs.-const NATIVE_WEB_SEARCH_TOOLS: Partial<Record<AIProviderName, (auth: BaseAIProviderAuthConfig) => ToolSet>> = {- [AIProviderName.ANTHROPIC]: ({ apiKey }) => ({ web_search: createAnthropic({ apiKey }).tools.webSearch_20250305({ maxUses: MAX_WEB_SEARCH_RESULTS }) }),- [AIProviderName.GOOGLE]: ({ apiKey }) => ({ google_search: createGoogleGenerativeAI({ apiKey }).tools.googleSearch({}) }),+// tool builders stay here because they need the provider SDKs. AI_PROVIDER_CAPABILITIES lists no+// web-search mode for OPENAI, so supportsWebSearch gates it off for callers that ask; a caller that+// names OPENAI outright still gets the Responses-API tool below. Keyed on the provider that serves+// the model, which is why buildWebSearchTools resolves through getEffectiveProviderAndModel first:+// a Cloudflare Gateway model is served by whichever submodel its id names, and there is no+// CLOUDFLARE_GATEWAY entry here to fall back to.+const NATIVE_WEB_SEARCH_TOOLS: Record<string, (params: NativeWebSearchToolParams) => ToolSet> = {+ [AIProviderName.ANTHROPIC]: ({ auth: { apiKey }, options }) => ({+ web_search: createAnthropic({ apiKey }).tools.webSearch_20250305({+ maxUses: options.maxUses ?? DEFAULT_WEB_SEARCH_RESULTS,+ ...spreadIfDefined('userLocation', buildUserLocation(options)),+ ...spreadIfDefined('allowedDomains', allowedSearchDomains(options)),+ ...spreadIfDefined('blockedDomains', blockedSearchDomains(options)),+ }),+ }),+ [AIProviderName.OPENAI]: ({ auth: { apiKey }, options }) => ({+ web_search_preview: createOpenAI({ apiKey }).tools.webSearchPreview({+ ...spreadIfDefined('searchContextSize', options.searchContextSize),+ ...spreadIfDefined('userLocation', buildUserLocation(options)),+ }),+ }),+ [AIProviderName.GOOGLE]: ({ auth: { apiKey } }) => ({ google_search: createGoogleGenerativeAI({ apiKey }).tools.googleSearch({}) }),}function supportsWebSearch(provider: AIProviderName): boolean {return AI_PROVIDER_CAPABILITIES[provider].webSearch !== undefined}-function buildWebSearchTools({ provider, auth }: {+function buildWebSearchTools({ provider, model, auth, options = {} }: {provider: AIProviderName+ model?: stringauth: Record<string, unknown>+ options?: WebSearchOptions}): ToolSet {- return NATIVE_WEB_SEARCH_TOOLS[provider]?.(auth as BaseAIProviderAuthConfig) ?? {}+ const { provider: searchProvider } = getEffectiveProviderAndModel({ provider, model })+ return NATIVE_WEB_SEARCH_TOOLS[searchProvider ?? provider]?.({ auth: auth as BaseAIProviderAuthConfig, options }) ?? {}}function webSearchModeOf(provider: AIProviderName): AIWebSearchMode | undefined {return AI_PROVIDER_CAPABILITIES[provider].webSearch}-function openRouterModelSettings(provider: AIProviderName, webSearchEnabled: boolean): OpenRouterChatSettings | undefined {+function buildWebSearchToolsOrThrow({ provider, model, auth, webSearchEnabled, options = {} }: {+ provider: AIProviderName+ model?: string+ auth: Record<string, unknown>+ webSearchEnabled: boolean+ options?: WebSearchOptions+}): ToolSet {+ if (!webSearchEnabled) {+ return {}+ }+ const { provider: searchProvider } = getEffectiveProviderAndModel({ provider, model })+ const resolvedProvider = searchProvider ?? provider+ if (AI_PROVIDER_CAPABILITIES[provider].webSearch === 'plugin') {+ return {}+ }+ if (isNil(NATIVE_WEB_SEARCH_TOOLS[resolvedProvider])) {+ throw new Error(`Provider ${resolvedProvider} is not supported for web search`)+ }+ return buildWebSearchTools({ provider, model, auth, options })+}++function buildUserLocation(options: WebSearchOptions): UserLocation | undefined {+ const location = {+ ...spreadIfDefined('city', options.userLocationCity),+ ...spreadIfDefined('region', options.userLocationRegion),+ ...spreadIfDefined('country', options.userLocationCountry),+ ...spreadIfDefined('timezone', options.userLocationTimezone),+ }+ return Object.keys(location).length === 0 ? undefined : { type: 'approximate', ...location }+}++function allowedSearchDomains(options: WebSearchOptions): string[] | undefined {+ const domains = options.allowedDomains?.map(({ domain }) => domain) ?? []+ return domains.length === 0 ? undefined : domains+}++function blockedSearchDomains(options: WebSearchOptions): string[] | undefined {+ if (!isNil(allowedSearchDomains(options))) {+ return undefined+ }+ const domains = options.blockedDomains?.map(({ domain }) => domain) ?? []+ return domains.length === 0 ? undefined : domains+}++function openRouterModelSettings({ provider, webSearchEnabled, options }: {+ provider: AIProviderName+ webSearchEnabled: boolean+ options?: WebSearchOptions+}): OpenRouterChatSettings | undefined {if (!webSearchEnabled || AI_PROVIDER_CAPABILITIES[provider].webSearch !== 'plugin') {return undefined}- return { plugins: [{ id: 'web', max_results: MAX_WEB_SEARCH_RESULTS }] }+ const maxResults = Math.min(+ Math.max(options?.maxUses ?? DEFAULT_WEB_SEARCH_RESULTS, MIN_OPENROUTER_WEB_SEARCH_RESULTS),+ MAX_OPENROUTER_WEB_SEARCH_RESULTS,+ )+ return { plugins: [{ id: 'web', max_results: maxResults }] }}-function createModel({ provider, auth, config, modelId, metadata, webSearchEnabled = false, onOutcome }: {+function createModel({ provider, auth, config, modelId, metadata, webSearchEnabled = false, webSearchOptions, onOutcome }: {provider: AIProviderNameauth: Record<string, unknown>config: Record<string, unknown>modelId: stringmetadata?: ChatModelMetadatawebSearchEnabled?: boolean+ webSearchOptions?: WebSearchOptionsonOutcome?: ProviderOutcomeReporter}): LanguageModel {if (provider === AIProviderName.CLOUDFLARE_GATEWAY) {@@ -67,7 +143,7 @@ function createModel({ provider, auth, config, modelId, metadata, webSearchEnablconfig,modelId,options: {- openRouterSettings: openRouterModelSettings(provider, webSearchEnabled),+ openRouterSettings: openRouterModelSettings({ provider, webSearchEnabled, options: webSearchOptions }),mistralViaOpenRouter: true,...spreadIfDefined('extraHeaders', managedProviderMetadataHeaders({ provider, metadata })),...spreadIfDefined('onOutcome', onOutcome),@@ -153,6 +229,32 @@ export const aiUtils = {supportsWebSearch,buildWebSearchTools,webSearchModeOf,+ buildWebSearchToolsOrThrow,+}++type NativeWebSearchToolParams = {+ auth: BaseAIProviderAuthConfig+ options: WebSearchOptions+}++type UserLocation = {+ type: 'approximate'+ city?: string+ region?: string+ country?: string+ timezone?: string+}++type WebSearchOptions = {+ maxUses?: number+ includeSources?: boolean+ userLocationCity?: string+ userLocationRegion?: string+ userLocationCountry?: string+ userLocationTimezone?: string+ allowedDomains?: { domain: string }[]+ blockedDomains?: { domain: string }[]+ searchContextSize?: 'low' | 'medium' | 'high'}type ChatModelMetadata = {@@ -161,4 +263,4 @@ type ChatModelMetadata = {runId?: string}-export type { ChatModelMetadata }+export type { ChatModelMetadata, WebSearchOptions }diff --git a/packages/server/utils/src/index.ts b/packages/server/utils/src/index.tsindex 1525db91b91..0a970a14f93 100644--- a/packages/server/utils/src/index.ts+++ b/packages/server/utils/src/index.ts@@ -30,3 +30,4 @@ export { systemUsage } from './system-usage'export { agentAiUtils } from './agent-ai-utils'export type { ContentPartLike } from './agent-ai-utils'export { aiUtils, EMBEDDING_DIMENSIONS } from './ai-utils'+export type { WebSearchOptions } from './ai-utils'diff --git a/packages/server/utils/test/ai-utils.test.ts b/packages/server/utils/test/ai-utils.test.tsnew file mode 100644index 00000000000..ff177b29ea9--- /dev/null+++ b/packages/server/utils/test/ai-utils.test.ts@@ -0,0 +1,114 @@+import { AIProviderName } from '@activepieces/core-utils'+import { describe, expect, it } from 'vitest'+import { aiUtils, WebSearchOptions } from '../src/ai-utils'++function anthropicSearchArgs(options: WebSearchOptions): Record<string, unknown> {+ const tools = aiUtils.buildWebSearchTools({ provider: AIProviderName.ANTHROPIC, auth: { apiKey: 'key' }, options })+ return toArgs(tools['web_search'])+}++function toArgs(tool: unknown): Record<string, unknown> {+ const args = (tool as { args?: Record<string, unknown> } | undefined)?.args+ return args ?? {}+}++describe('aiUtils.buildWebSearchTools', () => {+ it('defaults to five uses when the caller passes no options, as the agent does', () => {+ const tools = aiUtils.buildWebSearchTools({ provider: AIProviderName.ANTHROPIC, auth: { apiKey: 'key' } })+ expect(toArgs(tools['web_search'])).toEqual({ maxUses: 5 })+ })++ it('drops blocked domains when allowed domains are present, rather than sending both', () => {+ expect(anthropicSearchArgs({+ allowedDomains: [{ domain: 'docs.example.com' }],+ blockedDomains: [{ domain: 'spam.example.com' }],+ })).toEqual({ maxUses: 5, allowedDomains: ['docs.example.com'] })+ })++ it('sends blocked domains when no allowed domains narrow the search', () => {+ expect(anthropicSearchArgs({ blockedDomains: [{ domain: 'spam.example.com' }] }))+ .toEqual({ maxUses: 5, blockedDomains: ['spam.example.com'] })+ })++ it('treats an empty domain list as absent', () => {+ expect(anthropicSearchArgs({ allowedDomains: [], blockedDomains: [{ domain: 'spam.example.com' }] }))+ .toEqual({ maxUses: 5, blockedDomains: ['spam.example.com'] })+ })++ it('builds a partial user location from whichever fields were filled in', () => {+ expect(anthropicSearchArgs({ userLocationCity: 'Amman', userLocationTimezone: 'Asia/Amman' }))+ .toEqual({ maxUses: 5, userLocation: { type: 'approximate', city: 'Amman', timezone: 'Asia/Amman' } })+ })++ it('omits the user location entirely when no location field was filled in', () => {+ expect(anthropicSearchArgs({ maxUses: 2 })).toEqual({ maxUses: 2 })+ })++ it('gives OpenAI the Responses-API preview tool with its own options', () => {+ const tools = aiUtils.buildWebSearchTools({+ provider: AIProviderName.OPENAI,+ auth: { apiKey: 'key' },+ options: { searchContextSize: 'high', userLocationCountry: 'JO' },+ })+ expect(toArgs(tools['web_search_preview']))+ .toEqual({ searchContextSize: 'high', userLocation: { type: 'approximate', country: 'JO' } })+ })++ it('follows a Cloudflare Gateway model to the provider that actually serves it', () => {+ const tools = aiUtils.buildWebSearchTools({+ provider: AIProviderName.CLOUDFLARE_GATEWAY,+ model: 'anthropic/claude-sonnet-4-6',+ auth: { apiKey: 'key' },+ options: { maxUses: 3 },+ })+ expect(toArgs(tools['web_search'])).toEqual({ maxUses: 3 })+ })++ it('returns no tools for a Cloudflare Gateway model whose submodel has no native web search', () => {+ expect(aiUtils.buildWebSearchTools({+ provider: AIProviderName.CLOUDFLARE_GATEWAY,+ model: 'mistral/mistral-large',+ auth: { apiKey: 'key' },+ })).toEqual({})+ })++ it('returns no tools for a provider that has no native web search', () => {+ expect(aiUtils.buildWebSearchTools({ provider: AIProviderName.MISTRAL, auth: { apiKey: 'key' } })).toEqual({})+ })+})++describe('aiUtils.buildWebSearchToolsOrThrow', () => {+ it('fails the way the piece does when the provider has no web search', () => {+ expect(() => aiUtils.buildWebSearchToolsOrThrow({ provider: AIProviderName.AZURE, auth: { apiKey: 'key' }, webSearchEnabled: true }))+ .toThrow('Provider azure is not supported for web search')+ })++ it('fails on a Cloudflare Gateway model whose submodel has no web search, naming the gateway as the piece does', () => {+ expect(() => aiUtils.buildWebSearchToolsOrThrow({+ provider: AIProviderName.CLOUDFLARE_GATEWAY,+ model: 'mistral/mistral-large',+ auth: { apiKey: 'key' },+ webSearchEnabled: true,+ })).toThrow('Provider cloudflare-gateway is not supported for web search')+ })++ it('returns no tools without throwing for a plugin provider, which searches through the model instead', () => {+ expect(aiUtils.buildWebSearchToolsOrThrow({ provider: AIProviderName.ACTIVEPIECES, auth: { apiKey: 'key' }, webSearchEnabled: true })).toEqual({})+ expect(aiUtils.buildWebSearchToolsOrThrow({ provider: AIProviderName.OPENROUTER, auth: { apiKey: 'key' }, webSearchEnabled: true })).toEqual({})+ })++ it('builds the same tool as the total variant when the provider is supported', () => {+ const strict = aiUtils.buildWebSearchToolsOrThrow({+ provider: AIProviderName.CLOUDFLARE_GATEWAY,+ model: 'anthropic/claude-sonnet-4-6',+ auth: { apiKey: 'key' },+ webSearchEnabled: true,+ options: { maxUses: 3 },+ })+ expect(toArgs(strict['web_search'])).toEqual({ maxUses: 3 })+ })++ it('stays silent for an unsupported provider when web search is switched off', () => {+ expect(aiUtils.buildWebSearchToolsOrThrow({ provider: AIProviderName.AZURE, auth: { apiKey: 'key' }, webSearchEnabled: false })).toEqual({})+ })+})