Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(web-app): serve a same-named MCP web_search/web_fetch when built-in web search is off (#9458) (#9459)
Thinh Le00a168e2602c
diff --git a/web-app/src/hooks/useToolOrigin.ts b/web-app/src/hooks/useToolOrigin.tsindex c5536c991..e206e4fdb 100644--- a/web-app/src/hooks/useToolOrigin.ts+++ b/web-app/src/hooks/useToolOrigin.ts@@ -19,6 +19,7 @@ export const useToolOrigin = (toolName: string): ToolOrigin | undefined => {const webSearchProviderLabel = useWebSearchConfig((s) => getProviderMeta(s.searchProvider).label)+ const webSearchEnabled = useWebSearchConfig((s) => s.webSearchEnabled)return useMemo(() =>@@ -27,7 +28,15 @@ export const useToolOrigin = (toolName: string): ToolOrigin | undefined => {isRagTool,isAgentTool,webSearchProviderLabel,+ webSearchEnabled,}),- [toolName, mcpServer, isRagTool, isAgentTool, webSearchProviderLabel]+ [+ toolName,+ mcpServer,+ isRagTool,+ isAgentTool,+ webSearchProviderLabel,+ webSearchEnabled,+ ])}diff --git a/web-app/src/lib/__tests__/toolOrigin.test.ts b/web-app/src/lib/__tests__/toolOrigin.test.tsindex 8bd45b59f..944699097 100644--- a/web-app/src/lib/__tests__/toolOrigin.test.ts+++ b/web-app/src/lib/__tests__/toolOrigin.test.ts@@ -5,6 +5,7 @@ const context = {isRagTool: false,isAgentTool: false,webSearchProviderLabel: 'Exa',+ webSearchEnabled: true,}describe('resolveToolOrigin', () => {@@ -42,14 +43,35 @@ describe('resolveToolOrigin', () => {).toEqual({ kind: 'mcp', detail: 'filesystem' })})- // Mirrors the thread route's execution order, where native web tools are- // dispatched before any MCP tool of the same name.- it('prefers the native web tool over a same-named MCP tool', () => {+ // Mirrors the thread route: while web search is on the native tool is what+ // was offered and what runs, even when an MCP server has the same name.+ it('prefers the native web tool over a same-named MCP tool while web search is on', () => {expect(resolveToolOrigin('web_search', { ...context, mcpServer: 'someserver' })).toEqual({ kind: 'web-search', detail: 'Exa' })})+ // With it off the MCP server's tool is the one that ran (#9458); labelling+ // it as the built-in provider would credit a search Exa never saw.+ it.each(['web_search', 'web_fetch'])(+ 'credits a same-named MCP %s to its server while web search is off',+ (name) => {+ expect(+ resolveToolOrigin(name, {+ ...context,+ webSearchEnabled: false,+ mcpServer: 'parallel',+ })+ ).toEqual({ kind: 'mcp', detail: 'parallel' })+ }+ )++ it('keeps the built-in label for a recorded web call no server provides', () => {+ expect(+ resolveToolOrigin('web_search', { ...context, webSearchEnabled: false })+ ).toEqual({ kind: 'web-search', detail: 'Exa' })+ })+it('prefers RAG over MCP when both somehow match', () => {expect(resolveToolOrigin('search_documents', {diff --git a/web-app/src/lib/__tests__/webSearchTool.test.ts b/web-app/src/lib/__tests__/webSearchTool.test.tsindex 0e69c9b37..1216a868e 100644--- a/web-app/src/lib/__tests__/webSearchTool.test.ts+++ b/web-app/src/lib/__tests__/webSearchTool.test.ts@@ -20,7 +20,7 @@ vi.mock('@/hooks/useMCPServers', () => ({useMCPServers: { getState: () => h.mcp },}))-import { executeWebTool, webOutputCap } from '../webSearchTool'+import { executeWebTool, webOutputCap, webToolRoute } from '../webSearchTool'import { parseWebFetchOutput } from '../toolPresentation'const page = (content: string, truncated = false) => ({@@ -217,3 +217,36 @@ describe('webOutputCap', () => {expect(webOutputCap(undefined)).toBeUndefined()})})++// #9458: Parallel Search and other search servers expose tools called+// `web_search` / `web_fetch`, the built-ins' own names.+describe('webToolRoute', () => {+ const mcp = new Set(['web_search', 'web_fetch', 'read_file'])++ it.each(['web_search', 'web_fetch'])(+ 'serves %s with the built-in while web search is on, whatever MCP offers',+ (name) => {+ expect(webToolRoute(name, true, mcp)).toBe('builtin')+ expect(webToolRoute(name, true, new Set())).toBe('builtin')+ }+ )++ it.each(['web_search', 'web_fetch'])(+ 'hands %s to the user\'s MCP server while web search is off',+ (name) => {+ expect(webToolRoute(name, false, mcp)).toBe('other')+ }+ )++ it.each(['web_search', 'web_fetch'])(+ 'refuses %s while web search is off and no server provides it',+ (name) => {+ expect(webToolRoute(name, false, new Set(['read_file']))).toBe('disabled')+ }+ )++ it('leaves every other tool name alone', () => {+ expect(webToolRoute('read_file', false, mcp)).toBe('other')+ expect(webToolRoute('shell', false, new Set())).toBe('other')+ })+})diff --git a/web-app/src/lib/toolOrigin.ts b/web-app/src/lib/toolOrigin.tsindex 5ad765dde..a6b23ed3f 100644--- a/web-app/src/lib/toolOrigin.ts+++ b/web-app/src/lib/toolOrigin.ts@@ -20,6 +20,8 @@ export type ToolOriginContext = {isAgentTool: boolean/** Display name of the configured web search provider, e.g. "Exa". */webSearchProviderLabel: string+ /** Whether built-in web search is on: it only owns a web tool name then. */+ webSearchEnabled: boolean}export const WEB_SEARCH_TOOL = 'web_search'@@ -34,12 +36,22 @@ export const TASK_TOOL = 'task'*/export function resolveToolOrigin(toolName: string,- { mcpServer, isRagTool, isAgentTool, webSearchProviderLabel }: ToolOriginContext+ {+ mcpServer,+ isRagTool,+ isAgentTool,+ webSearchProviderLabel,+ webSearchEnabled,+ }: ToolOriginContext): ToolOrigin | undefined {- if (toolName === WEB_SEARCH_TOOL) {+ // With web search off nothing built-in was offered, so an MCP server's tool+ // of the same name is the one that ran (`webToolRoute`). A recorded call with+ // no such server keeps its built-in label: it is history, not a live route.+ const builtinWins = webSearchEnabled || !mcpServer+ if (toolName === WEB_SEARCH_TOOL && builtinWins) {return { kind: 'web-search', detail: webSearchProviderLabel }}- if (toolName === WEB_FETCH_TOOL) return { kind: 'web-fetch' }+ if (toolName === WEB_FETCH_TOOL && builtinWins) return { kind: 'web-fetch' }// Dispatched by the surface rather than the plugin, so it is not in the agent// tool set and would otherwise fall through to the unlabelled generic card.if (toolName === TASK_TOOL) return { kind: 'subagent' }diff --git a/web-app/src/lib/webSearchTool.ts b/web-app/src/lib/webSearchTool.tsindex 44953ecc8..9ee2fbe81 100644--- a/web-app/src/lib/webSearchTool.ts+++ b/web-app/src/lib/webSearchTool.ts@@ -5,6 +5,23 @@ import { TRUNCATION_MARKER } from '@/lib/toolPresentation'export const WEB_TOOL_NAMES = new Set(['web_search', 'web_fetch'])+/**+ * How a call to a built-in web tool name is served. While web search is on the+ * built-in tools are what the model was offered, so they serve the call. While+ * it is off nothing is offered, so an MCP tool of the same name belongs to the+ * user and is an MCP call; with none, the call is refused rather than reaching+ * the provider the user switched off. Any other name is not a web tool.+ */+export function webToolRoute(+ toolName: string,+ webSearchEnabled: boolean,+ mcpToolNames: ReadonlySet<string>+): 'builtin' | 'disabled' | 'other' {+ if (!WEB_TOOL_NAMES.has(toolName)) return 'other'+ if (webSearchEnabled) return 'builtin'+ return mcpToolNames.has(toolName) ? 'other' : 'disabled'+}+export const WEB_SEARCH_DESCRIPTION ='Search the web and return a ranked list of results (title, URL, snippet, and optional publish date). Use this to find current information, documentation, or sources you can then read with web_fetch. Cite the URLs you rely on.'diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsxindex 631e5f959..5f9f06078 100644--- a/web-app/src/routes/threads/$threadId.tsx+++ b/web-app/src/routes/threads/$threadId.tsx@@ -100,7 +100,8 @@ import { IconAlertCircle, IconRefresh, IconLoader2 } from '@tabler/icons-react'import { useToolApproval } from '@/hooks/useToolApproval'import { useToolApprovalRequests } from '@/hooks/useToolApprovalRequests'import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'-import { WEB_TOOL_NAMES, executeWebTool } from '@/lib/webSearchTool'+import { webToolRoute, executeWebTool } from '@/lib/webSearchTool'+import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'import { CHAT_AGENT_TOOL_NAMES, executeAgentTool } from '@/lib/agentTools'import DropdownModelProvider from '@/containers/DropdownModelProvider'import { ExtensionTypeEnum, VectorDBExtension } from '@janhq/core'@@ -245,6 +246,12 @@ const SHELL_DISABLED_TOOL_ERROR ='Shell is turned off: the user disabled it, so this command was not run. ' +'Do not call the shell again in this chat; use another approach or tell the user it is needed.'+// Recorded for a call to a built-in web tool while the user has web search off+// and no MCP server provides a tool of that name.+const WEB_DISABLED_TOOL_ERROR =+ 'Web search is turned off: the user disabled it, so this call was not run. ' ++ 'Do not call web_search or web_fetch again in this chat; answer from what you know or tell the user it is needed.'+// Rewrites a turn that is already stored with what its live copy holds now. A// turn is stored before its tools run, so a call's outcome (result, error,// stopped) only reaches storage when a later reply rewrites the turn; when no@@ -305,13 +312,27 @@ function isDisabledChatAgentTool(toolName: string): boolean {return chatShellRoute(toolName) === 'disabled'}+// How a call to a built-in web tool name is served. Same contract as the shell:+// while web search is on the built-in is what was offered, so it serves the+// call; while it is off nothing is offered, so an MCP tool of the same name is+// the user's own and is served as an MCP tool (it prompts like any other); with+// no such MCP tool the call is refused instead of reaching the search provider+// the user switched off.+function webRoute(toolName: string): 'builtin' | 'disabled' | 'other' {+ return webToolRoute(+ toolName,+ useWebSearchConfig.getState().webSearchEnabled,+ useAppState.getState().mcpToolNames+ )+}+// Internal tools never prompt: RAG and the native web tools are Jan's own, and// the built-in shell is gated in Rust (execute_tool refuses anything needing// approval), so only workspace-confined calls ever reach here.function isAutoAllowedTool(toolName: string): boolean {return (useAppState.getState().ragToolNames.has(toolName) ||- WEB_TOOL_NAMES.has(toolName) ||+ webRoute(toolName) === 'builtin' ||chatShellRoute(toolName) === 'builtin')}@@ -804,6 +825,16 @@ function ThreadDetail() {try {const toolName = toolCall.toolName+ if (webRoute(toolName) === 'disabled') {+ record({+ state: 'output-error',+ tool: toolCall.toolName,+ toolCallId: toolCall.toolCallId,+ errorText: WEB_DISABLED_TOOL_ERROR,+ })+ continue+ }+if (isDisabledChatAgentTool(toolName)) {record({state: 'output-error',@@ -865,7 +896,7 @@ function ThreadDetail() {// a hung MCP server) must not hold the loop, and the thread, busy.const result = await untilAborted<ToolRunResult>((async () => {- if (WEB_TOOL_NAMES.has(toolName)) {+ if (webRoute(toolName) === 'builtin') {return await executeWebTool(toolName, toolCall.input, {maxOutputChars,})@@ -1067,6 +1098,7 @@ function ThreadDetail() {if (!isAutoAllowedTool(toolCall.toolName) &&!isDisabledChatAgentTool(toolCall.toolName) &&+ webRoute(toolCall.toolName) !== 'disabled' &&!approvalsOf(threadId).has(toolCall.toolCallId)) {approvalsOf(threadId).set(diff --git a/web-app/src/routes/threads/__tests__/$threadId.test.tsx b/web-app/src/routes/threads/__tests__/$threadId.test.tsxindex b814d1c64..76f51a3ab 100644--- a/web-app/src/routes/threads/__tests__/$threadId.test.tsx+++ b/web-app/src/routes/threads/__tests__/$threadId.test.tsx@@ -1,5 +1,6 @@/* eslint-disable @typescript-eslint/no-explicit-any */import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import type * as WebSearchConfigModule from '@/hooks/useWebSearchConfig'import { render, screen, act, waitFor } from '@testing-library/react'import '@testing-library/jest-dom'import React from 'react'@@ -486,6 +487,16 @@ vi.mock('@/lib/webSearchTool', async (importOriginal) => ({executeWebTool: webTool.executeWebTool,}))+// The real store persists through localStorage on every write, which this+// environment does not provide; the route only reads the on/off switch.+const webConfig = vi.hoisted(() => ({ enabled: true }))+vi.mock('@/hooks/useWebSearchConfig', async (importOriginal) => ({+ ...(await importOriginal<typeof WebSearchConfigModule>()),+ useWebSearchConfig: {+ getState: () => ({ webSearchEnabled: webConfig.enabled }),+ },+}))+// -----------------------------------------------------------------------------// Import component AFTER mocks// -----------------------------------------------------------------------------@@ -1590,6 +1601,99 @@ describe('ThreadDetail route', () => {})})+ // #9458: search servers such as Parallel Search expose tools named+ // `web_search` / `web_fetch`, the built-ins' own names. Execution used to+ // route on the name alone, so the built-in provider answered (and failed)+ // even after the user switched web search off to use their own server.+ describe('built-in web tool names at execution time', () => {+ interface WebCall {+ toolCall: {+ toolCallId: string+ toolName: string+ input: { query: string }+ }+ }+ const webCall = (id: string, toolName = 'web_search'): WebCall => ({+ toolCall: { toolCallId: id, toolName, input: { query: 'jan' } },+ })+ const finish = () =>+ (h as any).capturedOnFinish({+ message: {+ id: 'a-web',+ role: 'assistant',+ parts: [{ type: 'text', text: '' }],+ metadata: { finishReason: 'tool-calls' },+ },+ isAbort: false,+ })+ const run = async (call: WebCall) => {+ renderComponent()+ await act(async () => {+ await (h as any).capturedOnToolCall(call)+ })+ await act(async () => {+ await finish()+ })+ }+ const serveMcp = () => {+ const callTool = vi.fn().mockResolvedValue({ error: '', content: [] })+ hub.mcp = () =>+ ({+ callToolWithCancellation: (args: unknown) => ({+ promise: callTool(args),+ cancel: vi.fn().mockResolvedValue(undefined),+ token: 't',+ }),+ }) as never+ return callTool+ }++ beforeEach(() => {+ webConfig.enabled = true+ webTool.executeWebTool.mockReset()+ webTool.executeWebTool.mockResolvedValue({ content: 'page' })+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)+ })+ afterEach(() => {+ webConfig.enabled = true+ })++ it('serves the call with the built-in, without a prompt, while web search is on', async () => {+ await run(webCall('w1'))+ expect(webTool.executeWebTool).toHaveBeenCalledTimes(1)+ expect(h.toolApprovalState.requestApproval).not.toHaveBeenCalled()+ })++ it.each(['web_search', 'web_fetch'])(+ 'serves an MCP tool named %s through MCP, with a prompt, while web search is off',+ async (name) => {+ webConfig.enabled = false+ h.appStateState.mcpToolNames = new Set([name])+ const callTool = serveMcp()+ await run(webCall('w2', name))+ expect(webTool.executeWebTool).not.toHaveBeenCalled()+ expect(h.toolApprovalState.requestApproval).toHaveBeenCalledTimes(1)+ expect(callTool).toHaveBeenCalledTimes(1)+ expect(callTool.mock.calls[0][0]).toMatchObject({ toolName: name })+ }+ )++ it('refuses the call, before any prompt, when web search is off and no server provides the tool', async () => {+ webConfig.enabled = false+ h.appStateState.mcpToolNames = new Set(['fetch'])+ await run(webCall('w3'))+ expect(webTool.executeWebTool).not.toHaveBeenCalled()+ expect(h.toolApprovalState.requestApproval).not.toHaveBeenCalled()+ expect(h.mockAddToolOutput).toHaveBeenCalledWith(+ expect.objectContaining({+ toolCallId: 'w3',+ state: 'output-error',+ errorText: expect.stringMatching(/turned off.*Do not call web_search/s),+ })+ )+ })+ })+describe('tool-call approval requested early, execution stays in onFinish', () => {const toolCall = (id: string) => ({toolCall: { toolCallId: id, toolName: 'fetch', input: { url: 'x' } },