From a4445e8d465d57f5efbf3061da2d3acb0a379beb Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Thu, 12 Nov 2026 23:59:09 +0100 Subject: [PATCH 01/19] ui: add an extension registry to Llama Chat Extensions are how a feature outside the core plugs into the app. Each one is known by a manifest, its code is imported only when it is activated, and it adds its parts through extension points. The registry holds those contributions and removes them, running the extension's cleanup, when the extension is switched off. The app starts its built-in extensions once the stores are ready. MCP is the first one: it is registered here and contributes nothing yet, the next commits move it behind the extension points one by one. Assisted-by: Claude (Opus 5.5 Medium) --- .../src/lib/constants/storage.constants.ts | 3 + ui/apps/chat/src/lib/extensions/builtin.ts | 16 + ui/apps/chat/src/lib/extensions/index.ts | 15 + ui/apps/chat/src/lib/extensions/mcp/index.ts | 12 + .../src/lib/extensions/registry.svelte.ts | 226 ++++++++++++++ ui/apps/chat/src/lib/extensions/types.ts | 95 ++++++ ui/apps/chat/src/lib/stores/init.ts | 8 + .../tests/unit/extensions-registry.test.ts | 277 ++++++++++++++++++ 8 files changed, 652 insertions(+) create mode 100644 ui/apps/chat/src/lib/extensions/builtin.ts create mode 100644 ui/apps/chat/src/lib/extensions/index.ts create mode 100644 ui/apps/chat/src/lib/extensions/mcp/index.ts create mode 100644 ui/apps/chat/src/lib/extensions/registry.svelte.ts create mode 100644 ui/apps/chat/src/lib/extensions/types.ts create mode 100644 ui/apps/chat/tests/unit/extensions-registry.test.ts diff --git a/ui/apps/chat/src/lib/constants/storage.constants.ts b/ui/apps/chat/src/lib/constants/storage.constants.ts index 1b10507dd491..fa8d6a09dfb9 100644 --- a/ui/apps/chat/src/lib/constants/storage.constants.ts +++ b/ui/apps/chat/src/lib/constants/storage.constants.ts @@ -24,6 +24,9 @@ export const DISABLED_TOOL_KEYS_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.disabled /** Default disabled tool categories, seeded into newly created conversations */ export const DISABLED_TOOL_CATEGORIES_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.disabledToolCategories`; + +/** The user's on/off choice per extension, by extension id */ +export const EXTENSIONS_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.extensions`; export const FAVORITE_MODELS_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.favoriteModels`; /** Open state the user set for a model list section or one of its families, by id. */ diff --git a/ui/apps/chat/src/lib/extensions/builtin.ts b/ui/apps/chat/src/lib/extensions/builtin.ts new file mode 100644 index 000000000000..b8c19f17ca2f --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/builtin.ts @@ -0,0 +1,16 @@ +import type { ExtensionManifest } from './types'; + +/** + * The extensions this build of Llama Chat is composed with. Each `load` is a + * dynamic import, so nothing of an extension runs until the registry + * activates it. llama-server embeds the app as a single bundle, so there the + * code ships either way; a build that splits chunks fetches it on demand. + */ +export const BUILT_IN_EXTENSIONS: ExtensionManifest[] = [ + { + description: 'Connect MCP servers and use their tools, prompts and resources in chats.', + id: 'mcp', + load: () => import('./mcp'), + name: 'MCP' + } +]; diff --git a/ui/apps/chat/src/lib/extensions/index.ts b/ui/apps/chat/src/lib/extensions/index.ts new file mode 100644 index 000000000000..73a048b37638 --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/index.ts @@ -0,0 +1,15 @@ +export { ExtensionRegistry, extensions } from './registry.svelte'; +export type { + Extension, + ExtensionContext, + ExtensionManifest, + ExtensionPoint, + ExtensionPoints, + ExtensionState, + ExtensionStatus, + FlowHook, + FlowInfo, + ToolProvider, + ToolProviderCall, + ToolProviderEntry +} from './types'; diff --git a/ui/apps/chat/src/lib/extensions/mcp/index.ts b/ui/apps/chat/src/lib/extensions/mcp/index.ts new file mode 100644 index 000000000000..03ac15f062a1 --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/index.ts @@ -0,0 +1,12 @@ +/** + * The MCP extension: everything Llama Chat does with MCP servers reaches the + * core through what `activate` contributes here. + */ + +import type { Extension } from '../types'; + +const mcp: Extension = { + activate() {} +}; + +export default mcp; diff --git a/ui/apps/chat/src/lib/extensions/registry.svelte.ts b/ui/apps/chat/src/lib/extensions/registry.svelte.ts new file mode 100644 index 000000000000..ee2d59742fb0 --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/registry.svelte.ts @@ -0,0 +1,226 @@ +/** + * extensions - The extension registry + * + * Knows every extension the app was composed with, loads and activates the + * ones that are switched on, and holds what they contribute to each extension + * point. The core reads contributions from here and never imports an + * extension's code; switching an extension off removes its contributions. + */ + +import type { + Extension, + ExtensionContext, + ExtensionManifest, + ExtensionPoint, + ExtensionPoints, + ExtensionState, + ExtensionStatus +} from './types'; +import { EXTENSIONS_LOCALSTORAGE_KEY } from '#lib/constants/index.ts'; +import { browser } from '$app/env'; +import { SvelteMap } from 'svelte/reactivity'; + +interface Contribution { + owner: string; + point: ExtensionPoint; + value: unknown; +} + +type Cleanup = () => void | Promise; + +class ExtensionRegistry { + // the user's explicit on/off choices; an extension without one follows its manifest + private _choices = new SvelteMap(); + private _contributions = $state.raw([]); + private _errors = new SvelteMap(); + private _manifests = $state.raw([]); + private _states = new SvelteMap(); + private choicesLoaded = false; + // bookkeeping, deliberately not reactive + private cleanups: Record = {}; + // one chain per extension, so switching it on and off in a hurry stays in order + private queues: Record> = {}; + private storageKey: string | null; + + /** Every known extension with its current state, in registration order. */ + get extensions(): ExtensionStatus[] { + return this._manifests.map((manifest) => ({ + description: manifest.description, + enabled: this.isEnabled(manifest.id), + error: this._errors.get(manifest.id) ?? null, + id: manifest.id, + name: manifest.name, + state: this._states.get(manifest.id) ?? 'inactive' + })); + } + + /** Activate every extension that is switched on. Called once at startup; resolves when all settled. */ + async activateEnabled(): Promise { + this.loadChoices(); + + await Promise.all( + this._manifests + .filter((manifest) => this.isEnabled(manifest.id)) + .map((manifest) => this.enqueue(manifest.id, () => this.activate(manifest))) + ); + } + + /** + * @param options.storageKey - Where the on/off choices are kept in localStorage. + * Null keeps them in memory only, for a registry that is not the app's. + */ + constructor(options: { storageKey?: string | null } = {}) { + this.storageKey = + options.storageKey === undefined ? EXTENSIONS_LOCALSTORAGE_KEY : options.storageKey; + } + + /** What the active extensions contribute to a point, in activation order. Reactive. */ + contributions

(point: P): ExtensionPoints[P][] { + const result: ExtensionPoints[P][] = []; + + for (const contribution of this._contributions) { + if (contribution.point === point) result.push(contribution.value as ExtensionPoints[P]); + } + + return result; + } + + isEnabled(id: string): boolean { + const manifest = this._manifests.find((m) => m.id === id); + + if (!manifest) return false; + + return this._choices.get(id) ?? !manifest.disabledByDefault; + } + + /** Make an extension known. Its code is not loaded until it is activated. */ + register(manifest: ExtensionManifest): void { + if (this._manifests.some((m) => m.id === manifest.id)) { + throw new Error(`Extension "${manifest.id}" is already registered`); + } + + // read here rather than on first use, so a known extension always shows its stored choice + this.loadChoices(); + this._manifests = [...this._manifests, manifest]; + } + + /** Switch an extension on or off, remember the choice, and resolve once it took effect. */ + async setEnabled(id: string, enabled: boolean): Promise { + const manifest = this._manifests.find((m) => m.id === id); + + if (!manifest) return; + + this.loadChoices(); + this._choices.set(id, enabled); + this.persistChoices(); + + await this.enqueue(id, () => (enabled ? this.activate(manifest) : this.deactivate(id))); + } + + private async activate(manifest: ExtensionManifest): Promise { + const { id } = manifest; + + if (this._states.get(id) === 'active') return; + + this._errors.delete(id); + this._states.set(id, 'activating'); + + const cleanups: Cleanup[] = []; + + let live = true; + + this.cleanups[id] = cleanups; + + const ctx: ExtensionContext = { + contribute: (point, value) => { + if (!live) throw new Error(`Extension "${id}" is not active`); + + this._contributions = [...this._contributions, { owner: id, point, value }]; + }, + onDeactivate: (cleanup) => { + cleanups.push(cleanup); + } + }; + + cleanups.push(() => { + live = false; + }); + + try { + const module: { default: Extension } = await manifest.load(); + + await module.default.activate(ctx); + this._states.set(id, 'active'); + } catch (error) { + console.error(`[extensions] "${id}" failed to activate:`, error); + + await this.deactivate(id); + this._errors.set(id, error instanceof Error ? error.message : String(error)); + this._states.set(id, 'failed'); + } + } + + private async deactivate(id: string): Promise { + // contributions go first, so nothing reaches for an extension that is tearing down + this._contributions = this._contributions.filter((c) => c.owner !== id); + + const cleanups = this.cleanups[id] ?? []; + + delete this.cleanups[id]; + + for (const cleanup of cleanups.reverse()) { + try { + await cleanup(); + } catch (error) { + console.error(`[extensions] "${id}" failed to clean up:`, error); + } + } + + this._errors.delete(id); + this._states.set(id, 'inactive'); + } + + private enqueue(id: string, task: () => Promise): Promise { + const next = (this.queues[id] ?? Promise.resolve()).then(task); + + this.queues[id] = next; + + return next; + } + + private loadChoices(): void { + if (this.choicesLoaded || !browser || !this.storageKey) return; + + this.choicesLoaded = true; + + try { + const stored = localStorage.getItem(this.storageKey); + + if (!stored) return; + + const parsed: unknown = JSON.parse(stored); + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return; + + for (const [id, enabled] of Object.entries(parsed)) { + if (typeof enabled === 'boolean') this._choices.set(id, enabled); + } + } catch (error) { + console.error('[extensions] Failed to load the on/off choices from localStorage:', error); + } + } + + private persistChoices(): void { + if (!browser || !this.storageKey) return; + + try { + localStorage.setItem(this.storageKey, JSON.stringify(Object.fromEntries(this._choices))); + } catch { + // ignore storage errors + } + } +} + +export { ExtensionRegistry }; + +export const extensions = new ExtensionRegistry(); diff --git a/ui/apps/chat/src/lib/extensions/types.ts b/ui/apps/chat/src/lib/extensions/types.ts new file mode 100644 index 000000000000..653c45992b31 --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/types.ts @@ -0,0 +1,95 @@ +/** + * The extension contract: what an extension is, and the points of the app it + * can add to. Built-in features and, later, installed plugins go through the + * same contract. + */ + +import type { ToolSource } from '#lib/enums/index.ts'; +import type { OpenAIToolDefinition, ToolExecutionResult } from '#lib/types/index.ts'; + +/** What the app knows about an extension before its code is loaded. */ +export interface ExtensionManifest { + /** Stable identity: the key its on/off choice is stored under. */ + id: string; + name: string; + description: string; + /** Stays off until the user switches it on. */ + disabledByDefault?: boolean; + /** + * Imports the extension's code. Called only when the extension is activated, so none of it + * runs while the extension is off, and a build that splits chunks fetches it only then. + */ + load: () => Promise<{ default: Extension }>; +} + +/** An extension's code: one function that adds its contributions. */ +export interface Extension { + activate(ctx: ExtensionContext): void | Promise; +} + +/** Handed to `activate`. Everything done through it is undone when the extension is switched off. */ +export interface ExtensionContext { + /** Add a contribution to an extension point. */ + contribute

(point: P, contribution: ExtensionPoints[P]): void; + /** Run this when the extension is switched off, for whatever `contribute` does not cover. */ + onDeactivate(cleanup: () => void | Promise): void; +} + +/** Every extension point, with the shape of what goes into it. */ +export interface ExtensionPoints { + /** Runs around every agentic flow. */ + flow: FlowHook; + /** Tools the model can call, listed and run by the extension. */ + tools: ToolProvider; +} + +export type ExtensionPoint = keyof ExtensionPoints; + +export type ExtensionState = 'inactive' | 'activating' | 'active' | 'failed'; + +/** An extension as the settings list shows it. */ +export interface ExtensionStatus { + id: string; + name: string; + description: string; + enabled: boolean; + state: ExtensionState; + /** Why it failed to load or activate, when it did. */ + error: string | null; +} + +export interface FlowInfo { + conversationId: string; +} + +/** Called when an agentic flow starts; a returned function runs when the flow ends. */ +export type FlowHook = (flow: FlowInfo) => void | (() => void | Promise); + +export interface ToolProviderEntry { + definition: OpenAIToolDefinition; + /** The group the tool is listed under and switched off with, e.g. one MCP server's id. */ + groupId: string; + groupLabel: string; +} + +export interface ToolProviderCall { + /** The arguments as the model wrote them: a JSON string. */ + arguments: string; + id?: string; + name: string; +} + +export interface ToolProvider { + /** The tool category the provider's tools belong to. One provider per category. */ + source: ToolSource; + /** The tools on offer right now. The tools store reads this reactively. */ + entries(): ToolProviderEntry[]; + /** Run one tool call. Throws when the call fails. */ + execute(call: ToolProviderCall, signal?: AbortSignal): Promise; + /** Icon URL of a group, when it has one. */ + groupIcon?(groupId: string): string | null; + /** Whether the provider could offer tools under the current settings, connected or not. */ + isConfigured(): boolean; + /** Get the tools ready to list and call, before a flow asks for them. */ + prepare?(): Promise; +} diff --git a/ui/apps/chat/src/lib/stores/init.ts b/ui/apps/chat/src/lib/stores/init.ts index 2d67ae408305..c12a5ef5a28c 100644 --- a/ui/apps/chat/src/lib/stores/init.ts +++ b/ui/apps/chat/src/lib/stores/init.ts @@ -6,6 +6,8 @@ import { settingsStore } from './settings/index.svelte'; import { tabsStore } from './tabs.svelte'; import { toolsStore } from './tools.svelte'; import { versionStore } from './version.svelte'; +import { BUILT_IN_EXTENSIONS } from '#lib/extensions/builtin.ts'; +import { extensions } from '#lib/extensions/registry.svelte.ts'; import { MigrationService } from '#lib/services/migration.service.ts'; import { validateApiKey } from '#lib/utils/api-key-validation.ts'; import { browser } from '$app/env'; @@ -34,6 +36,12 @@ export function initStores(): Promise { settingsStore.initialize(); permissionsStore.initialize(); toolsStore.initialize(); + + // extensions start once the settings they read are in place + for (const manifest of BUILT_IN_EXTENSIONS) extensions.register(manifest); + + await extensions.activateEnabled(); + void versionStore.initialize(); void groupsStore.initialize(); diff --git a/ui/apps/chat/tests/unit/extensions-registry.test.ts b/ui/apps/chat/tests/unit/extensions-registry.test.ts new file mode 100644 index 000000000000..613d342af6da --- /dev/null +++ b/ui/apps/chat/tests/unit/extensions-registry.test.ts @@ -0,0 +1,277 @@ +// The registry is the only door between the core and an extension: what an +// extension contributes must be there while it is on and gone, with its +// cleanup run, once it is off. + +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('$app/env', () => ({ browser: true })); + +import { EXTENSIONS_LOCALSTORAGE_KEY } from '#lib/constants/index.ts'; +import { ToolSource } from '#lib/enums/index.ts'; +import type { + Extension, + ExtensionManifest, + FlowHook, + ToolProvider +} from '#lib/extensions/index.ts'; +import { ExtensionRegistry } from '#lib/extensions/index.ts'; + +function makeStorage(initial: Record = {}) { + const data = new Map(Object.entries(initial)); + + return { + data, + getItem: (key: string) => data.get(key) ?? null, + setItem: (key: string, value: string) => void data.set(key, value) + }; +} + +function makeProvider(): ToolProvider { + return { + entries: () => [], + execute: async () => ({ content: '', isError: false }), + isConfigured: () => true, + source: ToolSource.MCP + }; +} + +function makeManifest( + extension: Extension, + overrides: Partial = {} +): ExtensionManifest { + return { + description: 'A test extension', + id: 'test', + load: async () => ({ default: extension }), + name: 'Test', + ...overrides + }; +} + +describe('ExtensionRegistry', () => { + let storage: ReturnType; + + beforeEach(() => { + storage = makeStorage(); + vi.stubGlobal('localStorage', storage); + }); + + it('holds what an active extension contributes, per point', async () => { + const registry = new ExtensionRegistry(); + const provider = makeProvider(); + const hook: FlowHook = () => {}; + + registry.register( + makeManifest({ + activate(ctx) { + ctx.contribute('tools', provider); + ctx.contribute('flow', hook); + } + }) + ); + + expect(registry.contributions('tools')).toEqual([]); + + await registry.activateEnabled(); + + expect(registry.contributions('tools')).toEqual([provider]); + expect(registry.contributions('flow')).toEqual([hook]); + expect(registry.extensions[0]).toMatchObject({ enabled: true, error: null, state: 'active' }); + }); + + it('does not load the code of an extension that is off', async () => { + const registry = new ExtensionRegistry(); + const load = vi.fn(async () => ({ default: { activate() {} } })); + + registry.register(makeManifest({ activate() {} }, { disabledByDefault: true, load })); + await registry.activateEnabled(); + + expect(load).not.toHaveBeenCalled(); + expect(registry.extensions[0]).toMatchObject({ enabled: false, state: 'inactive' }); + + await registry.setEnabled('test', true); + + expect(load).toHaveBeenCalledOnce(); + expect(registry.extensions[0]).toMatchObject({ enabled: true, state: 'active' }); + }); + + it('removes the contributions and runs the cleanup when switched off', async () => { + const registry = new ExtensionRegistry(); + const order: string[] = []; + + registry.register( + makeManifest({ + activate(ctx) { + ctx.contribute('tools', makeProvider()); + ctx.onDeactivate(() => void order.push('first')); + ctx.onDeactivate(async () => void order.push('second')); + } + }) + ); + await registry.activateEnabled(); + await registry.setEnabled('test', false); + + expect(registry.contributions('tools')).toEqual([]); + // last registered, first undone + expect(order).toEqual(['second', 'first']); + expect(registry.extensions[0]).toMatchObject({ enabled: false, state: 'inactive' }); + }); + + it('keeps only the contributions of the extensions that stay on', async () => { + const registry = new ExtensionRegistry(); + const kept = makeProvider(); + + registry.register( + makeManifest({ activate: (ctx) => ctx.contribute('tools', makeProvider()) }, { id: 'a' }) + ); + registry.register( + makeManifest({ activate: (ctx) => ctx.contribute('tools', kept) }, { id: 'b' }) + ); + await registry.activateEnabled(); + await registry.setEnabled('a', false); + + expect(registry.contributions('tools')).toEqual([kept]); + }); + + it('remembers the choice and applies it on the next start', async () => { + const first = new ExtensionRegistry(); + + first.register(makeManifest({ activate() {} })); + await first.setEnabled('test', false); + + expect(JSON.parse(storage.data.get(EXTENSIONS_LOCALSTORAGE_KEY) ?? '{}')).toEqual({ + test: false + }); + + const second = new ExtensionRegistry(); + const load = vi.fn(async () => ({ default: { activate() {} } })); + + second.register(makeManifest({ activate() {} }, { load })); + await second.activateEnabled(); + + expect(load).not.toHaveBeenCalled(); + expect(second.isEnabled('test')).toBe(false); + }); + + it('shows the stored choice as soon as the extension is known', () => { + storage.data.set(EXTENSIONS_LOCALSTORAGE_KEY, JSON.stringify({ test: false })); + + const registry = new ExtensionRegistry(); + + registry.register(makeManifest({ activate() {} })); + + expect(registry.extensions[0]).toMatchObject({ enabled: false, state: 'inactive' }); + }); + + it('keeps the choices in memory when it has no storage key', async () => { + storage.data.set(EXTENSIONS_LOCALSTORAGE_KEY, JSON.stringify({ test: false })); + + const registry = new ExtensionRegistry({ storageKey: null }); + + registry.register(makeManifest({ activate() {} })); + + expect(registry.isEnabled('test')).toBe(true); + + await registry.setEnabled('test', false); + + expect(registry.isEnabled('test')).toBe(false); + expect(storage.data.get(EXTENSIONS_LOCALSTORAGE_KEY)).toBe(JSON.stringify({ test: false })); + expect(storage.data.size).toBe(1); + }); + + it('rolls a failed activation back and reports why', async () => { + const registry = new ExtensionRegistry(); + const cleanup = vi.fn(); + + vi.spyOn(console, 'error').mockImplementation(() => {}); + + registry.register( + makeManifest({ + activate(ctx) { + ctx.contribute('tools', makeProvider()); + ctx.onDeactivate(cleanup); + + throw new Error('boom'); + } + }) + ); + await registry.activateEnabled(); + + expect(registry.contributions('tools')).toEqual([]); + expect(cleanup).toHaveBeenCalledOnce(); + expect(registry.extensions[0]).toMatchObject({ error: 'boom', state: 'failed' }); + }); + + it('reports an extension whose code fails to load', async () => { + const registry = new ExtensionRegistry(); + + vi.spyOn(console, 'error').mockImplementation(() => {}); + + registry.register( + makeManifest( + { activate() {} }, + { + load: async () => { + throw new Error('chunk missing'); + } + } + ) + ); + await registry.activateEnabled(); + + expect(registry.extensions[0]).toMatchObject({ error: 'chunk missing', state: 'failed' }); + }); + + it('applies on and off in the order they were asked for', async () => { + const registry = new ExtensionRegistry(); + + let release: () => void = () => {}; + + const gate = new Promise((resolve) => (release = resolve)); + + registry.register( + makeManifest({ + async activate(ctx) { + await gate; + ctx.contribute('tools', makeProvider()); + } + }) + ); + + const starting = registry.activateEnabled(); + const stopping = registry.setEnabled('test', false); + + release(); + await Promise.all([starting, stopping]); + + expect(registry.contributions('tools')).toEqual([]); + expect(registry.extensions[0]).toMatchObject({ enabled: false, state: 'inactive' }); + }); + + it('refuses a contribution from an extension that is no longer active', async () => { + const registry = new ExtensionRegistry(); + + let late: (() => void) | undefined; + + registry.register( + makeManifest({ + activate(ctx) { + late = () => ctx.contribute('tools', makeProvider()); + } + }) + ); + await registry.activateEnabled(); + await registry.setEnabled('test', false); + + expect(() => late?.()).toThrow(/not active/); + expect(registry.contributions('tools')).toEqual([]); + }); + + it('refuses a second extension with the same id', () => { + const registry = new ExtensionRegistry(); + + registry.register(makeManifest({ activate() {} })); + + expect(() => registry.register(makeManifest({ activate() {} }))).toThrow(/already registered/); + }); +}); From 2ee1e04d08e904ba4437565cf931eab7b24eb0b2 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Fri, 13 Nov 2026 00:32:20 +0100 Subject: [PATCH 02/19] ui: list and run MCP tools through the tools extension point The tools store, the agentic flow, the tool policy and the tools UI no longer import MCP. The MCP extension contributes a tool provider to the `tools` point, which lists the servers' tools, normalizes their schemas, runs the calls and gives the icons and hints the UI shows, and a hook to the `flow` point, which holds the connections while a flow runs. The core reads both from the extension registry, so with the MCP extension off the tools UI and the flow work the same, just without the MCP tools. The stored tool and group keys keep their format. Assisted-by: Claude (Opus 5.5 Medium) --- .../ChatFormActionAddDrawer.svelte | 2 +- .../ChatFormActionAddToolsSubmenu.svelte | 14 +- .../ChatMessageToolCall/ToolCallBlock.svelte | 12 +- .../SettingsChat/SettingsChatToolsTab.svelte | 16 +- .../app/settings/SettingsMcpServers.svelte | 5 +- ui/apps/chat/src/lib/extensions/index.ts | 16 +- .../mcp/McpToolGroupIdentity.svelte | 16 + ui/apps/chat/src/lib/extensions/mcp/index.ts | 5 +- ui/apps/chat/src/lib/extensions/mcp/tools.ts | 233 ++++++++++++ .../chat/src/lib/extensions/points/tools.ts | 70 ++++ ui/apps/chat/src/lib/extensions/types.ts | 39 +- .../src/lib/hooks/use-tools-panel.svelte.ts | 55 +-- .../src/lib/services/migration.service.ts | 2 +- .../src/lib/stores/agentic/index.svelte.ts | 73 ++-- .../conversations/preferences.svelte.ts | 52 +-- .../chat/src/lib/stores/mcp/index.svelte.ts | 6 +- ui/apps/chat/src/lib/stores/tools.svelte.ts | 310 +++++----------- ui/apps/chat/src/lib/types/tools.d.ts | 8 +- .../tools-extension-point.svelte.test.ts | 158 ++++++++ ui/apps/chat/tests/unit/agentic-flow.test.ts | 197 +++++++++- .../tests/unit/mcp-tools-extension.test.ts | 346 ++++++++++++++++++ .../tests/unit/tools-extension-point.test.ts | 244 ++++++++++++ 22 files changed, 1485 insertions(+), 394 deletions(-) create mode 100644 ui/apps/chat/src/lib/extensions/mcp/McpToolGroupIdentity.svelte create mode 100644 ui/apps/chat/src/lib/extensions/mcp/tools.ts create mode 100644 ui/apps/chat/src/lib/extensions/points/tools.ts create mode 100644 ui/apps/chat/tests/client/tools-extension-point.svelte.test.ts create mode 100644 ui/apps/chat/tests/unit/mcp-tools-extension.test.ts create mode 100644 ui/apps/chat/tests/unit/tools-extension-point.test.ts diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte index b777b7c00117..63a1a933395b 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte @@ -171,7 +171,7 @@ {@render groupRow(group)} {/each} - {#each toolsPanel.mcpGroups as group (group.key)} + {#each toolsPanel.providerGroups as group (group.key)} {@render groupRow(group)} {/each} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddToolsSubmenu.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddToolsSubmenu.svelte index ce32bdf3113e..a55c259a8f11 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddToolsSubmenu.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddToolsSubmenu.svelte @@ -6,11 +6,10 @@ import { Check, ChevronDown, ChevronRight, Info, Loader2, PencilRuler } from '@lucide/svelte'; import { ATTACHMENT_MENU_TEXT, CLI_FLAGS, ICON_CLASS_DEFAULT } from '#lib/constants/index.ts'; import { useToolsPanel } from '#lib/hooks/use-tools-panel.svelte.ts'; - import { mcpStore, toolsStore, uiStore } from '#lib/stores/index.ts'; + import { toolsStore } from '#lib/stores/index.ts'; import type { ToolGroup } from '#lib/types/index.ts'; const toolsPanel = useToolsPanel(); - const hasMcpServersAvailable = $derived(mcpStore.getServers().length > 0); open && toolsPanel.handleOpen()}> @@ -40,18 +39,17 @@ - - {#if uiStore.isMcpShown} + {#each toolsPanel.providerHints as hint (hint.toolsLabel)} - {hasMcpServersAvailable ? 'Enable' : 'Add'} MCP Server(s) to access + {hint.action} - MCP Tools. + {hint.toolsLabel}. - {/if} + {/each} {:else if toolsStore.error}

Failed to load tools
@@ -70,7 +68,7 @@ {@render groupRow(group)} {/each} - {#each toolsPanel.mcpGroups as group (group.key)} + {#each toolsPanel.providerGroups as group (group.key)} {@render groupRow(group)} {/each} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte index cafb077e5366..278eef10ff23 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte @@ -4,7 +4,7 @@ // - the collapsible wrapper (defaults to CollapsibleContentBlock; // `exec_shell_command` swaps in CollapsibleTerminalBlock via the // `wrapper` prop); - // - the icon, spinner state, and MCP favicon fallback chain; + // - the icon, spinner state, and tool provider icon fallback chain; // - the status subtitle pill. // Components supply only their `meta`, a title snippet, and a body // snippet - everything around them is this single source of truth. @@ -13,7 +13,7 @@ import { CollapsibleContentBlock } from '#lib/components/app/index.ts'; import { ICON_CLASS_DEFAULT, ICON_CLASS_SPIN } from '#lib/constants/index.ts'; import { AgenticSectionType } from '#lib/enums/index.ts'; - import { mcpStore } from '#lib/stores/index.ts'; + import { toolsStore } from '#lib/stores/index.ts'; import type { AgenticSection, ToolUiEntry } from '#lib/types/index.ts'; import { getToolUi } from '#lib/utils/index.ts'; import type { Component, Snippet } from 'svelte'; @@ -104,13 +104,11 @@ const toolIconClass = $derived( spinIconWhenActive && showSpinner ? ICON_CLASS_SPIN : ICON_CLASS_DEFAULT ); - // Drop the MCP favicon while the spinner is on so the title row + // Drop the provider's icon while the spinner is on so the title row // signals "in flight" without being overwritten by server branding. - const mcpServerFavicon = $derived( - showSpinner ? null : mcpStore.getServerFaviconForTool(section.toolName) - ); + const providerIcon = $derived(showSpinner ? null : toolsStore.getToolIcon(section.toolName)); const iconUrl = $derived( - showSpinner || (toolUi?.icon ?? null) || !mcpServerFavicon ? null : mcpServerFavicon + showSpinner || (toolUi?.icon ?? null) || !providerIcon ? null : providerIcon ); // No subtitle while the call is in flight - the spinner already diff --git a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatToolsTab.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatToolsTab.svelte index 354fdecd09b3..71abd1596083 100644 --- a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatToolsTab.svelte +++ b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatToolsTab.svelte @@ -2,10 +2,10 @@ import { Checkbox } from '@ggml-org/llama-ui/ui/checkbox'; import * as Collapsible from '@ggml-org/llama-ui/ui/collapsible'; import { ChevronDown, ChevronRight } from '@lucide/svelte'; - import { McpServerIdentity, TruncatedText } from '#lib/components/app/index.ts'; + import { TruncatedText } from '#lib/components/app/index.ts'; import { ICON_CLASS_DEFAULT } from '#lib/constants/index.ts'; import { ToolSource } from '#lib/enums/tools.enums.ts'; - import { conversationsStore, mcpStore, permissionsStore, toolsStore } from '#lib/stores/index.ts'; + import { conversationsStore, permissionsStore, toolsStore } from '#lib/stores/index.ts'; import { getToolUi } from '#lib/utils/index.ts'; import { SvelteSet } from 'svelte/reactivity'; @@ -51,17 +51,11 @@ onclick={(e) => e.stopPropagation()} /> - {@const faviconUrl = group.serverId ? mcpStore.getServerFavicon(group.serverId) : null} + {@const GroupIdentity = toolsStore.getGroupIdentity(group)} - {#if group.source === 'mcp'} - + {#if GroupIdentity && group.serverId} + {:else} {/if} diff --git a/ui/apps/chat/src/lib/components/app/settings/SettingsMcpServers.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsMcpServers.svelte index 4533ab44dc9b..b45eb9037ef1 100644 --- a/ui/apps/chat/src/lib/components/app/settings/SettingsMcpServers.svelte +++ b/ui/apps/chat/src/lib/components/app/settings/SettingsMcpServers.svelte @@ -8,7 +8,8 @@ } from '#lib/components/app/dialogs/index.ts'; import { McpServerCard, McpServerCardSkeleton } from '#lib/components/app/index.ts'; import { HealthCheckStatus } from '#lib/enums/index.ts'; - import { mcpStore, toolsStore } from '#lib/stores/index.ts'; + import { enableAllToolsForServer } from '#lib/extensions/mcp/tools.ts'; + import { mcpStore } from '#lib/stores/index.ts'; import { goto } from '$app/navigation'; import { page } from '$app/state'; import { onMount } from 'svelte'; @@ -102,7 +103,7 @@ // Promote the connection so tools/prompts/resources become // available right away instead of waiting for the next chat-init. await mcpStore.runHealthCheck(server, true); - toolsStore.enableAllToolsForServer(server.id); + enableAllToolsForServer(server.id); } }} onUpdate={(updates) => mcpStore.updateServer(server.id, updates)} diff --git a/ui/apps/chat/src/lib/extensions/index.ts b/ui/apps/chat/src/lib/extensions/index.ts index 73a048b37638..41e6385f0841 100644 --- a/ui/apps/chat/src/lib/extensions/index.ts +++ b/ui/apps/chat/src/lib/extensions/index.ts @@ -1,3 +1,12 @@ +export type { + FlowHook, + FlowInfo, + ToolGroupIdentityProps, + ToolProvider, + ToolProviderCall, + ToolProviderEmptyHint, + ToolProviderEntry +} from './points/tools'; export { ExtensionRegistry, extensions } from './registry.svelte'; export type { Extension, @@ -6,10 +15,5 @@ export type { ExtensionPoint, ExtensionPoints, ExtensionState, - ExtensionStatus, - FlowHook, - FlowInfo, - ToolProvider, - ToolProviderCall, - ToolProviderEntry + ExtensionStatus } from './types'; diff --git a/ui/apps/chat/src/lib/extensions/mcp/McpToolGroupIdentity.svelte b/ui/apps/chat/src/lib/extensions/mcp/McpToolGroupIdentity.svelte new file mode 100644 index 000000000000..b003603e4f15 --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/McpToolGroupIdentity.svelte @@ -0,0 +1,16 @@ + + + diff --git a/ui/apps/chat/src/lib/extensions/mcp/index.ts b/ui/apps/chat/src/lib/extensions/mcp/index.ts index 03ac15f062a1..8666089c54c0 100644 --- a/ui/apps/chat/src/lib/extensions/mcp/index.ts +++ b/ui/apps/chat/src/lib/extensions/mcp/index.ts @@ -4,9 +4,12 @@ */ import type { Extension } from '../types'; +import { contributeTools } from './tools'; const mcp: Extension = { - activate() {} + activate(ctx) { + contributeTools(ctx); + } }; export default mcp; diff --git a/ui/apps/chat/src/lib/extensions/mcp/tools.ts b/ui/apps/chat/src/lib/extensions/mcp/tools.ts new file mode 100644 index 000000000000..17e8b3bd21c0 --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/tools.ts @@ -0,0 +1,233 @@ +/** + * MCP's side of the `tools` and `flow` extension points: the tools of the MCP + * servers, listed and run through mcpStore, and the hold an agentic flow + * takes on the connections. + */ + +import type { FlowHook, ToolProvider, ToolProviderEntry } from '../points/tools'; +import type { ExtensionContext } from '../types'; +import McpToolGroupIdentity from './McpToolGroupIdentity.svelte'; +import { HealthCheckStatus, JsonSchemaType, ToolCallType, ToolSource } from '#lib/enums/index.ts'; +// direct imports of the stores, not via the barrel, to avoid circular deps +import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts'; +import { mcpStore } from '#lib/stores/mcp/index.svelte.ts'; +import { toolsStore } from '#lib/stores/tools.svelte.ts'; +import { uiStore } from '#lib/stores/ui.svelte.ts'; + +function inferTypeFromDefault(value: unknown): string | undefined { + if (typeof value === 'string') return 'string'; + + if (typeof value === 'boolean') return 'boolean'; + + if (typeof value === 'number') return Number.isInteger(value) ? 'integer' : 'number'; + + if (Array.isArray(value)) return 'array'; + + if (value !== null && typeof value === 'object') return 'object'; + + return undefined; +} + +/** + * Recursively normalize a JSON Schema object: infers `type` from `default` + * for properties / items that omit it, and descends into nested `properties` + * and `items`. Returns a new object -- does not mutate the input. + */ +function normalizeJsonSchema(schema: Record): Record { + if (!schema || typeof schema !== 'object') return schema; + + const normalized: Record = { ...schema }; + + if (normalized.properties && typeof normalized.properties === 'object') { + const props = normalized.properties as Record>; + const normalizedProps: Record> = {}; + + for (const [key, prop] of Object.entries(props)) { + if (!prop || typeof prop !== 'object') { + normalizedProps[key] = prop; + + continue; + } + + const normalizedProp: Record = { ...prop }; + + if (!normalizedProp.type && normalizedProp.default !== undefined) { + const inferred = inferTypeFromDefault(normalizedProp.default); + + if (inferred) normalizedProp.type = inferred; + } + + if (normalizedProp.properties) { + Object.assign(normalizedProp, normalizeJsonSchema(normalizedProp)); + } + + if (normalizedProp.items && typeof normalizedProp.items === 'object') { + normalizedProp.items = normalizeJsonSchema(normalizedProp.items as Record); + } + + normalizedProps[key] = normalizedProp; + } + normalized.properties = normalizedProps; + } + + return normalized; +} + +/** Get MCP tools from health check data, used when live connections aren't established yet */ +function getToolsFromHealthChecks(): { + serverId: string; + serverName: string; + tools: { name: string; description?: string }[]; +}[] { + const result: ReturnType = []; + + for (const server of mcpStore.getServers()) { + if (!server.enabled) continue; + + const health = mcpStore.getHealthCheckState(server.id); + + if (health.status === HealthCheckStatus.SUCCESS && health.tools.length > 0) { + result.push({ + serverId: server.id, + serverName: mcpStore.getServerLabel(server), + tools: health.tools + }); + } + } + + return result; +} + +/** Normalize MCP tools from live connections when available, fall back to health check data */ +function listTools(): ToolProviderEntry[] { + const out: ToolProviderEntry[] = []; + const connections = mcpStore.getConnections(); + + if (connections.size > 0) { + for (const [serverId, connection] of connections) { + const groupLabel = mcpStore.getServerDisplayName(serverId); + + for (const tool of connection.tools) { + const rawSchema = (tool.inputSchema as Record) ?? { + properties: {}, + required: [], + type: JsonSchemaType.OBJECT + }; + + out.push({ + definition: { + function: { + description: tool.description, + name: tool.name, + parameters: normalizeJsonSchema(rawSchema) + }, + type: ToolCallType.FUNCTION + }, + groupId: serverId, + groupLabel + }); + } + } + } else { + for (const { serverId, serverName, tools } of getToolsFromHealthChecks()) { + for (const tool of tools) { + out.push({ + definition: { + function: { + description: tool.description, + name: tool.name, + parameters: { properties: {}, required: [], type: JsonSchemaType.OBJECT } + }, + type: ToolCallType.FUNCTION + }, + groupId: serverId, + groupLabel: serverName + }); + } + } + } + + return out; +} + +/** + * MCP servers usable under the effective policy: globally enabled, url set, + * MCP category on and the server-scoped key not disabled. + */ +export function policyEnabledServerIds(): string[] { + const preferences = conversationsStore.preferences; + + if (!preferences.isCategoryEnabled(ToolSource.MCP)) return []; + + return mcpStore + .getServers() + .filter( + (server) => server.enabled && server.url.trim() && preferences.isServerToolsEnabled(server.id) + ) + .map((server) => server.id); +} + +/** Enable all tools belonging to a specific MCP server */ +export function enableAllToolsForServer(serverId: string): void { + const connection = mcpStore.getConnections().get(serverId); + + if (!connection) return; + + // the server-scoped group key disables every tool regardless of per-tool keys + toolsStore.enableTools([ + toolsStore.getGroupKey(ToolSource.MCP, serverId), + ...connection.tools.map((tool) => toolsStore.getToolKey(ToolSource.MCP, tool.name, serverId)) + ]); +} + +const toolProvider: ToolProvider = { + // only while MCP shows: with it hidden, there is nowhere to add a server + emptyHint: () => + uiStore.isMcpShown + ? { + action: `${mcpStore.getServers().length > 0 ? 'Enable' : 'Add'} MCP Server(s) to access`, + sentence: 'To see MCP Tools you need to add / enable MCP Server(s).', + toolsLabel: 'MCP Tools' + } + : undefined, + entries: listTools, + async execute(call, signal) { + const result = await mcpStore.executeTool( + { function: { arguments: call.arguments, name: call.name }, id: call.id }, + signal + ); + + // a result the server marks as an error still goes to the model as a normal result + return { content: result.content, isError: false }; + }, + groupIcon: (serverId) => mcpStore.getServerFavicon(serverId), + groupIdentity: McpToolGroupIdentity, + isConfigured: () => mcpStore.hasEnabledServers(), + /** + * Initialize every settings-enabled server. The tools store filters by the + * policy afterwards, so switching policies never re-initializes connections. + */ + async prepare() { + if (policyEnabledServerIds().length === 0) return; + + const initialized = await mcpStore.ensureInitialized(); + + if (!initialized) console.log('[MCP] Not initialized'); + }, + refresh: () => mcpStore.runHealthChecksForServers(mcpStore.getServers().filter((s) => s.enabled)), + source: ToolSource.MCP, + toolIcon: (toolName) => mcpStore.getServerFaviconForTool(toolName) +}; +/** Hold the connections for as long as a flow that can use them runs. */ +const flowHook: FlowHook = () => { + if (policyEnabledServerIds().length === 0) return; + + mcpStore.acquireConnection(); + + return () => mcpStore.releaseConnection(); +}; + +export function contributeTools(ctx: ExtensionContext): void { + ctx.contribute('tools', toolProvider); + ctx.contribute('flow', flowHook); +} diff --git a/ui/apps/chat/src/lib/extensions/points/tools.ts b/ui/apps/chat/src/lib/extensions/points/tools.ts new file mode 100644 index 000000000000..4744a658db13 --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/points/tools.ts @@ -0,0 +1,70 @@ +/** + * The `tools` and `flow` extension points: tools the model can call that an + * extension lists and runs, and hooks that run around every agentic flow. + */ + +import type { ToolSource } from '#lib/enums/index.ts'; +import type { OpenAIToolDefinition, ToolExecutionResult } from '#lib/types/index.ts'; +import type { Component } from 'svelte'; + +export interface FlowInfo { + conversationId: string; +} + +/** Called when an agentic flow starts; a returned function runs when the flow ends. */ +export type FlowHook = (flow: FlowInfo) => void | (() => void | Promise); + +export interface ToolProviderEntry { + definition: OpenAIToolDefinition; + /** The group the tool is listed under and switched off with, e.g. one MCP server's id. Not empty. */ + groupId: string; + groupLabel: string; +} + +export interface ToolProviderCall { + /** The arguments as the model wrote them: a JSON string. */ + arguments: string; + id: string; + name: string; +} + +/** What the tools panel says about a provider while there is no tool to list. */ +export interface ToolProviderEmptyHint { + /** How to get the tools, read in front of `toolsLabel`: "Enable MCP Server(s) to access". */ + action: string; + /** The same as one full sentence, for the plain-text hint. */ + sentence: string; + /** What the provider's tools are called: "MCP Tools". */ + toolsLabel: string; +} + +export interface ToolGroupIdentityProps { + groupId: string; + label: string; +} + +export interface ToolProvider { + /** The tool category the provider's tools belong to. One provider per category. */ + source: ToolSource; + /** + * How to get tools from the provider, shown while the tools panel is empty. Nothing when the provider's way to + * set it up is hidden, so the panel does not point at it. + */ + emptyHint?(): ToolProviderEmptyHint | undefined; + /** The tools on offer right now. The tools store reads this reactively. */ + entries(): ToolProviderEntry[]; + /** Run one tool call. Throws when the call fails. */ + execute(call: ToolProviderCall, signal?: AbortSignal): Promise; + /** Icon URL of a group, when it has one. */ + groupIcon?(groupId: string): string | null; + /** Draws a group's name in the tools settings, in place of the plain label. */ + groupIdentity?: Component; + /** Whether the provider could offer tools under the current settings, connected or not. */ + isConfigured(): boolean; + /** Get the tools ready to list and call, before a flow asks for them. */ + prepare?(): Promise; + /** Look for the tools again. Called when the tools panel opens. */ + refresh?(): void | Promise; + /** Icon URL for a call of this tool, also when the tool is not on offer any more. */ + toolIcon?(toolName: string): string | null; +} diff --git a/ui/apps/chat/src/lib/extensions/types.ts b/ui/apps/chat/src/lib/extensions/types.ts index 653c45992b31..8d3c172b65a3 100644 --- a/ui/apps/chat/src/lib/extensions/types.ts +++ b/ui/apps/chat/src/lib/extensions/types.ts @@ -4,8 +4,7 @@ * same contract. */ -import type { ToolSource } from '#lib/enums/index.ts'; -import type { OpenAIToolDefinition, ToolExecutionResult } from '#lib/types/index.ts'; +import type { FlowHook, ToolProvider } from './points/tools'; /** What the app knows about an extension before its code is loaded. */ export interface ExtensionManifest { @@ -57,39 +56,3 @@ export interface ExtensionStatus { /** Why it failed to load or activate, when it did. */ error: string | null; } - -export interface FlowInfo { - conversationId: string; -} - -/** Called when an agentic flow starts; a returned function runs when the flow ends. */ -export type FlowHook = (flow: FlowInfo) => void | (() => void | Promise); - -export interface ToolProviderEntry { - definition: OpenAIToolDefinition; - /** The group the tool is listed under and switched off with, e.g. one MCP server's id. */ - groupId: string; - groupLabel: string; -} - -export interface ToolProviderCall { - /** The arguments as the model wrote them: a JSON string. */ - arguments: string; - id?: string; - name: string; -} - -export interface ToolProvider { - /** The tool category the provider's tools belong to. One provider per category. */ - source: ToolSource; - /** The tools on offer right now. The tools store reads this reactively. */ - entries(): ToolProviderEntry[]; - /** Run one tool call. Throws when the call fails. */ - execute(call: ToolProviderCall, signal?: AbortSignal): Promise; - /** Icon URL of a group, when it has one. */ - groupIcon?(groupId: string): string | null; - /** Whether the provider could offer tools under the current settings, connected or not. */ - isConfigured(): boolean; - /** Get the tools ready to list and call, before a flow asks for them. */ - prepare?(): Promise; -} diff --git a/ui/apps/chat/src/lib/hooks/use-tools-panel.svelte.ts b/ui/apps/chat/src/lib/hooks/use-tools-panel.svelte.ts index b420d3937c05..b030c159434a 100644 --- a/ui/apps/chat/src/lib/hooks/use-tools-panel.svelte.ts +++ b/ui/apps/chat/src/lib/hooks/use-tools-panel.svelte.ts @@ -1,13 +1,15 @@ import { CLI_FLAGS } from '#lib/constants/index.ts'; -import { ToolSource } from '#lib/enums/index.ts'; -import { conversationsStore, mcpStore, toolsStore, uiStore } from '#lib/stores/index.ts'; +import type { ToolProviderEmptyHint } from '#lib/extensions/index.ts'; +import { conversationsStore, toolsStore } from '#lib/stores/index.ts'; import type { ToolEntry, ToolGroup } from '#lib/types/index.ts'; import { SvelteSet } from 'svelte/reactivity'; export interface UseToolsPanelReturn { readonly expandedGroups: SvelteSet; readonly categoryGroups: ToolGroup[]; - readonly mcpGroups: ToolGroup[]; + readonly providerGroups: ToolGroup[]; + /** What each tool provider says while there is no tool to list. */ + readonly providerHints: ToolProviderEmptyHint[]; readonly totalToolCount: number; readonly noToolsInfoMessage: string | null; isGroupChecked(group: ToolGroup): boolean; @@ -38,29 +40,30 @@ export interface UseToolsPanelReturn { export function useToolsPanel(): UseToolsPanelReturn { const expandedGroups = new SvelteSet(); const groups = $derived(toolsStore.toolGroups); - // non-MCP groups are 1:1 with tool categories; MCP tools group per server - const categoryGroups = $derived(groups.filter((g) => g.source !== ToolSource.MCP)); - const mcpGroups = $derived(groups.filter((g) => g.source === ToolSource.MCP)); + // groups without an id are 1:1 with tool categories; a provider's tools group by id + const categoryGroups = $derived(groups.filter((g) => !g.serverId)); + const providerGroups = $derived(groups.filter((g) => !!g.serverId)); + const providerHints = $derived( + toolsStore.providers.flatMap((provider) => provider.emptyHint?.() ?? []) + ); const totalToolCount = $derived(groups.reduce((n, g) => n + g.tools.length, 0)); const noToolsInfoMessage = $derived.by(() => { if (toolsStore.loading) return null; if (toolsStore.toolGroups.length > 0) return null; - // the MCP half only while MCP shows: with it hidden, there is nowhere to add a server - const mcpHint = uiStore.isMcpShown - ? ' To see MCP Tools you need to add / enable MCP Server(s).' - : ''; + const message = [ + `To enable Server Tools you need to run llama-server with ${CLI_FLAGS.TOOLS} all or ${CLI_FLAGS.TOOLS} flag.`, + ...providerHints.map((hint) => hint.sentence) + ].join(' '); // Tools endpoint unreachable (403) — server started without tools - if (toolsStore.isToolsEndpointUnreachable) { - return `To enable Server Tools you need to run llama-server with ${CLI_FLAGS.TOOLS} all or ${CLI_FLAGS.TOOLS} flag.${mcpHint}`; - } + if (toolsStore.isToolsEndpointUnreachable) return message; // Other errors — return null so UI shows "Failed to load tools" if (toolsStore.error) return null; - return `To enable Server Tools you need to run llama-server with ${CLI_FLAGS.TOOLS} all or ${CLI_FLAGS.TOOLS} flag.${mcpHint}`; + return message; }); function isGroupChecked(group: ToolGroup): boolean { @@ -73,7 +76,7 @@ export function useToolsPanel(): UseToolsPanelReturn { /** * Group checkbox state: checked is the parent flag (category on, or the - * server key on for MCP groups); indeterminate marks the mixed case where + * group key on for a group with an id); indeterminate marks the mixed case where * the parent is on but nothing or only part of the group is enabled. * isToolActive folds the parent gates into the count, so a disabled parent * always yields plain unchecked. @@ -88,17 +91,12 @@ export function useToolsPanel(): UseToolsPanelReturn { } function getFavicon(group: ToolGroup): string | null { - if (group.source !== ToolSource.MCP || !group.serverId) return null; - - return mcpStore.getServerFavicon(group.serverId); + return toolsStore.getGroupIcon(group); } function isGroupDisabled(group: ToolGroup): boolean { - // MCP server groups gray out while the whole MCP category is off - return ( - group.source === ToolSource.MCP && - !conversationsStore.preferences.isCategoryEnabled(ToolSource.MCP) - ); + // a group with an id grays out while its whole category is off + return !!group.serverId && !conversationsStore.preferences.isCategoryEnabled(group.source); } function isToolEnabled(entry: ToolEntry): boolean { @@ -135,7 +133,7 @@ export function useToolsPanel(): UseToolsPanelReturn { toolsStore.fetchServerTools(); } - mcpStore.runHealthChecksForServers(mcpStore.getServers().filter((s) => s.enabled)); + for (const provider of toolsStore.providers) void provider.refresh?.(); } return { @@ -151,12 +149,15 @@ export function useToolsPanel(): UseToolsPanelReturn { isGroupDisabled, isToolEnabled, isToolParentDisabled, - get mcpGroups() { - return mcpGroups; - }, get noToolsInfoMessage() { return noToolsInfoMessage; }, + get providerGroups() { + return providerGroups; + }, + get providerHints() { + return providerHints; + }, toggleGroupByKey, toggleGroupExpanded, toggleTool, diff --git a/ui/apps/chat/src/lib/services/migration.service.ts b/ui/apps/chat/src/lib/services/migration.service.ts index 238e31f9a608..68c798db3187 100644 --- a/ui/apps/chat/src/lib/services/migration.service.ts +++ b/ui/apps/chat/src/lib/services/migration.service.ts @@ -812,7 +812,7 @@ const mcpServerOverridesToToolPolicyMigration: Migration = { if (conv.disabledTools !== undefined) continue; // A legacy per-conversation server disable becomes a server-scoped tool - // key (same format as toolsStore.getMcpServerToolsKey). Per-conversation + // key (same format as toolsStore.getGroupKey). Per-conversation // enables are dropped: the global server flag governs now. const serverGroupKeys = (conv.mcpServerOverrides ?? []) .filter((o: McpServerOverride) => !o.enabled) diff --git a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts index df914c5d5327..c539c212321b 100644 --- a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts +++ b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts @@ -41,6 +41,7 @@ import { MimeTypePrefix, ToolCallType } from '#lib/enums/index.ts'; +import { extensions } from '#lib/extensions/index.ts'; import { ChatService } from '#lib/services/index.ts'; import { ReadMediaService } from '#lib/services/read-media.service.ts'; import { SandboxService } from '#lib/services/sandbox.service.ts'; @@ -49,7 +50,6 @@ import { ToolsService } from '#lib/services/tools.service.ts'; // direct imports between stores, not via the barrel, to avoid circular deps import { AgenticGates } from '#lib/stores/agentic/gates.svelte.ts'; import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts'; -import { mcpStore } from '#lib/stores/mcp/index.svelte.ts'; import { modelsStore } from '#lib/stores/models/index.svelte.ts'; import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; import { toolsStore } from '#lib/stores/tools.svelte.ts'; @@ -72,7 +72,6 @@ import type { AgenticFlowParams, AgenticFlowResult, AgenticSession, - MCPToolCall, SettingsConfigType, ToolExecutionResult } from '#lib/types/index.ts'; @@ -209,7 +208,7 @@ class AgenticStore { getConfig(settings: SettingsConfigType): AgenticConfig { const maxTurns = Number(settings.agenticMaxTurns) || DEFAULT_AGENTIC_CONFIG.maxTurns; const hasTools = - mcpStore.hasEnabledServers() || + toolsStore.providers.some((provider) => provider.isConfigured()) || toolsStore.serverTools.length > 0 || toolsStore.browserTools.length > 0 || toolsStore.customTools.length > 0; @@ -346,8 +345,6 @@ class AgenticStore { return { handled: false }; } - const hasMcpServers = conversationsStore.preferences.policyEnabledServerIds().length > 0; - console.log(`[AgenticStore] Starting agentic flow with ${tools.length} tools`); const normalizedMessages: ApiChatMessageData[] = await ChatService.normalizeMessagesForApi( @@ -364,7 +361,7 @@ class AgenticStore { totalToolCalls: 0 }); - if (hasMcpServers) mcpStore.acquireConnection(); + const flowCleanups = this.startFlowHooks(conversationId); try { await this.executeAgenticLoop({ @@ -392,12 +389,12 @@ class AgenticStore { liveLlm: null }); - if (hasMcpServers) { - await mcpStore - .releaseConnection() - .catch((err: unknown) => - console.warn('[AgenticStore] Failed to release MCP connection:', err) - ); + for (const cleanup of flowCleanups) { + try { + await cleanup(); + } catch (err) { + console.warn('[AgenticStore] A flow hook failed to clean up:', err); + } } } } @@ -451,7 +448,8 @@ class AgenticStore { /** * Run a tool call where its source runs it: on llama-server, in the - * browser or on an MCP server. Throws when the call fails. + * browser or in the extension that provides the tool. Throws when the + * call fails. */ private async dispatchTool(params: { callbacks: AgenticFlowCallbacks; @@ -533,13 +531,14 @@ class AgenticStore { return SandboxService.executeTool(toolName, args, signal); } - const mcpCall: MCPToolCall = { - function: { arguments: toolCall.function.arguments, name: toolName }, - id: toolCall.id - }; - const executionResult = await mcpStore.executeTool(mcpCall, signal); + const provider = toolsStore.providers.find((p) => p.source === toolSource); + + if (!provider) throw new Error(`Unknown tool: ${toolName}`); - return { content: executionResult.content, isError: false }; + return provider.execute( + { arguments: toolCall.function.arguments, id: toolCall.id, name: toolName }, + signal + ); } /** @@ -937,14 +936,34 @@ class AgenticStore { return JSON.parse(trimmed) as Record; } + /** + * Run the `flow` hooks of the extensions and collect what they want run + * when the flow ends. A hook that throws is skipped. + */ + private startFlowHooks(conversationId: string): Array<() => void | Promise> { + const cleanups: Array<() => void | Promise> = []; + + for (const hook of extensions.contributions('flow')) { + try { + const cleanup = hook({ conversationId }); + + if (cleanup) cleanups.push(cleanup); + } catch (err) { + console.warn('[AgenticStore] A flow hook failed:', err); + } + } + + return cleanups; + } + /** * The tools a flow under this policy offers the model, none when agentic * is off. Server tools are fetched first: a disabled /tools endpoint stays * disabled for the life of the server, so the tools panel is the only - * place that probes it again. Every settings-enabled MCP server is - * initialized, and the collection filters by the policy, so switching - * policies never re-initializes connections; a caller without a policy - * falls back to the global defaults. + * place that probes it again. The providers get their tools ready next, + * and the collection filters by the policy, so switching policies never + * makes a provider start over; a caller without a policy falls back to + * the global defaults. */ private async toolsFor(toolPolicy?: AgenticToolPolicy): Promise { if ( @@ -962,13 +981,7 @@ class AgenticStore { toolPolicy?.disabledToolCategories ?? toolsStore.disabledToolCategories ); - if (conversationsStore.preferences.policyEnabledServerIds().length > 0) { - const initialized = await mcpStore.ensureInitialized(); - - if (!initialized) { - console.log('[AgenticStore] MCP not initialized'); - } - } + for (const provider of toolsStore.providers) await provider.prepare?.(); return toolsStore.getEnabledToolsForLLM(disabledTools, disabledToolCategories); } diff --git a/ui/apps/chat/src/lib/stores/conversations/preferences.svelte.ts b/ui/apps/chat/src/lib/stores/conversations/preferences.svelte.ts index d2ce26710f37..b218af910e87 100644 --- a/ui/apps/chat/src/lib/stores/conversations/preferences.svelte.ts +++ b/ui/apps/chat/src/lib/stores/conversations/preferences.svelte.ts @@ -15,7 +15,6 @@ import { REASONING_EFFORT_DEFAULT_LOCALSTORAGE_KEY } from '#lib/constants/index. import { ReasoningEffort, ToolSource } from '#lib/enums/index.ts'; import { DatabaseService } from '#lib/services/database.service.ts'; // direct imports between stores, not via the barrel, to avoid circular deps -import { mcpStore } from '#lib/stores/mcp/index.svelte.ts'; import { toolsStore } from '#lib/stores/tools.svelte.ts'; import type { DatabaseConversation, ToolEntry, ToolGroup } from '#lib/types/index.ts'; @@ -156,52 +155,36 @@ export class ConversationPreferences { return !this._disabledToolCategories.has(source); } - /** Group checkbox state: the category flag, or the server key for MCP groups. */ + /** Group checkbox state: the category flag, or the group key for a group with an id. */ isGroupChecked(group: ToolGroup): boolean { - return group.source === ToolSource.MCP && group.serverId - ? this.isServerToolsEnabled(group.serverId) + return group.serverId + ? this.isServerToolsEnabled(group.serverId, group.source) : this.isCategoryEnabled(group.source); } - /** Server-scoped MCP group state: one key disables all of that server's tools. */ - isServerToolsEnabled(serverId: string): boolean { - return this.isToolEnabled(toolsStore.getMcpServerToolsKey(serverId)); + /** + * State of a tool group with an id: one key disables all of the group's + * tools. The source defaults to MCP, whose groups are its servers. + */ + isServerToolsEnabled(serverId: string, source: ToolSource = ToolSource.MCP): boolean { + return this.isToolEnabled(toolsStore.getGroupKey(source, serverId)); } - /** Effective state: own key, MCP server group key, and category all on. */ + /** Effective state: own key, group key, and category all on. */ isToolActive(entry: ToolEntry): boolean { return toolsStore.isEntryEnabled(entry, this._disabledTools, this._disabledToolCategories); } - /** Own-level state: the tool key itself, ignoring category and server group. */ + /** Own-level state: the tool key itself, ignoring category and group. */ isToolEnabled(key: string): boolean { return !this._disabledTools.has(key); } - /** True when a parent level (category or MCP server group) disables this entry. */ + /** True when a parent level (category or group) disables this entry. */ isToolParentDisabled(entry: ToolEntry): boolean { if (!this.isCategoryEnabled(entry.source)) return true; - return ( - entry.source === ToolSource.MCP && - !!entry.serverId && - !this.isServerToolsEnabled(entry.serverId) - ); - } - - /** - * MCP servers usable under the effective policy: globally enabled, url set, - * MCP category on and the server-scoped key not disabled. - */ - policyEnabledServerIds(): string[] { - if (!this.isCategoryEnabled(ToolSource.MCP)) return []; - - return mcpStore - .getServers() - .filter( - (server) => server.enabled && server.url.trim() && this.isServerToolsEnabled(server.id) - ) - .map((server) => server.id); + return !!entry.serverId && !this.isServerToolsEnabled(entry.serverId, entry.source); } /** Reload persisted defaults, e.g. when the active conversation is cleared. */ @@ -287,15 +270,16 @@ export class ConversationPreferences { } async toggleGroup(group: ToolGroup): Promise { - if (group.source === ToolSource.MCP && group.serverId) { - await this.toggleServerTools(group.serverId); + if (group.serverId) { + await this.toggleServerTools(group.serverId, group.source); } else { await this.toggleCategory(group.source); } } - async toggleServerTools(serverId: string): Promise { - await this.toggleTool(toolsStore.getMcpServerToolsKey(serverId)); + /** Toggle a tool group with an id; the source defaults to MCP, as in `isServerToolsEnabled`. */ + async toggleServerTools(serverId: string, source: ToolSource = ToolSource.MCP): Promise { + await this.toggleTool(toolsStore.getGroupKey(source, serverId)); } async toggleTool(key: string): Promise { diff --git a/ui/apps/chat/src/lib/stores/mcp/index.svelte.ts b/ui/apps/chat/src/lib/stores/mcp/index.svelte.ts index d65653a14e5b..932d8baa52c5 100644 --- a/ui/apps/chat/src/lib/stores/mcp/index.svelte.ts +++ b/ui/apps/chat/src/lib/stores/mcp/index.svelte.ts @@ -4,9 +4,9 @@ * Implements the MCP "Host" role, coordinating multiple server connections * and exposing a unified tool interface: lifecycle, name-conflict detection * and automatic tool-to-server routing. Owns connection state and raw - * `Tool[]` per server; the OpenAI-compatible wire format is built in - * toolsStore. Composes the health-check manager; uses MCPService for the - * protocol layer. + * `Tool[]` per server; the OpenAI-compatible wire format is built in the + * MCP extension's tool provider. Composes the health-check manager; uses + * MCPService for the protocol layer. */ import type { ListChangedHandlers } from '@modelcontextprotocol/sdk/types.js'; diff --git a/ui/apps/chat/src/lib/stores/tools.svelte.ts b/ui/apps/chat/src/lib/stores/tools.svelte.ts index 99b65a187647..60a1cc4aa986 100644 --- a/ui/apps/chat/src/lib/stores/tools.svelte.ts +++ b/ui/apps/chat/src/lib/stores/tools.svelte.ts @@ -2,9 +2,9 @@ * toolsStore - Tool registry and enablement * * Owns the server tool listing (with working-directory resolution), built-in - * browser tools, MCP tools and per-tool enablement, exposed as a unified - * tool set for the LLM and the tools UI. Consumed by the agentic loop and - * the chat flows. + * browser tools, the tools extensions provide and per-tool enablement, + * exposed as a unified tool set for the LLM and the tools UI. Consumed by + * the agentic loop and the chat flows. */ import { @@ -18,22 +18,20 @@ import { TOOL_GROUP_LABELS, TOOL_SERVER_LABELS } from '#lib/constants/index.ts'; +import { BuiltInTool, GlobSearchType, ToolSource } from '#lib/enums/index.ts'; import { - BuiltInTool, - GlobSearchType, - HealthCheckStatus, - JsonSchemaType, - ToolCallType, - ToolSource -} from '#lib/enums/index.ts'; + extensions, + type ToolGroupIdentityProps, + type ToolProvider +} from '#lib/extensions/index.ts'; import { ToolsService } from '#lib/services/tools.service.ts'; // direct imports between stores, not via the barrel, to avoid circular deps -import { mcpStore } from '#lib/stores/mcp/index.svelte.ts'; import { modelsStore } from '#lib/stores/models/index.svelte.ts'; import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; import type { OpenAIToolDefinition, ToolEntry, ToolGroup } from '#lib/types/index.ts'; import { ApiError, buildSandboxToolDefinition } from '#lib/utils/index.ts'; import { browser } from '$app/env'; +import type { Component } from 'svelte'; import { SvelteMap, SvelteSet } from 'svelte/reactivity'; /** Stable selection identity for a tool, shared by the disabled set and the permission store */ @@ -72,7 +70,7 @@ class ToolsStore { push({ definition: def, - key: this.toolKey(ToolSource.SERVER, name), + key: this.getToolKey(ToolSource.SERVER, name), source: ToolSource.SERVER }); } @@ -82,21 +80,23 @@ class ToolsStore { push({ definition: def, - key: this.toolKey(ToolSource.BROWSER, name), + key: this.getToolKey(ToolSource.BROWSER, name), source: ToolSource.BROWSER }); } - for (const { definition, serverId, serverName } of this.mcpEntries()) { - const name = definition.function.name; + for (const provider of this.providers) { + for (const { definition, groupId, groupLabel } of provider.entries()) { + const name = definition.function.name; - push({ - definition, - key: this.toolKey(ToolSource.MCP, name, serverId), - serverId, - serverName, - source: ToolSource.MCP - }); + push({ + definition, + key: this.getToolKey(provider.source, name, groupId), + serverId: groupId, + serverName: groupLabel, + source: provider.source + }); + } } for (const def of this.customTools) { @@ -104,7 +104,7 @@ class ToolsStore { push({ definition: def, - key: this.toolKey(ToolSource.CUSTOM, name), + key: this.getToolKey(ToolSource.CUSTOM, name), source: ToolSource.CUSTOM }); } @@ -175,8 +175,9 @@ class ToolsStore { return this._loading; } - get mcpTools(): OpenAIToolDefinition[] { - return this.mcpEntries().map((e) => e.definition); + /** The tool providers of the active extensions. */ + get providers(): ToolProvider[] { + return extensions.contributions('tools'); } get serverHome(): string | null { @@ -193,8 +194,9 @@ class ToolsStore { const byKey = new SvelteMap(); for (const entry of this.allTools) { - const groupKey = - entry.source === ToolSource.MCP ? `mcp:${entry.serverId ?? ''}` : entry.source; + const groupKey = entry.serverId + ? this.getGroupKey(entry.source, entry.serverId) + : entry.source; let group = byKey.get(groupKey); @@ -216,18 +218,9 @@ class ToolsStore { return groups; } - /** Enable all tools belonging to a specific MCP server */ - enableAllToolsForServer(serverId: string): void { - const connection = mcpStore.getConnections().get(serverId); - - if (!connection) return; - - // the server-scoped group key disables every tool regardless of per-tool keys - this._disabledTools.delete(this.getMcpServerToolsKey(serverId)); - - for (const tool of connection.tools) { - this._disabledTools.delete(this.toolKey(ToolSource.MCP, tool.name, serverId)); - } + /** Enable several tools or tool groups by key, in one write */ + enableTools(keys: string[]): void { + for (const key of keys) this._disabledTools.delete(key); this.persistDisabledTools(); } @@ -265,8 +258,7 @@ class ToolsStore { * Enabled tool definitions for sending to the LLM. Callers pass an * explicit policy (the active conversation's, resolved with global * defaults when absent); without arguments the store defaults apply. - * MCP tool schemas are normalized here so the wire payload is consistent - * across all four sources (server, browser/sandbox, MCP, custom JSON). + * The order is server, browser/sandbox, extension tools, custom JSON. * The API identifies tools by name, so a name is sent at most once. */ getEnabledToolsForLLM( @@ -294,16 +286,36 @@ class ToolsStore { for (const def of this._serverTools) take(def); for (const def of this.browserTools) take(def); - // mcpEntries() over mcpStore directly so wire shape stays normalized and aligned with the tools UI. - for (const entry of this.mcpEntries()) take(entry.definition); + + for (const provider of this.providers) { + for (const entry of provider.entries()) take(entry.definition); + } + for (const def of this.customTools) take(def); return result; } - /** Server-scoped tool key: disabling it disables all of that server's tools. */ - getMcpServerToolsKey(serverId: string): string { - return `mcp:${serverId}`; + /** Icon URL of a tool group, when its provider has one */ + getGroupIcon(group: ToolGroup): string | null { + if (!group.serverId) return null; + + return this.providerFor(group.source)?.groupIcon?.(group.serverId) ?? null; + } + + /** The component a provider draws a group's name with, null for the plain label */ + getGroupIdentity(group: ToolGroup): Component | null { + if (!group.serverId) return null; + + return this.providerFor(group.source)?.groupIdentity ?? null; + } + + /** + * Group-scoped tool key: disabling it disables all of that group's tools. + * The keys are persisted, so the format must not change. + */ + getGroupKey(source: ToolSource, groupId: string): string { + return `${source}:${groupId}`; } /** Permission key for a tool name, identical to the selection key */ @@ -311,13 +323,35 @@ class ToolsStore { return this.findEntryByName(toolName)?.key ?? null; } + /** Icon URL for a call of a tool, from the first provider that has one for it */ + getToolIcon(toolName: string | undefined): string | null { + if (!toolName) return null; + + for (const provider of this.providers) { + const icon = provider.toolIcon?.(toolName); + + if (icon) return icon; + } + + return null; + } + + /** + * Stable selection identity of a tool: `:`, or + * `-:` for a tool listed under a group. The keys + * are persisted, so the format must not change. + */ + getToolKey(source: ToolSource, name: string, groupId?: string): string { + return groupId ? `${source}-${groupId}:${name}` : `${source}:${name}`; + } + /** Get the display label for the server that owns a given tool */ getToolServerLabel(toolName: string): string { const entry = this.findEntryByName(toolName); if (!entry) return ''; - if (entry.serverName) return mcpStore.getServerDisplayName(entry.serverName); + if (entry.serverName) return entry.serverName; if (entry.source === ToolSource.SERVER) return TOOL_SERVER_LABELS[ToolSource.SERVER]; @@ -348,7 +382,7 @@ class ToolsStore { const name = def.function.name; return ( - this.cwdAwareTools.has(name) && !disabledTools.has(this.toolKey(ToolSource.SERVER, name)) + this.cwdAwareTools.has(name) && !disabledTools.has(this.getToolKey(ToolSource.SERVER, name)) ); }); } @@ -411,8 +445,8 @@ class ToolsStore { if (disabledTools.has(entry.key)) return false; - if (entry.source === ToolSource.MCP && entry.serverId) { - return !disabledTools.has(this.getMcpServerToolsKey(entry.serverId)); + if (entry.serverId) { + return !disabledTools.has(this.getGroupKey(entry.source, entry.serverId)); } return true; @@ -485,35 +519,10 @@ class ToolsStore { return null; } - /** Get MCP tools from health check data, used when live connections aren't established yet */ - private getMcpToolsFromHealthChecks(): { - serverId: string; - serverName: string; - tools: { name: string; description?: string }[]; - }[] { - const result: ReturnType = []; - - for (const server of mcpStore.getServers()) { - if (!server.enabled) continue; - - const health = mcpStore.getHealthCheckState(server.id); - - if (health.status === HealthCheckStatus.SUCCESS && health.tools.length > 0) { - result.push({ - serverId: server.id, - serverName: mcpStore.getServerLabel(server), - tools: health.tools - }); - } - } - - return result; - } - private groupLabel(entry: ToolEntry): string { + if (entry.serverId) return entry.serverName ?? ''; + switch (entry.source) { - case ToolSource.MCP: - return entry.serverName ?? ''; case ToolSource.CUSTOM: return TOOL_GROUP_LABELS[ToolSource.CUSTOM]; case ToolSource.BROWSER: @@ -527,134 +536,6 @@ class ToolsStore { return this._serverTools.some((def) => def.function.name === name); } - private inferTypeFromDefault(value: unknown): string | undefined { - if (typeof value === 'string') return 'string'; - - if (typeof value === 'boolean') return 'boolean'; - - if (typeof value === 'number') return Number.isInteger(value) ? 'integer' : 'number'; - - if (Array.isArray(value)) return 'array'; - - if (value !== null && typeof value === 'object') return 'object'; - - return undefined; - } - - private mcpDefinition( - name: string, - description: string | undefined, - schema?: Record - ): OpenAIToolDefinition { - return { - function: { - description, - name, - parameters: schema ?? { properties: {}, required: [], type: JsonSchemaType.OBJECT } - }, - type: ToolCallType.FUNCTION - }; - } - - /** Normalize MCP tools from live connections when available, fall back to health check data */ - private mcpEntries(): { - serverId: string; - serverName: string; - definition: OpenAIToolDefinition; - }[] { - const out: { serverId: string; serverName: string; definition: OpenAIToolDefinition }[] = []; - const connections = mcpStore.getConnections(); - - if (connections.size > 0) { - for (const [serverId, connection] of connections) { - const serverName = mcpStore.getServerDisplayName(serverId); - - for (const tool of connection.tools) { - const rawSchema = (tool.inputSchema as Record) ?? { - properties: {}, - required: [], - type: JsonSchemaType.OBJECT - }; - - out.push({ - definition: { - function: { - description: tool.description, - name: tool.name, - parameters: this.normalizeJsonSchema(rawSchema) - }, - type: ToolCallType.FUNCTION - }, - serverId, - serverName - }); - } - } - } else { - for (const { serverId, serverName, tools } of this.getMcpToolsFromHealthChecks()) { - for (const tool of tools) { - out.push({ - definition: this.mcpDefinition(tool.name, tool.description), - serverId, - serverName - }); - } - } - } - - return out; - } - - /** - * Recursively normalize a JSON Schema object: infers `type` from `default` - * for properties / items that omit it, and descends into nested `properties` - * and `items`. Returns a new object -- does not mutate the input. - */ - private normalizeJsonSchema(schema: Record): Record { - if (!schema || typeof schema !== 'object') return schema; - - const normalized: Record = { ...schema }; - - if (normalized.properties && typeof normalized.properties === 'object') { - const props = normalized.properties as Record>; - const normalizedProps: Record> = {}; - - for (const [key, prop] of Object.entries(props)) { - if (!prop || typeof prop !== 'object') { - normalizedProps[key] = prop; - - continue; - } - - const normalizedProp: Record = { ...prop }; - - if (!normalizedProp.type && normalizedProp.default !== undefined) { - const inferred = this.inferTypeFromDefault(normalizedProp.default); - - if (inferred) normalizedProp.type = inferred; - } - - if (normalizedProp.properties) { - Object.assign( - normalizedProp, - this.normalizeJsonSchema(normalizedProp as Record) - ); - } - - if (normalizedProp.items && typeof normalizedProp.items === 'object') { - normalizedProp.items = this.normalizeJsonSchema( - normalizedProp.items as Record - ); - } - - normalizedProps[key] = normalizedProp; - } - normalized.properties = normalizedProps; - } - - return normalized; - } - private persistDisabledToolCategories(): void { try { localStorage.setItem( @@ -677,6 +558,10 @@ class ToolsStore { } } + private providerFor(source: ToolSource): ToolProvider | undefined { + return this.providers.find((provider) => provider.source === source); + } + /** * `read_media` runs in the browser on top of the server's `read_file`, so it * exists only when that tool is served and the active model can perceive the @@ -697,21 +582,6 @@ class ToolsStore { return buildReadMediaToolDefinition(vision, audio); } - - private toolKey(source: ToolSource, name: string, serverId?: string): string { - switch (source) { - case ToolSource.MCP: - // with a serverId this is a per-tool key; without one it hits the - // server group key shape, which no MCP entry ever does - return serverId ? `mcp-${serverId}:${name}` : this.getMcpServerToolsKey(name); - case ToolSource.CUSTOM: - return `custom:${name}`; - case ToolSource.BROWSER: - return `browser:${name}`; - default: - return `server:${name}`; - } - } } export const toolsStore = new ToolsStore(); diff --git a/ui/apps/chat/src/lib/types/tools.d.ts b/ui/apps/chat/src/lib/types/tools.d.ts index 4f1ab120a1f2..b3531415313c 100644 --- a/ui/apps/chat/src/lib/types/tools.d.ts +++ b/ui/apps/chat/src/lib/types/tools.d.ts @@ -13,11 +13,11 @@ export interface ToolUiEntry { export interface ToolEntry { source: ToolSource; - /** For MCP tools, the server display name (used for UI grouping) */ + /** For a tool listed under a group, the group's display name (an MCP server's label) */ serverName?: string; - /** For MCP tools, the server ID (used for permission keys) */ + /** For a tool listed under a group, the group's id (an MCP server's id), part of the keys */ serverId?: string; - /** Stable selection identity: server:name, mcp-:name, mcp:name, custom:name */ + /** Stable selection identity: :name, or -:name under a group */ key: string; definition: OpenAIToolDefinition; } @@ -27,7 +27,7 @@ export interface ToolGroup { /** Stable identity for keyed rendering and toggles, unique per group */ key: string; label: string; - /** For MCP groups, the server ID */ + /** For a group a tool provider lists, its id (an MCP server's id); unset for a category group */ serverId?: string; tools: ToolEntry[]; } diff --git a/ui/apps/chat/tests/client/tools-extension-point.svelte.test.ts b/ui/apps/chat/tests/client/tools-extension-point.svelte.test.ts new file mode 100644 index 000000000000..9794a9687a8b --- /dev/null +++ b/ui/apps/chat/tests/client/tools-extension-point.svelte.test.ts @@ -0,0 +1,158 @@ +// The tools UI reads MCP only through the `tools` extension point: with the +// MCP extension on it shows the servers' tools as before, with it off it +// still renders, just without them. + +import SettingsChatToolsTab from '#lib/components/app/settings/SettingsChat/SettingsChatToolsTab.svelte'; +import { + DISABLED_TOOL_CATEGORIES_LOCALSTORAGE_KEY, + EXTENSIONS_LOCALSTORAGE_KEY +} from '#lib/constants/index.ts'; +import { ToolSource } from '#lib/enums/index.ts'; +import { BUILT_IN_EXTENSIONS } from '#lib/extensions/builtin.ts'; +import { extensions } from '#lib/extensions/registry.svelte.ts'; +import { useToolsPanel, type UseToolsPanelReturn } from '#lib/hooks/use-tools-panel.svelte.ts'; +import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts'; +import { mcpStore } from '#lib/stores/mcp/index.svelte.ts'; +import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; +import { toolsStore } from '#lib/stores/tools.svelte.ts'; +import type { MCPConnection } from '#lib/types/index.ts'; +import { flushSync, tick } from 'svelte'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { render } from 'vitest-browser-svelte'; + +const MCP_ID = 'mcp'; +const SERVER_HINT = + 'To enable Server Tools you need to run llama-server with --tools all or --tools flag.'; +// the favicon fallback resolves to the root domain of the server url +const FAVICON = 'https://example.com/favicon.ico'; + +let serverId = ''; + +function withPanel(run: (panel: UseToolsPanelReturn) => void): void { + const stop = $effect.root(() => { + const panel = useToolsPanel(); + + flushSync(); + run(panel); + }); + + stop(); +} + +beforeAll(() => { + for (const manifest of BUILT_IN_EXTENSIONS) extensions.register(manifest); +}); + +beforeEach(async () => { + settingsStore.updateConfig('mcpServers', '[]'); + serverId = mcpStore.addServer({ + displayName: 'Docs', + enabled: true, + url: 'https://mcp.example.com/mcp' + }).id; + vi.spyOn(mcpStore, 'getConnections').mockReturnValue( + new Map([[serverId, { tools: [{ name: 'search' }] } as unknown as MCPConnection]]) + ); + await extensions.setEnabled(MCP_ID, true); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +afterAll(async () => { + await extensions.setEnabled(MCP_ID, false); + settingsStore.updateConfig('mcpServers', '[]'); + localStorage.removeItem(EXTENSIONS_LOCALSTORAGE_KEY); + localStorage.removeItem(DISABLED_TOOL_CATEGORIES_LOCALSTORAGE_KEY); +}); + +describe('tools settings', () => { + it('draws an MCP server group with its icon while the MCP extension is on', async () => { + render(SettingsChatToolsTab); + await tick(); + + expect(document.body.textContent).toContain('Docs'); + expect(document.body.textContent).toContain('Browser'); + expect(document.querySelector(`img[src="${FAVICON}"]`)).not.toBeNull(); + }); + + it('renders without the MCP groups once the extension is off', async () => { + render(SettingsChatToolsTab); + await extensions.setEnabled(MCP_ID, false); + await tick(); + + expect(document.body.textContent).not.toContain('Docs'); + expect(document.body.textContent).toContain('Browser'); + expect(document.querySelector(`img[src="${FAVICON}"]`)).toBeNull(); + }); +}); + +describe('tools panel', () => { + it('keeps the MCP server groups apart from the category groups', () => { + withPanel((panel) => { + const [group] = panel.providerGroups; + + expect(panel.providerGroups).toHaveLength(1); + expect(group).toMatchObject({ key: `mcp:${serverId}`, label: 'Docs' }); + expect(panel.categoryGroups.map((g) => g.source)).toEqual([ToolSource.BROWSER]); + expect(panel.getFavicon(group)).toBe(FAVICON); + expect(panel.getFavicon(panel.categoryGroups[0])).toBeNull(); + expect(panel.isGroupDisabled(group)).toBe(false); + }); + }); + + it('grays an MCP server group out while the MCP category is off', async () => { + await conversationsStore.preferences.toggleCategory(ToolSource.MCP); + + withPanel((panel) => { + expect(panel.isGroupDisabled(panel.providerGroups[0])).toBe(true); + expect(panel.isGroupDisabled(panel.categoryGroups[0])).toBe(false); + }); + + await conversationsStore.preferences.toggleCategory(ToolSource.MCP); + }); + + it('checks the MCP servers again when it opens', () => { + const run = vi.spyOn(mcpStore, 'runHealthChecksForServers').mockResolvedValue(); + + vi.spyOn(toolsStore, 'fetchServerTools').mockResolvedValue(); + withPanel((panel) => panel.handleOpen()); + + expect(run).toHaveBeenCalledOnce(); + expect(run.mock.calls[0][0].map((server) => server.id)).toEqual([serverId]); + }); + + it('explains how to get MCP tools while there is no tool to list', () => { + vi.spyOn(toolsStore, 'toolGroups', 'get').mockReturnValue([]); + + withPanel((panel) => { + expect(panel.noToolsInfoMessage).toBe( + `${SERVER_HINT} To see MCP Tools you need to add / enable MCP Server(s).` + ); + expect(panel.providerHints).toEqual([ + { + action: 'Enable MCP Server(s) to access', + sentence: 'To see MCP Tools you need to add / enable MCP Server(s).', + toolsLabel: 'MCP Tools' + } + ]); + }); + }); + + it('works without the MCP extension', async () => { + await extensions.setEnabled(MCP_ID, false); + vi.spyOn(toolsStore, 'fetchServerTools').mockResolvedValue(); + + withPanel((panel) => { + expect(panel.providerGroups).toEqual([]); + expect(panel.providerHints).toEqual([]); + expect(panel.categoryGroups.map((g) => g.source)).toEqual([ToolSource.BROWSER]); + expect(() => panel.handleOpen()).not.toThrow(); + }); + + vi.spyOn(toolsStore, 'toolGroups', 'get').mockReturnValue([]); + + withPanel((panel) => expect(panel.noToolsInfoMessage).toBe(SERVER_HINT)); + }); +}); diff --git a/ui/apps/chat/tests/unit/agentic-flow.test.ts b/ui/apps/chat/tests/unit/agentic-flow.test.ts index e8992b60c841..7ebadf5902f6 100644 --- a/ui/apps/chat/tests/unit/agentic-flow.test.ts +++ b/ui/apps/chat/tests/unit/agentic-flow.test.ts @@ -1,13 +1,15 @@ // The agentic flow end to end, with the server and the tools mocked: what the // model is sent each turn, and the order the flow's callbacks fire in. -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; vi.mock('#lib/services/database.service.ts', () => ({ DatabaseService: {} })); import { BuiltInTool, MessageRole, ToolPermissionDecision, ToolSource } from '#lib/enums/index.ts'; +import type { Extension, ToolProvider } from '#lib/extensions/index.ts'; +import { extensions } from '#lib/extensions/index.ts'; import { ChatService } from '#lib/services/chat.service.ts'; import { ToolsService } from '#lib/services/tools.service.ts'; import { agenticStore } from '#lib/stores/agentic/index.svelte.ts'; @@ -100,6 +102,34 @@ function recorder() { }; } +// the registry has no way to forget an extension, so every test registers its own +let nextExtensionId = 0; + +const activeExtensionIds: string[] = []; + +async function activateExtension(extension: Extension): Promise { + const id = `flow-test-${nextExtensionId++}`; + + extensions.register({ + description: 'A test extension', + id, + load: async () => ({ default: extension }), + name: id + }); + await extensions.setEnabled(id, true); + activeExtensionIds.push(id); +} + +function makeProvider(overrides: Partial = {}): ToolProvider { + return { + entries: () => [], + execute: async () => ({ content: '', isError: false }), + isConfigured: () => true, + source: ToolSource.MCP, + ...overrides + }; +} + function runFlow(callbacks: AgenticFlowCallbacks, signal?: AbortSignal) { return agenticStore.runAgenticFlow({ callbacks, @@ -122,6 +152,10 @@ beforeEach(() => { vi.spyOn(permissionsStore, 'hasTool').mockReturnValue(true); }); +afterEach(async () => { + for (const id of activeExtensionIds.splice(0)) await extensions.setEnabled(id, false); +}); + describe('agentic flow', () => { it('is not handled when no tool is enabled', async () => { vi.spyOn(toolsStore, 'getEnabledToolsForLLM').mockReturnValue([]); @@ -370,3 +404,164 @@ describe('agentic flow', () => { expect(requests).toHaveLength(1); }); }); + +describe('agentic flow with extensions', () => { + it('gets the providers ready, then runs a tool call through the provider of its source', async () => { + const order: string[] = []; + const execute = vi.fn(async () => { + order.push('execute'); + + return { content: 'found it', isError: false }; + }); + + await activateExtension({ + activate: (ctx) => + ctx.contribute( + 'tools', + makeProvider({ execute, prepare: async () => void order.push('prepare') }) + ) + }); + mockTools(ToolSource.MCP, 'search'); + vi.mocked(toolsStore.getEnabledToolsForLLM).mockImplementation(() => { + order.push('list'); + + return [{ function: { name: 'search', parameters: {} }, type: 'function' }]; + }); + + const controller = new AbortController(); + const requests = mockTurns( + (options) => options.onToolCallChunk?.(toolCalls('search')), + (options) => options.onChunk?.('done') + ); + const { callbacks, named } = recorder(); + + expect(await runFlow(callbacks, controller.signal)).toEqual({ handled: true }); + expect(order).toEqual(['prepare', 'list', 'execute']); + expect(execute.mock.calls[0][0]).toEqual({ arguments: '{}', id: 'call_0', name: 'search' }); + expect(execute.mock.calls[0][1]).toBeInstanceOf(AbortSignal); + expect(requests[1][2]).toMatchObject({ content: 'found it', role: 'tool' }); + expect(named('onFlowComplete')[0][1]).toMatchObject({ + agentic: { toolCalls: [{ name: 'search', success: true }] } + }); + }); + + it('reports a failing provider to the model and goes on', async () => { + await activateExtension({ + activate: (ctx) => + ctx.contribute( + 'tools', + makeProvider({ + execute: async () => { + throw new Error('server is down'); + } + }) + ) + }); + mockTools(ToolSource.MCP, 'search'); + + const requests = mockTurns( + (options) => options.onToolCallChunk?.(toolCalls('search')), + (options) => options.onChunk?.('sorry') + ); + + expect(await runFlow(recorder().callbacks)).toEqual({ handled: true }); + expect(requests[1][2]).toMatchObject({ content: 'Error: server is down', role: 'tool' }); + }); + + it('tells the model the tool is unknown when no extension provides its source', async () => { + mockTools(ToolSource.MCP, 'search'); + + const requests = mockTurns( + (options) => options.onToolCallChunk?.(toolCalls('search')), + (options) => options.onChunk?.('sorry') + ); + const { callbacks, named } = recorder(); + + expect(await runFlow(callbacks)).toEqual({ handled: true }); + expect(requests[1][2]).toMatchObject({ content: 'Error: Unknown tool: search', role: 'tool' }); + expect(named('onFlowComplete')[0][1]).toMatchObject({ + agentic: { toolCalls: [{ name: 'search', success: false }] } + }); + }); + + it('is enabled by a configured provider alone', async () => { + vi.spyOn(toolsStore, 'browserTools', 'get').mockReturnValue([]); + + const config = () => agenticStore.getConfig({ agenticMaxTurns: 5 } as never); + + expect(config().enabled).toBe(false); + + await activateExtension({ + activate: (ctx) => ctx.contribute('tools', makeProvider({ isConfigured: () => false })) + }); + + expect(config().enabled).toBe(false); + + await activateExtension({ activate: (ctx) => ctx.contribute('tools', makeProvider()) }); + + expect(config().enabled).toBe(true); + }); + + it('runs the flow hooks around the flow, also when one of them fails', async () => { + const order: string[] = []; + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + await activateExtension({ + activate(ctx) { + ctx.contribute('flow', () => { + throw new Error('bad start'); + }); + ctx.contribute('flow', () => async () => { + order.push('failing end'); + + throw new Error('bad end'); + }); + ctx.contribute('flow', ({ conversationId }) => { + order.push(`start ${conversationId}`); + + return () => void order.push('end'); + }); + ctx.contribute('flow', () => void order.push('start without end')); + } + }); + mockTools(ToolSource.BROWSER, BuiltInTool.BROWSER_GET_DATETIME); + mockTurns((options) => { + order.push(`turn, running: ${agenticStore.isRunning(CONV_ID)}`); + options.onChunk?.('hi'); + }); + + expect(await runFlow(recorder().callbacks)).toEqual({ handled: true }); + expect(order).toEqual([ + `start ${CONV_ID}`, + 'start without end', + 'turn, running: true', + 'failing end', + 'end' + ]); + expect(warn).toHaveBeenCalledTimes(2); + expect(agenticStore.isRunning(CONV_ID)).toBe(false); + }); + + it('runs the end of the flow hooks when the flow fails', async () => { + const end = vi.fn(); + + await activateExtension({ activate: (ctx) => ctx.contribute('flow', () => end) }); + mockTools(ToolSource.BROWSER, BuiltInTool.BROWSER_GET_DATETIME); + mockTurns(() => { + throw new Error('HTTP 500'); + }); + + expect(await runFlow(recorder().callbacks)).toMatchObject({ handled: true }); + expect(end).toHaveBeenCalledOnce(); + }); + + it('leaves the flow hooks alone when no tool is enabled', async () => { + const hook = vi.fn(); + + await activateExtension({ activate: (ctx) => ctx.contribute('flow', hook) }); + vi.spyOn(toolsStore, 'getEnabledToolsForLLM').mockReturnValue([]); + + expect(await runFlow(recorder().callbacks)).toEqual({ handled: false }); + expect(hook).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/apps/chat/tests/unit/mcp-tools-extension.test.ts b/ui/apps/chat/tests/unit/mcp-tools-extension.test.ts new file mode 100644 index 000000000000..2c7b4dee5a46 --- /dev/null +++ b/ui/apps/chat/tests/unit/mcp-tools-extension.test.ts @@ -0,0 +1,346 @@ +// MCP reaches the tools of the core only through what its extension +// contributes: a tool provider built on mcpStore and a flow hook that holds +// the connections while a flow runs. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('#lib/services/database.service.ts', () => ({ + DatabaseService: {} +})); +// the component draws on the app's component barrel, which needs a browser +vi.mock('#lib/extensions/mcp/McpToolGroupIdentity.svelte', () => ({ default: () => {} })); + +import { HealthCheckStatus, ToolSource } from '#lib/enums/index.ts'; +import type { ExtensionContext, FlowHook, ToolProvider } from '#lib/extensions/index.ts'; +import { extensions } from '#lib/extensions/index.ts'; +import { + contributeTools, + enableAllToolsForServer, + policyEnabledServerIds +} from '#lib/extensions/mcp/tools.ts'; +import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts'; +import { mcpStore } from '#lib/stores/mcp/index.svelte.ts'; +import { toolsStore } from '#lib/stores/tools.svelte.ts'; +import type { HealthCheckState, MCPConnection, MCPServerSettingsEntry } from '#lib/types/index.ts'; + +const SERVERS: MCPServerSettingsEntry[] = [ + { enabled: true, id: 'srv-1', name: 'Docs', url: 'https://docs.example.com/mcp' }, + { enabled: false, id: 'srv-2', name: 'Off', url: 'https://off.example.com/mcp' }, + { enabled: true, id: 'srv-3', name: 'No url', url: ' ' } +]; + +function contributed(): { hook: FlowHook; provider: ToolProvider } { + const made: { hook?: FlowHook; provider?: ToolProvider } = {}; + const ctx: ExtensionContext = { + contribute: (point, contribution) => { + if (point === 'tools') made.provider = contribution as ToolProvider; + + if (point === 'flow') made.hook = contribution as FlowHook; + }, + onDeactivate: () => {} + }; + + contributeTools(ctx); + + return { hook: made.hook!, provider: made.provider! }; +} + +function connection(...tools: { description?: string; inputSchema?: unknown; name: string }[]) { + return { tools } as unknown as MCPConnection; +} + +function mockConnections(connections: Record) { + vi.spyOn(mcpStore, 'getConnections').mockReturnValue(new Map(Object.entries(connections))); +} + +beforeEach(() => { + vi.restoreAllMocks(); + vi.spyOn(mcpStore, 'getServers').mockReturnValue(SERVERS); + mockConnections({}); +}); + +afterEach(() => { + for (const key of [...toolsStore.disabledTools]) toolsStore.setToolEnabled(key, true); +}); + +describe('MCP tool provider', () => { + it('contributes one provider for the MCP category and one flow hook', () => { + const { hook, provider } = contributed(); + + expect(provider.source).toBe(ToolSource.MCP); + expect(hook).toBeTypeOf('function'); + }); + + it('lists the tools of the live connections, grouped by server', () => { + mockConnections({ + 'srv-1': connection( + { description: 'Search the docs', inputSchema: { type: 'object' }, name: 'search' }, + { name: 'ping' } + ) + }); + + const entries = contributed().provider.entries(); + + expect(entries).toEqual([ + { + definition: { + function: { + description: 'Search the docs', + name: 'search', + parameters: { type: 'object' } + }, + type: 'function' + }, + groupId: 'srv-1', + groupLabel: 'Docs' + }, + { + definition: { + function: { + description: undefined, + name: 'ping', + parameters: { properties: {}, required: [], type: 'object' } + }, + type: 'function' + }, + groupId: 'srv-1', + groupLabel: 'Docs' + } + ]); + }); + + it('gives a schema property without a type the type of its default', () => { + const inputSchema = { + properties: { + flag: { default: true }, + items: { items: { properties: { depth: { default: 1.5 } } }, type: 'array' }, + limit: { default: 5 }, + nested: { properties: { query: { default: 'all' } } }, + typed: { default: 5, type: 'string' }, + untyped: {} + }, + type: 'object' + }; + + mockConnections({ 'srv-1': connection({ inputSchema, name: 'search' }) }); + + const [{ definition }] = contributed().provider.entries(); + + expect(definition.function.parameters).toEqual({ + properties: { + flag: { default: true, type: 'boolean' }, + items: { + items: { properties: { depth: { default: 1.5, type: 'number' } } }, + type: 'array' + }, + limit: { default: 5, type: 'integer' }, + nested: { properties: { query: { default: 'all', type: 'string' } } }, + typed: { default: 5, type: 'string' }, + untyped: {} + }, + type: 'object' + }); + // the server's own schema is left as it was + expect(inputSchema.properties.limit).toEqual({ default: 5 }); + }); + + it('falls back to the tools the health checks found while nothing is connected', () => { + const health: Record = { + 'srv-1': { + logs: [], + status: HealthCheckStatus.SUCCESS, + tools: [{ description: 'Search the docs', name: 'search' }] + }, + // a server that is switched off is not listed, whatever its last check said + 'srv-2': { logs: [], status: HealthCheckStatus.SUCCESS, tools: [{ name: 'hidden' }] } + }; + + vi.spyOn(mcpStore, 'getHealthCheckState').mockImplementation( + (serverId) => health[serverId] ?? { status: HealthCheckStatus.IDLE } + ); + + expect(contributed().provider.entries()).toEqual([ + { + definition: { + function: { + description: 'Search the docs', + name: 'search', + parameters: { properties: {}, required: [], type: 'object' } + }, + type: 'function' + }, + groupId: 'srv-1', + groupLabel: 'Docs' + } + ]); + }); + + it('runs a call through mcpStore and hands back its text', async () => { + const executeTool = vi + .spyOn(mcpStore, 'executeTool') + .mockResolvedValue({ content: 'found it', isError: true }); + const { signal } = new AbortController(); + const result = await contributed().provider.execute( + { arguments: '{"query":"llama"}', id: 'call_0', name: 'search' }, + signal + ); + + expect(executeTool).toHaveBeenCalledWith( + { function: { arguments: '{"query":"llama"}', name: 'search' }, id: 'call_0' }, + signal + ); + expect(result).toEqual({ content: 'found it', isError: false }); + }); + + it('fails the call of a tool no connected server has', async () => { + await expect( + contributed().provider.execute({ arguments: '{}', id: 'call_0', name: 'nope' }) + ).rejects.toThrow('Unknown tool: nope'); + }); + + it('is configured once a server is enabled in the settings', () => { + const hasEnabledServers = vi.spyOn(mcpStore, 'hasEnabledServers').mockReturnValue(false); + const { provider } = contributed(); + + expect(provider.isConfigured()).toBe(false); + + hasEnabledServers.mockReturnValue(true); + + expect(provider.isConfigured()).toBe(true); + }); + + it('resolves icons through the servers', () => { + vi.spyOn(mcpStore, 'getServerFavicon').mockImplementation((id) => `icon:${id}`); + vi.spyOn(mcpStore, 'getServerFaviconForTool').mockImplementation((name) => `tool:${name}`); + + const { provider } = contributed(); + + expect(provider.groupIcon?.('srv-1')).toBe('icon:srv-1'); + expect(provider.toolIcon?.('search')).toBe('tool:search'); + expect(provider.groupIdentity).toBeDefined(); + }); + + it('checks the enabled servers again when asked to refresh', () => { + const run = vi.spyOn(mcpStore, 'runHealthChecksForServers').mockResolvedValue(); + + void contributed().provider.refresh?.(); + + expect(run).toHaveBeenCalledWith([SERVERS[0], SERVERS[2]]); + }); + + it('words the empty tools panel by whether a server exists', () => { + const { provider } = contributed(); + + expect(provider.emptyHint?.()).toEqual({ + action: 'Enable MCP Server(s) to access', + sentence: 'To see MCP Tools you need to add / enable MCP Server(s).', + toolsLabel: 'MCP Tools' + }); + + vi.mocked(mcpStore.getServers).mockReturnValue([]); + + expect(provider.emptyHint?.().action).toBe('Add MCP Server(s) to access'); + }); +}); + +describe('MCP servers under the tool policy', () => { + it('counts the enabled servers with a url whose group and category are on', async () => { + expect(policyEnabledServerIds()).toEqual(['srv-1']); + + toolsStore.setToolEnabled('mcp:srv-1', false); + + expect(policyEnabledServerIds()).toEqual([]); + + toolsStore.setToolEnabled('mcp:srv-1', true); + vi.spyOn(conversationsStore.preferences, 'isCategoryEnabled').mockImplementation( + (source) => source !== ToolSource.MCP + ); + + expect(policyEnabledServerIds()).toEqual([]); + }); + + it('connects before a flow only when the policy leaves a server on', async () => { + const ensureInitialized = vi.spyOn(mcpStore, 'ensureInitialized').mockResolvedValue(true); + const { provider } = contributed(); + + toolsStore.setToolEnabled('mcp:srv-1', false); + await provider.prepare?.(); + + expect(ensureInitialized).not.toHaveBeenCalled(); + + toolsStore.setToolEnabled('mcp:srv-1', true); + await provider.prepare?.(); + + expect(ensureInitialized).toHaveBeenCalledOnce(); + }); + + it('holds the connections for the length of a flow', async () => { + const acquire = vi.spyOn(mcpStore, 'acquireConnection').mockImplementation(() => {}); + const release = vi.spyOn(mcpStore, 'releaseConnection').mockResolvedValue(); + const end = contributed().hook({ conversationId: 'conv-1' }); + + expect(acquire).toHaveBeenCalledOnce(); + expect(release).not.toHaveBeenCalled(); + + await end?.(); + + expect(release).toHaveBeenCalledOnce(); + }); + + it('holds nothing when the policy leaves no server on', () => { + const acquire = vi.spyOn(mcpStore, 'acquireConnection').mockImplementation(() => {}); + + toolsStore.setToolEnabled('mcp:srv-1', false); + + expect(contributed().hook({ conversationId: 'conv-1' })).toBeUndefined(); + expect(acquire).not.toHaveBeenCalled(); + }); + + it('enables the group and every tool of a connected server', () => { + mockConnections({ 'srv-1': connection({ name: 'search' }, { name: 'ping' }) }); + toolsStore.setToolEnabled('mcp:srv-1', false); + toolsStore.setToolEnabled('mcp-srv-1:search', false); + toolsStore.setToolEnabled('mcp-srv-2:search', false); + + enableAllToolsForServer('srv-2'); + + expect(toolsStore.disabledTools.size).toBe(3); + + enableAllToolsForServer('srv-1'); + + expect([...toolsStore.disabledTools]).toEqual(['mcp-srv-2:search']); + }); +}); + +describe('the MCP extension in the registry', () => { + afterEach(() => extensions.setEnabled('mcp-test', false)); + + // these strings are stored in localStorage and on conversation rows + it('lists its tools in the tools store under the stored keys while it is on', async () => { + mockConnections({ 'srv-1': connection({ name: 'search' }) }); + extensions.register({ + description: "MCP's tools, as the extension contributes them", + id: 'mcp-test', + load: async () => ({ default: { activate: contributeTools } }), + name: 'MCP' + }); + + expect(toolsStore.getToolSource('search')).toBeNull(); + + await extensions.setEnabled('mcp-test', true); + + expect(toolsStore.getPermissionKey('search')).toBe('mcp-srv-1:search'); + expect(toolsStore.getToolServerLabel('search')).toBe('Docs'); + expect(toolsStore.toolGroups.find((group) => group.serverId === 'srv-1')).toMatchObject({ + key: 'mcp:srv-1', + label: 'Docs', + source: ToolSource.MCP + }); + expect(extensions.contributions('flow')).toHaveLength(1); + + await extensions.setEnabled('mcp-test', false); + + expect(toolsStore.getToolSource('search')).toBeNull(); + expect(extensions.contributions('flow')).toEqual([]); + }); +}); diff --git a/ui/apps/chat/tests/unit/tools-extension-point.test.ts b/ui/apps/chat/tests/unit/tools-extension-point.test.ts new file mode 100644 index 000000000000..87d57c11adb5 --- /dev/null +++ b/ui/apps/chat/tests/unit/tools-extension-point.test.ts @@ -0,0 +1,244 @@ +// The tools store and the tool policy know tools from extensions only through +// the `tools` extension point: a provider's tools are listed, keyed, switched +// and labelled like the built-in ones, and are gone once the extension is off. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('#lib/services/database.service.ts', () => ({ + DatabaseService: {} +})); + +import { BuiltInTool, ToolSource } from '#lib/enums/index.ts'; +import type { Extension, ToolProvider } from '#lib/extensions/index.ts'; +import { extensions } from '#lib/extensions/index.ts'; +import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts'; +import { toolsStore } from '#lib/stores/tools.svelte.ts'; +import type { OpenAIToolDefinition, ToolEntry, ToolGroup } from '#lib/types/index.ts'; + +const SERVER_ID = 'srv-1'; +const ICON_URL = 'https://example.com/favicon.ico'; + +function definition(name: string): OpenAIToolDefinition { + return { function: { name, parameters: {} }, type: 'function' }; +} + +function makeProvider(overrides: Partial = {}): ToolProvider { + return { + entries: () => [ + { definition: definition('search'), groupId: SERVER_ID, groupLabel: 'Docs' }, + { definition: definition('fetch'), groupId: SERVER_ID, groupLabel: 'Docs' } + ], + execute: async () => ({ content: '', isError: false }), + groupIcon: (groupId) => (groupId === SERVER_ID ? ICON_URL : null), + isConfigured: () => true, + source: ToolSource.MCP, + toolIcon: (toolName) => (toolName === 'search' ? ICON_URL : null), + ...overrides + }; +} + +// the registry has no way to forget an extension, so every test registers its own +let nextExtensionId = 0; + +const activeIds: string[] = []; + +async function activate(extension: Extension): Promise { + const id = `tools-test-${nextExtensionId++}`; + + extensions.register({ + description: 'A test extension', + id, + load: async () => ({ default: extension }), + name: id + }); + await extensions.setEnabled(id, true); + activeIds.push(id); + + return id; +} + +function activateProvider(provider: ToolProvider = makeProvider()): Promise { + return activate({ activate: (ctx) => ctx.contribute('tools', provider) }); +} + +function entry(name: string): ToolEntry { + return toolsStore.allTools.find((t) => t.definition.function.name === name)!; +} + +function group(serverId: string): ToolGroup { + return toolsStore.toolGroups.find((g) => g.serverId === serverId)!; +} + +beforeEach(() => { + vi.restoreAllMocks(); + (toolsStore as unknown as { _serverTools: OpenAIToolDefinition[] })._serverTools = [ + definition(BuiltInTool.SERVER_READ_FILE) + ]; + vi.spyOn(toolsStore, 'customTools', 'get').mockReturnValue([definition('my_tool')]); +}); + +afterEach(async () => { + for (const id of activeIds.splice(0)) await extensions.setEnabled(id, false); + + (toolsStore as unknown as { _serverTools: OpenAIToolDefinition[] })._serverTools = []; + + for (const key of [...toolsStore.disabledTools]) toolsStore.setToolEnabled(key, true); +}); + +describe('tools from an extension', () => { + // these strings are stored in localStorage and on conversation rows + it('keeps the stored key formats', async () => { + await activateProvider(); + + const keys = toolsStore.allTools.map((t) => t.key); + + expect(keys).toContain('server:read_file'); + expect(keys).toContain('browser:get_datetime'); + expect(keys).toContain('mcp-srv-1:search'); + expect(keys).toContain('mcp-srv-1:fetch'); + expect(keys).toContain('custom:my_tool'); + expect(group(SERVER_ID).key).toBe('mcp:srv-1'); + expect(toolsStore.getGroupKey(ToolSource.MCP, SERVER_ID)).toBe('mcp:srv-1'); + expect(toolsStore.getToolKey(ToolSource.MCP, 'search', SERVER_ID)).toBe('mcp-srv-1:search'); + expect(toolsStore.getPermissionKey('search')).toBe('mcp-srv-1:search'); + }); + + it('lists them with their group id and label', async () => { + await activateProvider(); + + expect(entry('search')).toMatchObject({ + serverId: SERVER_ID, + serverName: 'Docs', + source: ToolSource.MCP + }); + expect(group(SERVER_ID)).toMatchObject({ label: 'Docs', source: ToolSource.MCP }); + expect(group(SERVER_ID).tools.map((t) => t.definition.function.name)).toEqual([ + 'search', + 'fetch' + ]); + expect(toolsStore.getToolSource('search')).toBe(ToolSource.MCP); + expect(toolsStore.getToolServerLabel('search')).toBe('Docs'); + }); + + it('sends them to the model after the server and browser tools, before the custom ones', async () => { + await activateProvider(); + + const names = toolsStore + .getEnabledToolsForLLM(new Set(), new Set()) + .map((def) => def.function.name); + + expect(names[0]).toBe('read_file'); + expect(names.slice(-3)).toEqual(['search', 'fetch', 'my_tool']); + expect(names.indexOf('get_datetime')).toBeLessThan(names.indexOf('search')); + }); + + it('switches a tool, its group or its category off', async () => { + await activateProvider(); + + const offered = (disabledTools: string[], disabledCategories: ToolSource[] = []) => + toolsStore + .getEnabledToolsForLLM(new Set(disabledTools), new Set(disabledCategories)) + .map((def) => def.function.name); + + expect(offered(['mcp-srv-1:search'])).not.toContain('search'); + expect(offered(['mcp-srv-1:search'])).toContain('fetch'); + expect(offered(['mcp:srv-1'])).not.toContain('search'); + expect(offered(['mcp:srv-1'])).not.toContain('fetch'); + expect(offered([], [ToolSource.MCP])).not.toContain('fetch'); + expect(offered([], [ToolSource.MCP])).toContain('my_tool'); + }); + + it('asks the provider for the icon of a group and of a tool call', async () => { + await activateProvider(); + + expect(toolsStore.getGroupIcon(group(SERVER_ID))).toBe(ICON_URL); + expect(toolsStore.getGroupIcon(toolsStore.toolGroups[0])).toBeNull(); + expect(toolsStore.getToolIcon('search')).toBe(ICON_URL); + expect(toolsStore.getToolIcon('fetch')).toBeNull(); + expect(toolsStore.getToolIcon(undefined)).toBeNull(); + expect(toolsStore.getGroupIdentity(group(SERVER_ID))).toBeNull(); + }); + + it('toggles a group through the tool policy by its group key', async () => { + await activateProvider(); + + const preferences = conversationsStore.preferences; + + expect(preferences.isGroupChecked(group(SERVER_ID))).toBe(true); + expect(preferences.isServerToolsEnabled(SERVER_ID)).toBe(true); + expect(preferences.isToolParentDisabled(entry('search'))).toBe(false); + + await preferences.toggleGroup(group(SERVER_ID)); + + expect([...toolsStore.disabledTools]).toEqual(['mcp:srv-1']); + expect(preferences.isGroupChecked(group(SERVER_ID))).toBe(false); + expect(preferences.isServerToolsEnabled(SERVER_ID)).toBe(false); + expect(preferences.isToolParentDisabled(entry('search'))).toBe(true); + expect(preferences.isToolActive(entry('search'))).toBe(false); + // the tool's own key is untouched + expect(preferences.isToolEnabled(entry('search').key)).toBe(true); + + await preferences.toggleServerTools(SERVER_ID); + + expect([...toolsStore.disabledTools]).toEqual([]); + expect(preferences.isToolActive(entry('search'))).toBe(true); + }); + + it('enables several keys in one go', async () => { + toolsStore.setToolEnabled('mcp:srv-1', false); + toolsStore.setToolEnabled('mcp-srv-1:search', false); + toolsStore.setToolEnabled('server:read_file', false); + + toolsStore.enableTools(['mcp:srv-1', 'mcp-srv-1:search']); + + expect([...toolsStore.disabledTools]).toEqual(['server:read_file']); + }); + + it('drops the tools once the extension is switched off', async () => { + const id = await activateProvider(); + + expect(toolsStore.getToolSource('search')).toBe(ToolSource.MCP); + + await extensions.setEnabled(id, false); + + expect(toolsStore.providers).toEqual([]); + expect(toolsStore.getToolSource('search')).toBeNull(); + expect(toolsStore.getPermissionKey('search')).toBeNull(); + expect(toolsStore.getToolServerLabel('search')).toBe(''); + expect(toolsStore.getToolIcon('search')).toBeNull(); + }); +}); + +describe('tools without any extension', () => { + it('lists only the built-in categories', () => { + const groups = toolsStore.toolGroups; + + expect(toolsStore.providers).toEqual([]); + expect(groups.map((g) => g.source)).toEqual([ + ToolSource.SERVER, + ToolSource.BROWSER, + ToolSource.CUSTOM + ]); + expect(groups.every((g) => g.serverId === undefined)).toBe(true); + expect(groups.map((g) => g.key)).toEqual(['server', 'browser', 'custom']); + expect(toolsStore.getGroupIcon(groups[0])).toBeNull(); + expect(toolsStore.getGroupIdentity(groups[0])).toBeNull(); + }); + + it('toggles a category group by its category', async () => { + const preferences = conversationsStore.preferences; + const [serverGroup] = toolsStore.toolGroups; + + expect(preferences.isGroupChecked(serverGroup)).toBe(true); + + await preferences.toggleGroup(serverGroup); + + expect(preferences.isGroupChecked(serverGroup)).toBe(false); + expect(preferences.isToolParentDisabled(entry('read_file'))).toBe(true); + expect([...toolsStore.disabledTools]).toEqual([]); + + await preferences.toggleGroup(serverGroup); + + expect(preferences.isGroupChecked(serverGroup)).toBe(true); + }); +}); From 27f2015f70eeafaa49681f2293ba854ded96148e Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Fri, 13 Nov 2026 00:32:23 +0100 Subject: [PATCH 03/19] ui: open MCP from the sidebar and its page through the navigation and pages extension points The sidebar, the routes and the root layout no longer import MCP code. Two new extension points carry what they need instead. `navigation` is an entry in the sidebar: the MCP extension contributes its item, which the sidebar places between Models and Settings, lists in the search dialog and opens like before, as the MCP servers dialog on a desktop or tablet and as a page on a phone. The sidebar mounts the dialogs of contributed items itself. `pages` is a page at a path of its own: the static `mcp-servers` route gives way to one generic route that renders the page contributed for the path, and ends in the app's 404 when nothing is contributed for it. `#/mcp-servers` keeps working and the sidebar item is lit while its page shows. The background MCP health checks move from the root layout into the extension's activation and stop when the extension is switched off. Assisted-by: Claude (Opus 5.5 Medium) --- .../app/dialogs/DialogSearch.svelte | 34 +-- .../SidebarNavigation.svelte | 51 ++-- .../SidebarNavigationActions.svelte | 29 ++- .../SidebarNavigationFooter.svelte | 12 +- .../lib/components/app/navigation/index.ts | 2 +- .../src/lib/constants/routes.constants.ts | 4 +- .../chat/src/lib/constants/ui.constants.ts | 12 +- ui/apps/chat/src/lib/enums/ui.enums.ts | 1 - ui/apps/chat/src/lib/extensions/index.ts | 2 + .../extensions/mcp/McpServersPage.svelte} | 7 +- ui/apps/chat/src/lib/extensions/mcp/index.ts | 6 + .../chat/src/lib/extensions/mcp/navigation.ts | 20 ++ ui/apps/chat/src/lib/extensions/mcp/pages.ts | 11 + .../src/lib/extensions/mcp/startup.svelte.ts | 35 +++ .../src/lib/extensions/points/navigation.ts | 25 ++ .../chat/src/lib/extensions/points/pages.ts | 11 + ui/apps/chat/src/lib/extensions/types.ts | 6 + .../chat/src/lib/services/router.service.ts | 5 + ui/apps/chat/src/lib/stores/ui.svelte.ts | 7 +- ui/apps/chat/src/lib/types/navigation.d.ts | 3 + ui/apps/chat/src/lib/utils/index.ts | 2 + ui/apps/chat/src/lib/utils/sidebar-items.ts | 20 ++ ui/apps/chat/src/routes/+layout.svelte | 26 -- .../src/routes/[extensionPage]/+page.svelte | 26 ++ .../chat/src/routes/[extensionPage]/+page.ts | 13 + ui/apps/chat/src/routes/mcp-servers/+page.ts | 4 - .../components/ExtensionPageFixture.svelte | 2 + .../components/NavigationDialogFixture.svelte | 14 ++ .../extension-navigation.svelte.test.ts | 233 ++++++++++++++++++ .../client/mcp-navigation-glue.svelte.test.ts | 119 +++++++++ .../client/nested-surfaces.svelte.test.ts | 25 +- .../SidebarNavigation.stories.svelte | 15 ++ .../tests/unit/extension-page-route.test.ts | 61 +++++ ui/apps/chat/tests/unit/sidebar-items.test.ts | 60 +++++ 34 files changed, 817 insertions(+), 86 deletions(-) rename ui/apps/chat/src/{routes/mcp-servers/+page.svelte => lib/extensions/mcp/McpServersPage.svelte} (73%) create mode 100644 ui/apps/chat/src/lib/extensions/mcp/navigation.ts create mode 100644 ui/apps/chat/src/lib/extensions/mcp/pages.ts create mode 100644 ui/apps/chat/src/lib/extensions/mcp/startup.svelte.ts create mode 100644 ui/apps/chat/src/lib/extensions/points/navigation.ts create mode 100644 ui/apps/chat/src/lib/extensions/points/pages.ts create mode 100644 ui/apps/chat/src/lib/utils/sidebar-items.ts create mode 100644 ui/apps/chat/src/routes/[extensionPage]/+page.svelte create mode 100644 ui/apps/chat/src/routes/[extensionPage]/+page.ts delete mode 100644 ui/apps/chat/src/routes/mcp-servers/+page.ts create mode 100644 ui/apps/chat/tests/client/components/ExtensionPageFixture.svelte create mode 100644 ui/apps/chat/tests/client/components/NavigationDialogFixture.svelte create mode 100644 ui/apps/chat/tests/client/extension-navigation.svelte.test.ts create mode 100644 ui/apps/chat/tests/client/mcp-navigation-glue.svelte.test.ts create mode 100644 ui/apps/chat/tests/unit/extension-page-route.test.ts create mode 100644 ui/apps/chat/tests/unit/sidebar-items.test.ts diff --git a/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte b/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte index 2b4e0b71dad3..b8c227945455 100644 --- a/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte +++ b/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte @@ -6,13 +6,13 @@ ICON_CLASS_DEFAULT, ICON_CLASS_SM, ICON_CLASS_XS, - SIDEBAR_ACTIONS_ITEMS, - SIDEBAR_FOOTER_ITEMS + SIDEBAR_ACTIONS_ITEMS } from '#lib/constants/index.ts'; import { KeyboardKey, SidebarAction } from '#lib/enums/index.ts'; + import { extensions, type NavigationItem } from '#lib/extensions/index.ts'; import { RouterService } from '#lib/services/router.service.ts'; import { conversationsStore, deviceStore, uiStore } from '#lib/stores/index.ts'; - import { formatRelativeTime, isIMEComposing } from '#lib/utils/index.ts'; + import { formatRelativeTime, isIMEComposing, sidebarFooterItems } from '#lib/utils/index.ts'; import { goto } from '$app/navigation'; import type { Component } from 'svelte'; @@ -20,9 +20,11 @@ open: boolean; /** Runs a sidebar action picked from the actions section. */ onAction?: (action: SidebarAction) => void; + /** Opens an extension's item picked from the actions section. */ + onContributed?: (item: NavigationItem) => void; } - let { onAction, open = $bindable() }: Props = $props(); + let { onAction, onContributed, open = $bindable() }: Props = $props(); interface SearchEntry { icon: Component; @@ -71,22 +73,26 @@ ); const actionEntries = $derived.by((): SearchEntry[] => - // every sidebar action the sidebar shows but Search itself, which is what opened this - // dialog, and the models manager on a phone, which picks its models in the selector - [...SIDEBAR_ACTIONS_ITEMS, ...SIDEBAR_FOOTER_ITEMS] + // every sidebar action the sidebar shows but Search itself, which is what opened this dialog, and the + // models manager on a phone, which picks its models in the selector; extensions' items among them + [...SIDEBAR_ACTIONS_ITEMS, ...sidebarFooterItems(extensions.contributions('navigation'))] .filter( (item) => - item.action && + (item.action || item.contributed) && item.action !== SidebarAction.SEARCH && uiStore.isSidebarActionShown(item.action) && (item.action !== SidebarAction.MANAGE_MODELS || !deviceStore.isMobile) ) - .map((item) => ({ - icon: item.icon, - id: `action-${item.action}`, - keys: item.keys, - label: item.tooltip, - run: () => close(() => onAction?.(item.action!)) + .map(({ action, contributed, icon, keys, tooltip }) => ({ + icon, + id: `action-${action ?? contributed?.id}`, + keys, + label: tooltip, + run: () => + close(() => { + if (action) onAction?.(action); + else if (contributed) onContributed?.(contributed); + }) })) .filter((entry) => matches(entry.label)) ); diff --git a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte index a5b115fd4358..e989e7dbb98d 100644 --- a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte +++ b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte @@ -7,7 +7,6 @@ DialogDiscoverModels, DialogGroup, DialogGroupPicker, - DialogMcpServers, DialogSearch, DialogSettingsChat, Logo, @@ -22,7 +21,6 @@ SIDEBAR_COLLAPSE_WIDTH, SIDEBAR_COLLAPSED_WIDTH, SIDEBAR_CONTENT_FADE_MS, - SIDEBAR_FOOTER_ITEMS, SIDEBAR_MAX_WIDTH, SIDEBAR_MIN_WIDTH, SIDEBAR_OVERSTRETCH_PX, @@ -31,6 +29,7 @@ SIDEBAR_TOGGLE_MS } from '#lib/constants/index.ts'; import { SidebarAction, TooltipSide } from '#lib/enums/index.ts'; + import { extensions, type NavigationItem } from '#lib/extensions/index.ts'; import { useKeyboardShortcuts } from '#lib/hooks/use-keyboard-shortcuts.svelte.ts'; import { useMarqueeSelection } from '#lib/hooks/use-marquee-selection.svelte.ts'; import { RouterService } from '#lib/services/router.service.ts'; @@ -41,7 +40,7 @@ settingsStore, uiStore } from '#lib/stores/index.ts'; - import { buildConversationTree, remToPx } from '#lib/utils/index.ts'; + import { buildConversationTree, remToPx, sidebarFooterItems } from '#lib/utils/index.ts'; import { goto } from '$app/navigation'; import { resolve } from '$app/paths'; import { page } from '$app/state'; @@ -174,7 +173,6 @@ let renameDialogOpen = $state(false); let settingsDialogOpen = $state(false); - let mcpDialogOpen = $state(false); let renameTargetConversationId = $state(null); let renameDraft = $state(''); let renameOriginalTitle = $state(''); @@ -543,12 +541,7 @@ openDialog(() => uiStore.openModelsManager()); break; - // dialogs on a desktop or tablet; on a phone, pages of their own - case SidebarAction.MCP: - if (isOnMobile) navigateBehind(() => goto(resolve(ROUTES.MCP_SERVERS))); - else openDialog(() => (mcpDialogOpen = true)); - - break; + // a dialog on a desktop or tablet; on a phone, a page of its own case SidebarAction.SETTINGS: if (isOnMobile) navigateBehind(() => goto(resolve(ROUTES.SETTINGS))); else openDialog(() => (settingsDialogOpen = true)); @@ -556,6 +549,21 @@ break; } } + + const navigationItems = $derived(extensions.contributions('navigation')); + /** The extension's item whose dialog is open. Raw, so it compares by identity with the contributions. */ + let dialogItem = $state.raw(null); + + /** Opens an extension's item: its dialog on a desktop or tablet when it has one, its page otherwise. */ + function openContributedItem(item: NavigationItem): void { + if (isOnMobile || !item.dialog) navigateBehind(() => goto(item.route)); + else openDialog(() => (dialogItem = item)); + } + + function setItemDialogOpen(item: NavigationItem, open: boolean): void { + if (open) dialogItem = item; + else if (dialogItem === item) dialogItem = null; + } @@ -669,8 +677,11 @@ @@ -709,7 +720,10 @@ {#if !isOnMobile} - + {/if} @@ -759,9 +773,18 @@ - + - + +{#each navigationItems as item (item.id)} + {#if item.dialog} + dialogItem === item, (open) => setItemDialogOpen(item, open)} /> + {/if} +{/each} diff --git a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationActions.svelte b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationActions.svelte index 172eaff93b99..6577126917d1 100644 --- a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationActions.svelte +++ b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationActions.svelte @@ -5,9 +5,12 @@ ICON_CLASS_DEFAULT, ICON_STRIP_TRANSITION_DELAY_MULTIPLIER, ICON_STRIP_TRANSITION_DURATION, + ROUTES, SIDEBAR_ACTIONS_ITEMS } from '#lib/constants/index.ts'; import { SidebarAction } from '#lib/enums/index.ts'; + import type { NavigationItem } from '#lib/extensions/index.ts'; + import { RouterService } from '#lib/services/router.service.ts'; import { deviceStore, uiStore } from '#lib/stores/index.ts'; import type { DesktopIconStripItem } from '#lib/types/index.ts'; import { hapticTap } from '#lib/utils/index.ts'; @@ -23,11 +26,19 @@ /** The items to show: the sidebar's top actions unless given, e.g. its footer's. */ items?: DesktopIconStripItem[]; onAction?: (action: SidebarAction) => void; + /** Opens an item an extension contributed. */ + onContributed?: (item: NavigationItem) => void; /** Follows a route item, so a phone can open its page behind the sidebar and then close it. */ onNavigate?: (go: () => Promise) => void; } - let { class: className, items = SIDEBAR_ACTIONS_ITEMS, onAction, onNavigate }: Props = $props(); + let { + class: className, + items = SIDEBAR_ACTIONS_ITEMS, + onAction, + onContributed, + onNavigate + }: Props = $props(); // the models manager stays desktop-only: a phone picks its models in the selector; a phone // reaches search from the round key at the top of the sidebar instead. Models and MCP @@ -51,14 +62,18 @@ }, ICON_STRIP_TRANSITION_DELAY_MULTIPLIER * actions.length); }); - /** Click handler of one icon strip item: a sidebar action or a route. */ + /** Click handler of one icon strip item: a sidebar action, an extension's item or a route. */ function itemClickHandler(item: DesktopIconStripItem): (() => void) | undefined { - const { action, route } = item; + const { action, contributed, route } = item; if (action) { return () => onAction?.(action); } + if (contributed) { + return () => onContributed?.(contributed); + } + if (route) { return () => (onNavigate ? onNavigate(() => goto(route)) : void goto(route)); } @@ -67,6 +82,14 @@ } function isItemActive(item: DesktopIconStripItem): boolean { + // an extension's item is lit while the page it opens is the one shown + if (item.contributed) { + return ( + page.route.id === ROUTES.EXTENSION_PAGE && + RouterService.extensionPage(page.params.extensionPage ?? '') === item.contributed.route + ); + } + if (item.activeRouteId) { return page.route.id === item.activeRouteId; } diff --git a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte index b236dc3db653..1ae1f9cb6e6d 100644 --- a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte +++ b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte @@ -1,19 +1,25 @@ diff --git a/ui/apps/chat/src/lib/components/app/navigation/index.ts b/ui/apps/chat/src/lib/components/app/navigation/index.ts index a4dc758ad1e9..78120705c45a 100644 --- a/ui/apps/chat/src/lib/components/app/navigation/index.ts +++ b/ui/apps/chat/src/lib/components/app/navigation/index.ts @@ -182,7 +182,7 @@ export { default as SidebarNavigationSelectionBar } from './SidebarNavigation/Si export { default as SidebarNavigationConversationList } from './SidebarNavigation/SidebarNavigationConversationList.svelte'; export { default as SidebarNavigationActions } from './SidebarNavigation/SidebarNavigationActions.svelte'; -/** The sidebar's footer: Models, MCP and Settings in a group inset in the sidebar. */ +/** The sidebar's footer: Models, what extensions add and Settings, in a group inset in the sidebar. */ export { default as SidebarNavigationFooter } from './SidebarNavigation/SidebarNavigationFooter.svelte'; /** diff --git a/ui/apps/chat/src/lib/constants/routes.constants.ts b/ui/apps/chat/src/lib/constants/routes.constants.ts index 97cd886e517c..22b69cf5e39e 100644 --- a/ui/apps/chat/src/lib/constants/routes.constants.ts +++ b/ui/apps/chat/src/lib/constants/routes.constants.ts @@ -18,8 +18,8 @@ export const URL_PARAMS = { export const ROUTES = { /** A conversation. */ CHAT: '/(chat)/chat/[id]', - /** MCP servers - a page on a phone, a dialog elsewhere. */ - MCP_SERVERS: '/mcp-servers', + /** A page an extension contributes, see RouterService.extensionPage(). */ + EXTENSION_PAGE: '/[extensionPage]', /** Models manager. */ MODELS: '/models', /** Search — mobile-only full-page conversation search. */ diff --git a/ui/apps/chat/src/lib/constants/ui.constants.ts b/ui/apps/chat/src/lib/constants/ui.constants.ts index f0739b1e8626..8fd0876996c2 100644 --- a/ui/apps/chat/src/lib/constants/ui.constants.ts +++ b/ui/apps/chat/src/lib/constants/ui.constants.ts @@ -9,7 +9,6 @@ import { ROUTES } from './routes.constants'; import Search from '@lucide/svelte/icons/search'; import Settings from '@lucide/svelte/icons/settings'; import SquarePen from '@lucide/svelte/icons/square-pen'; -import McpLogo from '#lib/components/app/mcp/McpLogo.svelte'; import { SidebarAction, ToolSource } from '#lib/enums/index.ts'; import type { DesktopIconStripItem } from '#lib/types/index.ts'; @@ -165,7 +164,10 @@ export const SIDEBAR_ACTIONS_ITEMS: DesktopIconStripItem[] = [ { action: SidebarAction.SEARCH, icon: Search, keys: SHORTCUT_SEARCH, tooltip: 'Search' } ]; -/** The sidebar's footer: managing the app around the chats. */ +/** + * The sidebar's footer: managing the app around the chats. Extensions add their + * items right after Models, which opens it (see `sidebarFooterItems`). + */ export const SIDEBAR_FOOTER_ITEMS: DesktopIconStripItem[] = [ { action: SidebarAction.MANAGE_MODELS, @@ -174,12 +176,6 @@ export const SIDEBAR_FOOTER_ITEMS: DesktopIconStripItem[] = [ keys: SHORTCUT_MODELS, tooltip: 'Models' }, - { - action: SidebarAction.MCP, - activeRouteId: ROUTES.MCP_SERVERS, - icon: McpLogo, - tooltip: 'MCP' - }, { action: SidebarAction.SETTINGS, activeRouteId: ROUTES.SETTINGS, diff --git a/ui/apps/chat/src/lib/enums/ui.enums.ts b/ui/apps/chat/src/lib/enums/ui.enums.ts index 2ea3e5f31058..a7d94792d343 100644 --- a/ui/apps/chat/src/lib/enums/ui.enums.ts +++ b/ui/apps/chat/src/lib/enums/ui.enums.ts @@ -19,7 +19,6 @@ export enum ScrollCarouselVariant { */ export enum SidebarAction { MANAGE_MODELS = 'manage-models', - MCP = 'mcp', NEW_CHAT = 'new-chat', SEARCH = 'search', SETTINGS = 'settings' diff --git a/ui/apps/chat/src/lib/extensions/index.ts b/ui/apps/chat/src/lib/extensions/index.ts index 41e6385f0841..89cc94efff04 100644 --- a/ui/apps/chat/src/lib/extensions/index.ts +++ b/ui/apps/chat/src/lib/extensions/index.ts @@ -7,6 +7,8 @@ export type { ToolProviderEmptyHint, ToolProviderEntry } from './points/tools'; +export type { NavigationDialog, NavigationItem, NavigationPlacement } from './points/navigation'; +export type { ExtensionPage } from './points/pages'; export { ExtensionRegistry, extensions } from './registry.svelte'; export type { Extension, diff --git a/ui/apps/chat/src/routes/mcp-servers/+page.svelte b/ui/apps/chat/src/lib/extensions/mcp/McpServersPage.svelte similarity index 73% rename from ui/apps/chat/src/routes/mcp-servers/+page.svelte rename to ui/apps/chat/src/lib/extensions/mcp/McpServersPage.svelte index 0da72a67f05d..d1f98f0869e4 100644 --- a/ui/apps/chat/src/routes/mcp-servers/+page.svelte +++ b/ui/apps/chat/src/lib/extensions/mcp/McpServersPage.svelte @@ -1,12 +1,7 @@ - - MCP Servers - {APP_NAME} - -
uiStore.isMcpShown, + tooltip: 'MCP' + }); +} diff --git a/ui/apps/chat/src/lib/extensions/mcp/pages.ts b/ui/apps/chat/src/lib/extensions/mcp/pages.ts new file mode 100644 index 000000000000..c5c30165f935 --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/pages.ts @@ -0,0 +1,11 @@ +import type { ExtensionContext } from '../types'; +import McpServersPage from './McpServersPage.svelte'; + +/** The MCP servers page. Its path is what `ROUTES.MCP_SERVERS` leads to. */ +export function contributePages(ctx: ExtensionContext): void { + ctx.contribute('pages', { + component: McpServersPage, + path: 'mcp-servers', + title: 'MCP Servers' + }); +} diff --git a/ui/apps/chat/src/lib/extensions/mcp/startup.svelte.ts b/ui/apps/chat/src/lib/extensions/mcp/startup.svelte.ts new file mode 100644 index 000000000000..0dbe4d6bce50 --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/startup.svelte.ts @@ -0,0 +1,35 @@ +import type { ExtensionContext } from '../types'; +import { mcpStore } from '#lib/stores/mcp/index.svelte.ts'; +import { untrack } from 'svelte'; + +/** + * Background MCP server health checks, from the moment the extension is on. + * Health-check every configured server with a URL - including disabled ones - + * so the /mcp-servers page can display health metadata for servers that are + * currently turned off. Disabled servers never get promoted to active + * connections (see runHealthCheck), so their tools/prompts/resources stay + * out of the chat-side stores. + * Only IDLE servers are checked; already-resolved (SUCCESS / ERROR) servers + * keep their existing state, so adding or removing a server does not flash + * every other card back through skeleton state. + */ +export function contributeStartup(ctx: ExtensionContext): void { + // outside any component, so the effect needs a root of its own; it runs again when the server list changes + const dispose = $effect.root(() => { + $effect(() => { + const mcpServers = mcpStore.getServers(); + const serversWithUrls = mcpServers.filter((s) => s.url.trim()); + + if (serversWithUrls.length > 0) { + untrack(() => { + // Run health checks in background (don't await) + mcpStore.runHealthChecksForServers(serversWithUrls, true).catch((error) => { + console.warn('[mcp] MCP health checks failed:', error); + }); + }); + } + }); + }); + + ctx.onDeactivate(dispose); +} diff --git a/ui/apps/chat/src/lib/extensions/points/navigation.ts b/ui/apps/chat/src/lib/extensions/points/navigation.ts new file mode 100644 index 000000000000..30ed6cf53108 --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/points/navigation.ts @@ -0,0 +1,25 @@ +import type { Component } from 'svelte'; + +/** Where a contributed item sits: `footer` is the sidebar's footer, right after Models. */ +export type NavigationPlacement = 'footer'; + +/** A dialog the sidebar mounts for a navigation item and opens through its bindable `open`. */ +export type NavigationDialog = Component<{ open?: boolean }, Record, 'open'>; + +/** An entry in the sidebar that opens a page of the extension, or a dialog where the screen has room for one. */ +export interface NavigationItem { + /** Opened on a desktop or tablet in place of the route. A phone always opens the route. */ + dialog?: NavigationDialog; + icon: Component; + /** Stable identity among the sidebar's items. */ + id: string; + /** Key combination shown beside the label. A hint only: the sidebar does not bind it. */ + keys?: string[]; + placement: NavigationPlacement; + /** Hash route of the extension's page the item opens, e.g. `#/mcp-servers`. The item is lit while that page shows. */ + route: string; + /** Whether the item shows right now, read reactively; it always shows without this. */ + shown?(): boolean; + /** The item's label, also what the search dialog lists it under. */ + tooltip: string; +} diff --git a/ui/apps/chat/src/lib/extensions/points/pages.ts b/ui/apps/chat/src/lib/extensions/points/pages.ts new file mode 100644 index 000000000000..326c647f9d5c --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/points/pages.ts @@ -0,0 +1,11 @@ +import type { Component } from 'svelte'; + +/** A page of the extension, shown at `#/` inside the app's layout. */ +export interface ExtensionPage { + /** Renders the whole page, heading included. */ + component: Component; + /** One URL segment, e.g. `mcp-servers`. A route of the app itself with the same path wins. */ + path: string; + /** Document title, shown before the app's name. */ + title: string; +} diff --git a/ui/apps/chat/src/lib/extensions/types.ts b/ui/apps/chat/src/lib/extensions/types.ts index 8d3c172b65a3..93d3cc5d7511 100644 --- a/ui/apps/chat/src/lib/extensions/types.ts +++ b/ui/apps/chat/src/lib/extensions/types.ts @@ -4,6 +4,8 @@ * same contract. */ +import type { NavigationItem } from './points/navigation'; +import type { ExtensionPage } from './points/pages'; import type { FlowHook, ToolProvider } from './points/tools'; /** What the app knows about an extension before its code is loaded. */ @@ -38,6 +40,10 @@ export interface ExtensionContext { export interface ExtensionPoints { /** Runs around every agentic flow. */ flow: FlowHook; + /** Entries in the sidebar, each opening a page of the extension or a dialog. */ + navigation: NavigationItem; + /** Pages of the extension, each at a path of its own. */ + pages: ExtensionPage; /** Tools the model can call, listed and run by the extension. */ tools: ToolProvider; } diff --git a/ui/apps/chat/src/lib/services/router.service.ts b/ui/apps/chat/src/lib/services/router.service.ts index 13e8fccf69b0..247ecdca7780 100644 --- a/ui/apps/chat/src/lib/services/router.service.ts +++ b/ui/apps/chat/src/lib/services/router.service.ts @@ -13,4 +13,9 @@ export class RouterService { static chat(id: string): ResolvedPathname { return resolve(ROUTES.CHAT, { id }); } + + /** Route of the page an extension contributes at `path`. */ + static extensionPage(path: string): string { + return `${ROUTES.START}${path}`; + } } diff --git a/ui/apps/chat/src/lib/stores/ui.svelte.ts b/ui/apps/chat/src/lib/stores/ui.svelte.ts index b8117a8b2ddf..654415676894 100644 --- a/ui/apps/chat/src/lib/stores/ui.svelte.ts +++ b/ui/apps/chat/src/lib/stores/ui.svelte.ts @@ -185,12 +185,13 @@ class UiStore { if (this.collapsedSidebarSections.has(id)) this.toggleSidebarSection(id); } - /** Whether a sidebar action shows: Models and MCP wait behind their settings. */ + /** + * Whether a sidebar action shows: Models waits behind its setting. MCP's entry is the MCP + * extension's, which hides itself behind its own setting (`isMcpShown`). + */ isSidebarActionShown(action: SidebarAction | undefined): boolean { if (action === SidebarAction.MANAGE_MODELS) return this.isModelsManagerShown; - if (action === SidebarAction.MCP) return this.isMcpShown; - return true; } diff --git a/ui/apps/chat/src/lib/types/navigation.d.ts b/ui/apps/chat/src/lib/types/navigation.d.ts index 4de568a1741f..69e5b392e8c8 100644 --- a/ui/apps/chat/src/lib/types/navigation.d.ts +++ b/ui/apps/chat/src/lib/types/navigation.d.ts @@ -1,4 +1,5 @@ import type { MenuKind, SidebarAction } from '#lib/enums/index.ts'; +import type { NavigationItem } from '#lib/extensions/index.ts'; import type { ResolvedPathname } from '$app/types'; import type { Component, Snippet } from 'svelte'; @@ -12,6 +13,8 @@ export interface DesktopIconStripItem { route?: ResolvedPathname; /** Custom action handled by the sidebar, e.g. opening a new-chat tab */ action?: SidebarAction; + /** The item of an extension this one shows; the sidebar opens it in place of an `action` */ + contributed?: NavigationItem; activeRouteId?: string; activeRoutePrefix?: string; activeUrlIncludes?: string; diff --git a/ui/apps/chat/src/lib/utils/index.ts b/ui/apps/chat/src/lib/utils/index.ts index 0737b08f58d4..1e1360e451ea 100644 --- a/ui/apps/chat/src/lib/utils/index.ts +++ b/ui/apps/chat/src/lib/utils/index.ts @@ -225,6 +225,8 @@ export { export { resolveTabTarget, resolveTabView, type TabView } from './chat-tabs'; +export { sidebarFooterItems } from './sidebar-items'; + // Shared `file_glob_search` runner with a short-lived result cache export { runGlobSearch, runGlobSearchWithChildren } from './glob-search'; diff --git a/ui/apps/chat/src/lib/utils/sidebar-items.ts b/ui/apps/chat/src/lib/utils/sidebar-items.ts new file mode 100644 index 000000000000..0afcae39b997 --- /dev/null +++ b/ui/apps/chat/src/lib/utils/sidebar-items.ts @@ -0,0 +1,20 @@ +import { SIDEBAR_FOOTER_ITEMS } from '#lib/constants/index.ts'; +import type { NavigationItem } from '#lib/extensions/index.ts'; +import type { DesktopIconStripItem } from '#lib/types/index.ts'; + +/** The sidebar footer's items: the app's own, with what extensions contribute to the footer and show right now. */ +export function sidebarFooterItems(contributed: NavigationItem[]): DesktopIconStripItem[] { + const items = contributed + .filter((item) => item.placement === 'footer' && (item.shown?.() ?? true)) + .map( + (item): DesktopIconStripItem => ({ + contributed: item, + icon: item.icon, + keys: item.keys, + tooltip: item.tooltip + }) + ); + + // Models opens the footer: contributed items follow it, ahead of the rest + return [...SIDEBAR_FOOTER_ITEMS.slice(0, 1), ...items, ...SIDEBAR_FOOTER_ITEMS.slice(1)]; +} diff --git a/ui/apps/chat/src/routes/+layout.svelte b/ui/apps/chat/src/routes/+layout.svelte index aab112e06b34..8cef51a35afd 100644 --- a/ui/apps/chat/src/routes/+layout.svelte +++ b/ui/apps/chat/src/routes/+layout.svelte @@ -22,7 +22,6 @@ chatStore, conversationsStore, deviceStore, - mcpStore, modelsStore, serverStore, settingsStore, @@ -282,31 +281,6 @@ }; }); - // Background MCP server health checks on app load. - // Health-check every configured server with a URL - including disabled ones - - // so the /mcp-servers page can display health metadata for servers that are - // currently turned off. Disabled servers never get promoted to active - // connections (see runHealthCheck), so their tools/prompts/resources stay - // out of the chat-side stores. - // Only IDLE servers are checked; already-resolved (SUCCESS / ERROR) servers - // keep their existing state, so adding or removing a server does not flash - // every other card back through skeleton state. - $effect(() => { - if (!browser) return; - - const mcpServers = mcpStore.getServers(); - const serversWithUrls = mcpServers.filter((s) => s.url.trim()); - - if (serversWithUrls.length > 0) { - untrack(() => { - // Run health checks in background (don't await) - mcpStore.runHealthChecksForServers(serversWithUrls, true).catch((error) => { - console.warn('[layout] MCP health checks failed:', error); - }); - }); - } - }); - // Monitor API key changes and redirect to error page if removed or changed when required $effect(() => { checkApiKey(); diff --git a/ui/apps/chat/src/routes/[extensionPage]/+page.svelte b/ui/apps/chat/src/routes/[extensionPage]/+page.svelte new file mode 100644 index 000000000000..0d1ef042742f --- /dev/null +++ b/ui/apps/chat/src/routes/[extensionPage]/+page.svelte @@ -0,0 +1,26 @@ + + + + {#if contributed} + {contributed.title} - {APP_NAME} + {/if} + + + +{#if contributed} + +{/if} diff --git a/ui/apps/chat/src/routes/[extensionPage]/+page.ts b/ui/apps/chat/src/routes/[extensionPage]/+page.ts new file mode 100644 index 000000000000..af674fcc8f60 --- /dev/null +++ b/ui/apps/chat/src/routes/[extensionPage]/+page.ts @@ -0,0 +1,13 @@ +import type { PageLoad } from './$types'; +import { error } from '@sveltejs/kit'; +import { extensions } from '#lib/extensions/index.ts'; +import { loadAppRoute } from '#lib/stores/init.ts'; + +export const load: PageLoad = async ({ fetch, params }) => { + await loadAppRoute(fetch); + + // the extensions are active by now: a path none of them has a page for is the app's 404 + if (!extensions.contributions('pages').some((page) => page.path === params.extensionPage)) { + error(404, 'Not Found'); + } +}; diff --git a/ui/apps/chat/src/routes/mcp-servers/+page.ts b/ui/apps/chat/src/routes/mcp-servers/+page.ts deleted file mode 100644 index 3c3deac5178a..000000000000 --- a/ui/apps/chat/src/routes/mcp-servers/+page.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { PageLoad } from './$types'; -import { loadAppRoute } from '#lib/stores/init.ts'; - -export const load: PageLoad = ({ fetch }) => loadAppRoute(fetch); diff --git a/ui/apps/chat/tests/client/components/ExtensionPageFixture.svelte b/ui/apps/chat/tests/client/components/ExtensionPageFixture.svelte new file mode 100644 index 000000000000..818fe05c9faa --- /dev/null +++ b/ui/apps/chat/tests/client/components/ExtensionPageFixture.svelte @@ -0,0 +1,2 @@ + +

Fixture page

diff --git a/ui/apps/chat/tests/client/components/NavigationDialogFixture.svelte b/ui/apps/chat/tests/client/components/NavigationDialogFixture.svelte new file mode 100644 index 000000000000..607255d4da79 --- /dev/null +++ b/ui/apps/chat/tests/client/components/NavigationDialogFixture.svelte @@ -0,0 +1,14 @@ + + + +{#if open} +
+ +
+{/if} diff --git a/ui/apps/chat/tests/client/extension-navigation.svelte.test.ts b/ui/apps/chat/tests/client/extension-navigation.svelte.test.ts new file mode 100644 index 000000000000..73070b6d572b --- /dev/null +++ b/ui/apps/chat/tests/client/extension-navigation.svelte.test.ts @@ -0,0 +1,233 @@ +// The sidebar and the extension page route show what extensions contribute to +// `navigation` and `pages` and know nothing else about them: a contributed item +// sits right after Models, opens its dialog on a desktop and its page +// on a phone, is lit on its page, and is gone, with everything still working, +// once its extension is off. + +import '../../src/app.css'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const pageState = vi.hoisted(() => ({ + params: {} as Record, + route: { id: null as string | null }, + url: new URL('http://localhost/#/') +})); + +vi.mock('$app/state', () => ({ page: pageState })); +// no importOriginal: SvelteKit 3's client router does not load outside the app +vi.mock('$app/navigation', () => ({ + afterNavigate: vi.fn(), + beforeNavigate: vi.fn(), + disableScrollHandling: vi.fn(), + goto: vi.fn(async () => {}), + onNavigate: vi.fn(), + refreshAll: vi.fn(async () => {}) +})); + +import ExtensionPage from '../../src/routes/[extensionPage]/+page.svelte'; +import ExtensionPageFixture from './components/ExtensionPageFixture.svelte'; +import NavigationDialogFixture from './components/NavigationDialogFixture.svelte'; +import SidebarNavigationHarness from './components/SidebarNavigationHarness.svelte'; +import { Puzzle } from '@lucide/svelte'; +import SidebarNavigationFooter from '#lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte'; +import { + APP_NAME, + EXTENSION_PAGE_ROUTE_ID, + SIDEBAR_ACTIONS_ITEMS, + SIDEBAR_FOOTER_ITEMS +} from '#lib/constants/index.ts'; +import { extensions } from '#lib/extensions/index.ts'; +import { uiStore } from '#lib/stores/index.ts'; +import { goto, refreshAll } from '$app/navigation'; +import { page } from 'vitest/browser'; +import { render } from 'vitest-browser-svelte'; + +/** The labels of the sidebar's own items, in order: its top actions and its footer. */ +const ACTIONS = SIDEBAR_ACTIONS_ITEMS.map((item) => item.tooltip); +const FOOTER = SIDEBAR_FOOTER_ITEMS.map((item) => item.tooltip); +const FIXTURE_ID = 'navigation-fixture'; +const FIXTURE_ROUTE = '#/fixture-page'; +const gotoMock = vi.mocked(goto); +const refreshAllMock = vi.mocked(refreshAll); + +extensions.register({ + description: 'A sidebar item with a dialog, and a page', + disabledByDefault: true, + id: FIXTURE_ID, + load: async () => ({ + default: { + activate(ctx) { + ctx.contribute('navigation', { + dialog: NavigationDialogFixture, + icon: Puzzle, + id: 'fixture', + placement: 'footer', + route: FIXTURE_ROUTE, + tooltip: 'Fixture' + }); + ctx.contribute('pages', { + component: ExtensionPageFixture, + path: 'fixture-page', + title: 'Fixture' + }); + } + } + }), + name: 'Navigation fixture' +}); + +function showRoute(id: string | null, params: Record = {}) { + pageState.route.id = id; + pageState.params = params; +} + +/** Labels of the sidebar's rows, in order; its icon-only keys (the logo, a phone's search) have none. */ +function rowLabels(container: Element): string[] { + return [...container.querySelectorAll('[data-slot="button"]')] + .map((row) => row.querySelector('span span')?.textContent?.trim() ?? '') + .filter((label) => label !== ''); +} + +function row(container: Element, label: string): HTMLElement { + const found = [...container.querySelectorAll('[data-slot="button"]')].find( + (el) => el.querySelector('span span')?.textContent?.trim() === label + ); + + if (!found) throw new Error(`no "${label}" row`); + + return found; +} + +describe('navigation and pages extension points', () => { + let wasExpanded: boolean; + + beforeEach(async () => { + await page.viewport(1280, 900); + wasExpanded = uiStore.isSidebarExpanded; + uiStore.isSidebarExpanded = true; + showRoute(null); + gotoMock.mockClear(); + refreshAllMock.mockClear(); + }); + + afterEach(async () => { + await extensions.setEnabled(FIXTURE_ID, false); + uiStore.isSidebarExpanded = wasExpanded; + }); + + it('leaves the footer to its own items when no extension contributes', async () => { + const screen = render(SidebarNavigationFooter, {}); + + await vi.waitFor(() => expect(rowLabels(screen.container)).toEqual(FOOTER)); + }); + + it('shows a contributed item right after Models while its extension is on', async () => { + const screen = render(SidebarNavigationFooter, {}); + + await extensions.setEnabled(FIXTURE_ID, true); + await vi.waitFor(() => + expect(rowLabels(screen.container)).toEqual(['Models', 'Fixture', ...FOOTER.slice(1)]) + ); + + await extensions.setEnabled(FIXTURE_ID, false); + await vi.waitFor(() => expect(rowLabels(screen.container)).toEqual(FOOTER)); + }); + + it('lights a contributed item only while its page is the one shown', async () => { + await extensions.setEnabled(FIXTURE_ID, true); + showRoute(EXTENSION_PAGE_ROUTE_ID, { extensionPage: 'fixture-page' }); + + const onPage = render(SidebarNavigationFooter, {}); + + await vi.waitFor(() => + expect(row(onPage.container, 'Fixture').className).toContain('selected-row-surface') + ); + expect(row(onPage.container, 'Settings').className).not.toContain('selected-row-surface'); + onPage.unmount(); + + // another extension page, such as a path nothing is contributed for + showRoute(EXTENSION_PAGE_ROUTE_ID, { extensionPage: 'other-page' }); + + const elsewhere = render(SidebarNavigationFooter, {}); + + await vi.waitFor(() => expect(rowLabels(elsewhere.container)).toContain('Fixture')); + expect(row(elsewhere.container, 'Fixture').className).not.toContain('selected-row-surface'); + }); + + it('opens the dialog of a contributed item on a desktop, bound both ways', async () => { + await extensions.setEnabled(FIXTURE_ID, true); + + const screen = render(SidebarNavigationHarness); + const dialog = () => document.querySelector('[data-testid="navigation-dialog"]'); + + await vi.waitFor(() => expect(rowLabels(screen.container)).toContain('Fixture')); + expect(dialog()).toBeNull(); + + row(screen.container, 'Fixture').click(); + await vi.waitFor(() => expect(dialog()).not.toBeNull()); + expect(gotoMock).not.toHaveBeenCalled(); + + // the dialog closes itself through the binding, and opens again from the sidebar + dialog()!.querySelector('button')!.click(); + await vi.waitFor(() => expect(dialog()).toBeNull()); + + row(screen.container, 'Fixture').click(); + await vi.waitFor(() => expect(dialog()).not.toBeNull()); + + // switched off with its dialog open, the item takes the dialog with it, for good + await extensions.setEnabled(FIXTURE_ID, false); + await vi.waitFor(() => expect(dialog()).toBeNull()); + expect(rowLabels(screen.container)).not.toContain('Fixture'); + + await extensions.setEnabled(FIXTURE_ID, true); + await vi.waitFor(() => expect(rowLabels(screen.container)).toContain('Fixture')); + expect(dialog()).toBeNull(); + }); + + it('opens the page of a contributed item on a phone, among the top actions', async () => { + await page.viewport(390, 844); + await extensions.setEnabled(FIXTURE_ID, true); + + const screen = render(SidebarNavigationHarness); + + // a phone lists the footer's items with the actions, without Search and Models + await vi.waitFor(() => expect(rowLabels(screen.container)).toContain('Fixture')); + + const labels = rowLabels(screen.container); + + expect(labels[0]).toBe('New chat'); + expect(labels.at(-1)).toBe('Settings'); + expect(labels).not.toContain('Search'); + expect(labels).not.toContain('Models'); + + row(screen.container, 'Fixture').click(); + await vi.waitFor(() => expect(gotoMock).toHaveBeenCalledWith(FIXTURE_ROUTE)); + expect(document.querySelector('[data-testid="navigation-dialog"]')).toBeNull(); + }); + + it('renders the sidebar without any extension', async () => { + const screen = render(SidebarNavigationHarness); + + await vi.waitFor(() => expect(rowLabels(screen.container)).toEqual([...ACTIONS, ...FOOTER])); + }); + + it('renders the page contributed for the path, under its title', async () => { + await extensions.setEnabled(FIXTURE_ID, true); + showRoute(EXTENSION_PAGE_ROUTE_ID, { extensionPage: 'fixture-page' }); + + const screen = render(ExtensionPage); + + await vi.waitFor(() => + expect(screen.container.querySelector('[data-testid="extension-page"]')).not.toBeNull() + ); + await vi.waitFor(() => expect(document.title).toBe(`Fixture - ${APP_NAME}`)); + expect(refreshAllMock).not.toHaveBeenCalled(); + + // its extension goes off: the page leaves and the load is asked to run again, into the 404 + await extensions.setEnabled(FIXTURE_ID, false); + await vi.waitFor(() => + expect(screen.container.querySelector('[data-testid="extension-page"]')).toBeNull() + ); + await vi.waitFor(() => expect(refreshAllMock).toHaveBeenCalled()); + }); +}); diff --git a/ui/apps/chat/tests/client/mcp-navigation-glue.svelte.test.ts b/ui/apps/chat/tests/client/mcp-navigation-glue.svelte.test.ts new file mode 100644 index 000000000000..9368d0d47185 --- /dev/null +++ b/ui/apps/chat/tests/client/mcp-navigation-glue.svelte.test.ts @@ -0,0 +1,119 @@ +// What the MCP extension gives the sidebar, the page route and startup: its +// entry right after Models, the MCP servers page that entry leads to, +// and the background health checks, which stop when the extension goes off. + +import { ROUTES, SETTINGS_KEYS, SIDEBAR_FOOTER_ITEMS } from '#lib/constants/index.ts'; +import type { ExtensionContext, ExtensionPage, NavigationItem } from '#lib/extensions/index.ts'; +import { contributeNavigation } from '#lib/extensions/mcp/navigation.ts'; +import { contributePages } from '#lib/extensions/mcp/pages.ts'; +import { contributeStartup } from '#lib/extensions/mcp/startup.svelte.ts'; +import { RouterService } from '#lib/services/router.service.ts'; +import { mcpStore } from '#lib/stores/mcp/index.svelte.ts'; +import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; +import { sidebarFooterItems } from '#lib/utils/index.ts'; +import { flushSync } from 'svelte'; +import { describe, expect, it, vi } from 'vitest'; + +function makeContext() { + const cleanups: (() => void | Promise)[] = []; + const contributions: { point: string; value: unknown }[] = []; + const ctx: ExtensionContext = { + contribute: (point, value) => void contributions.push({ point, value }), + onDeactivate: (cleanup) => void cleanups.push(cleanup) + }; + + return { cleanups, contributions, ctx }; +} + +function setServers(servers: { enabled: boolean; id: string; url: string }[]) { + settingsStore.updateConfig(SETTINGS_KEYS.MCP_SERVERS, JSON.stringify(servers)); + flushSync(); +} + +describe('MCP navigation glue', () => { + it('contributes the MCP entry, which the sidebar places right after Models', () => { + const { contributions, ctx } = makeContext(); + + contributeNavigation(ctx); + + expect(contributions).toHaveLength(1); + expect(contributions[0].point).toBe('navigation'); + + const item = contributions[0].value as NavigationItem; + + expect(item).toMatchObject({ + id: 'mcp', + placement: 'footer', + route: ROUTES.MCP_SERVERS, + tooltip: 'MCP' + }); + expect(item.dialog).toBeDefined(); + expect(item.icon).toBeDefined(); + expect(item.keys).toBeUndefined(); + expect(sidebarFooterItems([item]).map((entry) => entry.tooltip)).toEqual([ + 'Models', + 'MCP', + ...SIDEBAR_FOOTER_ITEMS.slice(1).map((entry) => entry.tooltip) + ]); + }); + + it('contributes the MCP servers page at the route its entry opens', () => { + const { contributions, ctx } = makeContext(); + + contributePages(ctx); + + expect(contributions).toHaveLength(1); + expect(contributions[0].point).toBe('pages'); + + const mcpPage = contributions[0].value as ExtensionPage; + + expect(mcpPage.title).toBe('MCP Servers'); + expect(mcpPage.component).toBeDefined(); + expect(RouterService.extensionPage(mcpPage.path)).toBe(ROUTES.MCP_SERVERS); + }); + + it('health-checks every server with a URL, again when the list changes, until deactivated', async () => { + const original = settingsStore.config[SETTINGS_KEYS.MCP_SERVERS]; + const runHealthChecks = vi + .spyOn(mcpStore, 'runHealthChecksForServers') + .mockResolvedValue(undefined); + const { cleanups, ctx } = makeContext(); + + try { + setServers([ + { enabled: true, id: 'on', url: 'http://localhost:9001/mcp' }, + { enabled: false, id: 'off', url: 'http://localhost:9002/mcp' }, + { enabled: true, id: 'blank', url: ' ' } + ]); + runHealthChecks.mockClear(); + + contributeStartup(ctx); + flushSync(); + + // disabled servers too, so their cards show health; none without a URL + expect(runHealthChecks).toHaveBeenCalledTimes(1); + expect(runHealthChecks.mock.calls[0][0].map((server) => server.id)).toEqual(['on', 'off']); + expect(runHealthChecks.mock.calls[0][1]).toBe(true); + + setServers([{ enabled: true, id: 'new', url: 'http://localhost:9003/mcp' }]); + + expect(runHealthChecks).toHaveBeenCalledTimes(2); + expect(runHealthChecks.mock.calls[1][0].map((server) => server.id)).toEqual(['new']); + + // nothing to check, nothing run + setServers([]); + + expect(runHealthChecks).toHaveBeenCalledTimes(2); + + expect(cleanups).toHaveLength(1); + await cleanups[0](); + + setServers([{ enabled: true, id: 'late', url: 'http://localhost:9004/mcp' }]); + + expect(runHealthChecks).toHaveBeenCalledTimes(2); + } finally { + runHealthChecks.mockRestore(); + settingsStore.updateConfig(SETTINGS_KEYS.MCP_SERVERS, original); + } + }); +}); diff --git a/ui/apps/chat/tests/client/nested-surfaces.svelte.test.ts b/ui/apps/chat/tests/client/nested-surfaces.svelte.test.ts index dd92bca23d25..f30059dc2746 100644 --- a/ui/apps/chat/tests/client/nested-surfaces.svelte.test.ts +++ b/ui/apps/chat/tests/client/nested-surfaces.svelte.test.ts @@ -3,6 +3,7 @@ // them, on what the browser actually renders: a row's corners are concentric with its // group's, so its radius is the group's less the padding between their edges. import '../../src/app.css'; +import { Puzzle } from '@lucide/svelte'; import SidebarNavigationActions from '#lib/components/app/navigation/SidebarNavigation/SidebarNavigationActions.svelte'; import SidebarNavigationFooter from '#lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte'; import { @@ -10,11 +11,32 @@ import { SIDEBAR_ACTIONS_ITEMS, SIDEBAR_FOOTER_ITEMS } from '#lib/constants/index.ts'; +import { extensions } from '#lib/extensions/index.ts'; import { settingsStore } from '#lib/stores/index.ts'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { page } from 'vitest/browser'; import { render } from 'vitest-browser-svelte'; +// an extension's item is a footer row like the app's own, as MCP's is in the app +extensions.register({ + description: 'A sidebar footer item', + id: 'footer-fixture', + load: async () => ({ + default: { + activate(ctx) { + ctx.contribute('navigation', { + icon: Puzzle, + id: 'fixture', + placement: 'footer', + route: '#/fixture', + tooltip: 'Fixture' + }); + } + } + }), + name: 'Footer fixture' +}); + function px(value: string): number { return parseFloat(value); } @@ -23,7 +45,7 @@ async function renderFooter() { const screen = render(SidebarNavigationFooter, {}); const rows = () => [...screen.container.querySelectorAll('[data-slot="button"]')]; - await vi.waitFor(() => expect(rows()).toHaveLength(SIDEBAR_FOOTER_ITEMS.length)); + await vi.waitFor(() => expect(rows()).toHaveLength(SIDEBAR_FOOTER_ITEMS.length + 1)); const group = rows()[0].parentElement?.parentElement; @@ -40,6 +62,7 @@ describe('nested surfaces', () => { // Models and MCP wait behind their settings: show them, so every footer row is measured settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MODELS_MANAGER, true); settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MCP, true); + await extensions.activateEnabled(); }); it('round the footer group from its tokens', async () => { diff --git a/ui/apps/chat/tests/stories/navigation/SidebarNavigation.stories.svelte b/ui/apps/chat/tests/stories/navigation/SidebarNavigation.stories.svelte index 8c4f05ca8098..30ced8bf7409 100644 --- a/ui/apps/chat/tests/stories/navigation/SidebarNavigation.stories.svelte +++ b/ui/apps/chat/tests/stories/navigation/SidebarNavigation.stories.svelte @@ -1,8 +1,21 @@ + + + fillLoadedPrompt(composer, placeholderId, result)} + onPromptLoadError={(placeholderId, error) => failLoadingPrompt(composer, placeholderId, error)} + onPromptLoadStart={(placeholderId, promptInfo, args) => + addLoadingPrompt(composer, placeholderId, promptInfo, args)} + searchQuery={query} +/> diff --git a/ui/apps/chat/src/lib/extensions/mcp/ComposerMcpResources.svelte b/ui/apps/chat/src/lib/extensions/mcp/ComposerMcpResources.svelte new file mode 100644 index 000000000000..39fb968a14aa --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/ComposerMcpResources.svelte @@ -0,0 +1,36 @@ + + + + { + preSelectedResourceUri = uri; + isResourceDialogOpen = true; + }} +/> + + { + mcpStore.attachResource(resource.uri); + }} + onOpenChange={(newOpen: boolean) => { + if (!newOpen) { + preSelectedResourceUri = undefined; + } + }} + preSelectedUri={preSelectedResourceUri} +/> diff --git a/ui/apps/chat/src/lib/extensions/mcp/composer-prompts.ts b/ui/apps/chat/src/lib/extensions/mcp/composer-prompts.ts new file mode 100644 index 000000000000..f1193b4fbba0 --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/composer-prompts.ts @@ -0,0 +1,87 @@ +/** + * An MCP prompt as an attachment of the chat form: a chip that shows the + * prompt while its content loads, then holds the content or the error. + */ + +import type { ComposerHandle } from '../points/composer'; +import { INITIAL_FILE_SIZE, PROMPT_CONTENT_SEPARATOR } from '#lib/constants/index.ts'; +import { + ContentPartType, + FileExtensionText, + MimeTypeText, + SpecialFileType +} from '#lib/enums/index.ts'; +import type { + ChatUploadedFile, + GetPromptResult, + MCPPromptInfo, + PromptMessage +} from '#lib/types/index.ts'; + +/** Close the prompt picker and add the chip of a prompt that loads. */ +export function addLoadingPrompt( + composer: ComposerHandle, + placeholderId: string, + promptInfo: MCPPromptInfo, + args?: Record +): void { + composer.closePicker(); + + const placeholder: ChatUploadedFile = { + file: new File([], 'loading'), + id: placeholderId, + isLoading: true, + mcpPrompt: { + arguments: args ? { ...args } : undefined, + promptName: promptInfo.name, + serverName: promptInfo.serverName + }, + name: promptInfo.title || promptInfo.name, + size: INITIAL_FILE_SIZE, + type: SpecialFileType.MCP_PROMPT + }; + + composer.addUploadedFile(placeholder); + composer.focusInput(); +} + +/** Put the text of the loaded prompt into its chip. */ +export function fillLoadedPrompt( + composer: ComposerHandle, + placeholderId: string, + result: GetPromptResult +): void { + const promptText = result.messages + ?.map((msg: PromptMessage) => { + if (typeof msg.content === 'string') { + return msg.content; + } + + if (msg.content.type === ContentPartType.TEXT) { + return msg.content.text; + } + + return ''; + }) + .filter(Boolean) + .join(PROMPT_CONTENT_SEPARATOR); + + composer.updateUploadedFile(placeholderId, (f) => ({ + ...f, + file: new File([promptText], `${f.name}${FileExtensionText.TXT}`, { + type: MimeTypeText.PLAIN + }), + isLoading: false, + size: promptText.length, + textContent: promptText + })); +} + +/** Keep the chip of a prompt that failed to load, with the error on it. */ +export function failLoadingPrompt( + composer: ComposerHandle, + placeholderId: string, + error: string +): void { + composer.updateUploadedFile(placeholderId, (f) => ({ ...f, isLoading: false, loadError: error })); +} diff --git a/ui/apps/chat/src/lib/extensions/mcp/composer.ts b/ui/apps/chat/src/lib/extensions/mcp/composer.ts new file mode 100644 index 000000000000..9bf3a0406b5e --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/composer.ts @@ -0,0 +1,51 @@ +/** + * What MCP adds to the chat form: the `/prompt` command with its picker of + * MCP prompts, and the resources attached to the next message. + */ + +import type { ExtensionContext } from '../types'; +import ComposerMcpPrompts from './ComposerMcpPrompts.svelte'; +import ComposerMcpResources from './ComposerMcpResources.svelte'; +import { Sparkles } from '@lucide/svelte'; +import { ToolSource } from '#lib/enums/index.ts'; +import { conversationsStore, mcpStore } from '#lib/stores/index.ts'; + +export const MCP_PROMPTS_PICKER_ID = 'mcp-prompts'; + +/** + * Whether a server could offer prompts. Policy-aware, same rule as the agentic + * flow: MCP category on and at least one globally-enabled server whose group + * key is not disabled. + */ +export function hasPromptServers(): boolean { + const prefs = conversationsStore.preferences; + + if (!prefs.isCategoryEnabled(ToolSource.MCP)) return false; + + return mcpStore + .getServers() + .some((s) => s.enabled && prefs.isServerToolsEnabled(s.id) && s.url.trim()); +} + +export function contributeComposer(ctx: ExtensionContext): void { + ctx.contribute('composerCommands', { + description: 'Insert an MCP prompt', + icon: Sparkles, + isEnabled: hasPromptServers, + name: 'prompt', + // first in the list, before the built-in commands + order: -1, + run: (composer, args) => composer.openPicker(MCP_PROMPTS_PICKER_ID, args.trim()) + }); + + ctx.contribute('composerPickers', { + component: ComposerMcpPrompts, + id: MCP_PROMPTS_PICKER_ID + }); + + ctx.contribute('composerAttachments', { + component: ComposerMcpResources, + consume: () => mcpStore.consumeResourceAttachmentsAsExtras(), + hasPending: () => mcpStore.resources.hasAttachments + }); +} diff --git a/ui/apps/chat/src/lib/extensions/mcp/index.ts b/ui/apps/chat/src/lib/extensions/mcp/index.ts index 5ec115c98e05..45cf43848e68 100644 --- a/ui/apps/chat/src/lib/extensions/mcp/index.ts +++ b/ui/apps/chat/src/lib/extensions/mcp/index.ts @@ -4,6 +4,7 @@ */ import type { Extension } from '../types'; +import { contributeComposer } from './composer'; import { contributeNavigation } from './navigation'; import { contributePages } from './pages'; import { contributeStartup } from './startup.svelte'; @@ -11,6 +12,7 @@ import { contributeTools } from './tools'; const mcp: Extension = { activate(ctx) { + contributeComposer(ctx); contributeNavigation(ctx); contributePages(ctx); contributeStartup(ctx); diff --git a/ui/apps/chat/src/lib/extensions/points/composer.ts b/ui/apps/chat/src/lib/extensions/points/composer.ts new file mode 100644 index 000000000000..01ba6af8a086 --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/points/composer.ts @@ -0,0 +1,72 @@ +/** + * What an extension can add to the composer, the chat form: slash commands, + * the pickers they open, and attachments it holds until the message is sent. + */ + +import type { ChatUploadedFile, DatabaseMessageExtra } from '#lib/types/index.ts'; +import type { Component } from 'svelte'; + +/** What the chat form lets a contribution do to it. */ +export interface ComposerHandle { + /** Add an entry to the form's files, e.g. a chip for content that still loads. */ + addUploadedFile(file: ChatUploadedFile): void; + /** Close the contributed picker that is open. Focus stays where it is. */ + closePicker(): void; + focusInput(): void; + /** Open a contributed picker by its id, with `query` as its search. */ + openPicker(id: string, query?: string): void; + /** Change the entry with this id in the form's files, if it is still there. */ + updateUploadedFile(id: string, update: (file: ChatUploadedFile) => ChatUploadedFile): void; +} + +/** A slash command in the chat form's `/` picker. */ +export interface ComposerCommand { + /** What is typed after the slash, e.g. `prompt` for `/prompt`. No other command has it. */ + name: string; + description: string; + icon: Component; + /** Extra search terms that match the command in the picker. */ + keywords?: string[]; + /** Below zero it sorts before the built-in commands, otherwise (and by default) after them. */ + order?: number; + /** Whether it can be picked now. A command that can not stays in the list, greyed out. The form reads this reactively. */ + isEnabled(): boolean; + /** Called when the command is picked, after the form cleared its token. `args` is the text typed after the name. */ + run(composer: ComposerHandle, args: string): void; +} + +export interface ComposerPickerProps { + /** What the picker's popover floats by. */ + anchor: HTMLElement | null; + composer: ComposerHandle; + isOpen: boolean; + /** Closes the picker and gives the focus back to the input. */ + onClose: () => void; + /** What the picker was opened with, e.g. the text typed after its command. */ + query: string; +} + +export interface ComposerPickerExports { + /** Gets the keys typed in the input while the picker is open. Returns true for a key it used. */ + handleKeydown(event: KeyboardEvent): boolean; +} + +/** A popover picker the chat form mounts. A command opens it with `ComposerHandle.openPicker`. */ +export interface ComposerPicker { + id: string; + component: Component; +} + +export interface ComposerAttachmentsProps { + class?: string; +} + +/** Attachments that wait outside the chat form's files, e.g. in a store of the extension. */ +export interface ComposerAttachments { + /** Mounted under the input for as long as the form is. It draws the pending attachments, and nothing without them. */ + component: Component; + /** The pending attachments as the extras of the message that is sent now. Clears them at their source. */ + consume(): DatabaseMessageExtra[]; + /** The form reads this reactively: with attachments pending it does not fit a single row. */ + hasPending(): boolean; +} diff --git a/ui/apps/chat/src/lib/extensions/types.ts b/ui/apps/chat/src/lib/extensions/types.ts index 93d3cc5d7511..ae90a5d102b9 100644 --- a/ui/apps/chat/src/lib/extensions/types.ts +++ b/ui/apps/chat/src/lib/extensions/types.ts @@ -4,6 +4,7 @@ * same contract. */ +import type { ComposerAttachments, ComposerCommand, ComposerPicker } from './points/composer'; import type { NavigationItem } from './points/navigation'; import type { ExtensionPage } from './points/pages'; import type { FlowHook, ToolProvider } from './points/tools'; @@ -38,6 +39,12 @@ export interface ExtensionContext { /** Every extension point, with the shape of what goes into it. */ export interface ExtensionPoints { + /** Attachments held outside the chat form's files until the message is sent. */ + composerAttachments: ComposerAttachments; + /** Slash commands in the chat form's `/` picker. */ + composerCommands: ComposerCommand; + /** Popover pickers the chat form mounts, opened by a command. */ + composerPickers: ComposerPicker; /** Runs around every agentic flow. */ flow: FlowHook; /** Entries in the sidebar, each opening a page of the extension or a dialog. */ diff --git a/ui/apps/chat/src/lib/hooks/use-chat-form-pickers.svelte.ts b/ui/apps/chat/src/lib/hooks/use-chat-form-pickers.svelte.ts index 795978f236a4..955986b281e1 100644 --- a/ui/apps/chat/src/lib/hooks/use-chat-form-pickers.svelte.ts +++ b/ui/apps/chat/src/lib/hooks/use-chat-form-pickers.svelte.ts @@ -1,5 +1,6 @@ import { PROMPT_TRIGGER_PREFIX } from '#lib/constants/index.ts'; import { ChatFormCommandAction, KeyboardKey } from '#lib/enums/index.ts'; +import type { ComposerCommand, ComposerHandle } from '#lib/extensions/index.ts'; import type { ChatFormCommand } from '#lib/types/index.ts'; import { getChatCommands } from '#lib/utils/index.ts'; import { @@ -24,8 +25,6 @@ export interface UseChatFormPickersOptions { opensOnInput: () => boolean; /** Gates `/model`. */ getShowModelSelector: () => boolean; - /** Gates `/prompt`. */ - hasPrompts: () => boolean; /** Gates `/cwd`. */ hasCwdTools: () => boolean; /** Gates `/compact`. */ @@ -35,6 +34,10 @@ export interface UseChatFormPickersOptions { getCwd: () => string | null; /** Mention search fallback scope. */ getServerHome: () => string | null; + /** The slash commands extensions contribute. */ + getContributedCommands: () => ComposerCommand[]; + /** What a contributed command gets to act on the form. */ + getComposer: () => ComposerHandle; openModelSelector: () => void; /** Delegate a keydown to the mounted pickers component, if any. */ getPickersRef: () => { handleKeydown(event: KeyboardEvent): boolean } | undefined; @@ -48,8 +51,9 @@ export interface UseChatFormPickersOptions { export function useChatFormPickers(opts: UseChatFormPickersOptions) { let isCommandPickerOpen = $state(false); let commandQuery = $state(''); - let isPromptPickerOpen = $state(false); - let promptSearchQuery = $state(''); + // the picker an extension contributes that is open, and what it was opened with + let openPickerId = $state(null); + let pickerQuery = $state(''); let isMentionPickerOpen = $state(false); let mentionQuery = $state(''); let isWorkingDirectoryPickerOpen = $state(false); @@ -64,14 +68,26 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) { // before a cwd is set. const mentionScopePath = $derived(opts.getCwd() ?? opts.getServerHome() ?? null); const availableCommands = $derived( - getChatCommands({ - canCompact: opts.canCompact, - hasCwdTools: opts.hasCwdTools, - hasPrompts: opts.hasPrompts, - showModelSelector: opts.getShowModelSelector() - }) + getChatCommands( + { + canCompact: opts.canCompact, + hasCwdTools: opts.hasCwdTools, + showModelSelector: opts.getShowModelSelector() + }, + opts.getContributedCommands() + ) ); + function openPicker(id: string, query = '') { + openPickerId = id; + pickerQuery = query; + } + + function closePicker() { + openPickerId = null; + pickerQuery = ''; + } + // Dispatch a slash command picked from the list: consume the token and // open the target picker, seeding its search with `args`. Runs only on // explicit selection (Enter/click), so the buffer is never cleared @@ -80,19 +96,21 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) { isCommandPickerOpen = false; commandQuery = ''; + // a contributed command: the form consumes its token, the rest is up to the command + if ('run' in command) { + isWorkingDirectoryPickerOpen = false; + opts.setValue(''); + command.run(opts.getComposer(), args); + + return; + } + switch (command.action) { case ChatFormCommandAction.COMPACT: isWorkingDirectoryPickerOpen = false; opts.setValue(''); opts.onCompact(); - break; - case ChatFormCommandAction.PROMPT: - isWorkingDirectoryPickerOpen = false; - opts.setValue(''); - isPromptPickerOpen = true; - promptSearchQuery = args.trim(); - break; case ChatFormCommandAction.CWD: { // Keep `/cwd ` in the input so the search field and the @@ -128,8 +146,7 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) { if (value.startsWith(PROMPT_TRIGGER_PREFIX)) { isMentionPickerOpen = false; mentionQuery = ''; - isPromptPickerOpen = false; - promptSearchQuery = ''; + closePicker(); const token = findCommandToken(value); @@ -210,16 +227,14 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) { mentionDismissedSnapshot = null; isMentionPickerOpen = true; mentionQuery = token.query; - isPromptPickerOpen = false; - promptSearchQuery = ''; + closePicker(); return; } } } - isPromptPickerOpen = false; - promptSearchQuery = ''; + closePicker(); isMentionPickerOpen = false; mentionQuery = ''; @@ -234,9 +249,8 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) { return true; } - if (event.key === KeyboardKey.ESCAPE && isPromptPickerOpen) { - isPromptPickerOpen = false; - promptSearchQuery = ''; + if (event.key === KeyboardKey.ESCAPE && openPickerId !== null) { + closePicker(); return true; } @@ -262,7 +276,7 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) { commandQuery = ''; // Target picker manages its own focus: don't yank it back to the input. - if (!isPromptPickerOpen && !isMentionPickerOpen && !isWorkingDirectoryPickerOpen) { + if (openPickerId === null && !isMentionPickerOpen && !isWorkingDirectoryPickerOpen) { opts.focusInput(); } } @@ -280,9 +294,8 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) { opts.focusInput(); } - function handlePromptPickerClose() { - isPromptPickerOpen = false; - promptSearchQuery = ''; + function handlePickerClose() { + closePicker(); opts.focusInput(); } @@ -319,10 +332,7 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) { get availableCommands() { return availableCommands; }, - closePromptPicker() { - isPromptPickerOpen = false; - promptSearchQuery = ''; - }, + closePicker, get commandQuery() { return commandQuery; }, @@ -336,7 +346,7 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) { // True when a picker consumed the event, so the form skips submit. handleKeydown, handleMentionPickerClose, - handlePromptPickerClose, + handlePickerClose, handleWorkingDirectoryClose, handleWorkingDirectoryOpen, get isCommandPickerOpen() { @@ -351,12 +361,6 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) { set isMentionPickerOpen(v: boolean) { isMentionPickerOpen = v; }, - get isPromptPickerOpen() { - return isPromptPickerOpen; - }, - set isPromptPickerOpen(v: boolean) { - isPromptPickerOpen = v; - }, get isWorkingDirectoryPickerOpen() { return isWorkingDirectoryPickerOpen; }, @@ -372,14 +376,12 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) { get mentionScopePath() { return mentionScopePath; }, - openPromptPicker() { - isPromptPickerOpen = true; - }, - get promptSearchQuery() { - return promptSearchQuery; + openPicker, + get openPickerId() { + return openPickerId; }, - set promptSearchQuery(v: string) { - promptSearchQuery = v; + get pickerQuery() { + return pickerQuery; }, get workingDirectoryQuery() { return workingDirectoryQuery; diff --git a/ui/apps/chat/src/lib/stores/chat/index.svelte.ts b/ui/apps/chat/src/lib/stores/chat/index.svelte.ts index 20c95be39867..a9f3617681f9 100644 --- a/ui/apps/chat/src/lib/stores/chat/index.svelte.ts +++ b/ui/apps/chat/src/lib/stores/chat/index.svelte.ts @@ -23,6 +23,7 @@ import { ReasoningEffort, StreamConnectionState } from '#lib/enums/index.ts'; +import { extensions } from '#lib/extensions/registry.svelte.ts'; import { ChatService } from '#lib/services/chat.service.ts'; import { DatabaseService } from '#lib/services/database.service.ts'; // direct imports between stores, not via the barrel, to avoid circular deps @@ -33,7 +34,6 @@ import { chatProcessingStore } from '#lib/stores/chat/processing.svelte.ts'; import { type ChatStreamHost, ChatStreamManager } from '#lib/stores/chat/streams.svelte.ts'; import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts'; import { serverStore } from '#lib/stores/llama-server.svelte.ts'; -import { mcpStore } from '#lib/stores/mcp/index.svelte.ts'; import { modelsStore } from '#lib/stores/models/index.svelte.ts'; import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; import { toolsStore } from '#lib/stores/tools.svelte.ts'; @@ -756,9 +756,11 @@ class ChatStore implements ChatStreamHost, ChatFlowsHost { // Cancel any in-flight pre-encode request this.cancelPreEncode(); - // Consume MCP resource attachments - converts them to extras and clears the live store - const resourceExtras = mcpStore.consumeResourceAttachmentsAsExtras(); - const allExtras = resourceExtras.length > 0 ? [...(extras || []), ...resourceExtras] : extras; + // Attachments an extension holds outside the form go with this message, and are cleared at their source + const pendingExtras = extensions + .contributions('composerAttachments') + .flatMap((source) => source.consume()); + const allExtras = pendingExtras.length > 0 ? [...(extras || []), ...pendingExtras] : extras; let isNewConversation = false; diff --git a/ui/apps/chat/src/lib/types/chat.d.ts b/ui/apps/chat/src/lib/types/chat.d.ts index a72a8dfff984..2bea2effe6bb 100644 --- a/ui/apps/chat/src/lib/types/chat.d.ts +++ b/ui/apps/chat/src/lib/types/chat.d.ts @@ -9,6 +9,7 @@ import type { FileMentionEntryType, MessageRole } from '#lib/enums/index.ts'; +import type { ComposerCommand } from '#lib/extensions/points/composer.ts'; import type { Component } from 'svelte'; /** @@ -231,18 +232,12 @@ export interface FileMentionEntry { type: FileMentionEntryType; } -/** - * A slash command surfaced by the `/` command picker. `disabled` marks a - * command whose backing capability is unavailable (e.g. `/prompt` when no - * MCP server exposes prompts): visible but greyed out and not selectable. - */ +/** What gates the built-in slash commands. */ export interface ChatCommandsOptions { /** Gates `/compact`. */ canCompact: () => boolean; /** Gates `/model`. */ showModelSelector: boolean; - /** Gates `/prompt`. */ - hasPrompts: () => boolean; /** Gates `/cwd`. */ hasCwdTools: () => boolean; } @@ -250,15 +245,32 @@ export interface ChatCommandsOptions { /** Protocol-level verbs accepted by the realtime inference control endpoint. Mirrors `CONTROL_ACTION`. */ export type ControlAction = 'reasoning_end'; -export interface ChatFormCommand { +interface ChatFormCommandBase { name: string; description: string; /** Extra search terms that should match this command in the picker. */ keywords?: string[]; - action: ChatFormCommandAction; disabled: boolean; } +/** A built-in slash command: the chat form knows what its `action` does. */ +interface ChatFormBuiltInCommand extends ChatFormCommandBase { + action: ChatFormCommandAction; +} + +/** A slash command an extension contributes: it brings its icon and what it does. */ +interface ChatFormContributedCommand extends ChatFormCommandBase { + icon: Component; + run: ComposerCommand['run']; +} + +/** + * A slash command surfaced by the `/` command picker. `disabled` marks a + * command whose backing capability is unavailable (e.g. `/cwd` when no + * tool uses a working directory): visible but greyed out and not selectable. + */ +export type ChatFormCommand = ChatFormBuiltInCommand | ChatFormContributedCommand; + /** * Data shown in the message delete confirmation dialog. */ diff --git a/ui/apps/chat/src/lib/utils/chat-commands.ts b/ui/apps/chat/src/lib/utils/chat-commands.ts index 7bcb625aa73f..1d1f328e4c52 100644 --- a/ui/apps/chat/src/lib/utils/chat-commands.ts +++ b/ui/apps/chat/src/lib/utils/chat-commands.ts @@ -1,23 +1,37 @@ import { SET_WORKING_DIRECTORY_LABEL } from '#lib/constants/index.ts'; import { ChatFormCommandAction } from '#lib/enums/index.ts'; +import type { ComposerCommand } from '#lib/extensions/points/composer.ts'; import type { ChatCommandsOptions, ChatFormCommand } from '#lib/types/index.ts'; +function toChatFormCommand(command: ComposerCommand): ChatFormCommand { + return { + description: command.description, + disabled: !command.isEnabled(), + icon: command.icon, + keywords: command.keywords, + name: command.name, + run: (composer, args) => command.run(composer, args) + }; +} + /** - * The slash commands surfaced by the `/` command picker, in display order. + * The slash commands surfaced by the `/` command picker, in display order: + * the built-in ones, with the ones extensions contribute before or after + * them, as their `order` says. * * Availability is supplied as predicates rather than store imports: this * module is re-exported through the `#lib/utils/index.ts` barrel, and importing * stores at module load would create a circular dependency (the stores * themselves import from `#lib/utils/index.ts`). */ -export function getChatCommands(options: ChatCommandsOptions): ChatFormCommand[] { +export function getChatCommands( + options: ChatCommandsOptions, + contributed: ComposerCommand[] = [] +): ChatFormCommand[] { + const sorted = [...contributed].sort((a, b) => (a.order ?? 0) - (b.order ?? 0)); + return [ - { - action: ChatFormCommandAction.PROMPT, - description: 'Insert an MCP prompt', - disabled: !options.hasPrompts(), - name: 'prompt' - }, + ...sorted.filter((command) => (command.order ?? 0) < 0).map(toChatFormCommand), { action: ChatFormCommandAction.CWD, description: SET_WORKING_DIRECTORY_LABEL, @@ -37,6 +51,7 @@ export function getChatCommands(options: ChatCommandsOptions): ChatFormCommand[] disabled: !options.canCompact(), keywords: ['summarize', 'context'], name: 'compact' - } + }, + ...sorted.filter((command) => (command.order ?? 0) >= 0).map(toChatFormCommand) ]; } diff --git a/ui/apps/chat/tests/client/chat-form-composer-extensions.svelte.test.ts b/ui/apps/chat/tests/client/chat-form-composer-extensions.svelte.test.ts new file mode 100644 index 000000000000..f5e27822be55 --- /dev/null +++ b/ui/apps/chat/tests/client/chat-form-composer-extensions.svelte.test.ts @@ -0,0 +1,261 @@ +// Guards the chat form's extension points. Without extensions the form works with its +// built-in commands alone; with the MCP extension on, `/prompt` leads the commands and +// opens MCP's prompt picker, a picked prompt becomes a chip, and attached resources show +// under the input. Switching the extension off takes all of that away again. + +import ChatFormTestWrapper from './components/ChatFormTestWrapper.svelte'; +import { EditorView } from '@codemirror/view'; +import { EXTENSIONS_LOCALSTORAGE_KEY, SETTINGS_KEYS } from '#lib/constants/index.ts'; +import { MimeTypeText } from '#lib/enums/index.ts'; +import { BUILT_IN_EXTENSIONS } from '#lib/extensions/builtin.ts'; +import { extensions } from '#lib/extensions/index.ts'; +import { mcpStore } from '#lib/stores/mcp/index.svelte.ts'; +import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; +import type { GetPromptResult, MCPPromptInfo, MCPResourceInfo } from '#lib/types/index.ts'; +import { tick } from 'svelte'; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import { page, userEvent } from 'vitest/browser'; +import { render } from 'vitest-browser-svelte'; + +const MCP_EXTENSION_ID = 'mcp'; +const BUILT_IN_COMMANDS = ['/cwd', '/model', '/compact']; +const SERVER = { enabled: true, id: 'github', name: 'GitHub', url: 'https://mcp.example.com/mcp' }; +const PROMPTS: MCPPromptInfo[] = [ + { description: 'Review a pull request', name: 'code_review', serverName: 'github' }, + { + description: 'Summarize open issues by label', + name: 'issue_summary', + serverName: 'github', + title: 'Issue summary' + } +]; +const PROMPT_RESULT = { + messages: [{ content: { text: 'Summarize the open issues.', type: 'text' }, role: 'user' }] +} as GetPromptResult; +const RESOURCE: MCPResourceInfo = { + mimeType: MimeTypeText.MARKDOWN, + name: 'README.md', + serverName: 'github', + uri: 'repo://ggml-org/llama.cpp/README.md' +}; + +async function renderForm() { + const onSubmit = vi.fn(); + const { container } = render(ChatFormTestWrapper, { onSubmit, singleRow: true }); + + await tick(); + + const content = container.querySelector('.cm-content'); + const editor = content && EditorView.findFromDOM(content); + + if (!editor) throw new Error('editor not rendered'); + + await userEvent.click(editor.contentDOM); + + const card = container.querySelector('[data-slot="input-area"]')!; + + return { + container, + editor, + isInputFocused: () => editor.contentDOM.contains(document.activeElement), + isSingleRow: () => card.hasAttribute('data-single-row'), + onSubmit + }; +} + +const pickerRows = () => + Array.from(document.querySelectorAll('[data-slot="popover-content"] button')); +const commandNames = () => pickerRows().map((row) => row.querySelector('.font-mono')?.textContent); + +function seedPrompts() { + settingsStore.updateConfig(SETTINGS_KEYS.MCP_SERVERS, JSON.stringify([SERVER])); + vi.spyOn(mcpStore, 'ensureInitialized').mockResolvedValue(true); + vi.spyOn(mcpStore, 'getAllPrompts').mockResolvedValue(PROMPTS); +} + +/** Type `/prompt `, pick the command, and wait for MCP's prompt picker. */ +async function openPromptPicker(query: string) { + await userEvent.keyboard(`/prompt ${query}`); + await expect.poll(commandNames).toEqual(['/prompt']); + await userEvent.keyboard('{Enter}'); + await expect.poll(() => pickerRows().map((row) => row.textContent)).toHaveLength(1); +} + +afterEach(() => { + vi.restoreAllMocks(); + mcpStore.resources.clearAttachments(); + settingsStore.updateConfig(SETTINGS_KEYS.MCP_SERVERS, '[]'); +}); + +describe('ChatForm without extensions', () => { + it('lists only the built-in commands', async () => { + await renderForm(); + await userEvent.keyboard('/'); + + await expect.poll(commandNames).toEqual(BUILT_IN_COMMANDS); + }); + + it('draws no pending attachments and still sends', async () => { + await page.viewport(1280, 900); + mcpStore.resources.addAttachment(RESOURCE); + + const { container, isSingleRow, onSubmit } = await renderForm(); + + expect(container.textContent).not.toContain(RESOURCE.name); + expect(isSingleRow()).toBe(true); + + await userEvent.keyboard('hello{Enter}'); + await tick(); + + expect(onSubmit).toHaveBeenCalledOnce(); + }); +}); + +describe('ChatForm with the MCP extension', () => { + beforeAll(async () => { + for (const manifest of BUILT_IN_EXTENSIONS) extensions.register(manifest); + + await extensions.activateEnabled(); + }); + + afterAll(() => { + localStorage.removeItem(EXTENSIONS_LOCALSTORAGE_KEY); + }); + + it('lists /prompt first, disabled while no MCP server is usable', async () => { + await renderForm(); + await userEvent.keyboard('/'); + + await expect.poll(commandNames).toEqual(['/prompt', ...BUILT_IN_COMMANDS]); + expect(pickerRows()[0].disabled).toBe(true); + expect(pickerRows()[0].textContent).toContain('Insert an MCP prompt'); + }); + + it('enables /prompt once an MCP server is usable', async () => { + seedPrompts(); + await renderForm(); + await userEvent.keyboard('/'); + + await expect.poll(commandNames).toEqual(['/prompt', ...BUILT_IN_COMMANDS]); + expect(pickerRows()[0].disabled).toBe(false); + }); + + it('opens the prompt picker with the typed arguments and turns the picked prompt into a chip', async () => { + seedPrompts(); + + let resolvePrompt!: (result: GetPromptResult) => void; + + const getPrompt = vi.spyOn(mcpStore, 'getPrompt').mockReturnValue( + new Promise((resolve) => { + resolvePrompt = resolve; + }) + ); + const { container, editor, isInputFocused } = await renderForm(); + + await openPromptPicker('iss'); + + // the token is consumed, and the typed arguments are the picker's search + expect(editor.state.doc.toString()).toBe(''); + expect(pickerRows()[0].textContent).toContain('Issue summary'); + + await userEvent.keyboard('{Enter}'); + + // the chip is there while the prompt loads, the picker is gone, the input has focus + await expect.poll(() => container.textContent).toContain('Issue summary'); + await expect.poll(() => container.querySelector('.animate-pulse')).not.toBeNull(); + await expect.poll(pickerRows).toHaveLength(0); + expect(getPrompt).toHaveBeenCalledWith('github', 'issue_summary', {}); + await expect.poll(isInputFocused).toBe(true); + + resolvePrompt(PROMPT_RESULT); + + await expect.poll(() => container.querySelector('.animate-pulse')).toBeNull(); + expect(container.textContent).toContain('Issue summary'); + }); + + it('keeps the chip with the error when the prompt fails to load', async () => { + seedPrompts(); + vi.spyOn(mcpStore, 'getPrompt').mockRejectedValue(new Error('Server is not connected')); + + const { container } = await renderForm(); + + await openPromptPicker('iss'); + await userEvent.keyboard('{Enter}'); + + await expect.poll(() => container.textContent).toContain('Server is not connected'); + expect(container.textContent).toContain('Issue summary'); + expect(container.querySelector('.animate-pulse')).toBeNull(); + }); + + it('moves through the prompts with the arrows and closes the picker on Escape', async () => { + seedPrompts(); + + const getPrompt = vi.spyOn(mcpStore, 'getPrompt').mockResolvedValue(PROMPT_RESULT); + const { editor, isInputFocused, onSubmit } = await renderForm(); + + await userEvent.keyboard('/prompt'); + await expect.poll(commandNames).toEqual(['/prompt']); + await userEvent.keyboard('{Enter}'); + await expect.poll(pickerRows).toHaveLength(PROMPTS.length); + + await userEvent.keyboard('{ArrowDown}{Escape}'); + + await expect.poll(pickerRows).toHaveLength(0); + await expect.poll(isInputFocused).toBe(true); + expect(getPrompt).not.toHaveBeenCalled(); + expect(onSubmit).not.toHaveBeenCalled(); + expect(editor.state.doc.toString()).toBe(''); + }); + + it('picks the prompt the arrows moved to', async () => { + seedPrompts(); + + const getPrompt = vi.spyOn(mcpStore, 'getPrompt').mockResolvedValue(PROMPT_RESULT); + + await renderForm(); + await userEvent.keyboard('/prompt'); + await expect.poll(commandNames).toEqual(['/prompt']); + await userEvent.keyboard('{Enter}'); + await expect.poll(pickerRows).toHaveLength(PROMPTS.length); + + await userEvent.keyboard('{ArrowDown}{Enter}'); + + await expect.poll(() => getPrompt.mock.calls).toEqual([['github', 'issue_summary', {}]]); + }); + + it('shows attached resources under the input, on two rows', async () => { + await page.viewport(1280, 900); + + const { container, isSingleRow } = await renderForm(); + + expect(isSingleRow()).toBe(true); + + mcpStore.resources.addAttachment(RESOURCE); + + await expect.poll(() => container.textContent).toContain(RESOURCE.name); + await expect.poll(isSingleRow).toBe(false); + + mcpStore.resources.clearAttachments(); + + await expect.poll(() => container.textContent).not.toContain(RESOURCE.name); + await expect.poll(isSingleRow).toBe(true); + }); + + it('loses the command and the resources once the extension is off', async () => { + await page.viewport(1280, 900); + mcpStore.resources.addAttachment(RESOURCE); + + const { container, isSingleRow } = await renderForm(); + + await expect.poll(() => container.textContent).toContain(RESOURCE.name); + + await extensions.setEnabled(MCP_EXTENSION_ID, false); + + await expect.poll(() => container.textContent).not.toContain(RESOURCE.name); + await expect.poll(isSingleRow).toBe(true); + + await userEvent.keyboard('/'); + + await expect.poll(commandNames).toEqual(BUILT_IN_COMMANDS); + }); +}); diff --git a/ui/apps/chat/tests/client/chat-form-slash-commands.svelte.test.ts b/ui/apps/chat/tests/client/chat-form-slash-commands.svelte.test.ts index d053f7f60cff..0c30a3408dd5 100644 --- a/ui/apps/chat/tests/client/chat-form-slash-commands.svelte.test.ts +++ b/ui/apps/chat/tests/client/chat-form-slash-commands.svelte.test.ts @@ -4,10 +4,26 @@ // buffer must survive; only an actual selection consumes the token. import ChatFormPickersHarness from './components/ChatFormPickersHarness.svelte'; +import { ExtensionRegistry } from '#lib/extensions/index.ts'; +import { contributeComposer, MCP_PROMPTS_PICKER_ID } from '#lib/extensions/mcp/composer.ts'; import { tick } from 'svelte'; -import { describe, expect, it } from 'vitest'; +import { beforeAll, describe, expect, it } from 'vitest'; import { render } from 'vitest-browser-svelte'; +// `/prompt` is MCP's command: the form gets it as a contribution +const registry = new ExtensionRegistry(); + +beforeAll(async () => { + registry.register({ + description: 'What MCP adds to the chat form', + id: 'mcp-composer', + load: async () => ({ default: { activate: contributeComposer } }), + name: 'MCP composer' + }); + + await registry.activateEnabled(); +}); + describe('slash command dispatch', () => { it('does not dispatch or clear the buffer when a space follows the name', async () => { const screen = render(ChatFormPickersHarness); @@ -48,7 +64,9 @@ describe('slash command dispatch', () => { }); it('seeds the prompt picker search from the token args on selection', async () => { - const screen = render(ChatFormPickersHarness); + const screen = render(ChatFormPickersHarness, { + commands: registry.contributions('composerCommands') + }); await tick(); @@ -57,7 +75,7 @@ describe('slash command dispatch', () => { const pickers = screen.component.getPickers(); - expect(pickers.isPromptPickerOpen).toBe(false); + expect(pickers.openPickerId).toBeNull(); const prompt = pickers.availableCommands.find((c) => c.name === 'prompt'); @@ -67,8 +85,8 @@ describe('slash command dispatch', () => { await tick(); expect(screen.component.getValue()).toBe(''); - expect(pickers.isPromptPickerOpen).toBe(true); - expect(pickers.promptSearchQuery).toBe('weather'); + expect(pickers.openPickerId).toBe(MCP_PROMPTS_PICKER_ID); + expect(pickers.pickerQuery).toBe('weather'); }); it('normalizes a partial /cwd token on selection and keeps it in the buffer', async () => { diff --git a/ui/apps/chat/tests/client/components/ChatFormPickersHarness.svelte b/ui/apps/chat/tests/client/components/ChatFormPickersHarness.svelte index c8d56dfe10aa..5d307905d185 100644 --- a/ui/apps/chat/tests/client/components/ChatFormPickersHarness.svelte +++ b/ui/apps/chat/tests/client/components/ChatFormPickersHarness.svelte @@ -1,24 +1,41 @@ -{#if isMcpPrompt(item)} - {@const mcpPrompt = - item.attachment?.type === AttachmentType.MCP_PROMPT - ? (item.attachment as DatabaseMessageExtraMcpPrompt) - : item.uploadedFile?.mcpPrompt - ? { - arguments: item.uploadedFile.mcpPrompt.arguments, - content: item.textContent ?? '', - name: item.name, - promptName: item.uploadedFile.mcpPrompt.promptName, - serverName: item.uploadedFile.mcpPrompt.serverName, - type: AttachmentType.MCP_PROMPT as const - } - : null} - {#if mcpPrompt} - onFileRemove(item.id) : undefined} - prompt={mcpPrompt} - {readonly} - /> - {/if} -{:else if isMcpResource(item)} - {@const mcpResource = item.attachment as DatabaseMessageExtraMcpResource} - - onMcpResourcePreview?.(mcpResource)} +{#if renderer} + onFileRemove(item.id) : undefined} + {readonly} /> {:else if isAudioFile(item.attachment, item.uploadedFile)} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreview.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreview.svelte index de23eb85dd09..3a40b30328ae 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreview.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreview.svelte @@ -6,6 +6,7 @@ ChatAttachmentsPreviewThumbnailStrip } from '#lib/components/app/index.ts'; import { UI_DATA_ATTRS } from '#lib/constants/index.ts'; + import { extensions, findAttachmentRenderer } from '#lib/extensions/index.ts'; import { modelsStore } from '#lib/stores/index.ts'; import { createBase64DataUrl, @@ -14,8 +15,6 @@ getLanguageFromFilename, isAudioFile, isImageFile, - isMcpPrompt, - isMcpResource, isPdfFile, isTextFile, isVideoFile @@ -51,9 +50,11 @@ uploadedFiles = [] }: Props = $props(); + // items an extension draws are shown by that extension, not here + let attachmentRenderers = $derived(extensions.contributions('attachmentRenderers')); let allItems = $derived( getAttachmentDisplayItems({ attachments, uploadedFiles }) - .filter((item) => !isMcpPrompt(item) && !isMcpResource(item)) + .filter((item) => !findAttachmentRenderer(attachmentRenderers, item)) .map( (item): PreviewItem => ({ ...item, diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessage.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessage.svelte index f4172daaf969..ffcfada3b83b 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessage.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessage.svelte @@ -2,7 +2,6 @@ import { ChatMessageAssistant, ChatMessageCompaction, - ChatMessageMcpPrompt, ChatMessageSynthetic, ChatMessageSystem, ChatMessageUser @@ -14,19 +13,11 @@ SYSTEM_MESSAGE_PLACEHOLDER } from '#lib/constants/index.ts'; import { setChatMessageActionsContext, setChatMessageEditContext } from '#lib/contexts/index.ts'; - import { - AgenticSectionType, - AttachmentType, - MessageRole, - MessageType - } from '#lib/enums/index.ts'; + import { AgenticSectionType, MessageRole, MessageType } from '#lib/enums/index.ts'; + import { extensions, findMessageRenderer } from '#lib/extensions/index.ts'; import { DatabaseService } from '#lib/services/database.service.ts'; import { chatStore, conversationsStore, deviceStore } from '#lib/stores/index.ts'; - import type { - ChatMessageActions, - ChatMessageDeletionInfo, - DatabaseMessageExtraMcpPrompt - } from '#lib/types/index.ts'; + import type { ChatMessageActions, ChatMessageDeletionInfo } from '#lib/types/index.ts'; import { parseFilesToMessageExtras } from '#lib/utils/browser-only.ts'; import { deriveAgenticSections } from '#lib/utils/index.ts'; import { goto } from '$app/navigation'; @@ -186,9 +177,10 @@ return deletionInfo; }, get forkConversation() { - const isForkableUser = message.role === MessageRole.USER && !mcpPromptExtra; + const isForkableRole = + message.role === MessageRole.USER || message.role === MessageRole.ASSISTANT; - return isForkableUser || message.role === MessageRole.ASSISTANT + return isForkableRole && messageRenderer?.forkable !== false ? handleForkConversation : undefined; }, @@ -209,21 +201,10 @@ } }); - let mcpPromptExtra = $derived.by(() => { - if (message.role !== MessageRole.USER) return null; - - if (message.content.trim()) return null; - - if (!message.extra || message.extra.length !== 1) return null; - - const extra = message.extra[0]; - - if (extra.type === AttachmentType.MCP_PROMPT) { - return extra as DatabaseMessageExtraMcpPrompt; - } - - return null; - }); + // an extension can claim a message and draw it in place of the default + let messageRenderer = $derived( + findMessageRenderer(extensions.contributions('messageRenderers'), message) + ); $effect(() => { const pendingId = chatStore.pendingEditMessageId; @@ -426,8 +407,8 @@
{#if message.role === MessageRole.SYSTEM} - {:else if mcpPromptExtra} - + {:else if messageRenderer} + {:else if isCompaction} {:else if isSynthetic} diff --git a/ui/apps/chat/src/lib/extensions/index.ts b/ui/apps/chat/src/lib/extensions/index.ts index a21fe83cc3bf..985044de14ee 100644 --- a/ui/apps/chat/src/lib/extensions/index.ts +++ b/ui/apps/chat/src/lib/extensions/index.ts @@ -9,6 +9,13 @@ export type { } from './points/composer'; export type { NavigationDialog, NavigationItem, NavigationPlacement } from './points/navigation'; export type { ExtensionPage } from './points/pages'; +export { findAttachmentRenderer, findMessageRenderer } from './points/renderers'; +export type { + AttachmentRenderer, + AttachmentRendererProps, + MessageRenderer, + MessageRendererProps +} from './points/renderers'; export type { FlowHook, FlowInfo, diff --git a/ui/apps/chat/src/lib/extensions/mcp/McpPromptAttachmentRenderer.svelte b/ui/apps/chat/src/lib/extensions/mcp/McpPromptAttachmentRenderer.svelte new file mode 100644 index 000000000000..9ef2a0603294 --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/McpPromptAttachmentRenderer.svelte @@ -0,0 +1,42 @@ + + +{#if prompt} + +{/if} diff --git a/ui/apps/chat/src/lib/extensions/mcp/McpPromptMessageRenderer.svelte b/ui/apps/chat/src/lib/extensions/mcp/McpPromptMessageRenderer.svelte new file mode 100644 index 000000000000..b05b0b866cda --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/McpPromptMessageRenderer.svelte @@ -0,0 +1,18 @@ + + +{#if mcpPrompt} + +{/if} diff --git a/ui/apps/chat/src/lib/extensions/mcp/McpResourceAttachmentRenderer.svelte b/ui/apps/chat/src/lib/extensions/mcp/McpResourceAttachmentRenderer.svelte new file mode 100644 index 000000000000..f64bb9cf7b4d --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/McpResourceAttachmentRenderer.svelte @@ -0,0 +1,51 @@ + + +{#if extra} + openPreview(extra)} + /> +{/if} + +{#if previewExtra} + +{/if} diff --git a/ui/apps/chat/src/lib/extensions/mcp/index.ts b/ui/apps/chat/src/lib/extensions/mcp/index.ts index 45cf43848e68..c68c2ff048c7 100644 --- a/ui/apps/chat/src/lib/extensions/mcp/index.ts +++ b/ui/apps/chat/src/lib/extensions/mcp/index.ts @@ -7,6 +7,7 @@ import type { Extension } from '../types'; import { contributeComposer } from './composer'; import { contributeNavigation } from './navigation'; import { contributePages } from './pages'; +import { contributeRenderers } from './renderers'; import { contributeStartup } from './startup.svelte'; import { contributeTools } from './tools'; @@ -15,6 +16,7 @@ const mcp: Extension = { contributeComposer(ctx); contributeNavigation(ctx); contributePages(ctx); + contributeRenderers(ctx); contributeStartup(ctx); contributeTools(ctx); } diff --git a/ui/apps/chat/src/lib/extensions/mcp/renderers.ts b/ui/apps/chat/src/lib/extensions/mcp/renderers.ts new file mode 100644 index 000000000000..5f0ae149d9da --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/renderers.ts @@ -0,0 +1,43 @@ +/** + * How MCP prompts and resources are drawn in the chat: a message that is only + * an MCP prompt, and the MCP items of an attachments list. + */ + +import type { ExtensionContext } from '../types'; +import McpPromptAttachmentRenderer from './McpPromptAttachmentRenderer.svelte'; +import McpPromptMessageRenderer from './McpPromptMessageRenderer.svelte'; +import McpResourceAttachmentRenderer from './McpResourceAttachmentRenderer.svelte'; +import { AttachmentType, MessageRole } from '#lib/enums/index.ts'; +import type { DatabaseMessage } from '#lib/types/index.ts'; +import { isMcpPrompt, isMcpResource } from '#lib/utils/index.ts'; + +/** A user message with no text and exactly one extra, an MCP prompt. */ +function isMcpPromptMessage(message: DatabaseMessage): boolean { + if (message.role !== MessageRole.USER) return false; + + if (message.content.trim()) return false; + + if (!message.extra || message.extra.length !== 1) return false; + + return message.extra[0].type === AttachmentType.MCP_PROMPT; +} + +/** Contribute MCP's message and attachment renderers. */ +export function contributeRenderers(ctx: ExtensionContext): void { + ctx.contribute('messageRenderers', { + component: McpPromptMessageRenderer, + forkable: false, + match: isMcpPromptMessage + }); + + ctx.contribute('attachmentRenderers', { + component: McpPromptAttachmentRenderer, + match: isMcpPrompt + }); + + // the resource renderer opens its own preview dialog + ctx.contribute('attachmentRenderers', { + component: McpResourceAttachmentRenderer, + match: isMcpResource + }); +} diff --git a/ui/apps/chat/src/lib/extensions/points/renderers.ts b/ui/apps/chat/src/lib/extensions/points/renderers.ts new file mode 100644 index 000000000000..1f938043bb39 --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/points/renderers.ts @@ -0,0 +1,59 @@ +/** + * The renderer extension points: an extension draws the messages and the + * attachments it claims, in place of what the core draws for them. + */ + +import type { ChatAttachmentDisplayItem, DatabaseMessage } from '#lib/types/index.ts'; +import type { Component } from 'svelte'; + +/** What a message renderer's component gets. It is drawn inside the message, so the message contexts are there. */ +export interface MessageRendererProps { + class?: string; + message: DatabaseMessage; +} + +/** Draws the messages it claims in place of the default message. System messages are never offered. */ +export interface MessageRenderer { + component: Component; + /** False when a claimed message cannot be forked. Left out, it can. */ + forkable?: boolean; + /** Whether this renderer draws the message. The first renderer that claims it wins. */ + match(message: DatabaseMessage): boolean; +} + +/** What an attachment renderer's component gets. */ +export interface AttachmentRendererProps { + /** The classes the attachments list gives each of its items. */ + class?: string; + item: ChatAttachmentDisplayItem; + /** Removes the item. Left out where attachments cannot be removed. */ + onRemove?: () => void; + readonly?: boolean; +} + +/** + * Draws the attachments it claims in place of the default chip. A claimed + * attachment stays out of the built-in preview, so its renderer shows the + * content itself when it has a way to. + */ +export interface AttachmentRenderer { + component: Component; + /** Whether this renderer draws the item. The first renderer that claims it wins. */ + match(item: ChatAttachmentDisplayItem): boolean; +} + +/** The renderer that claims an attachment, if any. */ +export function findAttachmentRenderer( + renderers: AttachmentRenderer[], + item: ChatAttachmentDisplayItem +): AttachmentRenderer | undefined { + return renderers.find((renderer) => renderer.match(item)); +} + +/** The renderer that claims a message, if any. */ +export function findMessageRenderer( + renderers: MessageRenderer[], + message: DatabaseMessage +): MessageRenderer | undefined { + return renderers.find((renderer) => renderer.match(message)); +} diff --git a/ui/apps/chat/src/lib/extensions/types.ts b/ui/apps/chat/src/lib/extensions/types.ts index ae90a5d102b9..f0581fe8bb75 100644 --- a/ui/apps/chat/src/lib/extensions/types.ts +++ b/ui/apps/chat/src/lib/extensions/types.ts @@ -7,6 +7,7 @@ import type { ComposerAttachments, ComposerCommand, ComposerPicker } from './points/composer'; import type { NavigationItem } from './points/navigation'; import type { ExtensionPage } from './points/pages'; +import type { AttachmentRenderer, MessageRenderer } from './points/renderers'; import type { FlowHook, ToolProvider } from './points/tools'; /** What the app knows about an extension before its code is loaded. */ @@ -51,6 +52,10 @@ export interface ExtensionPoints { navigation: NavigationItem; /** Pages of the extension, each at a path of its own. */ pages: ExtensionPage; + /** Draws the attachments it claims, in place of the default attachment chip. */ + attachmentRenderers: AttachmentRenderer; + /** Draws the messages it claims, in place of the default message. */ + messageRenderers: MessageRenderer; /** Tools the model can call, listed and run by the extension. */ tools: ToolProvider; } diff --git a/ui/apps/chat/src/lib/utils/attachment-type.ts b/ui/apps/chat/src/lib/utils/attachment-type.ts index b245bff42aed..3c24eeed107c 100644 --- a/ui/apps/chat/src/lib/utils/attachment-type.ts +++ b/ui/apps/chat/src/lib/utils/attachment-type.ts @@ -33,8 +33,18 @@ export function isTextFile( } if (attachment) { + if ( + attachment.type === AttachmentType.TEXT || + attachment.type === AttachmentType.LEGACY_CONTEXT + ) { + return true; + } + + // a kind only an extension draws reads as a text file while nothing claims it, when it carries text return ( - attachment.type === AttachmentType.TEXT || attachment.type === AttachmentType.LEGACY_CONTEXT + attachment.type !== AttachmentType.PDF && + 'content' in attachment && + typeof attachment.content === 'string' ); } diff --git a/ui/apps/chat/tests/client/components/RenderersHarness.svelte b/ui/apps/chat/tests/client/components/RenderersHarness.svelte new file mode 100644 index 000000000000..34d1046fc5ab --- /dev/null +++ b/ui/apps/chat/tests/client/components/RenderersHarness.svelte @@ -0,0 +1,39 @@ + + + + + {#if message} + + {:else} + + {/if} + diff --git a/ui/apps/chat/tests/client/extension-renderers.svelte.test.ts b/ui/apps/chat/tests/client/extension-renderers.svelte.test.ts new file mode 100644 index 000000000000..b1ed3e6d8fb5 --- /dev/null +++ b/ui/apps/chat/tests/client/extension-renderers.svelte.test.ts @@ -0,0 +1,215 @@ +// MCP prompts and resources are drawn by the renderers the MCP extension +// contributes. These pin both sides of that seam: with the renderers the chat +// shows MCP's own components, and without them (the extension is off, or an old +// conversation is opened without it) the same data still shows, as plain text +// attachments, instead of disappearing. + +import RenderersHarness from './components/RenderersHarness.svelte'; +import { EXTENSIONS_LOCALSTORAGE_KEY } from '#lib/constants/index.ts'; +import { AttachmentType, MessageRole, MessageType, SpecialFileType } from '#lib/enums/index.ts'; +import { extensions } from '#lib/extensions/index.ts'; +import { contributeRenderers } from '#lib/extensions/mcp/renderers.ts'; +import type { + ChatUploadedFile, + DatabaseMessage, + DatabaseMessageExtraMcpPrompt, + DatabaseMessageExtraMcpResource, + DatabaseMessageExtraTextFile +} from '#lib/types/index.ts'; +import { getAttachmentDisplayItems } from '#lib/utils/index.ts'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; + +const EXTENSION_ID = 'test-mcp-renderers'; +const MCP_PROMPT_GROUP = 'MCP Prompt message with actions'; +const USER_GROUP = 'User message with actions'; +const mcpPrompt: DatabaseMessageExtraMcpPrompt = { + arguments: { path: 'src/agentic.ts' }, + content: 'Review the file at src/agentic.ts and list the bugs first.', + name: 'code_review', + promptName: 'code_review', + serverName: 'github', + type: AttachmentType.MCP_PROMPT +}; +const mcpResource: DatabaseMessageExtraMcpResource = { + content: 'Inference of LLMs in pure C/C++.', + mimeType: 'text/markdown', + name: 'README.md', + serverName: 'filesystem', + type: AttachmentType.MCP_RESOURCE, + uri: 'file:///workspace/README.md' +}; +const textFile: DatabaseMessageExtraTextFile = { + content: 'Plain notes.', + name: 'notes.txt', + type: AttachmentType.TEXT +}; +const pendingMcpPrompt: ChatUploadedFile = { + file: new File([], 'code_review'), + id: 'pending-prompt', + mcpPrompt: { promptName: 'code_review', serverName: 'github' }, + name: 'code_review', + size: 0, + type: SpecialFileType.MCP_PROMPT +}; + +function userMessage(fields: Partial = {}): DatabaseMessage { + return { + children: [], + content: '', + convId: 'conv-1', + id: 'user-1', + parent: null, + role: MessageRole.USER, + timestamp: 1, + type: MessageType.TEXT, + ...fields + }; +} + +describe('without a renderer', () => { + it('draws MCP attachments as plain text chips with their names', async () => { + const screen = render(RenderersHarness, { attachments: [mcpPrompt, mcpResource] }); + const promptChip = screen.getByRole('button', { name: 'Preview code_review' }); + const resourceChip = screen.getByRole('button', { name: 'Preview README.md' }); + + await expect.element(promptChip).toBeVisible(); + await expect.element(promptChip).toHaveTextContent('code_review'); + await expect.element(promptChip).toHaveTextContent('list the bugs first'); + await expect.element(resourceChip).toBeVisible(); + await expect.element(resourceChip).toHaveTextContent('README.md'); + }); + + it('shows MCP attachments in the built-in preview', async () => { + const screen = render(RenderersHarness, { attachments: [mcpPrompt, mcpResource] }); + + await screen.getByRole('button', { name: 'Preview README.md' }).click(); + + const dialog = screen.getByRole('dialog'); + + await expect.element(dialog).toBeVisible(); + await expect.element(dialog).toHaveTextContent('Inference of LLMs in pure C/C++.'); + // both are in the carousel + await expect.element(dialog.getByRole('button', { name: 'Go to README.md' })).toBeVisible(); + await expect.element(dialog.getByRole('button', { name: 'Go to code_review' })).toBeVisible(); + }); + + it('draws a message that is only an MCP prompt as a user message with that chip', async () => { + const screen = render(RenderersHarness, { message: userMessage({ extra: [mcpPrompt] }) }); + const group = screen.getByRole('group', { name: USER_GROUP }); + + await expect.element(group).toBeVisible(); + await expect.element(group.getByRole('button', { name: 'Preview code_review' })).toBeVisible(); + await expect + .element(screen.getByRole('group', { name: MCP_PROMPT_GROUP })) + .not.toBeInTheDocument(); + }); +}); + +describe("with MCP's renderers", () => { + beforeAll(async () => { + extensions.register({ + description: "MCP's renderers alone", + id: EXTENSION_ID, + load: async () => ({ default: { activate: contributeRenderers } }), + name: 'MCP renderers' + }); + + await extensions.activateEnabled(); + }); + + afterAll(async () => { + await extensions.setEnabled(EXTENSION_ID, false); + // switching it off stored the choice; leave nothing behind for other tests + localStorage.removeItem(EXTENSIONS_LOCALSTORAGE_KEY); + }); + + it('claims a user message whose only content is one MCP prompt, and nothing else', () => { + const [renderer] = extensions.contributions('messageRenderers'); + + expect(extensions.contributions('messageRenderers')).toHaveLength(1); + expect(renderer.forkable).toBe(false); + expect(renderer.match(userMessage({ extra: [mcpPrompt] }))).toBe(true); + expect(renderer.match(userMessage({ content: ' \n', extra: [mcpPrompt] }))).toBe(true); + expect(renderer.match(userMessage({ content: 'and this', extra: [mcpPrompt] }))).toBe(false); + expect(renderer.match(userMessage({ extra: [mcpPrompt, textFile] }))).toBe(false); + expect(renderer.match(userMessage({ extra: [mcpResource] }))).toBe(false); + expect(renderer.match(userMessage())).toBe(false); + expect(renderer.match(userMessage({ extra: [mcpPrompt], role: MessageRole.ASSISTANT }))).toBe( + false + ); + }); + + it('claims MCP prompt and MCP resource attachments, stored or pending, and nothing else', () => { + const renderers = extensions.contributions('attachmentRenderers'); + const [resourceItem, promptItem, textItem, pendingItem] = getAttachmentDisplayItems({ + attachments: [textFile, mcpPrompt, mcpResource], + uploadedFiles: [pendingMcpPrompt] + }); + const claims = (item: typeof promptItem) => renderers.map((renderer) => renderer.match(item)); + + expect(renderers).toHaveLength(2); + expect(claims(promptItem)).toEqual([true, false]); + expect(claims(pendingItem)).toEqual([true, false]); + expect(claims(resourceItem)).toEqual([false, true]); + expect(claims(textItem)).toEqual([false, false]); + }); + + it('draws a message that is only an MCP prompt as an MCP prompt, without a fork action', async () => { + const screen = render(RenderersHarness, { message: userMessage({ extra: [mcpPrompt] }) }); + const group = screen.getByRole('group', { name: MCP_PROMPT_GROUP }); + + await expect.element(group).toBeVisible(); + await expect.element(group).toHaveTextContent('list the bugs first'); + await expect.element(group.getByRole('button', { name: 'Copy' })).toBeVisible(); + await expect + .element(group.getByRole('button', { name: 'Fork conversation' })) + .not.toBeInTheDocument(); + await expect.element(screen.getByRole('group', { name: USER_GROUP })).not.toBeInTheDocument(); + }); + + it('leaves other user messages to the default, fork action included', async () => { + const screen = render(RenderersHarness, { + message: userMessage({ content: 'Hello', extra: [mcpPrompt] }) + }); + const group = screen.getByRole('group', { name: USER_GROUP }); + + await expect.element(group).toBeVisible(); + await expect.element(group.getByRole('button', { name: 'Fork conversation' })).toBeVisible(); + }); + + it('draws an MCP resource with its own preview dialog', async () => { + const screen = render(RenderersHarness, { attachments: [mcpResource] }); + + await expect + .element(screen.getByRole('button', { name: 'Preview README.md' })) + .not.toBeInTheDocument(); + + // the chip is a button inside its tooltip trigger, itself a button + await screen.getByRole('button', { name: 'README.md' }).last().click(); + + const dialog = screen.getByRole('dialog'); + + await expect.element(dialog).toBeVisible(); + await expect.element(dialog).toHaveTextContent('file:///workspace/README.md'); + await expect.element(dialog).toHaveTextContent('Inference of LLMs in pure C/C++.'); + }); + + it('keeps MCP attachments out of the built-in preview', async () => { + const screen = render(RenderersHarness, { attachments: [textFile, mcpPrompt, mcpResource] }); + + await screen.getByRole('button', { name: 'Preview notes.txt' }).click(); + + const dialog = screen.getByRole('dialog'); + + await expect.element(dialog).toBeVisible(); + await expect.element(dialog).toHaveTextContent('Plain notes.'); + // the text file is alone in the carousel, so there is no thumbnail strip + await expect + .element(dialog.getByRole('button', { name: 'Go to notes.txt' })) + .not.toBeInTheDocument(); + await expect + .element(dialog.getByRole('button', { name: 'Go to README.md' })) + .not.toBeInTheDocument(); + }); +}); diff --git a/ui/apps/chat/tests/stories/chat/attachments/ChatAttachmentsList.stories.svelte b/ui/apps/chat/tests/stories/chat/attachments/ChatAttachmentsList.stories.svelte index c32d4a072878..07433a7eb25c 100644 --- a/ui/apps/chat/tests/stories/chat/attachments/ChatAttachmentsList.stories.svelte +++ b/ui/apps/chat/tests/stories/chat/attachments/ChatAttachmentsList.stories.svelte @@ -1,4 +1,5 @@ - + + { + // the stored MCP resource is MCP's own chip, not the default text chip + await expect((await canvas.findAllByRole('button', { name: 'README.md' })).length).toBe(2); + await expect(canvas.queryByRole('button', { name: 'Preview README.md' })).toBeNull(); + }} +> + diff --git a/ui/apps/chat/tests/stories/chat/messages/ChatMessage.stories.svelte b/ui/apps/chat/tests/stories/chat/messages/ChatMessage.stories.svelte index aaf5f3d6e17f..cf7eb29375ba 100644 --- a/ui/apps/chat/tests/stories/chat/messages/ChatMessage.stories.svelte +++ b/ui/apps/chat/tests/stories/chat/messages/ChatMessage.stories.svelte @@ -1,4 +1,5 @@ {#snippet pill(result: SearchResult)} - {@const faviconUrl = buildProxiedIconUrl(faviconForUrl(result.url), mcpStore.isProxyAvailable)} + {@const faviconUrl = buildProxiedIconUrl(faviconForUrl(result.url), isProxyAvailable)} {@const safeUrl = sanitizeExternalUrl(result.url)} {@const showHoverCard = safeUrl !== null && hasDetails(result)} {#if safeUrl} diff --git a/ui/apps/chat/src/lib/components/app/chat/index.ts b/ui/apps/chat/src/lib/components/app/chat/index.ts index 10ed3147e91a..493044350295 100644 --- a/ui/apps/chat/src/lib/components/app/chat/index.ts +++ b/ui/apps/chat/src/lib/components/app/chat/index.ts @@ -52,26 +52,12 @@ export { default as ChatAttachmentsList } from './ChatAttachments/ChatAttachmentsList/ChatAttachmentsList.svelte'; /** - * Renders a single attachment item based on its type (image, file, MCP prompt, or MCP resource). - * Delegates to specialized sub-components: ChatAttachmentsListItemThumbnailImage, ChatAttachmentsListItemThumbnailFile, - * ChatAttachmentsListItemMcpPrompt, or ChatAttachmentsListItemMcpResource. + * Renders a single attachment item based on its type (image or file). + * Delegates to specialized sub-components: ChatAttachmentsListItemThumbnailImage or ChatAttachmentsListItemThumbnailFile. + * An item an extension claims (an MCP prompt or resource) is drawn by that extension's attachment renderer. */ export { default as ChatAttachmentsListItem } from './ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItem.svelte'; -/** - * Displays MCP Prompt attachment with expandable content preview. - * Shows server name, prompt name, and allows expanding to view full prompt arguments - * and content. Used when user selects a prompt from ChatFormPickerMcpPrompts. - */ -export { default as ChatAttachmentsListItemMcpPrompt } from './ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemMcpPrompt.svelte'; - -/** - * Displays a single MCP Resource attachment with icon, name, and server info. - * Shows loading/error states and supports remove action. - * Used within ChatAttachmentMcpResources for individual resource display. - */ -export { default as ChatAttachmentsListItemMcpResource } from './ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemMcpResource.svelte'; - /** * Thumbnail for non-image file attachments. Displays file type icon based on extension, * file name (truncated), and file size. @@ -110,10 +96,9 @@ export { default as ChatAttachmentsPreviewCurrentItem } from './ChatAttachments/ * FORM * * Components for the chat input area. The form handles user input, file attachments, - * audio recording, and MCP prompts & resources selection. It integrates with multiple stores: + * audio recording, and what extensions add (MCP prompts & resources selection). It integrates with multiple stores: * - `chatStore` for message submission and generation control * - `modelsStore` for model selection and validation - * - `mcpStore` for MCP prompt browsing and loading * * The form exposes a public API for programmatic control from parent components * (focus, height reset, model selector, validation). @@ -246,12 +231,6 @@ export { default as ChatFormContextGauge } from './ChatForm/ChatFormContextGauge */ export { default as ChatFormInputFileInputInvisible } from './ChatForm/ChatFormInput/ChatFormInputFileInputInvisible.svelte'; -/** - * Displays MCP Resource attachments as a horizontal carousel. - * Shows resource name, URI, and allows clicking to view resource content. - */ -export { default as ChatFormMcpResourcesList } from './ChatForm/ChatFormMcpResourcesList.svelte'; - /** * The message editor: a live-preview MarkdownEditor. Plain text reads like a * textarea; markdown blocks render as in chat messages until the cursor enters @@ -270,65 +249,6 @@ export { default as ChatFormInput } from './ChatForm/ChatFormInput/ChatFormInput */ export { default as ChatFormCurrentWorkingDirectory } from './ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectory.svelte'; -/** - * **ChatFormPickerMcpPrompts** - MCP prompt selection interface - * - * Floating picker for browsing and selecting MCP Server Prompts. - * Triggered by typing `/` in the chat input or choosing `MCP Prompt` option in ChatFormActionAddDropdown. - * Loads prompts from connected MCP servers and allows users to select and configure them. - * - * **Architecture:** - * - Fetches available prompts from mcpStore - * - Manages selection state and keyboard navigation internally - * - Delegates argument input to ChatFormPromptPickerArgumentForm - * - Communicates prompt loading lifecycle via callbacks - * - * **Prompt Loading Flow:** - * 1. User selects prompt → `onPromptLoadStart` called with placeholder ID - * 2. Prompt content fetched from MCP server asynchronously - * 3. On success → `onPromptLoadComplete` with full prompt data - * 4. On failure → `onPromptLoadError` with error details - * - * **Features:** - * - Search/filter prompts by name across all connected servers - * - Keyboard navigation (↑/↓ to navigate, Enter to select, Esc to close) - * - Argument input forms for prompts with required parameters - * - Autocomplete suggestions for argument values - * - Loading states with skeleton placeholders - * - Server information header per prompt for visual identification - * - * **Exported API:** - * - `handleKeydown(event): boolean` - Process keyboard events, returns true if handled - * - * @example - * ```svelte - * showPicker = false} - * onPromptLoadStart={(id, info) => addPlaceholder(id, info)} - * onPromptLoadComplete={(id, result) => replacePlaceholder(id, result)} - * onPromptLoadError={(id, error) => handleError(id, error)} - * /> - * ``` - */ -export { default as ChatFormPickerMcpPrompts } from './ChatForm/ChatFormPickers/ChatFormPickerMcpPrompts/ChatFormPickerMcpPrompts.svelte'; - -/** - * Form for entering MCP prompt arguments. Displays input fields for each - * required argument defined by the prompt. Validates input and submits - * when all required fields are filled. Shows argument descriptions as hints. - */ -export { default as ChatFormPromptPickerArgumentForm } from './ChatForm/ChatFormPickers/ChatFormPickerMcpPrompts/ChatFormPromptPickerArgumentForm.svelte'; - -/** - * Single argument input field with autocomplete suggestions. Fetches suggestions - * from MCP server based on argument type. Supports keyboard navigation through - * suggestions list. Used within ChatFormPromptPickerArgumentForm. - */ -export { default as ChatFormPromptPickerArgumentInput } from './ChatForm/ChatFormPickers/ChatFormPickerMcpPrompts/ChatFormPromptPickerArgumentInput.svelte'; - /** * Shared popover wrapper for inline picker popovers (prompts, resources). * Provides consistent positioning, styling, and open/close behavior. @@ -339,24 +259,17 @@ export { default as ChatFormPickerPopover } from './ChatForm/ChatFormPickers/Cha * Generic scrollable list for picker popovers. Provides search input, * scroll-into-view for keyboard navigation, loading skeletons, empty state, * and optional footer. Uses Svelte 5 snippets for item/skeleton/footer rendering. - * Shared by ChatFormPickerMcpPrompts and ChatFormPickerMention. + * Shared by ChatFormPickerMention and the MCP extension's prompt picker. */ export { default as ChatFormPickerList } from './ChatForm/ChatFormPickers/ChatFormPicker/ChatFormPickerList.svelte'; /** * Generic button wrapper for picker list items. Provides consistent styling, * hover/selected states, and data-picker-index attribute for scroll-into-view. - * Shared by ChatFormPickerMcpPrompts and ChatFormPickerMention. + * Shared by ChatFormPickerMention and the MCP extension's prompt picker. */ export { default as ChatFormPickerListItem } from './ChatForm/ChatFormPickers/ChatFormPicker/ChatFormPickerListItem.svelte'; -/** - * Generic header for picker items displaying server favicon, label, item title, - * and optional description. Accepts `titleExtra` and `subtitle` snippets for - * custom content like badges or URIs. Shared by both pickers. - */ -export { default as ChatFormPickerItemHeader } from './ChatForm/ChatFormPickers/ChatFormPicker/ChatFormPickerItemHeader.svelte'; - /** * Generic skeleton loading placeholder for picker list items. Configurable * title width and optional badge skeleton. Shared by both pickers. @@ -545,13 +458,6 @@ export { default as ChatMessageContextMenu } from './ChatMessages/ChatMessageAct export { default as ChatMessageStatistics } from './ChatMessages/ChatMessageStatistics/ChatMessageStatistics.svelte'; export { default as ChatMessageStatisticsBadge } from './ChatMessages/ChatMessageStatistics/ChatMessageStatisticsBadge.svelte'; -/** - * MCP prompt display in user messages. Shows when user selected an MCP prompt - * via ChatFormPickerMcpPrompts. Displays server name, prompt name, and expandable - * content preview. Stored in message.extra as DatabaseMessageExtraMcpPrompt. - */ -export { default as ChatMessageMcpPrompt } from './ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPrompt.svelte'; - /** * Synthetic working-directory-change message. Rendered in place of a user * bubble when the message content parses as a cwd message (see @@ -575,13 +481,6 @@ export { default as ChatMessageSynthetic } from './ChatMessages/ChatMessage/Chat */ export { default as ChatMessageCompaction } from './ChatMessages/ChatMessage/ChatMessageCompaction.svelte'; -/** - * Formatted content display for MCP prompt messages. Renders the full prompt - * content with arguments in a readable format. Used within ChatMessageMcpPrompt - * for the expanded view. - */ -export { default as ChatMessageMcpPromptContent } from './ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPromptContent.svelte'; - /** * Assistant message display component. Renders assistant responses with left-aligned styling. * Supports both plain markdown content (via MarkdownContent) and agentic content with tool calls diff --git a/ui/apps/chat/src/lib/components/app/dialogs/index.ts b/ui/apps/chat/src/lib/components/app/dialogs/index.ts index 5b3ca761d6f4..c7c5db37a183 100644 --- a/ui/apps/chat/src/lib/components/app/dialogs/index.ts +++ b/ui/apps/chat/src/lib/components/app/dialogs/index.ts @@ -10,22 +10,6 @@ * */ -/** - * **DialogMcpServerAddNew** - Add new MCP server dialog - * - * Modal dialog for adding a new MCP server with URL and optional headers. - * Validates URL format and integrates with mcpStore and conversationsStore. - */ -export { default as DialogMcpServerAddNew } from './DialogMcpServerAddNew.svelte'; - -/** - * **DialogMcpServers** - MCP servers dialog shown from the chat form - * - * Shows the same MCP server list as the `/mcp-servers` route inside a modal - * dialog. - */ -export { default as DialogMcpServers } from './DialogMcpServers.svelte'; - /** * **DialogSettingsChat** - Chat settings shown in a modal dialog * @@ -447,60 +431,6 @@ export { default as DialogModelNotAvailable } from './DialogModelNotAvailable.sv */ export { default as DialogConversationSelection } from './DialogConversationSelection.svelte'; -/** - * **DialogMcpResourcesBrowser** - MCP resources browser dialog - * - * Dialog for browsing and attaching MCP resources to chat context. - * Displays resources from connected MCP servers in a tree structure - * with preview panel and multi-select support. - * - * **Architecture:** - * - Uses ShadCN Dialog with two-panel layout - * - Left panel: McpResourcesBrowser with tree navigation - * - Right panel: McpResourcePreview for selected resource - * - Integrates with mcpStore for resource fetching and attachment - * - * **Features:** - * - Tree-based resource navigation by server and path - * - Single and multi-select with shift+click - * - Resource preview with content display - * - Quick attach button per resource - * - Batch attach for multiple selections - * - * @example - * ```svelte - * - * ``` - */ -export { default as DialogMcpResourcesBrowser } from './DialogMcpResourcesBrowser.svelte'; - -/** - * **DialogMcpResourcePreview** - MCP resource content preview - * - * Dialog for previewing the content of a stored MCP resource attachment. - * Displays the resource content with syntax highlighting for code, - * image rendering for images, and plain text for other content. - * - * **Features:** - * - Syntax highlighted code preview - * - Image rendering for image resources - * - Copy to clipboard and download actions - * - Server name and favicon display - * - MIME type badge - * - * @example - * ```svelte - * - * ``` - */ -export { default as DialogMcpResourcePreview } from './DialogMcpResourcePreview.svelte'; - /** * **DialogMermaidPreview** - Full-screen Mermaid diagram preview with zoom and pan * diff --git a/ui/apps/chat/src/lib/components/app/index.ts b/ui/apps/chat/src/lib/components/app/index.ts index a0a14c6173af..a1ea03a74b8d 100644 --- a/ui/apps/chat/src/lib/components/app/index.ts +++ b/ui/apps/chat/src/lib/components/app/index.ts @@ -4,7 +4,6 @@ export * from './chat'; export * from './content'; export * from './dialogs'; export * from './forms'; -export * from './mcp'; export * from './misc'; export * from './settings'; export * from './models'; diff --git a/ui/apps/chat/src/lib/components/app/settings/index.ts b/ui/apps/chat/src/lib/components/app/settings/index.ts index 2d44c88921ba..4e8d1396cadf 100644 --- a/ui/apps/chat/src/lib/components/app/settings/index.ts +++ b/ui/apps/chat/src/lib/components/app/settings/index.ts @@ -67,12 +67,6 @@ export { default as SettingsChatVoiceTab } from './SettingsChat/SettingsChatVoic */ export { default as SettingsChatImportExportSection } from './SettingsChat/SettingsChatImportExportSection.svelte'; -/** - * MCP Servers configuration panel. - * Provides UI for managing Model Context Protocol (MCP) server connections. - */ -export { default as SettingsMcpServers } from './SettingsMcpServers.svelte'; - /** * Form fields renderer for individual settings. Generates appropriate input * components based on field type (text, number, select, checkbox, textarea). diff --git a/ui/apps/chat/src/lib/components/app/mcp/McpActiveServersAvatars.svelte b/ui/apps/chat/src/lib/extensions/mcp/components/McpActiveServersAvatars.svelte similarity index 96% rename from ui/apps/chat/src/lib/components/app/mcp/McpActiveServersAvatars.svelte rename to ui/apps/chat/src/lib/extensions/mcp/components/McpActiveServersAvatars.svelte index c61c68a7424b..1030442fe34b 100644 --- a/ui/apps/chat/src/lib/components/app/mcp/McpActiveServersAvatars.svelte +++ b/ui/apps/chat/src/lib/extensions/mcp/components/McpActiveServersAvatars.svelte @@ -1,9 +1,10 @@ { // the stored MCP resource is MCP's own chip, not the default text chip diff --git a/ui/apps/chat/tests/stories/chat/form/ChatScreenForm.stories.svelte b/ui/apps/chat/tests/stories/chat/form/ChatScreenForm.stories.svelte index a86ab85b2b52..5c2037d3de49 100644 --- a/ui/apps/chat/tests/stories/chat/form/ChatScreenForm.stories.svelte +++ b/ui/apps/chat/tests/stories/chat/form/ChatScreenForm.stories.svelte @@ -1,5 +1,4 @@ + +
+

+ Features you can switch off. An extension that is off does not run. +

+ + {#if registry.extensions.length === 0} +
No extensions available
+ {:else} +
    + {#each registry.extensions as extension (extension.id)} + {@const switchId = `extension-${extension.id}`} + {@const descriptionId = `${switchId}-description`} + +
  • +
    + + +

    + {extension.description} +

    + + {#if extension.state === 'failed'} + + {/if} +
    + + void registry.setEnabled(extension.id, checked)} + /> +
  • + {/each} +
+ {/if} +
diff --git a/ui/apps/chat/src/lib/components/app/settings/index.ts b/ui/apps/chat/src/lib/components/app/settings/index.ts index 4e8d1396cadf..184a34fc7f51 100644 --- a/ui/apps/chat/src/lib/components/app/settings/index.ts +++ b/ui/apps/chat/src/lib/components/app/settings/index.ts @@ -52,6 +52,15 @@ export { default as SettingsResetButton } from './SettingsResetButton.svelte'; */ export { default as SettingsChatImportExportTab } from './SettingsChat/SettingsChatImportExportTab.svelte'; +/** + * **SettingsChatExtensionsTab** - Extensions section of the settings + * + * Lists the extensions the app knows (name, description) with a switch for + * each. A switch takes effect at once and the choice is remembered. An + * extension that failed to load or activate shows why. + */ +export { default as SettingsChatExtensionsTab } from './SettingsChat/SettingsChatExtensionsTab.svelte'; + /** * **SettingsChatVoiceTab** - Voice section of the settings * diff --git a/ui/apps/chat/src/lib/constants/settings.constants.ts b/ui/apps/chat/src/lib/constants/settings.constants.ts index cf5eb06b81cc..b47bf088f598 100644 --- a/ui/apps/chat/src/lib/constants/settings.constants.ts +++ b/ui/apps/chat/src/lib/constants/settings.constants.ts @@ -17,6 +17,7 @@ import Mic from '@lucide/svelte/icons/mic'; import Monitor from '@lucide/svelte/icons/monitor'; import Moon from '@lucide/svelte/icons/moon'; import PencilRuler from '@lucide/svelte/icons/pencil-ruler'; +import Puzzle from '@lucide/svelte/icons/puzzle'; import SlidersVertical from '@lucide/svelte/icons/sliders-vertical'; import Sun from '@lucide/svelte/icons/sun'; import TextCursorInput from '@lucide/svelte/icons/text-cursor-input'; @@ -37,6 +38,7 @@ export const SETTINGS_SECTIONS = { AGENTIC: { slug: 'agentic', title: 'Agentic' }, DEVELOPER: { slug: 'developer', title: 'Developer' }, DISPLAY: { slug: 'display', title: 'Display' }, + EXTENSIONS: { slug: 'extensions', title: 'Extensions' }, GENERAL: { slug: 'general', title: 'General' }, IMPORT_EXPORT: { slug: 'import-export', title: 'Import/Export' }, SAMPLING_PENALTIES: { slug: 'sampling-penalties', title: 'Sampling & Penalties' }, @@ -48,6 +50,7 @@ export const SETTINGS_SECTION_SLUGS = { AGENTIC: SETTINGS_SECTIONS.AGENTIC.slug, DEVELOPER: SETTINGS_SECTIONS.DEVELOPER.slug, DISPLAY: SETTINGS_SECTIONS.DISPLAY.slug, + EXTENSIONS: SETTINGS_SECTIONS.EXTENSIONS.slug, GENERAL: SETTINGS_SECTIONS.GENERAL.slug, IMPORT_EXPORT: SETTINGS_SECTIONS.IMPORT_EXPORT.slug, SAMPLING_PENALTIES: SETTINGS_SECTIONS.SAMPLING_PENALTIES.slug, @@ -59,6 +62,7 @@ export const SETTINGS_SECTION_TITLES = { AGENTIC: SETTINGS_SECTIONS.AGENTIC.title, DEVELOPER: SETTINGS_SECTIONS.DEVELOPER.title, DISPLAY: SETTINGS_SECTIONS.DISPLAY.title, + EXTENSIONS: SETTINGS_SECTIONS.EXTENSIONS.title, GENERAL: SETTINGS_SECTIONS.GENERAL.title, IMPORT_EXPORT: SETTINGS_SECTIONS.IMPORT_EXPORT.title, SAMPLING_PENALTIES: SETTINGS_SECTIONS.SAMPLING_PENALTIES.title, @@ -521,6 +525,7 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [ }, { defaultValue: DEFAULT_MCP_CONFIG.requestTimeoutSeconds, + extension: 'mcp', help: 'Timeout for individual MCP tool calls.', isPositiveInteger: true, key: SETTINGS_KEYS.MCP_REQUEST_TIMEOUT_SECONDS, @@ -542,6 +547,13 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [ slug: SETTINGS_SECTION_SLUGS.AGENTIC, title: SETTINGS_SECTION_TITLES.AGENTIC }, + // Extensions: the list comes from the extension registry, not from settings + { + icon: Puzzle, + settings: [], + slug: SETTINGS_SECTION_SLUGS.EXTENSIONS, + title: SETTINGS_SECTION_TITLES.EXTENSIONS + }, // Import/Export { icon: Database, @@ -841,6 +853,7 @@ function toSettingsSection(section: SettingsSectionEntry): SettingsSection { .filter((s) => s.standaloneField !== false) .map((s) => ({ dependsOn: s.dependsOn, + extension: s.extension, help: s.help, isExperimental: s.isExperimental, isPositiveInteger: s.isPositiveInteger, diff --git a/ui/apps/chat/src/lib/extensions/mcp/composer.ts b/ui/apps/chat/src/lib/extensions/mcp/composer.ts index 3f03fe08eb52..0efd4c69b177 100644 --- a/ui/apps/chat/src/lib/extensions/mcp/composer.ts +++ b/ui/apps/chat/src/lib/extensions/mcp/composer.ts @@ -49,4 +49,7 @@ export function contributeComposer(ctx: ExtensionContext): void { consume: () => mcpStore.consumeResourceAttachmentsAsExtras(), hasPending: () => mcpStore.resources.hasAttachments }); + + // resources still attached would come back, unseen until then, when MCP is switched on again + ctx.onDeactivate(() => mcpStore.clearResourceAttachments()); } diff --git a/ui/apps/chat/src/lib/extensions/mcp/startup.svelte.ts b/ui/apps/chat/src/lib/extensions/mcp/startup.svelte.ts index 69678c98739f..cb692ae9bc4b 100644 --- a/ui/apps/chat/src/lib/extensions/mcp/startup.svelte.ts +++ b/ui/apps/chat/src/lib/extensions/mcp/startup.svelte.ts @@ -12,8 +12,13 @@ import { untrack } from 'svelte'; * Only IDLE servers are checked; already-resolved (SUCCESS / ERROR) servers * keep their existing state, so adding or removing a server does not flash * every other card back through skeleton state. + * When the extension is switched off the checks stop and the live + * connections are closed. */ export function contributeStartup(ctx: ExtensionContext): void { + // cleanups run last-in first-out: the checks stop first, then the connections close + ctx.onDeactivate(() => mcpStore.shutdown()); + // outside any component, so the effect needs a root of its own; it runs again when the server list changes const dispose = $effect.root(() => { $effect(() => { diff --git a/ui/apps/chat/tests/client/mcp-navigation-glue.svelte.test.ts b/ui/apps/chat/tests/client/mcp-navigation-glue.svelte.test.ts index cf5fe1ea2085..c1a7ef5047f0 100644 --- a/ui/apps/chat/tests/client/mcp-navigation-glue.svelte.test.ts +++ b/ui/apps/chat/tests/client/mcp-navigation-glue.svelte.test.ts @@ -1,6 +1,7 @@ // What the MCP extension gives the sidebar, the page route and startup: its // entry right after Models, the MCP servers page that entry leads to, -// and the background health checks, which stop when the extension goes off. +// and the background health checks, which stop when the extension goes off, +// when the live connections close too. import { ROUTES, SETTINGS_KEYS, SIDEBAR_FOOTER_ITEMS } from '#lib/constants/index.ts'; import type { ExtensionContext, ExtensionPage, NavigationItem } from '#lib/extensions/index.ts'; @@ -77,6 +78,7 @@ describe('MCP navigation glue', () => { const runHealthChecks = vi .spyOn(mcpStore, 'runHealthChecksForServers') .mockResolvedValue(undefined); + const shutdown = vi.spyOn(mcpStore, 'shutdown').mockResolvedValue(); const { cleanups, ctx } = makeContext(); try { @@ -105,14 +107,20 @@ describe('MCP navigation glue', () => { expect(runHealthChecks).toHaveBeenCalledTimes(2); - expect(cleanups).toHaveLength(1); - await cleanups[0](); + // the registry runs the cleanups last-in first-out: the checks stop, then the connections close + expect(cleanups).toHaveLength(2); + expect(shutdown).not.toHaveBeenCalled(); + + for (const cleanup of [...cleanups].reverse()) await cleanup(); + + expect(shutdown).toHaveBeenCalledOnce(); setServers([{ enabled: true, id: 'late', url: 'http://localhost:9004/mcp' }]); expect(runHealthChecks).toHaveBeenCalledTimes(2); } finally { runHealthChecks.mockRestore(); + shutdown.mockRestore(); settingsStore.updateConfig(SETTINGS_KEYS.MCP_SERVERS, original); } }); diff --git a/ui/apps/chat/tests/client/settings-extensions.svelte.test.ts b/ui/apps/chat/tests/client/settings-extensions.svelte.test.ts new file mode 100644 index 000000000000..313dd93197f5 --- /dev/null +++ b/ui/apps/chat/tests/client/settings-extensions.svelte.test.ts @@ -0,0 +1,240 @@ +// The Extensions section of the settings switches an extension on and off, at +// once: with MCP off its sidebar entry, the `/prompt` command and its tools are +// gone and its connections close; switched on again they are back. The choice +// is stored, so a reload keeps it. + +import SidebarNavigationFooter from '#lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte'; +import SettingsChatExtensionsTab from '#lib/components/app/settings/SettingsChat/SettingsChatExtensionsTab.svelte'; +import { + EXTENSIONS_LOCALSTORAGE_KEY, + SETTINGS_KEYS, + SIDEBAR_FOOTER_ITEMS +} from '#lib/constants/index.ts'; +import { ToolSource } from '#lib/enums/index.ts'; +import { BUILT_IN_EXTENSIONS } from '#lib/extensions/builtin.ts'; +import { ExtensionRegistry, extensions } from '#lib/extensions/index.ts'; +import { mcpStore } from '#lib/extensions/mcp/stores/index.svelte.ts'; +import { uiStore } from '#lib/stores/index.ts'; +import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; +import { toolsStore } from '#lib/stores/tools.svelte.ts'; +import type { MCPConnection, MCPResourceInfo } from '#lib/types/index.ts'; +import { getChatCommands } from '#lib/utils/index.ts'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { page } from 'vitest/browser'; +import { render } from 'vitest-browser-svelte'; + +const MCP_ID = 'mcp'; +/** The labels of the footer's own items, in order. */ +const FOOTER = SIDEBAR_FOOTER_ITEMS.map((item) => item.tooltip); +const RESOURCE: MCPResourceInfo = { + name: 'README.md', + serverName: 'docs', + uri: 'repo://ggml-org/llama.cpp/README.md' +}; + +/** Labels of the sidebar footer's rows, in order. */ +function footerLabels(container: Element): string[] { + return [...container.querySelectorAll('[data-slot="button"]')] + .map((row) => row.querySelector('span span')?.textContent?.trim() ?? '') + .filter((label) => label !== ''); +} + +/** The slash commands as the chat form lists them. */ +function commandNames(): string[] { + return getChatCommands( + { canCompact: () => false, hasCwdTools: () => false, showModelSelector: false }, + extensions.contributions('composerCommands') + ).map((command) => command.name); +} + +function mcpToolNames(): string[] { + return toolsStore.allTools + .filter((tool) => tool.source === ToolSource.MCP) + .map((tool) => tool.definition.function.name); +} + +function storedChoices(): unknown { + return JSON.parse(localStorage.getItem(EXTENSIONS_LOCALSTORAGE_KEY) ?? 'null'); +} + +/** The registry a reloaded app starts with: the same extensions, the choices read from storage. */ +async function reloadedRegistry(): Promise { + const registry = new ExtensionRegistry(); + + for (const manifest of BUILT_IN_EXTENSIONS) registry.register(manifest); + + await registry.activateEnabled(); + + return registry; +} + +describe('Extensions settings', () => { + let wasExpanded: boolean; + + beforeAll(() => { + localStorage.removeItem(EXTENSIONS_LOCALSTORAGE_KEY); + + for (const manifest of BUILT_IN_EXTENSIONS) extensions.register(manifest); + }); + + beforeEach(async () => { + await page.viewport(1280, 900); + wasExpanded = uiStore.isSidebarExpanded; + uiStore.isSidebarExpanded = true; + + settingsStore.updateConfig(SETTINGS_KEYS.MCP_SERVERS, '[]'); + + const serverId = mcpStore.addServer({ + displayName: 'Docs', + enabled: true, + url: 'https://mcp.example.com/mcp' + }).id; + + // no network: the server is "connected" with one tool + vi.spyOn(mcpStore, 'runHealthChecksForServers').mockResolvedValue(); + vi.spyOn(mcpStore, 'getConnections').mockReturnValue( + new Map([[serverId, { tools: [{ name: 'search' }] } as unknown as MCPConnection]]) + ); + vi.spyOn(mcpStore, 'shutdown').mockResolvedValue(); + + // every test starts with MCP on, as a fresh app does + await extensions.setEnabled(MCP_ID, true); + }); + + afterEach(async () => { + await extensions.setEnabled(MCP_ID, false); + vi.restoreAllMocks(); + mcpStore.resources.clearAttachments(); + settingsStore.updateConfig(SETTINGS_KEYS.MCP_SERVERS, '[]'); + localStorage.removeItem(EXTENSIONS_LOCALSTORAGE_KEY); + uiStore.isSidebarExpanded = wasExpanded; + }); + + afterAll(() => { + localStorage.removeItem(EXTENSIONS_LOCALSTORAGE_KEY); + }); + + it('lists MCP with its description, switched on', async () => { + const screen = render(SettingsChatExtensionsTab); + + await expect.element(screen.getByRole('switch', { name: 'MCP' })).toBeChecked(); + await expect + .element( + screen.getByText('Connect MCP servers and use their tools, prompts and resources in chats.') + ) + .toBeVisible(); + expect(screen.container.querySelector('[role="alert"]')).toBeNull(); + }); + + it('takes MCP out of the sidebar, the commands and the tools, and puts it back', async () => { + const settings = render(SettingsChatExtensionsTab); + const sidebar = render(SidebarNavigationFooter, {}); + const mcpSwitch = settings.getByRole('switch', { name: 'MCP' }); + + await vi.waitFor(() => + expect(footerLabels(sidebar.container)).toEqual(['Models', 'MCP', ...FOOTER.slice(1)]) + ); + expect(commandNames()).toEqual(['prompt', 'cwd', 'model', 'compact']); + expect(mcpToolNames()).toEqual(['search']); + + mcpStore.resources.addAttachment(RESOURCE); + + await mcpSwitch.click(); + + await expect.element(mcpSwitch).not.toBeChecked(); + await vi.waitFor(() => expect(footerLabels(sidebar.container)).toEqual(FOOTER)); + expect(commandNames()).toEqual(['cwd', 'model', 'compact']); + expect(mcpToolNames()).toEqual([]); + // the live connections close and the resources waiting in the chat form are dropped + expect(mcpStore.shutdown).toHaveBeenCalledOnce(); + expect(mcpStore.resources.hasAttachments).toBe(false); + expect(extensions.extensions.find((e) => e.id === MCP_ID)).toMatchObject({ + enabled: false, + state: 'inactive' + }); + + await mcpSwitch.click(); + + await expect.element(mcpSwitch).toBeChecked(); + await vi.waitFor(() => + expect(footerLabels(sidebar.container)).toEqual(['Models', 'MCP', ...FOOTER.slice(1)]) + ); + expect(commandNames()).toEqual(['prompt', 'cwd', 'model', 'compact']); + expect(mcpToolNames()).toEqual(['search']); + }); + + it('keeps the choice over a reload', async () => { + const settings = render(SettingsChatExtensionsTab); + const mcpSwitch = settings.getByRole('switch', { name: 'MCP' }); + + await mcpSwitch.click(); + await expect.element(mcpSwitch).not.toBeChecked(); + + expect(storedChoices()).toEqual({ [MCP_ID]: false }); + + const off = await reloadedRegistry(); + + expect(off.extensions).toMatchObject([{ enabled: false, id: MCP_ID, state: 'inactive' }]); + expect(off.contributions('navigation')).toEqual([]); + expect(off.contributions('tools')).toEqual([]); + + const reloadedSettings = render(SettingsChatExtensionsTab, { registry: off }); + + await expect.element(reloadedSettings.getByRole('switch', { name: 'MCP' })).not.toBeChecked(); + + await mcpSwitch.click(); + await expect.element(mcpSwitch).toBeChecked(); + + expect(storedChoices()).toEqual({ [MCP_ID]: true }); + + const on = await reloadedRegistry(); + + try { + expect(on.extensions).toMatchObject([{ enabled: true, id: MCP_ID, state: 'active' }]); + expect(on.contributions('navigation')).toHaveLength(1); + } finally { + await on.setEnabled(MCP_ID, false); + } + }); + + it('says why an extension did not start, and tries again when switched off and on', async () => { + const registry = new ExtensionRegistry(); + + let attempts = 0; + + registry.register({ + description: 'Fails the first time it loads.', + id: 'settings-extensions-flaky', + load: async () => { + attempts++; + + if (attempts === 1) throw new Error('chunk did not load'); + + return { default: { activate: () => {} } }; + }, + name: 'Flaky' + }); + + vi.spyOn(console, 'error').mockImplementation(() => {}); + await registry.activateEnabled(); + + const screen = render(SettingsChatExtensionsTab, { registry }); + const flaky = screen.getByRole('switch', { name: 'Flaky' }); + + await expect.element(flaky).toBeChecked(); + await expect + .element(screen.getByRole('alert')) + .toHaveTextContent( + 'Flaky did not start: chunk did not load. Switch it off and on to try again.' + ); + + await flaky.click(); + await expect.element(flaky).not.toBeChecked(); + expect(screen.container.querySelector('[role="alert"]')).toBeNull(); + + await flaky.click(); + await expect.element(flaky).toBeChecked(); + await vi.waitFor(() => expect(registry.extensions[0].state).toBe('active')); + expect(screen.container.querySelector('[role="alert"]')).toBeNull(); + }); +}); diff --git a/ui/apps/chat/tests/stories/settings/SettingsChatExtensionsTab.stories.svelte b/ui/apps/chat/tests/stories/settings/SettingsChatExtensionsTab.stories.svelte new file mode 100644 index 000000000000..b31e9ac34dec --- /dev/null +++ b/ui/apps/chat/tests/stories/settings/SettingsChatExtensionsTab.stories.svelte @@ -0,0 +1,123 @@ + + +{#snippet frame(args: { registry?: ExtensionRegistry })} +
+ +
+{/snippet} + + + { + await builtIn.activateEnabled(); + }} + name="Default" + play={async ({ canvas }) => { + await expect(canvas.getByRole('switch', { name: 'MCP' })).toBeChecked(); + }} + template={frame} +/> + + + { + await states.activateEnabled(); + }} + name="States" + play={async ({ canvas }) => { + await expect(canvas.getByRole('switch', { name: 'MCP' })).toBeChecked(); + await expect(canvas.getByRole('switch', { name: 'Notes' })).not.toBeChecked(); + await expect(canvas.getByRole('switch', { name: 'Voice' })).toBeChecked(); + await expect(await canvas.findByRole('alert')).toHaveTextContent( + 'Voice did not start: Failed to fetch dynamically imported module. Switch it off and on to try again.' + ); + }} + template={frame} +/> + + + { + await switching.setEnabled('story-switching', true); + }} + name="SwitchOffAndOn" + play={async (context) => { + const { canvas } = context; + const pace = getPace(context); + const notes = canvas.getByRole('switch', { name: 'Notes' }); + + await expect(notes).toBeChecked(); + await pace.pause(); + await pace.user.click(notes); + await expect(notes).not.toBeChecked(); + await waitFor(() => expect(switching.extensions[0].state).toBe('inactive')); + + await pace.pause(); + await pace.user.click(notes); + await expect(notes).toBeChecked(); + await waitFor(() => expect(switching.extensions[0].state).toBe('active')); + }} + template={frame} +/> diff --git a/ui/apps/chat/tests/stories/settings/SettingsSections.stories.svelte b/ui/apps/chat/tests/stories/settings/SettingsSections.stories.svelte index de2d6b8f9063..ce5d46823f80 100644 --- a/ui/apps/chat/tests/stories/settings/SettingsSections.stories.svelte +++ b/ui/apps/chat/tests/stories/settings/SettingsSections.stories.svelte @@ -23,6 +23,8 @@ + + Date: Fri, 13 Nov 2026 00:13:25 +0100 Subject: [PATCH 09/19] ui: move the MCP client to MCP SDK v2 Replace @modelcontextprotocol/sdk with @modelcontextprotocol/client. The client keeps the session handshake, so behaviour does not change. SDK v2 has no WebSocket client transport, so the v1 one now lives in the app. The demo MCP servers use @modelcontextprotocol/server and @modelcontextprotocol/node. Assisted-by: Claude (Opus 5.5 Medium) --- ui/apps/chat/demo/fixtures/mcp-servers.ts | 8 +- ui/apps/chat/package-lock.json | 880 ++---------------- ui/apps/chat/package.json | 4 +- .../mcp/services/mcp-websocket-transport.ts | 76 ++ .../extensions/mcp/services/mcp.service.ts | 27 +- .../lib/extensions/mcp/stores/index.svelte.ts | 2 +- ui/apps/chat/src/lib/types/mcp.d.ts | 2 +- ui/apps/chat/tests/unit/mcp-service.test.ts | 2 +- .../unit/mcp-websocket-transport.test.ts | 101 ++ 9 files changed, 256 insertions(+), 846 deletions(-) create mode 100644 ui/apps/chat/src/lib/extensions/mcp/services/mcp-websocket-transport.ts create mode 100644 ui/apps/chat/tests/unit/mcp-websocket-transport.test.ts diff --git a/ui/apps/chat/demo/fixtures/mcp-servers.ts b/ui/apps/chat/demo/fixtures/mcp-servers.ts index 15529e4a314e..46b637c670da 100644 --- a/ui/apps/chat/demo/fixtures/mcp-servers.ts +++ b/ui/apps/chat/demo/fixtures/mcp-servers.ts @@ -8,8 +8,8 @@ */ import { DEMO_MCP_PORT, DEMO_MCP_SERVERS, type DemoMcpServer } from './demo-config.ts'; -import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; -import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; +import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node'; +import { McpServer } from '@modelcontextprotocol/server'; import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; import { z } from 'zod'; @@ -19,7 +19,7 @@ function buildServer(fixture: DemoMcpServer): McpServer { for (const tool of fixture.tools) { server.registerTool( tool.name, - { description: tool.description, inputSchema: { query: z.string().optional() } }, + { description: tool.description, inputSchema: z.object({ query: z.string().optional() }) }, async () => ({ content: [{ text: tool.result, type: 'text' }] }) ); } @@ -72,7 +72,7 @@ const httpServer = createServer(async (req, res) => { } const server = buildServer(fixture); - const transport = new StreamableHTTPServerTransport({ + const transport = new NodeStreamableHTTPServerTransport({ enableJsonResponse: true, sessionIdGenerator: undefined }); diff --git a/ui/apps/chat/package-lock.json b/ui/apps/chat/package-lock.json index 6309a89be0f9..b8fec081487f 100644 --- a/ui/apps/chat/package-lock.json +++ b/ui/apps/chat/package-lock.json @@ -24,7 +24,9 @@ "@internationalized/date": "3.12.2", "@lezer/highlight": "1.2.5", "@lucide/svelte": "1.46.0", - "@modelcontextprotocol/sdk": "1.32.1", + "@modelcontextprotocol/client": "2.4.0", + "@modelcontextprotocol/node": "2.1.2", + "@modelcontextprotocol/server": "2.4.0", "@playwright/test": "1.56.1", "@storybook/addon-a11y": "10.6.6", "@storybook/addon-docs": "10.6.6", @@ -1937,45 +1939,67 @@ "react": ">=16" } }, - "node_modules/@modelcontextprotocol/sdk": { - "version": "1.32.1", - "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.32.1.tgz", - "integrity": "sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw==", + "node_modules/@modelcontextprotocol/client": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.4.0.tgz", + "integrity": "sha512-LgrD2OphHuG12vfKFKz6SOnq7bKHQmhGJIAYdD+MZBn2npHEyry6uD8zvktodtl5CQM85MO0anUyD9JwmUmxww==", "dev": true, - "license": "MIT", + "license": "Apache-2.0", "dependencies": { - "@hono/node-server": "^1.19.9 || ^2.0.5", - "ajv": "^8.17.1", - "ajv-formats": "^3.0.1", - "content-type": "^1.0.5", - "cors": "^2.8.5", + "@modelcontextprotocol/core": "2.4.0", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", - "eventsource-parser": "^3.0.0", - "express": "^5.2.1", - "express-rate-limit": "^8.2.1", - "hono": "^4.11.4", + "eventsource-parser": "^3.0.8", "jose": "^6.1.3", - "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", - "raw-body": "^3.0.0", - "zod": "^3.25 || ^4.0", - "zod-to-json-schema": "^3.25.1" + "zod": "^4.2.0" }, "engines": { - "node": ">=18" + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/core": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.4.0.tgz", + "integrity": "sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/node": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/node/-/node-2.1.2.tgz", + "integrity": "sha512-IIcIqBpr6NCQQs5DgJTgvbSOAw+3iaR/uquqg+e0nXCdudfjPg/80x0TseUnQx14AUAtE4fsJCEpJKPyb6WPVA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@hono/node-server": "^1.19.9 || ^2.1.3", + "hono": "^4.11.4" + }, + "engines": { + "node": ">=20" }, "peerDependencies": { - "@cfworker/json-schema": "^4.1.1", - "zod": "^3.25 || ^4.0" + "@modelcontextprotocol/server": "^2.4.0" + } + }, + "node_modules/@modelcontextprotocol/server": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.4.0.tgz", + "integrity": "sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@modelcontextprotocol/core": "2.4.0", + "zod": "^4.2.0" }, - "peerDependenciesMeta": { - "@cfworker/json-schema": { - "optional": true - }, - "zod": { - "optional": false - } + "engines": { + "node": ">=20" } }, "node_modules/@napi-rs/canvas": { @@ -5230,20 +5254,6 @@ "dev": true, "license": "MIT" }, - "node_modules/accepts": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", - "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", - "dev": true, - "license": "MIT", - "dependencies": { - "mime-types": "^3.0.0", - "negotiator": "^1.0.0" - }, - "engines": { - "node": ">= 0.6" - } - }, "node_modules/acorn": { "version": "8.19.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", @@ -5267,41 +5277,6 @@ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, - "node_modules/ajv": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", - "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.3", - "fast-uri": "^3.0.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/ajv-formats": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", - "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ajv": "^8.0.0" - }, - "peerDependencies": { - "ajv": "^8.0.0" - }, - "peerDependenciesMeta": { - "ajv": { - "optional": true - } - } - }, "node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", @@ -5484,45 +5459,6 @@ } } }, - "node_modules/body-parser": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", - "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "bytes": "^3.1.2", - "content-type": "^2.1.0", - "debug": "^4.4.3", - "http-errors": "^2.0.1", - "iconv-lite": "^0.7.3", - "on-finished": "^2.4.1", - "qs": "^6.16.1", - "raw-body": "^3.0.2", - "type-is": "^2.1.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/body-parser/node_modules/content-type": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", - "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/brace-expansion": { "version": "5.0.12", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", @@ -5552,16 +5488,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/bytes": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", - "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/cac": { "version": "6.7.14", "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", @@ -5813,30 +5739,6 @@ "node": "^14.18.0 || >=16.10.0" } }, - "node_modules/content-disposition": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz", - "integrity": "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/content-type": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", - "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -5858,34 +5760,6 @@ "url": "https://opencollective.com/express" } }, - "node_modules/cookie-signature": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", - "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.6.0" - } - }, - "node_modules/cors": { - "version": "2.8.6", - "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", - "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", - "dev": true, - "license": "MIT", - "dependencies": { - "object-assign": "^4", - "vary": "^1" - }, - "engines": { - "node": ">= 0.10" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/corser": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/corser/-/corser-2.0.1.tgz", @@ -6106,16 +5980,6 @@ "dev": true, "license": "MIT" }, - "node_modules/depd": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", - "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/dequal": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", @@ -6196,27 +6060,6 @@ "node": ">= 0.4" } }, - "node_modules/ee-first": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", - "dev": true, - "license": "MIT" - }, - "node_modules/encodeurl": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.1.tgz", - "integrity": "sha512-Ev/hIyePLZtpL98x562lvPtenrUfGr0lfaf44HFZ+hDEwso7ccV9QAZrEVLg0hxNAzygaAFxy2dYaAKKM0G06A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/enhanced-resolve": { "version": "5.26.1", "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.26.1.tgz", @@ -6339,13 +6182,6 @@ "@esbuild/win32-x64": "0.28.2" } }, - "node_modules/escape-html": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", - "dev": true, - "license": "MIT" - }, "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", @@ -6724,16 +6560,6 @@ "node": ">=0.10.0" } }, - "node_modules/etag": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, "node_modules/eventemitter3": { "version": "4.0.7", "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", @@ -6774,84 +6600,6 @@ "node": ">=12.0.0" } }, - "node_modules/express": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/express/-/express-5.3.0.tgz", - "integrity": "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==", - "dev": true, - "license": "MIT", - "dependencies": { - "accepts": "^2.0.0", - "body-parser": "^2.3.0", - "content-disposition": "^2.0.1", - "content-type": "^2.0.0", - "cookie": "^0.7.1", - "cookie-signature": "^1.2.1", - "debug": "^4.4.0", - "depd": "^2.0.0", - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "etag": "^1.8.1", - "finalhandler": "^2.1.0", - "fresh": "^2.0.0", - "http-errors": "^2.0.0", - "merge-descriptors": "^2.0.0", - "mime-types": "^3.0.0", - "on-finished": "^2.4.1", - "once": "^1.4.0", - "parseurl": "^1.3.3", - "proxy-addr": "^2.0.8", - "qs": "^6.16.0", - "range-parser": "^1.2.1", - "router": "^2.2.0", - "send": "^1.1.0", - "serve-static": "^2.2.0", - "statuses": "^2.0.1", - "type-is": "^2.1.0", - "vary": "^1.1.2" - }, - "engines": { - "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/express-rate-limit": { - "version": "8.7.3", - "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.3.tgz", - "integrity": "sha512-zPLqDI2f0gV2WmGnacLf9XSSqn4VldRyP5LCzOwx0BKH40mO6+2PCFkoSsRO2jePx87/Kf6NUF6P2QOTKXHbQA==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.4.3", - "ip-address": "^10.2.0" - }, - "engines": { - "node": ">= 16" - }, - "funding": { - "url": "https://github.com/sponsors/express-rate-limit" - }, - "peerDependencies": { - "express": ">= 4.11" - } - }, - "node_modules/express/node_modules/content-type": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", - "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/extend": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", @@ -6880,23 +6628,6 @@ "dev": true, "license": "MIT" }, - "node_modules/fast-uri": { - "version": "3.1.9", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", - "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "BSD-3-Clause" - }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -6932,28 +6663,6 @@ "flat-cache": "^6.1.23" } }, - "node_modules/finalhandler": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", - "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.4.0", - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "on-finished": "^2.4.1", - "parseurl": "^1.3.3", - "statuses": "^2.0.1" - }, - "engines": { - "node": ">= 18.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/find-up": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", @@ -7011,26 +6720,6 @@ } } }, - "node_modules/forwarded": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", - "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/fresh": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", - "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", @@ -7446,27 +7135,6 @@ "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/http-errors": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", - "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "depd": "~2.0.0", - "inherits": "~2.0.4", - "setprototypeof": "~1.2.0", - "statuses": "~2.0.2", - "toidentifier": "~1.0.1" - }, - "engines": { - "node": ">= 0.8" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/http-proxy": { "version": "1.18.1", "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.18.1.tgz", @@ -7517,27 +7185,10 @@ "dev": true, "license": "MPL-2.0" }, - "node_modules/iconv-lite": { - "version": "0.7.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", - "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/ignore": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", - "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", "dev": true, "license": "MIT", "engines": { @@ -7571,13 +7222,6 @@ "node": ">=8" } }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true, - "license": "ISC" - }, "node_modules/inline-style-parser": { "version": "0.2.7", "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz", @@ -7585,26 +7229,6 @@ "dev": true, "license": "MIT" }, - "node_modules/ip-address": { - "version": "10.7.6", - "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz", - "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 12" - } - }, - "node_modules/ipaddr.js": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", - "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.10" - } - }, "node_modules/is-docker": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-3.0.0.tgz", @@ -7676,13 +7300,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/is-promise": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", - "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", - "dev": true, - "license": "MIT" - }, "node_modules/is-reference": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz", @@ -7789,20 +7406,6 @@ "dev": true, "license": "MIT" }, - "node_modules/json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "dev": true, - "license": "MIT" - }, - "node_modules/json-schema-typed": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", - "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", - "dev": true, - "license": "BSD-2-Clause" - }, "node_modules/json-stable-stringify-without-jsonify": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", @@ -8638,33 +8241,6 @@ "url": "https://opencollective.com/unified" } }, - "node_modules/media-typer": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", - "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/merge-descriptors": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", - "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/micromark": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.3.tgz", @@ -9311,33 +8887,6 @@ "node": ">=4" } }, - "node_modules/mime-db": { - "version": "1.54.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", - "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", - "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "mime-db": "^1.54.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/min-indent": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz", @@ -9499,37 +9048,6 @@ "node": ">=18" } }, - "node_modules/negotiator": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", - "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", - "dev": true, - "license": "MIT", - "dependencies": { - "content-type": "^2.1.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/negotiator/node_modules/content-type": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", - "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/node-addon-api": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz", @@ -9538,16 +9056,6 @@ "license": "MIT", "optional": true }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/object-inspect": { "version": "1.13.4", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", @@ -9575,33 +9083,6 @@ "node": ">=12.20.0" } }, - "node_modules/on-finished": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.2.tgz", - "integrity": "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ee-first": "1.1.1" - }, - "engines": { - "node": ">= 0.8" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, - "license": "ISC", - "dependencies": { - "wrappy": "1" - } - }, "node_modules/open": { "version": "10.2.0", "resolved": "https://registry.npmjs.org/open/-/open-10.2.0.tgz", @@ -9763,16 +9244,6 @@ "url": "https://github.com/inikulin/parse5?sponsor=1" } }, - "node_modules/parseurl": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", - "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -9793,17 +9264,6 @@ "node": ">=8" } }, - "node_modules/path-to-regexp": { - "version": "8.4.2", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", - "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", - "dev": true, - "license": "MIT", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/pathe": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", @@ -10242,24 +9702,6 @@ "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/proxy-addr": { - "version": "2.0.8", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", - "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "forwarded": "0.2.0", - "ipaddr.js": "1.9.1" - }, - "engines": { - "node": ">= 0.10" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", @@ -10324,36 +9766,6 @@ ], "license": "MIT" }, - "node_modules/range-parser": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", - "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/raw-body": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", - "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", - "dev": true, - "license": "MIT", - "dependencies": { - "bytes": "~3.1.2", - "http-errors": "~2.0.1", - "iconv-lite": "~0.7.0", - "unpipe": "~1.0.0" - }, - "engines": { - "node": ">= 0.10" - } - }, "node_modules/react": { "version": "19.3.1", "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", @@ -10621,16 +10033,6 @@ "url": "https://opencollective.com/unified" } }, - "node_modules/require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/requires-port": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", @@ -10682,23 +10084,6 @@ "url": "https://github.com/sponsors/oxc-project" } }, - "node_modules/router": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", - "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.4.0", - "depd": "^2.0.0", - "is-promise": "^4.0.0", - "parseurl": "^1.3.3", - "path-to-regexp": "^8.0.0" - }, - "engines": { - "node": ">= 18" - } - }, "node_modules/run-applescript": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/run-applescript/-/run-applescript-7.1.0.tgz", @@ -10748,13 +10133,6 @@ "dev": true, "license": "MIT" }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "dev": true, - "license": "MIT" - }, "node_modules/sass": { "version": "1.100.0", "resolved": "https://registry.npmjs.org/sass/-/sass-1.100.0.tgz", @@ -10810,60 +10188,6 @@ "node": ">=10" } }, - "node_modules/send": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", - "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.4.3", - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "etag": "^1.8.1", - "fresh": "^2.0.0", - "http-errors": "^2.0.1", - "mime-types": "^3.0.2", - "ms": "^2.1.3", - "on-finished": "^2.4.1", - "range-parser": "^1.2.1", - "statuses": "^2.0.2" - }, - "engines": { - "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/serve-static": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", - "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", - "dev": true, - "license": "MIT", - "dependencies": { - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "parseurl": "^1.3.3", - "send": "^1.2.0" - }, - "engines": { - "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/setprototypeof": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", - "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", - "dev": true, - "license": "ISC" - }, "node_modules/sharp": { "version": "0.35.5", "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", @@ -11092,16 +10416,6 @@ "dev": true, "license": "MIT" }, - "node_modules/statuses": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", - "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/std-env": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", @@ -11693,16 +11007,6 @@ "dev": true, "license": "MIT" }, - "node_modules/toidentifier": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", - "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.6" - } - }, "node_modules/totalist": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/totalist/-/totalist-3.0.1.tgz", @@ -11801,39 +11105,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/type-is": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", - "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", - "dev": true, - "license": "MIT", - "dependencies": { - "content-type": "^2.0.0", - "media-typer": "^1.1.0", - "mime-types": "^3.0.0" - }, - "engines": { - "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/type-is/node_modules/content-type": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", - "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/typescript": { "version": "6.0.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", @@ -12040,16 +11311,6 @@ "node": ">= 10.0.0" } }, - "node_modules/unpipe": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", - "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/unplugin": { "version": "2.3.11", "resolved": "https://registry.npmjs.org/unplugin/-/unplugin-2.3.11.tgz", @@ -12136,16 +11397,6 @@ } } }, - "node_modules/vary": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", - "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/vaul-svelte": { "version": "1.0.0-next.7", "resolved": "https://registry.npmjs.org/vaul-svelte/-/vaul-svelte-1.0.0-next.7.tgz", @@ -12625,13 +11876,6 @@ "node": ">=0.10.0" } }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true, - "license": "ISC" - }, "node_modules/ws": { "version": "8.22.2", "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.2.tgz", @@ -12700,16 +11944,6 @@ "url": "https://github.com/sponsors/colinhacks" } }, - "node_modules/zod-to-json-schema": { - "version": "3.25.2", - "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", - "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", - "dev": true, - "license": "ISC", - "peerDependencies": { - "zod": "^3.25.28 || ^4" - } - }, "node_modules/zwitch": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", diff --git a/ui/apps/chat/package.json b/ui/apps/chat/package.json index 16ee71c5eaaa..c0ac96470726 100644 --- a/ui/apps/chat/package.json +++ b/ui/apps/chat/package.json @@ -83,7 +83,9 @@ "@internationalized/date": "3.12.2", "@lezer/highlight": "1.2.5", "@lucide/svelte": "1.46.0", - "@modelcontextprotocol/sdk": "1.32.1", + "@modelcontextprotocol/client": "2.4.0", + "@modelcontextprotocol/node": "2.1.2", + "@modelcontextprotocol/server": "2.4.0", "@playwright/test": "1.56.1", "@storybook/addon-a11y": "10.6.6", "@storybook/addon-docs": "10.6.6", diff --git a/ui/apps/chat/src/lib/extensions/mcp/services/mcp-websocket-transport.ts b/ui/apps/chat/src/lib/extensions/mcp/services/mcp-websocket-transport.ts new file mode 100644 index 000000000000..9b5eb943ee2c --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/services/mcp-websocket-transport.ts @@ -0,0 +1,76 @@ +/** + * WebSocket client transport for MCP + * + * MCP SDK v2 has no WebSocket transport, it is not a spec transport. + * This is the v1 transport, kept so WebSocket servers still work. Consumed by mcp.service. + */ + +import { + type JSONRPCMessage, + parseJSONRPCMessage, + type Transport +} from '@modelcontextprotocol/client'; + +const SUBPROTOCOL = 'mcp'; + +export class WebSocketClientTransport implements Transport { + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + + private socket?: WebSocket; + + async close(): Promise { + this.socket?.close(); + } + + constructor(private url: URL) {} + + async send(message: JSONRPCMessage): Promise { + if (!this.socket) { + throw new Error('Not connected'); + } + + this.socket.send(JSON.stringify(message)); + } + + start(): Promise { + if (this.socket) { + throw new Error('WebSocketClientTransport already started'); + } + + return new Promise((resolve, reject) => { + const socket = new WebSocket(this.url, SUBPROTOCOL); + + this.socket = socket; + + socket.onerror = (event) => { + const error = + 'error' in event + ? (event.error as Error) + : new Error(`WebSocket error: ${JSON.stringify(event)}`); + + reject(error); + this.onerror?.(error); + }; + + socket.onopen = () => resolve(); + + socket.onclose = () => this.onclose?.(); + + socket.onmessage = (event: MessageEvent) => { + let message: JSONRPCMessage; + + try { + message = parseJSONRPCMessage(JSON.parse(event.data)); + } catch (error) { + this.onerror?.(error as Error); + + return; + } + + this.onmessage?.(message); + }; + }); + } +} diff --git a/ui/apps/chat/src/lib/extensions/mcp/services/mcp.service.ts b/ui/apps/chat/src/lib/extensions/mcp/services/mcp.service.ts index 3a801744ee9e..04f16addece5 100644 --- a/ui/apps/chat/src/lib/extensions/mcp/services/mcp.service.ts +++ b/ui/apps/chat/src/lib/extensions/mcp/services/mcp.service.ts @@ -6,20 +6,18 @@ * formatting. No reactive state; consumed by mcpStore and its managers. */ -import { Client } from '@modelcontextprotocol/sdk/client'; -import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js'; +import { WebSocketClientTransport } from './mcp-websocket-transport'; import { + Client, + type GetPromptResult, + type ListChangedHandlers, + type Prompt, + SdkHttpError, + SSEClientTransport, StreamableHTTPClientTransport, - StreamableHTTPError -} from '@modelcontextprotocol/sdk/client/streamableHttp.js'; -import { WebSocketClientTransport } from '@modelcontextprotocol/sdk/client/websocket.js'; -import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'; -import type { - GetPromptResult, - ListChangedHandlers, - Prompt, - Tool -} from '@modelcontextprotocol/sdk/types.js'; + type Tool, + type Transport +} from '@modelcontextprotocol/client'; import { CORS_PROXY, CORS_PROXY_ENDPOINT, @@ -116,7 +114,6 @@ export class MCPService { try { const result = await connection.client.callTool( { arguments: params.arguments, name: params.name }, - undefined, { signal, timeout: connection.requestTimeoutMs } ); @@ -651,7 +648,7 @@ export class MCPService { * @returns true if the error is a StreamableHTTP 404 (session not found) */ static isSessionExpiredError(error: unknown): boolean { - return error instanceof StreamableHTTPError && error.code === 404; + return error instanceof SdkHttpError && error.status === 404; } /** @@ -1118,7 +1115,7 @@ export class MCPService { return { description: impl.description, - icons: impl.icons?.map((icon: MCPResourceIcon) => ({ + icons: (impl.icons as MCPResourceIcon[] | undefined)?.map((icon) => ({ mimeType: icon.mimeType, sizes: icon.sizes, src: icon.src, diff --git a/ui/apps/chat/src/lib/extensions/mcp/stores/index.svelte.ts b/ui/apps/chat/src/lib/extensions/mcp/stores/index.svelte.ts index ccb0cfe775d8..c3ccabb743f1 100644 --- a/ui/apps/chat/src/lib/extensions/mcp/stores/index.svelte.ts +++ b/ui/apps/chat/src/lib/extensions/mcp/stores/index.svelte.ts @@ -13,7 +13,7 @@ import { MCPService } from '../services/mcp.service'; // direct imports between stores, not via the barrel, to avoid circular deps import { MCPHealthCheckManager, type McpHealthHost } from './health.svelte'; import { mcpResourceStore } from './resources.svelte'; -import type { ListChangedHandlers } from '@modelcontextprotocol/sdk/types.js'; +import type { ListChangedHandlers } from '@modelcontextprotocol/client'; import { SETTINGS_KEYS } from '#lib/constants/index.ts'; import { CACHE, diff --git a/ui/apps/chat/src/lib/types/mcp.d.ts b/ui/apps/chat/src/lib/types/mcp.d.ts index 2c44cce44c22..7c70854a73f5 100644 --- a/ui/apps/chat/src/lib/types/mcp.d.ts +++ b/ui/apps/chat/src/lib/types/mcp.d.ts @@ -10,7 +10,7 @@ import type { ServerCapabilities as SDKServerCapabilities, Tool, Transport -} from '@modelcontextprotocol/sdk'; +} from '@modelcontextprotocol/client'; import type { ColorMode } from '#lib/enums/index.ts'; import type { HealthCheckStatus, MCPConnectionPhase, MCPLogLevel } from '#lib/enums/mcp.enums.ts'; import type { ToolSource } from '#lib/enums/tools.enums.ts'; diff --git a/ui/apps/chat/tests/unit/mcp-service.test.ts b/ui/apps/chat/tests/unit/mcp-service.test.ts index a70d72099525..3b4ef7d30f6d 100644 --- a/ui/apps/chat/tests/unit/mcp-service.test.ts +++ b/ui/apps/chat/tests/unit/mcp-service.test.ts @@ -1,4 +1,4 @@ -import { Client } from '@modelcontextprotocol/sdk/client'; +import { Client } from '@modelcontextprotocol/client'; import { CORS_PROXY } from '#lib/constants/index.ts'; import { MCPConnectionPhase, MCPTransportType } from '#lib/enums/index.ts'; import { MCPService } from '#lib/extensions/mcp/services/mcp.service.ts'; diff --git a/ui/apps/chat/tests/unit/mcp-websocket-transport.test.ts b/ui/apps/chat/tests/unit/mcp-websocket-transport.test.ts new file mode 100644 index 000000000000..a55a2963011c --- /dev/null +++ b/ui/apps/chat/tests/unit/mcp-websocket-transport.test.ts @@ -0,0 +1,101 @@ +import { WebSocketClientTransport } from '#lib/extensions/mcp/services/mcp-websocket-transport.ts'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +class FakeWebSocket { + static instances: FakeWebSocket[] = []; + + onclose?: () => void; + onerror?: (event: unknown) => void; + onmessage?: (event: { data: string }) => void; + onopen?: () => void; + sent: string[] = []; + + close() { + this.onclose?.(); + } + + constructor( + public url: URL, + public protocol: string + ) { + FakeWebSocket.instances.push(this); + } + + send(data: string) { + this.sent.push(data); + } +} + +async function startTransport() { + const transport = new WebSocketClientTransport(new URL('ws://example.com/mcp')); + const started = transport.start(); + const socket = FakeWebSocket.instances.at(-1)!; + + socket.onopen?.(); + await started; + + return { socket, transport }; +} + +describe('WebSocketClientTransport', () => { + afterEach(() => { + FakeWebSocket.instances = []; + vi.unstubAllGlobals(); + }); + + it('opens the socket with the mcp subprotocol and sends JSON-RPC messages', async () => { + vi.stubGlobal('WebSocket', FakeWebSocket); + + const { socket, transport } = await startTransport(); + + expect(socket.url.href).toBe('ws://example.com/mcp'); + expect(socket.protocol).toBe('mcp'); + + await transport.send({ id: 1, jsonrpc: '2.0', method: 'ping' }); + + expect(socket.sent).toEqual(['{"id":1,"jsonrpc":"2.0","method":"ping"}']); + }); + + it('delivers valid messages and reports invalid frames as errors', async () => { + vi.stubGlobal('WebSocket', FakeWebSocket); + + const { socket, transport } = await startTransport(); + const onmessage = vi.fn(); + const onerror = vi.fn(); + + transport.onmessage = onmessage; + transport.onerror = onerror; + + socket.onmessage?.({ data: '{"id":1,"jsonrpc":"2.0","result":{}}' }); + socket.onmessage?.({ data: 'not json' }); + socket.onmessage?.({ data: '{"foo":"bar"}' }); + + expect(onmessage).toHaveBeenCalledTimes(1); + expect(onmessage).toHaveBeenCalledWith({ id: 1, jsonrpc: '2.0', result: {} }); + expect(onerror).toHaveBeenCalledTimes(2); + }); + + it('rejects start when the socket fails and notifies on close', async () => { + vi.stubGlobal('WebSocket', FakeWebSocket); + + const failing = new WebSocketClientTransport(new URL('ws://example.com/mcp')); + const started = failing.start(); + + FakeWebSocket.instances.at(-1)!.onerror?.({ error: new Error('refused') }); + await expect(started).rejects.toThrow('refused'); + + const { transport } = await startTransport(); + const onclose = vi.fn(); + + transport.onclose = onclose; + await transport.close(); + + expect(onclose).toHaveBeenCalledTimes(1); + await expect( + new WebSocketClientTransport(new URL('ws://example.com/mcp')).send({ + jsonrpc: '2.0', + method: 'notifications/initialized' + }) + ).rejects.toThrow('Not connected'); + }); +}); From 980f3a2755dae2f3e241eb4ba239eb71ac037c9a Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Fri, 13 Nov 2026 00:24:14 +0100 Subject: [PATCH 10/19] ui: negotiate the stateless MCP protocol, fall back to the session handshake Streamable HTTP connections probe the server with server/discover (MCP 2026-07-28) and fall back to the initialize handshake on older servers. SSE and WebSocket connections keep the initialize handshake. The connection log and the server card show the negotiated protocol version. On a stateless connection, resource subscriptions use a subscriptions/listen stream. Assisted-by: Claude (Opus 5.5 Medium) --- .../extensions/mcp/services/mcp.service.ts | 63 ++++- ui/apps/chat/src/lib/types/mcp.d.ts | 3 + .../tests/unit/mcp-service-protocol.test.ts | 223 ++++++++++++++++++ 3 files changed, 280 insertions(+), 9 deletions(-) create mode 100644 ui/apps/chat/tests/unit/mcp-service-protocol.test.ts diff --git a/ui/apps/chat/src/lib/extensions/mcp/services/mcp.service.ts b/ui/apps/chat/src/lib/extensions/mcp/services/mcp.service.ts index 04f16addece5..730add62306a 100644 --- a/ui/apps/chat/src/lib/extensions/mcp/services/mcp.service.ts +++ b/ui/apps/chat/src/lib/extensions/mcp/services/mcp.service.ts @@ -173,7 +173,7 @@ export class MCPService { * * Performs the full MCP connection lifecycle: * 1. Transport creation (with automatic fallback) - * 2. Client initialization and capability exchange + * 2. Protocol negotiation (stateless `server/discover`, else the `initialize` handshake) and capability exchange * 3. Tool discovery via `listTools` * * Reports progress via `onPhase` callback at each step, enabling @@ -237,6 +237,10 @@ export class MCPService { { transportType } ); + // Streamable HTTP servers can speak the stateless protocol (2026-07-28): probe with + // server/discover, fall back to the initialize handshake for older servers. + // SSE and WebSocket servers are session-only, a probe there can only fail the connection. + const negotiatesProtocol = transportType === MCPTransportType.STREAMABLE_HTTP; const client = new Client( { name: effectiveClientInfo.name, @@ -244,7 +248,8 @@ export class MCPService { }, { capabilities: effectiveCapabilities, - listChanged: listChangedHandlers + listChanged: listChangedHandlers, + versionNegotiation: { mode: negotiatesProtocol ? 'auto' : 'legacy' } } ); const runtimeErrorHandler = (error: Error) => { @@ -288,10 +293,13 @@ export class MCPService { // Phase: Initializing onPhase?.( MCPConnectionPhase.INITIALIZING, - this.createLog(MCPConnectionPhase.INITIALIZING, 'Sending initialize request...') + this.createLog( + MCPConnectionPhase.INITIALIZING, + negotiatesProtocol ? 'Negotiating protocol version...' : 'Sending initialize request...' + ) ); - // The SDK timeout only covers the initialize request, not transport.start(), + // The SDK timeout only covers the handshake requests, not transport.start(), // which can hang forever on an unreachable host (SSE endpoint wait, WebSocket // handshake, proxied fetch). This race bounds the whole handshake and closes // the transport on expiry so the underlying fetch or socket is aborted. @@ -331,7 +339,7 @@ export class MCPService { MCPConnectionPhase.ERROR, this.createLog( MCPConnectionPhase.ERROR, - `Connection failed during initialize: ${ + `Connection failed during handshake: ${ error instanceof Error ? error.message : String(error) }`, MCPLogLevel.ERROR, @@ -363,15 +371,20 @@ export class MCPService { const serverCapabilities = client.getServerCapabilities(); const instructions = client.getInstructions(); const serverInfo = this.extractServerInfo(serverVersion); + const protocolVersion = client.getNegotiatedProtocolVersion(); + const isStateless = client.getProtocolEra() === 'modern'; // Phase: Capabilities exchanged onPhase?.( MCPConnectionPhase.CAPABILITIES_EXCHANGED, this.createLog( MCPConnectionPhase.CAPABILITIES_EXCHANGED, - 'Capabilities exchanged successfully', + `Capabilities exchanged successfully (protocol ${protocolVersion ?? 'unknown'}, ${ + isStateless ? 'stateless' : 'initialize handshake' + })`, MCPLogLevel.INFO, { + protocolVersion, serverCapabilities, serverInfo } @@ -379,6 +392,7 @@ export class MCPService { { clientCapabilities: effectiveCapabilities, instructions, + protocolVersion, serverCapabilities, serverInfo } @@ -426,7 +440,7 @@ export class MCPService { clientCapabilities: effectiveCapabilities, connectionTimeMs, instructions, - protocolVersion: DEFAULT_MCP_CONFIG.protocolVersion, + protocolVersion, requestTimeoutMs: serverConfig.requestTimeoutMs ?? DEFAULT_MCP_CONFIG.requestTimeoutSeconds * 1000, serverCapabilities, @@ -594,6 +608,7 @@ export class MCPService { try { // Terminate the session first for streamable-http transports to cleanly // close streams, matching the inspector's disconnect flow. + // No request is sent when the server gave no session (stateless protocol). if (connection.transport instanceof StreamableHTTPClientTransport) { await connection.transport.terminateSession(); } @@ -816,7 +831,11 @@ export class MCPService { */ static async subscribeResource(connection: MCPConnection, uri: string): Promise { try { - await connection.client.subscribeResource({ uri }); + if (connection.client.getProtocolEra() === 'modern') { + await this.listenToResource(connection, uri); + } else { + await connection.client.subscribeResource({ uri }); + } console.log(`[MCPService][${connection.serverName}] Subscribed to resource: ${uri}`); } catch (error) { @@ -859,7 +878,12 @@ export class MCPService { */ static async unsubscribeResource(connection: MCPConnection, uri: string): Promise { try { - await connection.client.unsubscribeResource({ uri }); + if (connection.client.getProtocolEra() === 'modern') { + await connection.resourceSubscriptions?.get(uri)?.close(); + connection.resourceSubscriptions?.delete(uri); + } else { + await connection.client.unsubscribeResource({ uri }); + } if (import.meta.env.DEV && import.meta.env.VITE_DEBUG) { console.log(`[MCPService][${connection.serverName}] Unsubscribed from resource: ${uri}`); @@ -1250,6 +1274,27 @@ export class MCPService { return hints; } + /** + * Open a subscriptions/listen stream for one resource. + * The stateless protocol has no resources/subscribe request. + */ + private static async listenToResource(connection: MCPConnection, uri: string): Promise { + if (connection.resourceSubscriptions?.has(uri)) { + return; + } + + const subscription = await connection.client.listen({ resourceSubscriptions: [uri] }); + + if (!subscription.honoredFilter.resourceSubscriptions?.includes(uri)) { + await subscription.close(); + + throw new Error(`Server did not accept the subscription to ${uri}`); + } + + connection.resourceSubscriptions ??= new Map(); + connection.resourceSubscriptions.set(uri, subscription); + } + /** * Walk a cursor-paginated MCP list endpoint, collecting every page. */ diff --git a/ui/apps/chat/src/lib/types/mcp.d.ts b/ui/apps/chat/src/lib/types/mcp.d.ts index 7c70854a73f5..559d406edd36 100644 --- a/ui/apps/chat/src/lib/types/mcp.d.ts +++ b/ui/apps/chat/src/lib/types/mcp.d.ts @@ -5,6 +5,7 @@ import type { ClientCapabilities as SDKClientCapabilities, GetPromptResult, Implementation as SDKImplementation, + McpSubscription, Prompt, PromptMessage, ServerCapabilities as SDKServerCapabilities, @@ -137,6 +138,8 @@ export interface MCPConnection { connectionTimeMs: number; /** Configured timeout for individual requests (tool calls, etc.) in milliseconds */ requestTimeoutMs: number; + /** Open resource update streams by URI, stateless protocol only */ + resourceSubscriptions?: Map; } /** diff --git a/ui/apps/chat/tests/unit/mcp-service-protocol.test.ts b/ui/apps/chat/tests/unit/mcp-service-protocol.test.ts new file mode 100644 index 000000000000..970641cbbea0 --- /dev/null +++ b/ui/apps/chat/tests/unit/mcp-service-protocol.test.ts @@ -0,0 +1,223 @@ +import { + createMcpHandler, + McpServer, + WebStandardStreamableHTTPServerTransport +} from '@modelcontextprotocol/server'; +import { MCPConnectionPhase, MCPTransportType } from '#lib/enums/index.ts'; +import { MCPService } from '#lib/extensions/mcp/services/mcp.service.ts'; +import type { MCPConnectionLog, MCPServerConfig } from '#lib/types/index.ts'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +const RESOURCE_URI = 'config://app'; +const HTTP_CONFIG: MCPServerConfig = { + transport: MCPTransportType.STREAMABLE_HTTP, + url: 'https://example.com/mcp' +}; + +interface RecordedRequest { + method: string; + rpcMethod?: string; + sessionId: string | null; +} + +function buildServer(): McpServer { + const server = new McpServer( + { name: 'test-server', version: '1.0.0' }, + { capabilities: { resources: { subscribe: true } } } + ); + + server.registerTool('ping', { description: 'Reply with pong' }, async () => ({ + content: [{ text: 'pong', type: 'text' }] + })); + server.registerResource('config', RESOURCE_URI, {}, async (uri) => ({ + contents: [{ text: '{}', uri: uri.href }] + })); + + return server; +} + +// Sends the client's fetch calls to an in-process MCP server and records them +function serveWith(handle: (request: Request) => Promise): RecordedRequest[] { + const requests: RecordedRequest[] = []; + + vi.stubGlobal('fetch', async (input: RequestInfo | URL, init?: RequestInit) => { + const request = new Request(input, init); + const body = typeof init?.body === 'string' ? JSON.parse(init.body) : undefined; + + requests.push({ + method: request.method, + rpcMethod: body?.method, + sessionId: request.headers.get('mcp-session-id') + }); + + return handle(request); + }); + + return requests; +} + +describe('MCPService protocol negotiation', () => { + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + }); + + it('uses the stateless protocol when the server speaks it', async () => { + const handler = createMcpHandler(buildServer, { legacy: 'reject' }); + const requests = serveWith((request) => handler.fetch(request)); + const logs: MCPConnectionLog[] = []; + const onToolsChanged = vi.fn(); + const connection = await MCPService.connect( + 'test-server', + HTTP_CONFIG, + undefined, + undefined, + (_phase, log) => logs.push(log), + { tools: { onChanged: onToolsChanged } } + ); + + expect(connection.protocolVersion).toBe('2026-07-28'); + expect(connection.transport.sessionId).toBeUndefined(); + expect(connection.serverInfo?.name).toBe('test-server'); + expect(connection.tools.map((tool) => tool.name)).toEqual(['ping']); + expect(requests.map((request) => request.rpcMethod)).toEqual([ + 'server/discover', + 'subscriptions/listen', + 'tools/list' + ]); + expect( + logs.find((log) => log.phase === MCPConnectionPhase.CAPABILITIES_EXCHANGED)?.message + ).toBe('Capabilities exchanged successfully (protocol 2026-07-28, stateless)'); + + await expect(MCPService.callTool(connection, { arguments: {}, name: 'ping' })).resolves.toEqual( + { content: 'pong', isError: false } + ); + + // list changes arrive on the subscriptions/listen stream + handler.notify.toolsChanged(); + await vi.waitFor(() => expect(onToolsChanged).toHaveBeenCalledTimes(1)); + expect(onToolsChanged.mock.calls[0][1]).toHaveLength(1); + + await MCPService.subscribeResource(connection, RESOURCE_URI); + + expect(requests.at(-1)?.rpcMethod).toBe('subscriptions/listen'); + expect(connection.resourceSubscriptions?.has(RESOURCE_URI)).toBe(true); + + await MCPService.unsubscribeResource(connection, RESOURCE_URI); + + expect(connection.resourceSubscriptions?.size).toBe(0); + + await MCPService.disconnect(connection); + await handler.close(); + + expect(requests.every((request) => request.method === 'POST')).toBe(true); + expect(requests.every((request) => request.sessionId === null)).toBe(true); + expect(requests.some((request) => request.rpcMethod === 'initialize')).toBe(false); + }); + + it('falls back to the session handshake on an older server', async () => { + const server = buildServer(); + const serverTransport = new WebStandardStreamableHTTPServerTransport({ + enableJsonResponse: true, + sessionIdGenerator: () => 'session-1' + }); + + // McpServer has no handler for the session-only subscribe request + server.server.setRequestHandler('resources/subscribe', async () => ({})); + await server.connect(serverTransport); + + const requests = serveWith((request) => serverTransport.handleRequest(request)); + const logs: MCPConnectionLog[] = []; + const connection = await MCPService.connect( + 'test-server', + HTTP_CONFIG, + undefined, + undefined, + (_phase, log) => logs.push(log) + ); + + expect(connection.protocolVersion).toMatch(/^2025-/); + expect(connection.transport.sessionId).toBe('session-1'); + expect(connection.tools.map((tool) => tool.name)).toEqual(['ping']); + expect(requests.slice(0, 3).map((request) => request.rpcMethod)).toEqual([ + 'server/discover', + 'initialize', + 'notifications/initialized' + ]); + expect( + logs.find((log) => log.phase === MCPConnectionPhase.CAPABILITIES_EXCHANGED)?.message + ).toBe( + `Capabilities exchanged successfully (protocol ${connection.protocolVersion}, initialize handshake)` + ); + + await expect(MCPService.callTool(connection, { arguments: {}, name: 'ping' })).resolves.toEqual( + { content: 'pong', isError: false } + ); + + await MCPService.subscribeResource(connection, RESOURCE_URI); + + expect(requests.at(-1)).toEqual({ + method: 'POST', + rpcMethod: 'resources/subscribe', + sessionId: 'session-1' + }); + expect(connection.resourceSubscriptions).toBeUndefined(); + + await MCPService.disconnect(connection); + await server.close(); + + expect(requests.at(-1)).toEqual({ + method: 'DELETE', + rpcMethod: undefined, + sessionId: 'session-1' + }); + }); + + it('does not probe a WebSocket server', async () => { + const sent: string[] = []; + + class FakeWebSocket { + onclose?: () => void; + onmessage?: (event: { data: string }) => void; + onopen?: () => void; + + close() { + this.onclose?.(); + } + + constructor() { + queueMicrotask(() => this.onopen?.()); + } + + send(data: string) { + const message = JSON.parse(data); + + sent.push(message.method); + + if (message.method !== 'initialize') return; + + const result = { + capabilities: {}, + protocolVersion: message.params.protocolVersion, + serverInfo: { name: 'ws-server', version: '1.0.0' } + }; + + queueMicrotask(() => + this.onmessage?.({ data: JSON.stringify({ id: message.id, jsonrpc: '2.0', result }) }) + ); + } + } + + vi.stubGlobal('WebSocket', FakeWebSocket); + + const connection = await MCPService.connect('ws-server', { + transport: MCPTransportType.WEBSOCKET, + url: 'ws://example.com/mcp' + }); + + expect(sent).toEqual(['initialize', 'notifications/initialized']); + expect(connection.protocolVersion).toMatch(/^2025-/); + + await MCPService.disconnect(connection); + }); +}); From c3c5be4e486dc23ec0450a92d09b0695ef54a9c9 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Fri, 13 Nov 2026 00:41:23 +0100 Subject: [PATCH 11/19] ui: keep stateless MCP connections as dependable as session ones - A failed stateless probe (HTTP 5xx, unusable reply, no reply) is retried once with the session handshake, with a warning in the connection log. Authorization failures are not retried. - A subscriptions/listen stream that the server or a proxy ends is opened again with a backoff, until the connection is closed. - List calls always reach the server, the SDK cache cannot answer them. - A 404 means an expired session only on a connection that has a session. - Remove the unused protocol version constant and update comments that described the session flow as the only one. Assisted-by: Claude (Opus 5.5 Medium) --- .../chat/src/lib/constants/mcp.constants.ts | 8 - .../extensions/mcp/services/mcp.service.ts | 187 +++++++++++-- .../lib/extensions/mcp/stores/index.svelte.ts | 8 +- ui/apps/chat/src/lib/types/mcp.d.ts | 1 - ui/apps/chat/tests/stories/mcp/fixtures.ts | 10 +- .../tests/unit/mcp-service-protocol.test.ts | 247 ++++++++++++++++-- ui/apps/chat/tests/unit/mcp-service.test.ts | 25 +- 7 files changed, 431 insertions(+), 55 deletions(-) diff --git a/ui/apps/chat/src/lib/constants/mcp.constants.ts b/ui/apps/chat/src/lib/constants/mcp.constants.ts index fffbdc9de96e..9a3dd1fde444 100644 --- a/ui/apps/chat/src/lib/constants/mcp.constants.ts +++ b/ui/apps/chat/src/lib/constants/mcp.constants.ts @@ -21,18 +21,10 @@ export const MCP_ALLOWED_ICON_MIME_TYPES = new Set([ MimeTypeImage.ICO_MICROSOFT ]); -/** - * MCP specification version this client targets. - * Update when the upstream MCP spec introduces a new stable version: - * https://spec.modelcontextprotocol.io/ - */ -export const MCP_PROTOCOL_VERSION = '2025-06-18'; - export const DEFAULT_MCP_CONFIG = { capabilities: { tools: { listChanged: true } } as ClientCapabilities, clientInfo: { name: MCP_CLIENT_NAME, version: DEFAULT_CLIENT_VERSION } as Implementation, connectionTimeoutMs: 10_000, // 10 seconds for connection establishment - protocolVersion: MCP_PROTOCOL_VERSION, requestTimeoutSeconds: 300 // 5 minutes for long-running tools } as const; diff --git a/ui/apps/chat/src/lib/extensions/mcp/services/mcp.service.ts b/ui/apps/chat/src/lib/extensions/mcp/services/mcp.service.ts index 730add62306a..48b330ee6e36 100644 --- a/ui/apps/chat/src/lib/extensions/mcp/services/mcp.service.ts +++ b/ui/apps/chat/src/lib/extensions/mcp/services/mcp.service.ts @@ -11,7 +11,10 @@ import { Client, type GetPromptResult, type ListChangedHandlers, + type McpSubscription, type Prompt, + SdkError, + SdkErrorCode, SdkHttpError, SSEClientTransport, StreamableHTTPClientTransport, @@ -25,6 +28,7 @@ import { DEFAULT_IMAGE_MIME_TYPE, DEFAULT_MCP_CONFIG, HEADERS, + MCP_RECONNECT, NEWLINE } from '#lib/constants/index.ts'; import { @@ -67,6 +71,10 @@ import { throwIfAborted } from '#lib/utils/index.ts'; +// The stores decide when to list again, so a list call must reach the server. +// On a stateless connection the SDK can answer it from a cache the server set a TTL for. +const FRESH_LIST = { cacheMode: 'refresh' } as const; + interface ToolResultContentItem { type: string; text?: string; @@ -127,7 +135,7 @@ export class MCPService { } // Let session-expired errors propagate unwrapped for reconnection handling - if (this.isSessionExpiredError(error)) { + if (this.isSessionExpiredError(error, connection)) { throw error; } @@ -213,11 +221,12 @@ export class MCPService { console.log(`[MCPService][${serverName}] Creating transport...`); } - const { - stopPhaseLogging, - transport, - type: transportType - } = this.createTransport(serverName, serverConfig, (log) => onPhase?.(log.phase, log)); + const createdTransport = this.createTransport(serverName, serverConfig, (log) => + onPhase?.(log.phase, log) + ); + const transportType = createdTransport.type; + + let { stopPhaseLogging, transport } = createdTransport; // Setup WebSocket reconnection handler if (transportType === MCPTransportType.WEBSOCKET) { @@ -241,6 +250,8 @@ export class MCPService { // server/discover, fall back to the initialize handshake for older servers. // SSE and WebSocket servers are session-only, a probe there can only fail the connection. const negotiatesProtocol = transportType === MCPTransportType.STREAMABLE_HTTP; + const handshakeTimeoutMs = + serverConfig.handshakeTimeoutMs ?? DEFAULT_MCP_CONFIG.connectionTimeoutMs; const client = new Client( { name: effectiveClientInfo.name, @@ -249,7 +260,11 @@ export class MCPService { { capabilities: effectiveCapabilities, listChanged: listChangedHandlers, - versionNegotiation: { mode: negotiatesProtocol ? 'auto' : 'legacy' } + versionNegotiation: { + mode: negotiatesProtocol ? 'auto' : 'legacy', + // half the handshake time, the rest is for the session handshake retry below + probe: { timeoutMs: handshakeTimeoutMs / 2 } + } } ); const runtimeErrorHandler = (error: Error) => { @@ -303,9 +318,6 @@ export class MCPService { // which can hang forever on an unreachable host (SSE endpoint wait, WebSocket // handshake, proxied fetch). This race bounds the whole handshake and closes // the transport on expiry so the underlying fetch or socket is aborted. - const handshakeTimeoutMs = - serverConfig.handshakeTimeoutMs ?? DEFAULT_MCP_CONFIG.connectionTimeoutMs; - try { let handshakeTimer: ReturnType | undefined; @@ -321,6 +333,35 @@ export class MCPService { client.connect(transport, { timeout: handshakeTimeoutMs }), handshakeDeadline ]); + } catch (error) { + if (!negotiatesProtocol || !this.isProbeFailure(error)) { + throw error; + } + + // The probe got no usable answer, which says nothing about the server. + // A server that only knows the session handshake can fail this way, so try that once. + onPhase?.( + MCPConnectionPhase.INITIALIZING, + this.createLog( + MCPConnectionPhase.INITIALIZING, + `Stateless protocol probe failed (${ + error instanceof Error ? error.message : String(error) + }), using the session handshake`, + MCPLogLevel.WARN, + { error: this.summarizeError(error) } + ) + ); + + // the SDK closed the probed transport + stopPhaseLogging(); + ({ stopPhaseLogging, transport } = this.createTransport(serverName, serverConfig, (log) => + onPhase?.(log.phase, log) + )); + + await Promise.race([ + client.connect(transport, { prior: { kind: 'legacy' }, timeout: handshakeTimeoutMs }), + handshakeDeadline + ]); } finally { clearTimeout(handshakeTimer); } @@ -374,6 +415,11 @@ export class MCPService { const protocolVersion = client.getNegotiatedProtocolVersion(); const isStateless = client.getProtocolEra() === 'modern'; + // list-changed notifications of a stateless connection + if (client.autoOpenedSubscription) { + void this.keepListening(serverName, client, client.autoOpenedSubscription); + } + // Phase: Capabilities exchanged onPhase?.( MCPConnectionPhase.CAPABILITIES_EXCHANGED, @@ -658,12 +704,19 @@ export class MCPService { * Detect if an error indicates an expired/invalidated MCP session. * Per MCP spec 2025-11-25: HTTP 404 means session invalidated, client MUST * discard its session ID and start a new session with a fresh initialize request. + * A connection without a session (stateless protocol) has nothing to expire: + * there a 404 is a failed request like any other. * * @param error - The caught error to inspect - * @returns true if the error is a StreamableHTTP 404 (session not found) + * @param connection - The connection the request was sent on + * @returns true if the error is a StreamableHTTP 404 on a connection that has a session */ - static isSessionExpiredError(error: unknown): boolean { - return error instanceof SdkHttpError && error.status === 404; + static isSessionExpiredError(error: unknown, connection: MCPConnection): boolean { + return ( + error instanceof SdkHttpError && + error.status === 404 && + connection.transport.sessionId !== undefined + ); } /** @@ -701,12 +754,12 @@ export class MCPService { */ static async listPrompts(connection: MCPConnection): Promise { try { - const result = await connection.client.listPrompts(); + const result = await connection.client.listPrompts(undefined, FRESH_LIST); return result.prompts ?? []; } catch (error) { // Let session-expired errors propagate for reconnection handling - if (this.isSessionExpiredError(error)) { + if (this.isSessionExpiredError(error, connection)) { throw error; } @@ -727,14 +780,17 @@ export class MCPService { cursor?: string ): Promise<{ resources: MCPResource[]; nextCursor?: string }> { try { - const result = await connection.client.listResources(cursor ? { cursor } : undefined); + const result = await connection.client.listResources( + cursor ? { cursor } : undefined, + FRESH_LIST + ); return { nextCursor: result.nextCursor, resources: (result.resources ?? []) as MCPResource[] }; } catch (error) { - if (this.isSessionExpiredError(error)) { + if (this.isSessionExpiredError(error, connection)) { throw error; } @@ -755,14 +811,17 @@ export class MCPService { cursor?: string ): Promise<{ resourceTemplates: MCPResourceTemplate[]; nextCursor?: string }> { try { - const result = await connection.client.listResourceTemplates(cursor ? { cursor } : undefined); + const result = await connection.client.listResourceTemplates( + cursor ? { cursor } : undefined, + FRESH_LIST + ); return { nextCursor: result.nextCursor, resourceTemplates: (result.resourceTemplates ?? []) as MCPResourceTemplate[] }; } catch (error) { - if (this.isSessionExpiredError(error)) { + if (this.isSessionExpiredError(error, connection)) { throw error; } @@ -784,12 +843,12 @@ export class MCPService { */ static async listTools(connection: MCPConnection): Promise { try { - const result = await connection.client.listTools(); + const result = await connection.client.listTools(undefined, FRESH_LIST); return result.tools ?? []; } catch (error) { // Let session-expired errors propagate for reconnection handling - if (this.isSessionExpiredError(error)) { + if (this.isSessionExpiredError(error, connection)) { throw error; } @@ -1274,6 +1333,76 @@ export class MCPService { return hints; } + /** + * Whether a negotiated connect failed on the server/discover probe itself: + * HTTP 5xx, an unusable reply or no reply in time. A 401 or 403 has its own + * error code and is not a probe failure. Neither is a probe that was aborted. + */ + private static isProbeFailure(error: unknown): boolean { + return ( + error instanceof SdkError && + (error.code === SdkErrorCode.EraNegotiationFailed || + error.code === SdkErrorCode.RequestTimeout) && + !isAbortError(error.cause) + ); + } + + /** + * Keep a subscriptions/listen stream open on a stateless connection. + * The SDK reports that a stream ended but does not listen again, so a stream cut by + * the server or a proxy would stop its notifications for good. + * Stops when the subscription or the client is closed. + * + * @param accept - Takes the reopened stream in place of the closed one, false to drop it + */ + private static async keepListening( + serverName: string, + client: Client, + subscription: McpSubscription, + accept: (closed: McpSubscription, reopened: McpSubscription) => boolean = () => true + ): Promise { + let delay = MCP_RECONNECT.INITIAL_DELAY; + + while (true) { + const openedAt = performance.now(); + + // 'local' is our own close() + if ((await subscription.closed) === 'local') { + return; + } + + // a stream that stayed open was cut, not refused: start the backoff again + if (performance.now() - openedAt > MCP_RECONNECT.MAX_DELAY) { + delay = MCP_RECONNECT.INITIAL_DELAY; + } + + await new Promise((resolve) => setTimeout(resolve, delay)); + delay = Math.min(delay * MCP_RECONNECT.BACKOFF_MULTIPLIER, MCP_RECONNECT.MAX_DELAY); + + // closing the client ends its streams too, and a closed client has no negotiated protocol + if (!client.transport || client.getProtocolEra() !== 'modern') { + return; + } + + try { + const reopened = await client.listen(subscription.honoredFilter); + + if (!accept(subscription, reopened)) { + await reopened.close(); + + return; + } + + subscription = reopened; + } catch (error) { + console.warn( + `[MCPService][${serverName}] Failed to reopen the subscriptions/listen stream:`, + error + ); + } + } + } + /** * Open a subscriptions/listen stream for one resource. * The stateless protocol has no resources/subscribe request. @@ -1293,6 +1422,22 @@ export class MCPService { connection.resourceSubscriptions ??= new Map(); connection.resourceSubscriptions.set(uri, subscription); + + void this.keepListening( + connection.serverName, + connection.client, + subscription, + (closed, reopened) => { + // unsubscribed, or subscribed again, while the stream was down + if (connection.resourceSubscriptions?.get(uri) !== closed) { + return false; + } + + connection.resourceSubscriptions.set(uri, reopened); + + return true; + } + ); } /** diff --git a/ui/apps/chat/src/lib/extensions/mcp/stores/index.svelte.ts b/ui/apps/chat/src/lib/extensions/mcp/stores/index.svelte.ts index c3ccabb743f1..2dab8966ecc7 100644 --- a/ui/apps/chat/src/lib/extensions/mcp/stores/index.svelte.ts +++ b/ui/apps/chat/src/lib/extensions/mcp/stores/index.svelte.ts @@ -367,7 +367,7 @@ class MCPStore implements McpHealthHost { try { return await MCPService.callTool(connection, { arguments: args, name: toolName }, signal); } catch (error) { - if (MCPService.isSessionExpiredError(error)) { + if (MCPService.isSessionExpiredError(error, connection)) { await this.reconnectServer(serverName); const newConnection = this.connections.get(serverName); @@ -919,7 +919,7 @@ class MCPStore implements McpHealthHost { } } - /** Store a server config so auto-reconnect can rebuild the session. */ + /** Store a server config so auto-reconnect can rebuild the connection. */ registerServerConfig(name: string, config: MCPServerConfig): void { this.serverConfigs.set(name, config); } @@ -927,7 +927,7 @@ class MCPStore implements McpHealthHost { /** * Release a connection reference. * By default, keeps connections alive for reuse (shutdownIfUnused=false). - * MCP spec encourages long-lived sessions to avoid reconnection overhead. + * A kept connection saves the handshake, and the session of a server that has one. */ async releaseConnection(shutdownIfUnused = false): Promise { this.activeFlowCount = Math.max(0, this.activeFlowCount - 1); @@ -1115,7 +1115,6 @@ class MCPStore implements McpHealthHost { return { capabilities: DEFAULT_MCP_CONFIG.capabilities, clientInfo: DEFAULT_MCP_CONFIG.clientInfo, - protocolVersion: DEFAULT_MCP_CONFIG.protocolVersion, requestTimeoutMs: this.getRequestTimeoutMs(), servers }; @@ -1367,6 +1366,7 @@ class MCPStore implements McpHealthHost { * Immediately reconnect to a server by creating a fresh transport and session. * Used when a session-expired error (HTTP 404) is detected during tool execution. * Per MCP spec 2025-11-25: client MUST discard session ID and re-initialize. + * Only connections with a session get here, a stateless connection has none to expire. * * Unlike autoReconnect (which uses exponential backoff for connectivity issues), * this performs a single immediate reconnection attempt since the server is known diff --git a/ui/apps/chat/src/lib/types/mcp.d.ts b/ui/apps/chat/src/lib/types/mcp.d.ts index 559d406edd36..48fb5160f048 100644 --- a/ui/apps/chat/src/lib/types/mcp.d.ts +++ b/ui/apps/chat/src/lib/types/mcp.d.ts @@ -195,7 +195,6 @@ export type MCPServerConfig = { export type MCPClientConfig = { servers: Record; - protocolVersion?: string; capabilities?: ClientCapabilities; clientInfo?: Implementation; requestTimeoutMs?: number; diff --git a/ui/apps/chat/tests/stories/mcp/fixtures.ts b/ui/apps/chat/tests/stories/mcp/fixtures.ts index dc1431b12dce..94e87e4373a1 100644 --- a/ui/apps/chat/tests/stories/mcp/fixtures.ts +++ b/ui/apps/chat/tests/stories/mcp/fixtures.ts @@ -28,8 +28,12 @@ const log = ( export const connectionLogs: MCPConnectionLog[] = [ log(0, MCPConnectionPhase.TRANSPORT_CREATING, 'Creating streamable HTTP transport'), log(42, MCPConnectionPhase.TRANSPORT_READY, 'Transport ready'), - log(118, MCPConnectionPhase.INITIALIZING, 'Sending initialize request'), - log(204, MCPConnectionPhase.CAPABILITIES_EXCHANGED, 'Negotiated protocol 2025-06-18'), + log(118, MCPConnectionPhase.INITIALIZING, 'Negotiating protocol version...'), + log( + 204, + MCPConnectionPhase.CAPABILITIES_EXCHANGED, + 'Capabilities exchanged successfully (protocol 2026-07-28, stateless)' + ), log(266, MCPConnectionPhase.LISTING_TOOLS, 'Listing tools'), log(301, MCPConnectionPhase.CONNECTED, 'Connected with 3 tools') ]; @@ -69,7 +73,7 @@ const states: Record = { capabilities, connectionTimeMs: 301, logs: connectionLogs, - protocolVersion: '2025-06-18', + protocolVersion: '2026-07-28', serverInfo: { name: 'docs-search', version: '1.4.0' }, status: HealthCheckStatus.SUCCESS, tools: [ diff --git a/ui/apps/chat/tests/unit/mcp-service-protocol.test.ts b/ui/apps/chat/tests/unit/mcp-service-protocol.test.ts index 970641cbbea0..48d7af127d09 100644 --- a/ui/apps/chat/tests/unit/mcp-service-protocol.test.ts +++ b/ui/apps/chat/tests/unit/mcp-service-protocol.test.ts @@ -1,9 +1,11 @@ import { createMcpHandler, McpServer, + type ServerOptions, WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server'; -import { MCPConnectionPhase, MCPTransportType } from '#lib/enums/index.ts'; +import { MCP_RECONNECT } from '#lib/constants/index.ts'; +import { MCPConnectionPhase, MCPLogLevel, MCPTransportType } from '#lib/enums/index.ts'; import { MCPService } from '#lib/extensions/mcp/services/mcp.service.ts'; import type { MCPConnectionLog, MCPServerConfig } from '#lib/types/index.ts'; import { afterEach, describe, expect, it, vi } from 'vitest'; @@ -20,10 +22,10 @@ interface RecordedRequest { sessionId: string | null; } -function buildServer(): McpServer { +function buildServer(options?: ServerOptions): McpServer { const server = new McpServer( { name: 'test-server', version: '1.0.0' }, - { capabilities: { resources: { subscribe: true } } } + { capabilities: { resources: { subscribe: true } }, ...options } ); server.registerTool('ping', { description: 'Reply with pong' }, async () => ({ @@ -36,8 +38,25 @@ function buildServer(): McpServer { return server; } +// An older server: 2025-era protocol with a session +async function startSessionServer() { + const server = buildServer(); + const transport = new WebStandardStreamableHTTPServerTransport({ + enableJsonResponse: true, + sessionIdGenerator: () => 'session-1' + }); + + // McpServer has no handler for the session-only subscribe request + server.server.setRequestHandler('resources/subscribe', async () => ({})); + await server.connect(transport); + + return { handle: (request: Request) => transport.handleRequest(request), server }; +} + // Sends the client's fetch calls to an in-process MCP server and records them -function serveWith(handle: (request: Request) => Promise): RecordedRequest[] { +function serveWith( + handle: (request: Request, rpcMethod?: string) => Promise +): RecordedRequest[] { const requests: RecordedRequest[] = []; vi.stubGlobal('fetch', async (input: RequestInfo | URL, init?: RequestInit) => { @@ -50,12 +69,40 @@ function serveWith(handle: (request: Request) => Promise): RecordedReq sessionId: request.headers.get('mcp-session-id') }); - return handle(request); + return handle(request, body?.method); }); return requests; } +// Passes a response on with a body the test can end, like a proxy that cuts a long stream +function cuttable(response: Response): { cut: () => void; response: Response } { + const reader = response.body!.getReader(); + + let cut = () => {}; + + const body = new ReadableStream({ + async pull(controller) { + const { done, value } = await reader.read(); + + try { + if (done) controller.close(); + else controller.enqueue(value); + } catch { + // already cut + } + }, + start(controller) { + cut = () => controller.close(); + } + }); + + return { + cut: () => cut(), + response: new Response(body, { headers: response.headers, status: response.status }) + }; +} + describe('MCPService protocol negotiation', () => { afterEach(() => { vi.restoreAllMocks(); @@ -63,7 +110,7 @@ describe('MCPService protocol negotiation', () => { }); it('uses the stateless protocol when the server speaks it', async () => { - const handler = createMcpHandler(buildServer, { legacy: 'reject' }); + const handler = createMcpHandler(() => buildServer(), { legacy: 'reject' }); const requests = serveWith((request) => handler.fetch(request)); const logs: MCPConnectionLog[] = []; const onToolsChanged = vi.fn(); @@ -116,17 +163,8 @@ describe('MCPService protocol negotiation', () => { }); it('falls back to the session handshake on an older server', async () => { - const server = buildServer(); - const serverTransport = new WebStandardStreamableHTTPServerTransport({ - enableJsonResponse: true, - sessionIdGenerator: () => 'session-1' - }); - - // McpServer has no handler for the session-only subscribe request - server.server.setRequestHandler('resources/subscribe', async () => ({})); - await server.connect(serverTransport); - - const requests = serveWith((request) => serverTransport.handleRequest(request)); + const { handle, server } = await startSessionServer(); + const requests = serveWith(handle); const logs: MCPConnectionLog[] = []; const connection = await MCPService.connect( 'test-server', @@ -220,4 +258,179 @@ describe('MCPService protocol negotiation', () => { await MCPService.disconnect(connection); }); + + it('retries with the session handshake when the probe gets a server error', async () => { + const { handle, server } = await startSessionServer(); + const requests = serveWith(async (request, rpcMethod) => + rpcMethod === 'server/discover' ? new Response('oops', { status: 500 }) : handle(request) + ); + const logs: MCPConnectionLog[] = []; + const connection = await MCPService.connect( + 'test-server', + HTTP_CONFIG, + undefined, + undefined, + (_phase, log) => logs.push(log) + ); + + expect(connection.protocolVersion).toMatch(/^2025-/); + expect(connection.transport.sessionId).toBe('session-1'); + expect(connection.tools.map((tool) => tool.name)).toEqual(['ping']); + expect(requests.slice(0, 3).map((request) => request.rpcMethod)).toEqual([ + 'server/discover', + 'initialize', + 'notifications/initialized' + ]); + expect( + logs.filter( + (log) => + log.level === MCPLogLevel.WARN && + log.message === + 'Stateless protocol probe failed (Version negotiation failed: the server answered the probe with HTTP 500), using the session handshake' + ) + ).toHaveLength(1); + + await MCPService.disconnect(connection); + await server.close(); + }); + + it('retries with the session handshake when the probe gets no reply', async () => { + const { handle, server } = await startSessionServer(); + const requests = serveWith(async (request, rpcMethod) => + rpcMethod === 'server/discover' ? new Response(null, { status: 202 }) : handle(request) + ); + const connection = await MCPService.connect('test-server', { + ...HTTP_CONFIG, + handshakeTimeoutMs: 1000 + }); + + expect(connection.transport.sessionId).toBe('session-1'); + expect(requests.slice(0, 2).map((request) => request.rpcMethod)).toEqual([ + 'server/discover', + 'initialize' + ]); + + await MCPService.disconnect(connection); + await server.close(); + }); + + it('does not retry when the server asks for authorization', async () => { + const requests = serveWith(async () => new Response('Unauthorized', { status: 401 })); + const logs: MCPConnectionLog[] = []; + + await expect( + MCPService.connect('test-server', HTTP_CONFIG, undefined, undefined, (_phase, log) => + logs.push(log) + ) + ).rejects.toMatchObject({ status: 401 }); + + expect(requests.map((request) => request.rpcMethod)).toEqual(['server/discover']); + expect(logs.some((log) => log.message.startsWith('Stateless protocol probe failed'))).toBe( + false + ); + }); + + it('does not retry a failed session handshake', async () => { + const requests = serveWith( + async (_request, rpcMethod) => + new Response('oops', { status: rpcMethod === 'server/discover' ? 404 : 500 }) + ); + + await expect(MCPService.connect('test-server', HTTP_CONFIG)).rejects.toMatchObject({ + status: 500 + }); + + expect(requests.map((request) => request.rpcMethod)).toEqual(['server/discover', 'initialize']); + }); +}); + +describe('MCPService stateless connection', () => { + const initialDelay = MCP_RECONNECT.INITIAL_DELAY; + + afterEach(() => { + MCP_RECONNECT.INITIAL_DELAY = initialDelay; + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + }); + + it('reopens a listen stream that was cut and stops when disconnected', async () => { + MCP_RECONNECT.INITIAL_DELAY = 20; + + const handler = createMcpHandler(() => buildServer(), { legacy: 'reject' }); + const streams: { cut: () => void }[] = []; + const requests = serveWith(async (request, rpcMethod) => { + const response = await handler.fetch(request); + + if (rpcMethod !== 'subscriptions/listen') return response; + + const stream = cuttable(response); + + streams.push(stream); + + return stream.response; + }); + const listens = () => + requests.filter((request) => request.rpcMethod === 'subscriptions/listen').length; + const onToolsChanged = vi.fn(); + const warn = vi.spyOn(console, 'warn'); + const connection = await MCPService.connect( + 'test-server', + HTTP_CONFIG, + undefined, + undefined, + undefined, + { tools: { onChanged: onToolsChanged } } + ); + + expect(listens()).toBe(1); + + // the list-changed stream + streams[0].cut(); + await vi.waitFor(() => expect(listens()).toBe(2)); + + handler.notify.toolsChanged(); + await vi.waitFor(() => expect(onToolsChanged).toHaveBeenCalledTimes(1)); + + // a resource stream + await MCPService.subscribeResource(connection, RESOURCE_URI); + + const subscription = connection.resourceSubscriptions?.get(RESOURCE_URI); + + expect(listens()).toBe(3); + + streams[2].cut(); + await vi.waitFor(() => expect(listens()).toBe(4)); + await vi.waitFor(() => + expect(connection.resourceSubscriptions?.get(RESOURCE_URI)).not.toBe(subscription) + ); + + await MCPService.unsubscribeResource(connection, RESOURCE_URI); + + expect(connection.resourceSubscriptions?.size).toBe(0); + + streams[1].cut(); + await MCPService.disconnect(connection); + await new Promise((resolve) => setTimeout(resolve, 100)); + + expect(listens()).toBe(4); + expect(warn).not.toHaveBeenCalled(); + + await handler.close(); + }); + + it('lists from the server again when the server allows a cached answer', async () => { + const handler = createMcpHandler( + () => buildServer({ cacheHints: { 'tools/list': { ttlMs: 60_000 } } }), + { legacy: 'reject' } + ); + const requests = serveWith((request) => handler.fetch(request)); + const connection = await MCPService.connect('test-server', HTTP_CONFIG); + + await MCPService.listTools(connection); + + expect(requests.filter((request) => request.rpcMethod === 'tools/list')).toHaveLength(2); + + await MCPService.disconnect(connection); + await handler.close(); + }); }); diff --git a/ui/apps/chat/tests/unit/mcp-service.test.ts b/ui/apps/chat/tests/unit/mcp-service.test.ts index 3b4ef7d30f6d..27b22259d86b 100644 --- a/ui/apps/chat/tests/unit/mcp-service.test.ts +++ b/ui/apps/chat/tests/unit/mcp-service.test.ts @@ -1,4 +1,4 @@ -import { Client } from '@modelcontextprotocol/client'; +import { Client, SdkErrorCode, SdkHttpError } from '@modelcontextprotocol/client'; import { CORS_PROXY } from '#lib/constants/index.ts'; import { MCPConnectionPhase, MCPTransportType } from '#lib/enums/index.ts'; import { MCPService } from '#lib/extensions/mcp/services/mcp.service.ts'; @@ -330,6 +330,29 @@ describe('MCPService', () => { ).toHaveLength(0); }); + it('treats a 404 as an expired session only on a connection with a session', async () => { + const notFound = new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, 'Not Found', { + status: 404, + statusText: 'Not Found' + }); + const connectionWith = (sessionId?: string) => + ({ + client: { callTool: vi.fn().mockRejectedValue(notFound) }, + requestTimeoutMs: 9000, + serverName: 'test-server', + transport: { sessionId } + }) as unknown as MCPConnection; + const params = { arguments: {}, name: 'tool' }; + + // propagates as it is, the store reconnects on it + await expect(MCPService.callTool(connectionWith('session-1'), params)).rejects.toBe(notFound); + await expect(MCPService.callTool(connectionWith(), params)).rejects.toThrow( + 'Tool "tool" execution failed on server "test-server": Not Found' + ); + expect(MCPService.isSessionExpiredError(notFound, connectionWith('session-1'))).toBe(true); + expect(MCPService.isSessionExpiredError(notFound, connectionWith())).toBe(false); + }); + it('falls back to structuredContent when content array is empty', async () => { const connection = { client: { From 38b6f0b0af4bd093366d9a70818be34ab5f8b4a6 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Fri, 13 Nov 2026 01:26:55 +0100 Subject: [PATCH 12/19] ui: end an MCP reconnect loop when its server is gone or the store shut down A reconnect loop kept the server's config it started with, so shutting the store down between two attempts did not stop it: the next attempt brought a connection back. Switching the MCP extension off shuts the store down, which made that reachable from Settings. The loop now checks that its config is still the registered one before each attempt and after a connect, and closes a connection that arrives too late. A shutdown with no live connection forgets the configs too. Assisted-by: Claude (Opus 5.5 Medium) --- .../lib/extensions/mcp/stores/index.svelte.ts | 14 ++++ .../tests/unit/mcp-reconnect-shutdown.test.ts | 80 +++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 ui/apps/chat/tests/unit/mcp-reconnect-shutdown.test.ts diff --git a/ui/apps/chat/src/lib/extensions/mcp/stores/index.svelte.ts b/ui/apps/chat/src/lib/extensions/mcp/stores/index.svelte.ts index 2dab8966ecc7..086c55741eb5 100644 --- a/ui/apps/chat/src/lib/extensions/mcp/stores/index.svelte.ts +++ b/ui/apps/chat/src/lib/extensions/mcp/stores/index.svelte.ts @@ -215,6 +215,9 @@ class MCPStore implements McpHealthHost { while (true) { await new Promise((resolve) => setTimeout(resolve, backoff)); + // the server was removed or the store shut down while this waited + if (this.serverConfigs.get(serverName) !== serverConfig) break; + console.log(`[MCPStore][${serverName}] Auto-reconnecting...`); try { @@ -256,6 +259,13 @@ class MCPStore implements McpHealthHost { ); const connection = await Promise.race([connectPromise, timeoutPromise]); + // same check after the connect: a connection nobody asked for any more is closed + if (this.serverConfigs.get(serverName) !== serverConfig) { + await MCPService.disconnect(connection).catch(() => {}); + + break; + } + this.connections.set(serverName, connection); // Rebuild tool index for this server @@ -986,6 +996,10 @@ class MCPStore implements McpHealthHost { } if (this.connections.size === 0) { + // nothing to close, but a reconnect loop may still be waiting on these + this.serverConfigs.clear(); + this.configSignature = null; + return; } diff --git a/ui/apps/chat/tests/unit/mcp-reconnect-shutdown.test.ts b/ui/apps/chat/tests/unit/mcp-reconnect-shutdown.test.ts new file mode 100644 index 000000000000..cec8c5e42116 --- /dev/null +++ b/ui/apps/chat/tests/unit/mcp-reconnect-shutdown.test.ts @@ -0,0 +1,80 @@ +// A reconnect loop waits between attempts. Shutting the store down, as +// switching the MCP extension off does, must end the loop instead of letting +// it bring a connection back. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('#lib/extensions/mcp/services/mcp.service.ts', () => ({ + MCPService: { + connect: vi.fn(), + disconnect: vi.fn(async () => {}) + } +})); + +import { MCP_RECONNECT } from '#lib/constants/index.ts'; +import { MCPService } from '#lib/extensions/mcp/services/mcp.service.ts'; +import { mcpStore } from '#lib/extensions/mcp/stores/index.svelte.ts'; +import type { MCPConnection, MCPServerConfig } from '#lib/types/index.ts'; + +const connectMock = vi.mocked(MCPService.connect); +const disconnectMock = vi.mocked(MCPService.disconnect); +const CONFIG = { url: 'https://docs.example.com/mcp' } as MCPServerConfig; +const CONNECTION = { serverName: 'docs', tools: [] } as unknown as MCPConnection; + +describe('mcpStore.autoReconnect', () => { + beforeEach(() => { + vi.useFakeTimers(); + vi.spyOn(console, 'log').mockImplementation(() => {}); + connectMock.mockReset(); + disconnectMock.mockClear(); + }); + + afterEach(async () => { + await mcpStore.shutdown(); + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it('reconnects a server that is still configured', async () => { + connectMock.mockResolvedValue(CONNECTION); + mcpStore.registerServerConfig('docs', CONFIG); + + const loop = mcpStore.autoReconnect('docs'); + + await vi.advanceTimersByTimeAsync(MCP_RECONNECT.INITIAL_DELAY); + await loop; + + expect(connectMock).toHaveBeenCalledOnce(); + expect(mcpStore.getConnections().get('docs')).toBe(CONNECTION); + }); + + it('gives up when the store shuts down while it waits', async () => { + mcpStore.registerServerConfig('docs', CONFIG); + + const loop = mcpStore.autoReconnect('docs'); + + await mcpStore.shutdown(); + await vi.advanceTimersByTimeAsync(MCP_RECONNECT.INITIAL_DELAY); + await loop; + + expect(connectMock).not.toHaveBeenCalled(); + expect(mcpStore.getConnections().size).toBe(0); + }); + + it('closes a connection that arrives after the store shut down', async () => { + let arrive: (connection: MCPConnection) => void = () => {}; + + connectMock.mockReturnValue(new Promise((resolve) => (arrive = resolve))); + mcpStore.registerServerConfig('docs', CONFIG); + + const loop = mcpStore.autoReconnect('docs'); + + await vi.advanceTimersByTimeAsync(MCP_RECONNECT.INITIAL_DELAY); + await mcpStore.shutdown(); + arrive(CONNECTION); + await loop; + + expect(disconnectMock).toHaveBeenCalledWith(CONNECTION); + expect(mcpStore.getConnections().size).toBe(0); + }); +}); From e8b0e5bb2d627440e4ab2d83824c21af95d191ba Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Fri, 13 Nov 2026 01:28:26 +0100 Subject: [PATCH 13/19] ui: hide an extension's settings fields while it is off A setting can now name the extension it belongs to. Its field is drawn only while that extension is running; the stored value and its default stay, so settings export, sync and migrations see the same keys either way. The MCP request timeout is the first such field: with MCP switched off it no longer shows in Settings. Assisted-by: Claude (Opus 5.5 Medium) --- .../SettingsChat/SettingsChatFields.svelte | 8 ++- .../src/lib/extensions/registry.svelte.ts | 5 ++ ui/apps/chat/src/lib/types/settings.d.ts | 4 ++ .../settings-extension-fields.svelte.test.ts | 65 +++++++++++++++++++ .../tests/unit/extensions-registry.test.ts | 2 + 5 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 ui/apps/chat/tests/client/settings-extension-fields.svelte.test.ts diff --git a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte index 4dc97756d7fa..9d864ca7cd49 100644 --- a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte +++ b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte @@ -14,6 +14,7 @@ SETTINGS_KEYS } from '#lib/constants/index.ts'; import { SettingsFieldType } from '#lib/enums/settings.enums.ts'; + import { extensions } from '#lib/extensions/index.ts'; import { modelsStore, serverStore, settingsStore } from '#lib/stores/index.ts'; import { normalizeFloatingPoint } from '#lib/utils/precision.ts'; import type { Component } from 'svelte'; @@ -31,6 +32,11 @@ // are read-only while discover is on let discoverOn = $derived(Boolean(localConfig[SETTINGS_KEYS.ENABLE_DISCOVER_MODELS])); + // a field that belongs to an extension shows only while that extension is on + let visibleFields = $derived( + fields.filter((field) => !field.extension || extensions.isActive(field.extension)) + ); + function isLockedField(key: string): boolean { return ( discoverOn && @@ -58,7 +64,7 @@ }); -{#each fields as field (field.key)} +{#each visibleFields as field (field.key)} {#if !field.dependsOn || Boolean(localConfig[field.dependsOn])}
{#if field.type === SettingsFieldType.INPUT} diff --git a/ui/apps/chat/src/lib/extensions/registry.svelte.ts b/ui/apps/chat/src/lib/extensions/registry.svelte.ts index ee2d59742fb0..a28939938f3b 100644 --- a/ui/apps/chat/src/lib/extensions/registry.svelte.ts +++ b/ui/apps/chat/src/lib/extensions/registry.svelte.ts @@ -85,6 +85,11 @@ class ExtensionRegistry { return result; } + /** True while the extension is running: switched on and activated without failing. */ + isActive(id: string): boolean { + return this._states.get(id) === 'active'; + } + isEnabled(id: string): boolean { const manifest = this._manifests.find((m) => m.id === id); diff --git a/ui/apps/chat/src/lib/types/settings.d.ts b/ui/apps/chat/src/lib/types/settings.d.ts index d58d91a5ef52..cca82cd997bd 100644 --- a/ui/apps/chat/src/lib/types/settings.d.ts +++ b/ui/apps/chat/src/lib/types/settings.d.ts @@ -38,6 +38,8 @@ export interface SettingsEntry { min?: number; max?: number; dependsOn?: string; + /** The extension the setting belongs to: its field shows only while that extension is on. The value and its default are kept either way. */ + extension?: string; sync?: { serverKey: string; paramType: SyncableParameterType; @@ -63,6 +65,8 @@ export interface SettingsFieldConfig { min?: number; max?: number; dependsOn?: string; + /** The extension the field belongs to; hidden while that extension is off. */ + extension?: string; help?: string; options?: Array<{ value: string; label: string; icon?: typeof Icon }>; /** Options rendered for RADIO fields. Each entry maps a `value` (the radio's selected value) to the underlying config `key` whose boolean state mirrors it. */ diff --git a/ui/apps/chat/tests/client/settings-extension-fields.svelte.test.ts b/ui/apps/chat/tests/client/settings-extension-fields.svelte.test.ts new file mode 100644 index 000000000000..68ff5d299319 --- /dev/null +++ b/ui/apps/chat/tests/client/settings-extension-fields.svelte.test.ts @@ -0,0 +1,65 @@ +// A setting can belong to an extension. Its field is drawn only while that +// extension is on; the other fields of the section are not affected. + +import SettingsChatFields from '#lib/components/app/settings/SettingsChat/SettingsChatFields.svelte'; +import { SETTINGS_CHAT_SECTIONS, SETTINGS_KEYS } from '#lib/constants/index.ts'; +import { SettingsFieldType } from '#lib/enums/settings.enums.ts'; +import { extensions } from '#lib/extensions/index.ts'; +import type { SettingsFieldConfig } from '#lib/types/index.ts'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; + +const EXTENSION_ID = 'fields-fixture'; +const FIELDS: SettingsFieldConfig[] = [ + { key: 'coreSetting', label: 'Core setting', type: SettingsFieldType.INPUT }, + { + extension: EXTENSION_ID, + key: 'extensionSetting', + label: 'Extension setting', + type: SettingsFieldType.INPUT + } +]; + +function labels(container: Element): string[] { + return [...container.querySelectorAll('label')].map((label) => label.textContent?.trim() ?? ''); +} + +describe('settings fields of an extension', () => { + beforeAll(() => { + extensions.register({ + description: 'Owns one settings field', + disabledByDefault: true, + id: EXTENSION_ID, + load: async () => ({ default: { activate() {} } }), + name: 'Fields fixture' + }); + }); + + afterAll(async () => { + await extensions.setEnabled(EXTENSION_ID, false); + }); + + it('draws the field only while its extension is on', async () => { + const { container } = render(SettingsChatFields, { + fields: FIELDS, + localConfig: { coreSetting: '1', extensionSetting: '2' }, + onConfigChange: () => {} + }); + + expect(labels(container)).toEqual(['Core setting']); + + await extensions.setEnabled(EXTENSION_ID, true); + await expect.poll(() => labels(container)).toEqual(['Core setting', 'Extension setting']); + + await extensions.setEnabled(EXTENSION_ID, false); + await expect.poll(() => labels(container)).toEqual(['Core setting']); + }); + + it('marks the MCP request timeout as the MCP extension’s', () => { + const field = SETTINGS_CHAT_SECTIONS.flatMap((section) => section.fields ?? []).find( + (entry) => entry.key === SETTINGS_KEYS.MCP_REQUEST_TIMEOUT_SECONDS + ); + + expect(field?.extension).toBe('mcp'); + }); +}); diff --git a/ui/apps/chat/tests/unit/extensions-registry.test.ts b/ui/apps/chat/tests/unit/extensions-registry.test.ts index 613d342af6da..16737e03475d 100644 --- a/ui/apps/chat/tests/unit/extensions-registry.test.ts +++ b/ui/apps/chat/tests/unit/extensions-registry.test.ts @@ -77,6 +77,7 @@ describe('ExtensionRegistry', () => { expect(registry.contributions('tools')).toEqual([provider]); expect(registry.contributions('flow')).toEqual([hook]); expect(registry.extensions[0]).toMatchObject({ enabled: true, error: null, state: 'active' }); + expect(registry.isActive('test')).toBe(true); }); it('does not load the code of an extension that is off', async () => { @@ -115,6 +116,7 @@ describe('ExtensionRegistry', () => { // last registered, first undone expect(order).toEqual(['second', 'first']); expect(registry.extensions[0]).toMatchObject({ enabled: false, state: 'inactive' }); + expect(registry.isActive('test')).toBe(false); }); it('keeps only the contributions of the extensions that stay on', async () => { From b811de25ec01b4c0a57a6428ec0fa66065911d7d Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Fri, 13 Nov 2026 01:30:35 +0100 Subject: [PATCH 14/19] ui: say in the README how a setting belongs to an extension MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A setting can name its extension (`extension` in SETTINGS_REGISTRY), so its field shows only while the extension is on and the stored value stays either way. An extension's code ships in the single bundle llama-server embeds, but none of it runs while the extension is off. The Architecture › Extensions page that came with this lives with the Storybook's Architecture section, outside this stack. Assisted-by: Claude (Opus 5.5 Medium) --- ui/apps/chat/README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ui/apps/chat/README.md b/ui/apps/chat/README.md index 083c2e2e4614..bf089c97a49e 100644 --- a/ui/apps/chat/README.md +++ b/ui/apps/chat/README.md @@ -164,6 +164,10 @@ MCP is the first extension. All of its code is in `src/lib/extensions/mcp/`: MCP's shared data stays in the core: types, enums, constants, `utils/mcp.ts`, settings keys and the stored message formats. +A setting can name the extension it belongs to (`extension` in `SETTINGS_REGISTRY`): its field shows only while that extension is on, and the stored value stays either way. + +llama-server embeds the app as a single bundle, so an extension's code ships whether it is on or off; nothing of it runs while it is off. + ### Cross-origin isolation llama-server serves the UI with `Cross-Origin-Embedder-Policy: require-corp` and `Cross-Origin-Opener-Policy: same-origin`, so every cross-origin asset needs the other origin's consent. Hugging Face Hub avatars and metadata are requested in CORS mode, which the Hub allows. MCP server icons and search-result favicons go through llama-server's `/cors-proxy` when it runs with `--ui-mcp-proxy`, and fall back to a bundled icon otherwise. From 19b13e6383bd78bba1610ef26a7ce24aba267298 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Fri, 13 Nov 2026 01:35:23 +0100 Subject: [PATCH 15/19] ui: draw an unsent attachment of an unclaimed kind as text An MCP prompt picked into the chat form is an attachment of the app's own kind, drawn by MCP's renderer. With the extension switched off before the message is sent, it fell back to the generic file chip with its kind as an overflowing label. It now reads as a text file once its text has loaded, the same rule a stored attachment of such a kind already follows. Assisted-by: Claude (Opus 5.5 Medium) --- ui/apps/chat/src/lib/utils/attachment-type.ts | 13 +++++++++++- .../tests/unit/extension-renderers.test.ts | 20 ++++++++++++++++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/ui/apps/chat/src/lib/utils/attachment-type.ts b/ui/apps/chat/src/lib/utils/attachment-type.ts index 3c24eeed107c..14f19f7e3e84 100644 --- a/ui/apps/chat/src/lib/utils/attachment-type.ts +++ b/ui/apps/chat/src/lib/utils/attachment-type.ts @@ -29,7 +29,18 @@ export function isTextFile( uploadedFile?: ChatUploadedFile ): boolean { if (uploadedFile) { - return getUploadedFileCategory(uploadedFile) === FileTypeCategory.TEXT; + const category = getUploadedFileCategory(uploadedFile); + + if (category === FileTypeCategory.TEXT) return true; + + // the same rule as for a stored attachment below, for one not sent yet: a kind of + // the app's own (not a MIME type) that only an extension draws, carrying text + return ( + category === null && + uploadedFile.type !== '' && + !uploadedFile.type.includes('/') && + typeof uploadedFile.textContent === 'string' + ); } if (attachment) { diff --git a/ui/apps/chat/tests/unit/extension-renderers.test.ts b/ui/apps/chat/tests/unit/extension-renderers.test.ts index d1bd40c29221..c7c50cb9f8cb 100644 --- a/ui/apps/chat/tests/unit/extension-renderers.test.ts +++ b/ui/apps/chat/tests/unit/extension-renderers.test.ts @@ -2,7 +2,7 @@ // renderer claims it. These pin how a renderer is picked, and what the core // falls back to for the MCP attachment kinds when no renderer claims them. -import { AttachmentType, MessageRole, MessageType } from '#lib/enums/index.ts'; +import { AttachmentType, MessageRole, MessageType, SpecialFileType } from '#lib/enums/index.ts'; import type { AttachmentRenderer, AttachmentRendererProps, @@ -178,6 +178,24 @@ describe('attachments no renderer claims', () => { expect(isTextFile(MCP_RESOURCE)).toBe(true); }); + it('read as text files before they are sent too, once their text has loaded', () => { + const pending = { + file: new File([], 'loading'), + id: 'pending', + name: 'code_review', + size: 17, + type: SpecialFileType.MCP_PROMPT + }; + + expect(isTextFile(undefined, { ...pending, textContent: 'Review this file.' })).toBe(true); + expect(isTextFile(undefined, pending)).toBe(false); + // an upload of a kind the browser could not name is not one of the app's own kinds + expect(isTextFile(undefined, { ...pending, textContent: 'text', type: '' })).toBe(false); + expect( + isTextFile(undefined, { ...pending, textContent: 'text', type: 'application/x-unknown' }) + ).toBe(false); + }); + it('keep their name and text as display items', () => { const [resource, prompt] = displayItems([MCP_PROMPT, MCP_RESOURCE]); From f63aace8c87e62ede8c9b492788e1b834a83f87b Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Mon, 16 Nov 2026 18:36:29 +0100 Subject: [PATCH 16/19] server : name the MCP server of each tool in /tools A tool of an MCP server llama-server runs from --mcp-servers-config is listed as _, so a client could only guess the server from the name, and guess wrong when the server's name has an underscore. GET /tools now gives it in `mcp_server` for such tools. Built-in tools are listed as before. Assisted-by: Claude (Opus 5.5 Medium) --- tools/server/README-dev.md | 1 + tools/server/README.md | 2 +- tools/server/server-tools.cpp | 7 ++++++- tools/server/server-tools.h | 1 + tools/server/tests/unit/test_mcp_servers.py | 3 +++ 5 files changed, 12 insertions(+), 2 deletions(-) diff --git a/tools/server/README-dev.md b/tools/server/README-dev.md index afe729878603..a4bd587cdc54 100644 --- a/tools/server/README-dev.md +++ b/tools/server/README-dev.md @@ -190,6 +190,7 @@ Get a list of tools, each tool has these fields: - `tool` (string): the ID name of the tool, to be used in POST call. Example: `read_file` - `display_name` (string): the name to be displayed on UI. Example: `Read file` - `type` (string): `"server"` for a server tool, or `"mcp"` for a tool exposed by an MCP server +- `mcp_server` (string, only when `type` is `"mcp"`): the name of the MCP server the tool comes from, as declared in `--mcp-servers-config`. Example: `imcp` - `permissions` (object): a mapping string --> boolean that indicates the permission required by this tool. This is useful for the UI to ask the user before calling the tool. For now, the only permission supported is `"write"` - `definition` (object): the OAI-compat definition of this tool diff --git a/tools/server/README.md b/tools/server/README.md index 292fe598ed52..cc93b22c418b 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -389,7 +389,7 @@ The same JSON can be passed inline with `--mcp-servers-json`. Each entry under ` | `cwd` | working directory of the child process | | `timeout_ms` | per-tool-call timeout (default: 30000) | -Every server is spawned once at startup to list its tools, then stopped, and respawned on demand when one of its tools is called. Tools are exposed as `_` alongside the built-in ones: they show up in Llama Chat and in `GET /tools`, and the model calls them like any other tool. A name colliding with an already registered tool is skipped. This is independent of `--tools`, MCP servers can be the only tools available. +Every server is spawned once at startup to list its tools, then stopped, and respawned on demand when one of its tools is called. Tools are exposed as `_` alongside the built-in ones: they show up in Llama Chat, which lists each of these servers on its MCP servers page, and in `GET /tools`, with `"type": "mcp"` and the server's name in `mcp_server`. The model calls them like any other tool. A name colliding with an already registered tool is skipped. This is independent of `--tools`, MCP servers can be the only tools available. The child process runs with the same privileges as the server, so only declare commands you trust. As with `--tools`, `--cors-origins` then defaults to `localhost`. diff --git a/tools/server/server-tools.cpp b/tools/server/server-tools.cpp index 63626ddcc3df..633d0a5a51e6 100644 --- a/tools/server/server-tools.cpp +++ b/tools/server/server-tools.cpp @@ -89,7 +89,7 @@ static std::string console_output_to_utf8(const std::string & text) { } json server_tool::to_json() const { - return { + json res = { {"display_name", display_name}, {"tool", name}, {"type", type()}, @@ -99,6 +99,10 @@ json server_tool::to_json() const { {"uses_cwd", uses_cwd}, {"definition", get_definition()}, }; + if (!mcp_server.empty()) { + res["mcp_server"] = mcp_server; + } + return res; } static constexpr size_t SERVER_TOOL_GIT_LS_FILES_MAX_OUTPUT = 8 * 1024 * 1024; // 8 MB @@ -1814,6 +1818,7 @@ struct server_mcp_tool : server_tool { { name = server_name + "_" + tool_name; display_name = name; + mcp_server = server_name; permission_write = false; support_stream = false; } diff --git a/tools/server/server-tools.h b/tools/server/server-tools.h index 5a63ee973bef..1dc1d6e1e60b 100644 --- a/tools/server/server-tools.h +++ b/tools/server/server-tools.h @@ -15,6 +15,7 @@ struct server_tool { bool permission_write = false; bool support_stream = false; // if true, output can be streamed bool uses_cwd = false; // if true, the tool resolves paths and runs against the working directory + std::string mcp_server; // the MCP server the tool comes from, empty for a built-in tool virtual ~server_tool() = default; virtual json get_definition() const = 0; diff --git a/tools/server/tests/unit/test_mcp_servers.py b/tools/server/tests/unit/test_mcp_servers.py index 7a9f0bea57b3..6500d432485e 100644 --- a/tools/server/tests/unit/test_mcp_servers.py +++ b/tools/server/tests/unit/test_mcp_servers.py @@ -77,6 +77,9 @@ def get_tool_name(t): # Verify tool structure echo_tool = next(t for t in mcp_tools if get_tool_name(t) == "echo_echo") assert "description" in echo_tool or "definition" in echo_tool + assert echo_tool["type"] == "mcp" + assert echo_tool["mcp_server"] == "echo" + assert all("mcp_server" not in t for t in tools if t["type"] != "mcp") finally: server.stop() From be690156699a6ede2c4f55c33427fd4a589f7c8a Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Mon, 16 Nov 2026 18:36:29 +0100 Subject: [PATCH 17/19] ui: list the MCP servers llama-server runs beside the ones it connects to A page cannot start a process, so a local MCP server that runs as a command (stdio) is one llama-server starts from --mcp-servers-config. Its tools reached Llama Chat as plain server tools, under the llama-server group, unlike the MCP servers the browser connects to by URL. The MCP extension now takes those tools over: a tool provider can claim llama-server's tools of one /tools type, and MCP claims `mcp`. They are listed one group per server, switched off and allowed like the tools of any other MCP server, and still run on llama-server. The MCP servers page shows each of these servers as a card marked as run by llama-server, and explains how to add a local server to llama-server's config. With MCP switched off, the core lists them as server tools again. Assisted-by: Claude (Opus 5.5 Medium) --- ui/apps/chat/README.md | 2 + ui/apps/chat/src/lib/enums/index.ts | 1 + ui/apps/chat/src/lib/enums/tools.enums.ts | 7 + .../mcp/components/McpLlamaServerCard.svelte | 66 ++++++ .../mcp/components/McpLlamaServerHowTo.svelte | 65 ++++++ .../contributions/McpToolGroupIdentity.svelte | 25 ++- .../settings/SettingsMcpServers.svelte | 15 +- .../src/lib/extensions/mcp/llama-server.ts | 96 +++++++++ ui/apps/chat/src/lib/extensions/mcp/tools.ts | 37 +++- .../chat/src/lib/extensions/points/tools.ts | 9 +- .../src/lib/hooks/use-tools-panel.svelte.ts | 2 +- .../src/lib/stores/agentic/index.svelte.ts | 4 +- ui/apps/chat/src/lib/stores/tools.svelte.ts | 59 +++++- ui/apps/chat/src/lib/types/mcp.d.ts | 6 +- .../chat/tests/stories/chat/form/fixtures.ts | 6 +- .../stories/mcp/McpLlamaServer.stories.svelte | 87 ++++++++ .../chat/tests/unit/mcp-llama-server.test.ts | 198 ++++++++++++++++++ 17 files changed, 656 insertions(+), 29 deletions(-) create mode 100644 ui/apps/chat/src/lib/extensions/mcp/components/McpLlamaServerCard.svelte create mode 100644 ui/apps/chat/src/lib/extensions/mcp/components/McpLlamaServerHowTo.svelte create mode 100644 ui/apps/chat/src/lib/extensions/mcp/llama-server.ts create mode 100644 ui/apps/chat/tests/stories/mcp/McpLlamaServer.stories.svelte create mode 100644 ui/apps/chat/tests/unit/mcp-llama-server.test.ts diff --git a/ui/apps/chat/README.md b/ui/apps/chat/README.md index bf089c97a49e..538485fe9086 100644 --- a/ui/apps/chat/README.md +++ b/ui/apps/chat/README.md @@ -164,6 +164,8 @@ MCP is the first extension. All of its code is in `src/lib/extensions/mcp/`: MCP's shared data stays in the core: types, enums, constants, `utils/mcp.ts`, settings keys and the stored message formats. +MCP servers come two ways. A remote server (Streamable HTTP, SSE or WebSocket) is one the browser connects to by URL, added on the MCP servers page. A local server that runs as a command (stdio) is one llama-server starts from `--mcp-servers-config`, since a page cannot start a process: llama-server lists its tools in `/tools` with the type `mcp` and the server's name in `mcp_server`, and runs them on `POST /tools`. The MCP extension takes those tools over from the core's server tools (`serverToolType` on its tool provider, see `llama-server.ts`), so both kinds show up the same way, one group per server, on the MCP servers page and in the tools menu. With the extension off, the core lists them as server tools again. + A setting can name the extension it belongs to (`extension` in `SETTINGS_REGISTRY`): its field shows only while that extension is on, and the stored value stays either way. llama-server embeds the app as a single bundle, so an extension's code ships whether it is on or off; nothing of it runs while it is off. diff --git a/ui/apps/chat/src/lib/enums/index.ts b/ui/apps/chat/src/lib/enums/index.ts index 3378504c67ea..c9c520e0cbc6 100644 --- a/ui/apps/chat/src/lib/enums/index.ts +++ b/ui/apps/chat/src/lib/enums/index.ts @@ -117,6 +117,7 @@ export { GlobSearchType, SearchChatsMessageSelection, SearchChatsOrder, + ServerToolType, ToolSource, ToolPermissionDecision, ToolResponseField diff --git a/ui/apps/chat/src/lib/enums/tools.enums.ts b/ui/apps/chat/src/lib/enums/tools.enums.ts index 2bda6872284b..d46d7af83407 100644 --- a/ui/apps/chat/src/lib/enums/tools.enums.ts +++ b/ui/apps/chat/src/lib/enums/tools.enums.ts @@ -5,6 +5,13 @@ export enum ToolSource { SERVER = 'server' } +/** The `type` of a tool in llama-server's `/tools` listing. */ +export enum ServerToolType { + /** A tool of one of the MCP servers llama-server runs, from `--mcp-servers-config` */ + MCP = 'mcp', + SERVER = 'server' +} + export enum ToolPermissionDecision { ALWAYS = 'always', ALWAYS_SERVER = 'always_server', diff --git a/ui/apps/chat/src/lib/extensions/mcp/components/McpLlamaServerCard.svelte b/ui/apps/chat/src/lib/extensions/mcp/components/McpLlamaServerCard.svelte new file mode 100644 index 000000000000..11d929f7824d --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/components/McpLlamaServerCard.svelte @@ -0,0 +1,66 @@ + + + + +
+
+ + + + {server.name} + + +
+ + + + stdio + + + Run by llama-server +
+
+ + toolsStore.setToolEnabled(groupKey, checked)} + /> +
+ +

+ llama-server starts this server from its config file. To change or remove it, edit the file and + restart llama-server. +

+ + {#if tools.length > 0} + + {/if} +
diff --git a/ui/apps/chat/src/lib/extensions/mcp/components/McpLlamaServerHowTo.svelte b/ui/apps/chat/src/lib/extensions/mcp/components/McpLlamaServerHowTo.svelte new file mode 100644 index 000000000000..0cc497f9bbec --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/components/McpLlamaServerHowTo.svelte @@ -0,0 +1,65 @@ + + + + + + + + Use a local MCP server (stdio) + + {#if open} + + {:else} + + {/if} + + + +

+ A server that runs as a command on your computer, like iMCP or a filesystem server, is started + by llama-server, not by this page. List it in a config file: +

+ +
+
{LLAMA_SERVER_MCP_CONFIG_EXAMPLE}
+ +
+ +
+
+ +

Then start llama-server with it:

+ +
+
{command}
+ +
+ +
+
+ +

+ Its tools then show up here and in the tools menu, and llama-server runs them when a model + calls them. +

+
+
diff --git a/ui/apps/chat/src/lib/extensions/mcp/components/contributions/McpToolGroupIdentity.svelte b/ui/apps/chat/src/lib/extensions/mcp/components/contributions/McpToolGroupIdentity.svelte index e51f80f85b8e..5fa334d721fb 100644 --- a/ui/apps/chat/src/lib/extensions/mcp/components/contributions/McpToolGroupIdentity.svelte +++ b/ui/apps/chat/src/lib/extensions/mcp/components/contributions/McpToolGroupIdentity.svelte @@ -1,16 +1,27 @@ - + +{#if groupId.startsWith(LLAMA_SERVER_MCP_GROUP_PREFIX)} + + + + {label} + +{:else} + +{/if} diff --git a/ui/apps/chat/src/lib/extensions/mcp/components/settings/SettingsMcpServers.svelte b/ui/apps/chat/src/lib/extensions/mcp/components/settings/SettingsMcpServers.svelte index cb905103fc33..7d74fecc7203 100644 --- a/ui/apps/chat/src/lib/extensions/mcp/components/settings/SettingsMcpServers.svelte +++ b/ui/apps/chat/src/lib/extensions/mcp/components/settings/SettingsMcpServers.svelte @@ -1,8 +1,11 @@ + + { + const canvas = within(canvasElement); + + await expect(canvas.getByText('imcp')).toBeInTheDocument(); + await expect(canvas.getAllByText('Run by llama-server')).toHaveLength(2); + await expect(canvas.getByRole('switch', { name: 'Use the tools of imcp' })).toBeChecked(); + await expect(canvas.getByText('3 tools available · Show details')).toBeInTheDocument(); + }} +> + + + + + + + + + + + + { + const canvas = within(canvasElement); + + await expect(canvas.getByText(/llama-server --mcp-servers-config mcp.json/)).toBeVisible(); + await expect(canvas.getByRole('button', { name: 'Copy the config example' })).toBeVisible(); + }} +> +
+ +
+
diff --git a/ui/apps/chat/tests/unit/mcp-llama-server.test.ts b/ui/apps/chat/tests/unit/mcp-llama-server.test.ts new file mode 100644 index 000000000000..b79f1f24b602 --- /dev/null +++ b/ui/apps/chat/tests/unit/mcp-llama-server.test.ts @@ -0,0 +1,198 @@ +// The MCP servers llama-server runs from `--mcp-servers-config` (stdio): their +// tools come in llama-server's `/tools` listing with the type `mcp`. The core +// lists them as server tools until the MCP extension takes them over; then +// they are MCP tools, grouped per server and run on llama-server. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('#lib/services/database.service.ts', () => ({ + DatabaseService: {} +})); +// the component draws on the app's component barrel, which needs a browser +vi.mock('#lib/extensions/mcp/components/contributions/McpToolGroupIdentity.svelte', () => ({ + default: () => {} +})); + +import { BuiltInTool, ServerToolType, ToolSource } from '#lib/enums/index.ts'; +import type { ExtensionContext, ToolProvider } from '#lib/extensions/index.ts'; +import { extensions } from '#lib/extensions/index.ts'; +import { llamaServerMcpServers } from '#lib/extensions/mcp/llama-server.ts'; +import { mcpStore } from '#lib/extensions/mcp/stores/index.svelte.ts'; +import { contributeTools } from '#lib/extensions/mcp/tools.ts'; +import { ToolsService } from '#lib/services/tools.service.ts'; +import { toolsStore } from '#lib/stores/tools.svelte.ts'; +import type { OpenAIToolDefinition, ServerToolInfo } from '#lib/types/index.ts'; + +const EXTENSION_ID = 'mcp-llama-server-test'; + +function info(tool: string, type: ServerToolType, mcpServer?: string): ServerToolInfo { + return { + definition: { + function: { description: `${tool} tool`, name: tool, parameters: {} }, + type: 'function' + }, + display_name: tool, + ...(mcpServer ? { mcp_server: mcpServer } : {}), + permissions: { write: false }, + tool, + type, + uses_cwd: false + }; +} + +// what a llama-server started with `--tools all --mcp-servers-config` lists +const LISTING: ServerToolInfo[] = [ + info(BuiltInTool.SERVER_READ_FILE, ServerToolType.SERVER), + info('imcp_weather_current', ServerToolType.MCP, 'imcp'), + info('imcp_contacts_search', ServerToolType.MCP, 'imcp'), + info('my_fs_read', ServerToolType.MCP, 'my_fs') +]; + +interface ToolsStoreInternals { + _serverToolInfos: ServerToolInfo[]; + _serverTools: OpenAIToolDefinition[]; +} + +function seedListing(listing: ServerToolInfo[]): void { + const internals = toolsStore as unknown as ToolsStoreInternals; + + internals._serverToolInfos = listing; + internals._serverTools = listing.map((i) => i.definition); +} + +function provider(): ToolProvider { + let made: ToolProvider | undefined; + + const ctx: ExtensionContext = { + contribute: (point, contribution) => { + if (point === 'tools') made = contribution as ToolProvider; + }, + onDeactivate: () => {} + }; + + contributeTools(ctx); + + return made!; +} + +function names(defs: OpenAIToolDefinition[]): string[] { + return defs.map((def) => def.function.name); +} + +extensions.register({ + description: "MCP's tools, as the extension contributes them", + id: EXTENSION_ID, + load: async () => ({ default: { activate: contributeTools } }), + name: 'MCP' +}); + +beforeEach(() => { + vi.restoreAllMocks(); + vi.spyOn(mcpStore, 'getServers').mockReturnValue([]); + vi.spyOn(mcpStore, 'getConnections').mockReturnValue(new Map()); + seedListing(LISTING); +}); + +afterEach(async () => { + await extensions.setEnabled(EXTENSION_ID, false); + seedListing([]); + + for (const key of [...toolsStore.disabledTools]) toolsStore.setToolEnabled(key, true); +}); + +describe('llama-server MCP tools without the MCP extension', () => { + it('stay server tools', () => { + expect(names(toolsStore.serverTools)).toEqual([ + 'read_file', + 'imcp_weather_current', + 'imcp_contacts_search', + 'my_fs_read' + ]); + expect(toolsStore.getToolSource('imcp_weather_current')).toBe(ToolSource.SERVER); + expect(toolsStore.getPermissionKey('imcp_weather_current')).toBe('server:imcp_weather_current'); + }); +}); + +describe('llama-server MCP tools with the MCP extension', () => { + beforeEach(() => extensions.setEnabled(EXTENSION_ID, true)); + + it('leave the server tools for the MCP category', () => { + expect(names(toolsStore.serverTools)).toEqual(['read_file']); + expect(toolsStore.hasServerTools).toBe(true); + expect(toolsStore.getToolSource('read_file')).toBe(ToolSource.SERVER); + expect(toolsStore.getToolSource('imcp_weather_current')).toBe(ToolSource.MCP); + }); + + it('are grouped per server, under keys that cannot meet a configured server', () => { + const group = toolsStore.toolGroups.find((g) => g.serverId === 'llama-server:imcp'); + + expect(group).toMatchObject({ key: 'mcp:llama-server:imcp', label: 'imcp' }); + expect(group?.tools.map((t) => t.definition.function.name)).toEqual([ + 'imcp_weather_current', + 'imcp_contacts_search' + ]); + expect(toolsStore.getPermissionKey('imcp_weather_current')).toBe( + 'mcp-llama-server:imcp:imcp_weather_current' + ); + expect(toolsStore.getToolServerLabel('my_fs_read')).toBe('my_fs'); + }); + + it('are sent to the model once each, and not after their server is switched off', () => { + const all = names(toolsStore.getEnabledToolsForLLM(new Set(), new Set())); + + expect(all.filter((n) => n === 'imcp_weather_current')).toHaveLength(1); + expect(all).toContain('my_fs_read'); + + const off = names( + toolsStore.getEnabledToolsForLLM(new Set(['mcp:llama-server:imcp']), new Set()) + ); + + expect(off).not.toContain('imcp_weather_current'); + expect(off).toContain('my_fs_read'); + expect(off).toContain('read_file'); + }); + + it('run on llama-server, with the arguments the model wrote', async () => { + const execute = vi + .spyOn(ToolsService, 'executeTool') + .mockResolvedValue({ content: 'sunny', isError: false }); + const executeOnMcp = vi.spyOn(mcpStore, 'executeTool'); + const result = await provider().execute({ + arguments: '{"city":"Kraków"}', + id: 'call-1', + name: 'imcp_weather_current' + }); + + expect(result).toEqual({ content: 'sunny', isError: false }); + expect(execute).toHaveBeenCalledWith('imcp_weather_current', { city: 'Kraków' }, undefined); + expect(executeOnMcp).not.toHaveBeenCalled(); + + await provider().execute({ arguments: 'not json', id: 'call-2', name: 'my_fs_read' }); + + expect(execute).toHaveBeenLastCalledWith('my_fs_read', {}, undefined); + }); + + it('make the provider configured without any server of its own', () => { + expect(provider().isConfigured()).toBe(true); + + seedListing([LISTING[0]]); + + expect(provider().isConfigured()).toBe(false); + }); +}); + +describe('the servers llama-server runs', () => { + it('are named by llama-server, or by the tool name of an older llama-server', () => { + seedListing([ + ...LISTING, + // no `mcp_server`: llama-server before the field, `_` + info('github_list_issues', ServerToolType.MCP) + ]); + + expect(llamaServerMcpServers().map((s) => [s.name, s.tools.length])).toEqual([ + ['imcp', 2], + ['my_fs', 1], + ['github', 1] + ]); + }); +}); From 4a1794a359eee9db8d61aa6924423029b398e66d Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Wed, 18 Nov 2026 13:41:04 +0100 Subject: [PATCH 18/19] ui: show Models and MCP in the extension tests, now that both wait behind settings Since ggml-org/llama.cpp#32527, Models and MCP are hidden until "Show Models" and "Show MCP" are on. The MCP extension's tests rendered the sidebar, the tools panel and the search commands expecting both, so they switch the settings on first, as the nested-surfaces test does. Two new cases check the hidden side: the MCP entry leaves the sidebar and the tools panel says nothing about MCP servers while "Show MCP" is off. Assisted-by: Claude (Opus 5.5 Medium) --- .../extension-navigation.svelte.test.ts | 5 +++++ .../client/mcp-navigation-glue.svelte.test.ts | 20 ++++++++++++++++++- .../client/settings-extensions.svelte.test.ts | 3 +++ .../tools-extension-point.svelte.test.ts | 5 ++++- .../tests/unit/mcp-tools-extension.test.ts | 14 ++++++++++++- 5 files changed, 44 insertions(+), 3 deletions(-) diff --git a/ui/apps/chat/tests/client/extension-navigation.svelte.test.ts b/ui/apps/chat/tests/client/extension-navigation.svelte.test.ts index 73070b6d572b..50dfd80e7a63 100644 --- a/ui/apps/chat/tests/client/extension-navigation.svelte.test.ts +++ b/ui/apps/chat/tests/client/extension-navigation.svelte.test.ts @@ -33,11 +33,13 @@ import SidebarNavigationFooter from '#lib/components/app/navigation/SidebarNavig import { APP_NAME, EXTENSION_PAGE_ROUTE_ID, + SETTINGS_KEYS, SIDEBAR_ACTIONS_ITEMS, SIDEBAR_FOOTER_ITEMS } from '#lib/constants/index.ts'; import { extensions } from '#lib/extensions/index.ts'; import { uiStore } from '#lib/stores/index.ts'; +import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; import { goto, refreshAll } from '$app/navigation'; import { page } from 'vitest/browser'; import { render } from 'vitest-browser-svelte'; @@ -105,6 +107,9 @@ describe('navigation and pages extension points', () => { await page.viewport(1280, 900); wasExpanded = uiStore.isSidebarExpanded; uiStore.isSidebarExpanded = true; + // Models and MCP wait behind their settings: show them, so their entries are there to find + settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MODELS_MANAGER, true); + settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MCP, true); showRoute(null); gotoMock.mockClear(); refreshAllMock.mockClear(); diff --git a/ui/apps/chat/tests/client/mcp-navigation-glue.svelte.test.ts b/ui/apps/chat/tests/client/mcp-navigation-glue.svelte.test.ts index c1a7ef5047f0..4d6552025ad7 100644 --- a/ui/apps/chat/tests/client/mcp-navigation-glue.svelte.test.ts +++ b/ui/apps/chat/tests/client/mcp-navigation-glue.svelte.test.ts @@ -13,7 +13,7 @@ import { RouterService } from '#lib/services/router.service.ts'; import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; import { sidebarFooterItems } from '#lib/utils/index.ts'; import { flushSync } from 'svelte'; -import { describe, expect, it, vi } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; function makeContext() { const cleanups: (() => void | Promise)[] = []; @@ -32,6 +32,9 @@ function setServers(servers: { enabled: boolean; id: string; url: string }[]) { } describe('MCP navigation glue', () => { + // MCP waits behind its setting: show it, so its entry is there to find + beforeEach(() => settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MCP, true)); + it('contributes the MCP entry, which the sidebar places right after Models', () => { const { contributions, ctx } = makeContext(); @@ -58,6 +61,21 @@ describe('MCP navigation glue', () => { ]); }); + it('leaves the MCP entry out of the sidebar while MCP is hidden', () => { + const { contributions, ctx } = makeContext(); + + contributeNavigation(ctx); + + const item = contributions[0].value as NavigationItem; + + settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MCP, false); + + expect(item.shown?.()).toBe(false); + expect(sidebarFooterItems([item]).map((entry) => entry.tooltip)).toEqual( + SIDEBAR_FOOTER_ITEMS.map((entry) => entry.tooltip) + ); + }); + it('contributes the MCP servers page at the route its entry opens', () => { const { contributions, ctx } = makeContext(); diff --git a/ui/apps/chat/tests/client/settings-extensions.svelte.test.ts b/ui/apps/chat/tests/client/settings-extensions.svelte.test.ts index 313dd93197f5..db16f8068774 100644 --- a/ui/apps/chat/tests/client/settings-extensions.svelte.test.ts +++ b/ui/apps/chat/tests/client/settings-extensions.svelte.test.ts @@ -81,6 +81,9 @@ describe('Extensions settings', () => { await page.viewport(1280, 900); wasExpanded = uiStore.isSidebarExpanded; uiStore.isSidebarExpanded = true; + // Models and MCP wait behind their settings: show them, so their entries are there to find + settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MODELS_MANAGER, true); + settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MCP, true); settingsStore.updateConfig(SETTINGS_KEYS.MCP_SERVERS, '[]'); diff --git a/ui/apps/chat/tests/client/tools-extension-point.svelte.test.ts b/ui/apps/chat/tests/client/tools-extension-point.svelte.test.ts index acffbdbf69d4..352341c9e518 100644 --- a/ui/apps/chat/tests/client/tools-extension-point.svelte.test.ts +++ b/ui/apps/chat/tests/client/tools-extension-point.svelte.test.ts @@ -5,7 +5,8 @@ import SettingsChatToolsTab from '#lib/components/app/settings/SettingsChat/SettingsChatToolsTab.svelte'; import { DISABLED_TOOL_CATEGORIES_LOCALSTORAGE_KEY, - EXTENSIONS_LOCALSTORAGE_KEY + EXTENSIONS_LOCALSTORAGE_KEY, + SETTINGS_KEYS } from '#lib/constants/index.ts'; import { ToolSource } from '#lib/enums/index.ts'; import { BUILT_IN_EXTENSIONS } from '#lib/extensions/builtin.ts'; @@ -44,6 +45,8 @@ beforeAll(() => { }); beforeEach(async () => { + // MCP waits behind its setting: show it, so the panel can point at its servers + settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MCP, true); settingsStore.updateConfig('mcpServers', '[]'); serverId = mcpStore.addServer({ displayName: 'Docs', diff --git a/ui/apps/chat/tests/unit/mcp-tools-extension.test.ts b/ui/apps/chat/tests/unit/mcp-tools-extension.test.ts index d29dff02e343..716f66dbc329 100644 --- a/ui/apps/chat/tests/unit/mcp-tools-extension.test.ts +++ b/ui/apps/chat/tests/unit/mcp-tools-extension.test.ts @@ -12,6 +12,7 @@ vi.mock('#lib/extensions/mcp/components/contributions/McpToolGroupIdentity.svelt default: () => {} })); +import { SETTINGS_KEYS } from '#lib/constants/index.ts'; import { HealthCheckStatus, ToolSource } from '#lib/enums/index.ts'; import type { ExtensionContext, FlowHook, ToolProvider } from '#lib/extensions/index.ts'; import { extensions } from '#lib/extensions/index.ts'; @@ -22,6 +23,7 @@ import { policyEnabledServerIds } from '#lib/extensions/mcp/tools.ts'; import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts'; +import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; import { toolsStore } from '#lib/stores/tools.svelte.ts'; import type { HealthCheckState, MCPConnection, MCPServerSettingsEntry } from '#lib/types/index.ts'; @@ -57,6 +59,8 @@ function mockConnections(connections: Record) { beforeEach(() => { vi.restoreAllMocks(); + // MCP waits behind its setting: show it, so the empty tools panel can point at its servers + settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MCP, true); vi.spyOn(mcpStore, 'getServers').mockReturnValue(SERVERS); mockConnections({}); }); @@ -241,7 +245,15 @@ describe('MCP tool provider', () => { vi.mocked(mcpStore.getServers).mockReturnValue([]); - expect(provider.emptyHint?.().action).toBe('Add MCP Server(s) to access'); + expect(provider.emptyHint?.()?.action).toBe('Add MCP Server(s) to access'); + }); + + it('says nothing in the empty tools panel while MCP is hidden', () => { + const { provider } = contributed(); + + settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MCP, false); + + expect(provider.emptyHint?.()).toBeUndefined(); }); }); From 212792c67e5c79ac905c4a42537e5b6e7c3eefa5 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Wed, 18 Nov 2026 16:08:29 +0100 Subject: [PATCH 19/19] ui: bring the MCP extension in line with the PRs now below it Assisted-by: Claude (Opus 5.5 Medium) --- ui/apps/chat/src/lib/extensions/mcp/composer.ts | 2 +- ui/apps/chat/src/lib/extensions/mcp/navigation.ts | 5 +++-- ui/apps/chat/src/lib/extensions/mcp/pages.ts | 7 +++++-- ui/apps/chat/src/lib/extensions/points/navigation.ts | 8 ++++++-- ui/apps/chat/src/lib/services/router.service.ts | 4 ++-- .../tests/client/extension-navigation.svelte.test.ts | 12 ++++++------ .../tests/client/mcp-navigation-glue.svelte.test.ts | 6 +++--- .../chat/tests/client/nested-surfaces.svelte.test.ts | 3 ++- ui/apps/chat/tests/unit/sidebar-items.test.ts | 4 ++-- 9 files changed, 30 insertions(+), 21 deletions(-) diff --git a/ui/apps/chat/src/lib/extensions/mcp/composer.ts b/ui/apps/chat/src/lib/extensions/mcp/composer.ts index 0efd4c69b177..289432dba9d5 100644 --- a/ui/apps/chat/src/lib/extensions/mcp/composer.ts +++ b/ui/apps/chat/src/lib/extensions/mcp/composer.ts @@ -7,7 +7,7 @@ import type { ExtensionContext } from '../types'; import ComposerMcpPrompts from './components/contributions/ComposerMcpPrompts.svelte'; import ComposerMcpResources from './components/contributions/ComposerMcpResources.svelte'; import { mcpStore } from './stores/index.svelte'; -import { Sparkles } from '@lucide/svelte'; +import Sparkles from '@lucide/svelte/icons/sparkles'; import { ToolSource } from '#lib/enums/index.ts'; import { conversationsStore } from '#lib/stores/index.ts'; diff --git a/ui/apps/chat/src/lib/extensions/mcp/navigation.ts b/ui/apps/chat/src/lib/extensions/mcp/navigation.ts index cf53c3b48520..e3dce88dfb47 100644 --- a/ui/apps/chat/src/lib/extensions/mcp/navigation.ts +++ b/ui/apps/chat/src/lib/extensions/mcp/navigation.ts @@ -1,7 +1,8 @@ import type { ExtensionContext } from '../types'; import DialogMcpServers from './components/dialogs/DialogMcpServers.svelte'; import McpLogo from './components/McpLogo.svelte'; -import { ROUTES } from '#lib/constants/index.ts'; +import { MCP_SERVERS_PAGE_PATH } from './pages'; +import { RouterService } from '#lib/services/router.service.ts'; // direct import of the store, not via the barrel, to avoid circular deps import { uiStore } from '#lib/stores/ui.svelte.ts'; @@ -12,7 +13,7 @@ export function contributeNavigation(ctx: ExtensionContext): void { icon: McpLogo, id: 'mcp', placement: 'footer', - route: ROUTES.MCP_SERVERS, + route: RouterService.extensionPage(MCP_SERVERS_PAGE_PATH), // MCP waits behind its setting; servers already added keep working while it hides shown: () => uiStore.isMcpShown, tooltip: 'MCP' diff --git a/ui/apps/chat/src/lib/extensions/mcp/pages.ts b/ui/apps/chat/src/lib/extensions/mcp/pages.ts index 1fc3197478cf..a024673f32a8 100644 --- a/ui/apps/chat/src/lib/extensions/mcp/pages.ts +++ b/ui/apps/chat/src/lib/extensions/mcp/pages.ts @@ -1,11 +1,14 @@ import type { ExtensionContext } from '../types'; import McpServersPage from './components/contributions/McpServersPage.svelte'; -/** The MCP servers page. Its path is what `ROUTES.MCP_SERVERS` leads to. */ +/** Path of the MCP servers page, where the sidebar's MCP entry leads on a phone. */ +export const MCP_SERVERS_PAGE_PATH = 'mcp-servers'; + +/** The MCP servers page. */ export function contributePages(ctx: ExtensionContext): void { ctx.contribute('pages', { component: McpServersPage, - path: 'mcp-servers', + path: MCP_SERVERS_PAGE_PATH, title: 'MCP Servers' }); } diff --git a/ui/apps/chat/src/lib/extensions/points/navigation.ts b/ui/apps/chat/src/lib/extensions/points/navigation.ts index 30ed6cf53108..53096fdf0466 100644 --- a/ui/apps/chat/src/lib/extensions/points/navigation.ts +++ b/ui/apps/chat/src/lib/extensions/points/navigation.ts @@ -1,3 +1,4 @@ +import type { ResolvedPathname } from '$app/types'; import type { Component } from 'svelte'; /** Where a contributed item sits: `footer` is the sidebar's footer, right after Models. */ @@ -16,8 +17,11 @@ export interface NavigationItem { /** Key combination shown beside the label. A hint only: the sidebar does not bind it. */ keys?: string[]; placement: NavigationPlacement; - /** Hash route of the extension's page the item opens, e.g. `#/mcp-servers`. The item is lit while that page shows. */ - route: string; + /** + * URL of the extension's page the item opens, from RouterService.extensionPage(). The item is lit + * while that page shows. + */ + route: ResolvedPathname; /** Whether the item shows right now, read reactively; it always shows without this. */ shown?(): boolean; /** The item's label, also what the search dialog lists it under. */ diff --git a/ui/apps/chat/src/lib/services/router.service.ts b/ui/apps/chat/src/lib/services/router.service.ts index 247ecdca7780..189fdf359577 100644 --- a/ui/apps/chat/src/lib/services/router.service.ts +++ b/ui/apps/chat/src/lib/services/router.service.ts @@ -15,7 +15,7 @@ export class RouterService { } /** Route of the page an extension contributes at `path`. */ - static extensionPage(path: string): string { - return `${ROUTES.START}${path}`; + static extensionPage(path: string): ResolvedPathname { + return resolve(ROUTES.EXTENSION_PAGE, { extensionPage: path }); } } diff --git a/ui/apps/chat/tests/client/extension-navigation.svelte.test.ts b/ui/apps/chat/tests/client/extension-navigation.svelte.test.ts index 50dfd80e7a63..9d42dda54a13 100644 --- a/ui/apps/chat/tests/client/extension-navigation.svelte.test.ts +++ b/ui/apps/chat/tests/client/extension-navigation.svelte.test.ts @@ -3,8 +3,8 @@ // sits right after Models, opens its dialog on a desktop and its page // on a phone, is lit on its page, and is gone, with everything still working, // once its extension is off. - import '../../src/app.css'; +import { RouterService } from '#lib/services/router.service.ts'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; const pageState = vi.hoisted(() => ({ @@ -32,7 +32,7 @@ import { Puzzle } from '@lucide/svelte'; import SidebarNavigationFooter from '#lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte'; import { APP_NAME, - EXTENSION_PAGE_ROUTE_ID, + ROUTES, SETTINGS_KEYS, SIDEBAR_ACTIONS_ITEMS, SIDEBAR_FOOTER_ITEMS @@ -48,7 +48,7 @@ import { render } from 'vitest-browser-svelte'; const ACTIONS = SIDEBAR_ACTIONS_ITEMS.map((item) => item.tooltip); const FOOTER = SIDEBAR_FOOTER_ITEMS.map((item) => item.tooltip); const FIXTURE_ID = 'navigation-fixture'; -const FIXTURE_ROUTE = '#/fixture-page'; +const FIXTURE_ROUTE = RouterService.extensionPage('fixture-page'); const gotoMock = vi.mocked(goto); const refreshAllMock = vi.mocked(refreshAll); @@ -140,7 +140,7 @@ describe('navigation and pages extension points', () => { it('lights a contributed item only while its page is the one shown', async () => { await extensions.setEnabled(FIXTURE_ID, true); - showRoute(EXTENSION_PAGE_ROUTE_ID, { extensionPage: 'fixture-page' }); + showRoute(ROUTES.EXTENSION_PAGE, { extensionPage: 'fixture-page' }); const onPage = render(SidebarNavigationFooter, {}); @@ -151,7 +151,7 @@ describe('navigation and pages extension points', () => { onPage.unmount(); // another extension page, such as a path nothing is contributed for - showRoute(EXTENSION_PAGE_ROUTE_ID, { extensionPage: 'other-page' }); + showRoute(ROUTES.EXTENSION_PAGE, { extensionPage: 'other-page' }); const elsewhere = render(SidebarNavigationFooter, {}); @@ -218,7 +218,7 @@ describe('navigation and pages extension points', () => { it('renders the page contributed for the path, under its title', async () => { await extensions.setEnabled(FIXTURE_ID, true); - showRoute(EXTENSION_PAGE_ROUTE_ID, { extensionPage: 'fixture-page' }); + showRoute(ROUTES.EXTENSION_PAGE, { extensionPage: 'fixture-page' }); const screen = render(ExtensionPage); diff --git a/ui/apps/chat/tests/client/mcp-navigation-glue.svelte.test.ts b/ui/apps/chat/tests/client/mcp-navigation-glue.svelte.test.ts index 4d6552025ad7..f3336af0537a 100644 --- a/ui/apps/chat/tests/client/mcp-navigation-glue.svelte.test.ts +++ b/ui/apps/chat/tests/client/mcp-navigation-glue.svelte.test.ts @@ -3,7 +3,7 @@ // and the background health checks, which stop when the extension goes off, // when the live connections close too. -import { ROUTES, SETTINGS_KEYS, SIDEBAR_FOOTER_ITEMS } from '#lib/constants/index.ts'; +import { SETTINGS_KEYS, SIDEBAR_FOOTER_ITEMS } from '#lib/constants/index.ts'; import type { ExtensionContext, ExtensionPage, NavigationItem } from '#lib/extensions/index.ts'; import { contributeNavigation } from '#lib/extensions/mcp/navigation.ts'; import { contributePages } from '#lib/extensions/mcp/pages.ts'; @@ -48,7 +48,7 @@ describe('MCP navigation glue', () => { expect(item).toMatchObject({ id: 'mcp', placement: 'footer', - route: ROUTES.MCP_SERVERS, + route: '#/mcp-servers', tooltip: 'MCP' }); expect(item.dialog).toBeDefined(); @@ -88,7 +88,7 @@ describe('MCP navigation glue', () => { expect(mcpPage.title).toBe('MCP Servers'); expect(mcpPage.component).toBeDefined(); - expect(RouterService.extensionPage(mcpPage.path)).toBe(ROUTES.MCP_SERVERS); + expect(RouterService.extensionPage(mcpPage.path)).toBe('#/mcp-servers'); }); it('health-checks every server with a URL, again when the list changes, until deactivated', async () => { diff --git a/ui/apps/chat/tests/client/nested-surfaces.svelte.test.ts b/ui/apps/chat/tests/client/nested-surfaces.svelte.test.ts index f30059dc2746..65065e2f6ed6 100644 --- a/ui/apps/chat/tests/client/nested-surfaces.svelte.test.ts +++ b/ui/apps/chat/tests/client/nested-surfaces.svelte.test.ts @@ -12,6 +12,7 @@ import { SIDEBAR_FOOTER_ITEMS } from '#lib/constants/index.ts'; import { extensions } from '#lib/extensions/index.ts'; +import { RouterService } from '#lib/services/router.service.ts'; import { settingsStore } from '#lib/stores/index.ts'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { page } from 'vitest/browser'; @@ -28,7 +29,7 @@ extensions.register({ icon: Puzzle, id: 'fixture', placement: 'footer', - route: '#/fixture', + route: RouterService.extensionPage('fixture'), tooltip: 'Fixture' }); } diff --git a/ui/apps/chat/tests/unit/sidebar-items.test.ts b/ui/apps/chat/tests/unit/sidebar-items.test.ts index 3d9d9685d6b6..687bd933509a 100644 --- a/ui/apps/chat/tests/unit/sidebar-items.test.ts +++ b/ui/apps/chat/tests/unit/sidebar-items.test.ts @@ -1,10 +1,10 @@ // The sidebar's footer is the app's own items plus what extensions contribute: // without a contribution it must be whole, and a contribution must land // right after Models, ahead of the footer's other items. - import { SIDEBAR_FOOTER_ITEMS } from '#lib/constants/index.ts'; import { SidebarAction } from '#lib/enums/index.ts'; import type { NavigationItem } from '#lib/extensions/index.ts'; +import { RouterService } from '#lib/services/router.service.ts'; import { sidebarFooterItems } from '#lib/utils/sidebar-items.ts'; import type { Component } from 'svelte'; import { describe, expect, it } from 'vitest'; @@ -18,7 +18,7 @@ function makeItem(overrides: Partial = {}): NavigationItem { icon: Icon, id: 'fake', placement: 'footer', - route: '#/fake', + route: RouterService.extensionPage('fake'), tooltip: 'Fake', ...overrides };