Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat: route MCP tools via orchestrator in CustomChatTransport
dataCenter430ed363e404777
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.tsindex e3c554271..0df2cfe5a 100644--- a/web-app/src/lib/custom-chat-transport.ts+++ b/web-app/src/lib/custom-chat-transport.ts@@ -19,6 +19,7 @@ import { useThreads } from '@/hooks/useThreads'import { useAttachments } from '@/hooks/useAttachments'import { ExtensionManager } from '@/lib/extension'import { ExtensionTypeEnum, VectorDBExtension } from '@janhq/core'+import { mcpOrchestrator } from '@/lib/mcp-orchestrator'export type TokenUsageCallback = (usage: LanguageModelUsage,@@ -43,7 +44,15 @@ export type ServiceHub = {}mcp(): {getTools(): Promise<- Array<{ name: string; description: string; inputSchema: unknown }>+ Array<{ name: string; description: string; inputSchema: unknown; server?: string }>+ >+ /** Optional — present in TauriMCPService, absent in DefaultMCPService. */+ getToolsForServers?(serverNames: string[]): Promise<+ Array<{ name: string; description: string; inputSchema: unknown; server?: string }>+ >+ /** Optional — present in TauriMCPService, absent in DefaultMCPService. */+ getServerSummaries?(): Promise<+ Array<{ name: string; capabilities: string[]; description: string }>>}}@@ -95,6 +104,8 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {private serviceHub: ServiceHub | nullprivate threadId?: stringprivate continueFromContent: string | null = null+ /** Latest user message text — used by the MCP orchestrator for tool routing. */+ private lastUserMessage = ''constructor(systemMessage?: string, threadId?: string) {this.systemMessage = systemMessage@@ -103,6 +114,10 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {// Tools will be loaded when updateRagToolsAvailability is called with model capabilities}+ setLastUserMessage(message: string): void {+ this.lastUserMessage = message+ }+updateSystemMessage(systemMessage: string | undefined) {this.systemMessage = systemMessage}@@ -216,15 +231,35 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {}}- // Load MCP tools (they don't depend on documents)+ // Load MCP tools — route through the orchestrator when available so only+ // relevant servers are queried instead of all of them.try {- const mcpTools = await this.serviceHub.mcp().getTools()+ const mcpService = this.serviceHub.mcp() as {+ getTools(): Promise<Array<{ name: string; description: string; inputSchema: unknown; server?: string }>>+ getToolsForServers?(serverNames: string[]): Promise<Array<{ name: string; description: string; inputSchema: unknown; server?: string }>>+ getServerSummaries?(): Promise<Array<{ name: string; capabilities: string[]; description: string }>>+ }++ let mcpTools: Array<{ name: string; description: string; inputSchema: unknown; server?: string }>++ if (mcpService.getToolsForServers && mcpService.getServerSummaries) {+ mcpTools = await mcpOrchestrator.getRelevantTools(+ this.lastUserMessage,+ {+ getTools: () => mcpService.getTools(),+ getToolsForServers: (names) => mcpService.getToolsForServers!(names),+ getServerSummaries: () => mcpService.getServerSummaries!(),+ },+ disabledToolKeys+ )+ } else {+ mcpTools = await mcpService.getTools()+ }+if (Array.isArray(mcpTools) && mcpTools.length > 0) {- // Convert MCP tools to AI SDK format, filtering out disabled tools- // MCP tools added after RAG tools, so they take precedence in case of name conflicts+ // MCP tools added after RAG tools, so they take precedence on name conflictsmcpTools.forEach((tool) => {- // MCP tools use MCPTool interface with server field- const serverName = (tool as { server?: string }).server || 'unknown'+ const serverName = tool.server || 'unknown'if (!isToolDisabled(serverName, tool.name)) {toolsRecord[tool.name] = {description: tool.description,diff --git a/web-app/src/lib/mcp-orchestrator/__tests__/intent-classifier.test.ts b/web-app/src/lib/mcp-orchestrator/__tests__/intent-classifier.test.tsnew file mode 100644index 000000000..dc93917f2--- /dev/null+++ b/web-app/src/lib/mcp-orchestrator/__tests__/intent-classifier.test.ts@@ -0,0 +1,159 @@+import { describe, it, expect } from 'vitest'+import {+ tokenize,+ classifyIntent,+ ROUTING_THRESHOLD,+ MAX_ROUTED_SERVERS,+} from '../intent-classifier'+import type { ServerSummary } from '@/services/mcp/types'++// ---------------------------------------------------------------------------+// tokenize+// ---------------------------------------------------------------------------++describe('tokenize', () => {+ it('lowercases and splits on non-alphanumeric separators', () => {+ expect(tokenize('Read a File from Disk')).toContain('read')+ expect(tokenize('Read a File from Disk')).toContain('file')+ expect(tokenize('Read a File from Disk')).toContain('disk')+ })++ it('strips stop words', () => {+ const tokens = tokenize('a the and or is are')+ expect(tokens).toHaveLength(0)+ })++ it('removes single-character tokens', () => {+ const tokens = tokenize('x y z hello')+ expect(tokens).not.toContain('x')+ expect(tokens).not.toContain('y')+ expect(tokens).toContain('hello')+ })++ it('handles empty string', () => {+ expect(tokenize('')).toEqual([])+ })++ it('handles punctuation and special chars', () => {+ const tokens = tokenize('read/write the file_path.txt')+ expect(tokens).toContain('read')+ expect(tokens).toContain('write')+ expect(tokens).toContain('file')+ expect(tokens).toContain('path')+ expect(tokens).toContain('txt')+ })+})++// ---------------------------------------------------------------------------+// classifyIntent — small server set (no routing needed)+// ---------------------------------------------------------------------------++describe('classifyIntent — below threshold', () => {+ const servers: ServerSummary[] = [+ { name: 'fs', capabilities: ['filesystem'], description: 'file operations' },+ { name: 'web', capabilities: ['web', 'browser'], description: 'browse the web' },+ { name: 'db', capabilities: ['database'], description: 'query databases' },+ ]++ it('returns all servers when count ≤ threshold', () => {+ // servers.length (3) ≤ ROUTING_THRESHOLD (5)+ const result = classifyIntent('read a file', servers)+ expect(result).toHaveLength(servers.length)+ expect(result).toContain('fs')+ expect(result).toContain('web')+ expect(result).toContain('db')+ })+})++// ---------------------------------------------------------------------------+// classifyIntent — routing active (> threshold servers)+// ---------------------------------------------------------------------------++const manyServers: ServerSummary[] = [+ { name: 'filesystem', capabilities: ['filesystem', 'files'], description: 'read and write files on disk' },+ { name: 'browser', capabilities: ['web', 'browser', 'search'], description: 'browse web pages and search' },+ { name: 'database', capabilities: ['database', 'sql'], description: 'query relational databases' },+ { name: 'calendar', capabilities: ['calendar', 'events', 'schedule'], description: 'manage calendar events' },+ { name: 'email', capabilities: ['email', 'mail'], description: 'send and read emails' },+ { name: 'code', capabilities: ['code', 'git', 'github'], description: 'interact with code repositories' },+]++describe('classifyIntent — above threshold', () => {+ it('returns only relevant servers for a filesystem query', () => {+ const result = classifyIntent('read the config file from disk', manyServers)+ expect(result).toContain('filesystem')+ expect(result).not.toContain('calendar')+ expect(result).not.toContain('email')+ })++ it('returns only relevant servers for a web query', () => {+ const result = classifyIntent('search the web for news', manyServers)+ expect(result).toContain('browser')+ expect(result).not.toContain('filesystem')+ expect(result).not.toContain('calendar')+ })++ it('returns only relevant servers for a code query', () => {+ const result = classifyIntent('show me git commits on github', manyServers)+ expect(result).toContain('code')+ })++ it('returns all servers when no keywords match (safe fallback)', () => {+ const result = classifyIntent('zxqfoo bar baz', manyServers)+ expect(result).toHaveLength(manyServers.length)+ })++ it('returns all servers for an empty message', () => {+ const result = classifyIntent('', manyServers)+ expect(result).toHaveLength(manyServers.length)+ })++ it('respects maxServers option', () => {+ // Craft a message that matches all servers+ const wideMessage = 'files web database calendar email code git'+ const result = classifyIntent(wideMessage, manyServers, { maxServers: 2 })+ expect(result.length).toBeLessThanOrEqual(2)+ })++ it('returns empty array for empty server list', () => {+ expect(classifyIntent('read a file', [])).toEqual([])+ })++ it('does not exceed MAX_ROUTED_SERVERS by default', () => {+ const lotsOfServers: ServerSummary[] = Array.from({ length: 20 }, (_, i) => ({+ name: `server${i}`,+ capabilities: ['generic'],+ description: 'generic server',+ }))+ const wideMessage = 'do something generic with all servers'+ const result = classifyIntent(wideMessage, lotsOfServers)+ expect(result.length).toBeLessThanOrEqual(MAX_ROUTED_SERVERS)+ })+})++// ---------------------------------------------------------------------------+// classifyIntent — exact vs partial capability matches+// ---------------------------------------------------------------------------++describe('classifyIntent — scoring weights', () => {+ const servers: ServerSummary[] = [+ { name: 'exact', capabilities: ['email'], description: 'email server' },+ { name: 'partial', capabilities: ['emailing'], description: 'handles emailing tasks' },+ { name: 'desc', capabilities: ['messaging'], description: 'send email notifications' },+ { name: 'unrelated', capabilities: ['filesystem'], description: 'read local files' },+ { name: 'unrelated2', capabilities: ['calendar'], description: 'manage events' },+ { name: 'unrelated3', capabilities: ['database'], description: 'sql queries' },+ ]++ it('prefers exact capability match over description match', () => {+ const result = classifyIntent('send an email', servers)+ const exactIdx = result.indexOf('exact')+ const descIdx = result.indexOf('desc')++ expect(exactIdx).toBeGreaterThanOrEqual(0)+ // exact match should score higher (appear earlier) than desc-only match+ if (descIdx !== -1) {+ expect(exactIdx).toBeLessThanOrEqual(descIdx)+ }+ })+})diff --git a/web-app/src/lib/mcp-orchestrator/__tests__/mcp-orchestrator.test.ts b/web-app/src/lib/mcp-orchestrator/__tests__/mcp-orchestrator.test.tsnew file mode 100644index 000000000..d20a6cf84--- /dev/null+++ b/web-app/src/lib/mcp-orchestrator/__tests__/mcp-orchestrator.test.ts@@ -0,0 +1,228 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { MCPOrchestrator } from '../mcp-orchestrator'+import type { MCPServiceLike } from '../mcp-orchestrator'+import type { ServerSummary } from '@/services/mcp/types'++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++function makeService(overrides: Partial<MCPServiceLike> = {}): MCPServiceLike {+ return {+ getTools: vi.fn().mockResolvedValue([]),+ getToolsForServers: vi.fn().mockResolvedValue([]),+ getServerSummaries: vi.fn().mockResolvedValue([]),+ ...overrides,+ }+}++const fewSummaries: ServerSummary[] = [+ { name: 'fs', capabilities: ['filesystem'], description: 'read/write files' },+ { name: 'web', capabilities: ['browser'], description: 'browse the web' },+]++const manySummaries: ServerSummary[] = [+ { name: 'filesystem', capabilities: ['filesystem', 'files'], description: 'read and write files on disk' },+ { name: 'browser', capabilities: ['web', 'browser', 'search'], description: 'browse web pages' },+ { name: 'database', capabilities: ['database', 'sql'], description: 'query databases' },+ { name: 'calendar', capabilities: ['calendar', 'events'], description: 'manage calendar events' },+ { name: 'email', capabilities: ['email', 'mail'], description: 'send and read emails' },+ { name: 'code', capabilities: ['code', 'git'], description: 'interact with code repositories' },+]++// ---------------------------------------------------------------------------+// Tests+// ---------------------------------------------------------------------------++describe('MCPOrchestrator', () => {+ let orchestrator: MCPOrchestrator++ beforeEach(() => {+ orchestrator = new MCPOrchestrator()+ })++ // ─── below threshold — uses getTools() ───────────────────────────────────++ describe('when few servers (≤ threshold)', () => {+ it('calls getTools() directly', async () => {+ const mockTools = [+ { name: 'read_file', description: 'reads a file', inputSchema: {}, server: 'fs' },+ ]+ const service = makeService({+ getServerSummaries: vi.fn().mockResolvedValue(fewSummaries),+ getTools: vi.fn().mockResolvedValue(mockTools),+ })++ const tools = await orchestrator.getRelevantTools('read a file', service, [])++ expect(service.getTools).toHaveBeenCalled()+ expect(service.getToolsForServers).not.toHaveBeenCalled()+ expect(tools).toEqual(mockTools)+ })++ it('filters disabled tools', async () => {+ const mockTools = [+ { name: 'read_file', description: 'reads a file', inputSchema: {}, server: 'fs' },+ { name: 'write_file', description: 'writes a file', inputSchema: {}, server: 'fs' },+ ]+ const service = makeService({+ getServerSummaries: vi.fn().mockResolvedValue(fewSummaries),+ getTools: vi.fn().mockResolvedValue(mockTools),+ })++ const tools = await orchestrator.getRelevantTools('read a file', service, ['fs::write_file'])++ expect(tools).toHaveLength(1)+ expect(tools[0].name).toBe('read_file')+ })+ })++ // ─── above threshold — uses getToolsForServers() ─────────────────────────++ describe('when many servers (> threshold)', () => {+ it('calls getToolsForServers() with intent-selected server names', async () => {+ const mockTools = [+ { name: 'read_file', description: 'reads a file', inputSchema: {}, server: 'filesystem' },+ ]+ const service = makeService({+ getServerSummaries: vi.fn().mockResolvedValue(manySummaries),+ getToolsForServers: vi.fn().mockResolvedValue(mockTools),+ })++ await orchestrator.getRelevantTools('read the file from disk', service, [])++ expect(service.getToolsForServers).toHaveBeenCalled()+ const calledWith = (service.getToolsForServers as ReturnType<typeof vi.fn>).mock.calls[0][0] as string[]+ expect(calledWith).toContain('filesystem')+ // Should NOT include unrelated servers+ expect(calledWith).not.toContain('email')+ expect(calledWith).not.toContain('calendar')+ })++ it('falls back to all servers when intent yields no match', async () => {+ const service = makeService({+ getServerSummaries: vi.fn().mockResolvedValue(manySummaries),+ getTools: vi.fn().mockResolvedValue([]),+ getToolsForServers: vi.fn().mockResolvedValue([]),+ })++ // Gibberish message → no keyword match → all servers+ await orchestrator.getRelevantTools('zzzzxxx', service, [])+ // When all servers are returned by classifyIntent the count equals manySummaries.length+ const calledWith = (service.getToolsForServers as ReturnType<typeof vi.fn>).mock.calls[0][0] as string[]+ expect(calledWith).toHaveLength(manySummaries.length)+ })+ })++ // ─── caching ─────────────────────────────────────────────────────────────++ describe('tool caching', () => {+ it('uses cached tools on second call without hitting the service again', async () => {+ const mockTools = [+ { name: 'read_file', description: 'reads a file', inputSchema: {}, server: 'filesystem' },+ ]+ const service = makeService({+ getServerSummaries: vi.fn().mockResolvedValue(manySummaries),+ getToolsForServers: vi.fn().mockResolvedValue(mockTools),+ })++ await orchestrator.getRelevantTools('read a file from disk', service, [])+ await orchestrator.getRelevantTools('read a file from disk', service, [])++ // getToolsForServers should only be called once — second call uses cache+ expect(service.getToolsForServers).toHaveBeenCalledTimes(1)+ })++ it('clears the full cache on invalidateCache() with no argument', async () => {+ const mockTools = [+ { name: 'read_file', description: 'reads a file', inputSchema: {}, server: 'filesystem' },+ ]+ const service = makeService({+ getServerSummaries: vi.fn().mockResolvedValue(manySummaries),+ getToolsForServers: vi.fn().mockResolvedValue(mockTools),+ })++ await orchestrator.getRelevantTools('read a file from disk', service, [])+ orchestrator.invalidateCache()+ await orchestrator.getRelevantTools('read a file from disk', service, [])++ expect(service.getToolsForServers).toHaveBeenCalledTimes(2)+ })++ it('clears only one server cache on invalidateCache(serverName)', async () => {+ const fsTools = [{ name: 'read_file', description: '', inputSchema: {}, server: 'filesystem' }]+ const browserTools = [{ name: 'browse', description: '', inputSchema: {}, server: 'browser' }]++ const service = makeService({+ getServerSummaries: vi.fn().mockResolvedValue(manySummaries),+ getToolsForServers: vi.fn()+ .mockResolvedValueOnce([...fsTools, ...browserTools])+ .mockResolvedValueOnce(fsTools),+ })++ await orchestrator.getRelevantTools('read file and browse web', service, [])+ orchestrator.invalidateCache('filesystem')+ await orchestrator.getRelevantTools('read file and browse web', service, [])++ // Second call should refetch — but only for filesystem, browser is still cached+ expect(service.getToolsForServers).toHaveBeenCalledTimes(2)+ })+ })++ // ─── summary caching ─────────────────────────────────────────────────────++ describe('server summary caching', () => {+ it('fetches summaries only once for multiple consecutive calls', async () => {+ const service = makeService({+ getServerSummaries: vi.fn().mockResolvedValue(fewSummaries),+ getTools: vi.fn().mockResolvedValue([]),+ })++ await orchestrator.getRelevantTools('hello', service, [])+ await orchestrator.getRelevantTools('world', service, [])+ await orchestrator.getRelevantTools('foo', service, [])++ expect(service.getServerSummaries).toHaveBeenCalledTimes(1)+ })++ it('re-fetches summaries after invalidateCache()', async () => {+ const service = makeService({+ getServerSummaries: vi.fn().mockResolvedValue(fewSummaries),+ getTools: vi.fn().mockResolvedValue([]),+ })++ await orchestrator.getRelevantTools('hello', service, [])+ orchestrator.invalidateCache()+ await orchestrator.getRelevantTools('world', service, [])++ expect(service.getServerSummaries).toHaveBeenCalledTimes(2)+ })+ })++ // ─── error resilience ────────────────────────────────────────────────────++ describe('error resilience', () => {+ it('falls back to getTools() when getServerSummaries() throws', async () => {+ const mockTools = [{ name: 'tool', description: '', inputSchema: {}, server: 's' }]+ const service = makeService({+ getServerSummaries: vi.fn().mockRejectedValue(new Error('network error')),+ getTools: vi.fn().mockResolvedValue(mockTools),+ })++ const tools = await orchestrator.getRelevantTools('do something', service, [])+ // summaries failed → empty list → below threshold → getTools()+ expect(service.getTools).toHaveBeenCalled()+ expect(tools).toEqual(mockTools)+ })++ it('returns empty tools when getToolsForServers() throws', async () => {+ const service = makeService({+ getServerSummaries: vi.fn().mockResolvedValue(manySummaries),+ getToolsForServers: vi.fn().mockRejectedValue(new Error('server down')),+ })++ const tools = await orchestrator.getRelevantTools('read a file', service, [])+ expect(tools).toEqual([])+ })+ })+})diff --git a/web-app/src/lib/mcp-orchestrator/index.ts b/web-app/src/lib/mcp-orchestrator/index.tsnew file mode 100644index 000000000..ad70ff49b--- /dev/null+++ b/web-app/src/lib/mcp-orchestrator/index.ts@@ -0,0 +1,3 @@+export { classifyIntent, tokenize, ROUTING_THRESHOLD, MAX_ROUTED_SERVERS } from './intent-classifier'+export { MCPOrchestrator, mcpOrchestrator } from './mcp-orchestrator'+export type { MCPServiceLike } from './mcp-orchestrator'diff --git a/web-app/src/lib/mcp-orchestrator/intent-classifier.ts b/web-app/src/lib/mcp-orchestrator/intent-classifier.tsnew file mode 100644index 000000000..306c8a968--- /dev/null+++ b/web-app/src/lib/mcp-orchestrator/intent-classifier.ts@@ -0,0 +1,91 @@+import type { ServerSummary } from '@/services/mcp/types'++// Skip routing when connected servers are at or below this count.+export const ROUTING_THRESHOLD = 5+// Hard cap on how many servers are selected when routing is active.+export const MAX_ROUTED_SERVERS = 5++const STOP_WORDS = new Set([+ 'a', 'an', 'the', 'is', 'are', 'was', 'were', 'be', 'been', 'being',+ 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could',+ 'should', 'may', 'might', 'can', 'shall', 'to', 'of', 'in', 'for',+ 'on', 'with', 'at', 'by', 'from', 'up', 'about', 'into', 'through',+ 'during', 'and', 'but', 'or', 'nor', 'so', 'yet', 'both', 'either',+ 'neither', 'not', 'only', 'same', 'than', 'too', 'very', 'just',+ 'me', 'my', 'you', 'your', 'we', 'our', 'it', 'its', 'this', 'that',+ 'i', 'what', 'how', 'when', 'where', 'which', 'who', 'please', 'help',+])++/** Lowercase alpha-numeric tokens with stop words and single-char tokens removed. */+export function tokenize(text: string): string[] {+ return text+ .toLowerCase()+ .split(/[^a-z0-9]+/)+ .filter((t) => t.length > 1 && !STOP_WORDS.has(t))+}++interface ScoredServer {+ name: string+ score: number+}++// Weights: exact capability match +4, partial capability match +2, description token match +1.+function scoreServer(server: ServerSummary, messageTokens: string[]): number {+ if (messageTokens.length === 0) return 0++ const capTokens = server.capabilities.map((c) => c.toLowerCase())+ const descTokens = tokenize(server.description)+ let score = 0++ for (const msgToken of messageTokens) {+ for (const cap of capTokens) {+ if (cap === msgToken) {+ score += 4+ } else if (cap.includes(msgToken) || msgToken.includes(cap)) {+ score += 2+ }+ }+ for (const descToken of descTokens) {+ if (descToken === msgToken) {+ score += 1+ }+ }+ }++ return score+}++/**+ * Returns server names relevant to `userMessage`, up to MAX_ROUTED_SERVERS.+ * Falls back to all servers when the count is small or no keywords match.+ */+export function classifyIntent(+ userMessage: string,+ servers: ServerSummary[],+ options?: { threshold?: number; maxServers?: number }+): string[] {+ const threshold = options?.threshold ?? ROUTING_THRESHOLD+ const maxServers = options?.maxServers ?? MAX_ROUTED_SERVERS++ if (servers.length === 0) return []+ if (servers.length <= threshold) return servers.map((s) => s.name)++ const messageTokens = tokenize(userMessage)+ if (messageTokens.length === 0) return servers.map((s) => s.name)++ const scored: ScoredServer[] = servers.map((server) => ({+ name: server.name,+ score: scoreServer(server, messageTokens),+ }))++ // Require score ≥ 2 so a single common-verb match in a description+ // (e.g. "read" in "send and read emails") doesn't route to an unrelated server.+ const positive = scored.filter((s) => s.score >= 2)++ if (positive.length === 0) return servers.map((s) => s.name)++ return positive+ .sort((a, b) => b.score - a.score)+ .slice(0, maxServers)+ .map((s) => s.name)+}diff --git a/web-app/src/lib/mcp-orchestrator/mcp-orchestrator.ts b/web-app/src/lib/mcp-orchestrator/mcp-orchestrator.tsnew file mode 100644index 000000000..3a7a26d12--- /dev/null+++ b/web-app/src/lib/mcp-orchestrator/mcp-orchestrator.ts@@ -0,0 +1,130 @@+import type { MCPTool } from '@/types/completion'+import type { ServerSummary } from '@/services/mcp/types'+import { classifyIntent, ROUTING_THRESHOLD } from './intent-classifier'++export interface MCPServiceLike {+ getTools(): Promise<MCPTool[]>+ getToolsForServers(serverNames: string[]): Promise<MCPTool[]>+ getServerSummaries(): Promise<ServerSummary[]>+}++interface CacheEntry {+ tools: MCPTool[]+ expiresAt: number+}++const CACHE_TTL_MS = 30_000+const SUMMARY_TTL_MS = 60_000++export class MCPOrchestrator {+ private toolCache = new Map<string, CacheEntry>()+ private summaryCache: ServerSummary[] | null = null+ private summaryExpiresAt = 0++ /** Returns tools relevant to `userMessage` with disabled keys filtered out. */+ async getRelevantTools(+ userMessage: string,+ service: MCPServiceLike,+ disabledKeys: string[]+ ): Promise<MCPTool[]> {+ const summaries = await this.fetchSummaries(service)++ if (summaries.length <= ROUTING_THRESHOLD) {+ const tools = await this.fetchAllTools(service)+ return this.filterDisabled(tools, disabledKeys)+ }++ const selectedNames = classifyIntent(userMessage, summaries)+ const tools = await this.fetchToolsForServers(selectedNames, service)+ return this.filterDisabled(tools, disabledKeys)+ }++ /**+ * Clears cached tool data.+ * Pass a server name to invalidate only that server; omit to clear everything.+ */+ invalidateCache(serverName?: string): void {+ if (serverName) {+ this.toolCache.delete(serverName)+ } else {+ this.toolCache.clear()+ this.summaryCache = null+ this.summaryExpiresAt = 0+ }+ }++ private async fetchSummaries(service: MCPServiceLike): Promise<ServerSummary[]> {+ const now = Date.now()+ if (this.summaryCache !== null && now < this.summaryExpiresAt) {+ return this.summaryCache+ }+ try {+ const summaries = await service.getServerSummaries()+ this.summaryCache = summaries+ this.summaryExpiresAt = now + SUMMARY_TTL_MS+ return summaries+ } catch {+ return []+ }+ }++ private async fetchAllTools(service: MCPServiceLike): Promise<MCPTool[]> {+ try {+ return await service.getTools()+ } catch {+ return []+ }+ }++ private async fetchToolsForServers(+ serverNames: string[],+ service: MCPServiceLike+ ): Promise<MCPTool[]> {+ const now = Date.now()+ const result: MCPTool[] = []+ const uncached: string[] = []++ for (const name of serverNames) {+ const entry = this.toolCache.get(name)+ if (entry && now < entry.expiresAt) {+ result.push(...entry.tools)+ } else {+ uncached.push(name)+ }+ }++ if (uncached.length > 0) {+ try {+ const fresh = await service.getToolsForServers(uncached)++ const byServer = new Map<string, MCPTool[]>()+ for (const tool of fresh) {+ const srv = (tool as { server?: string }).server ?? 'unknown'+ if (!byServer.has(srv)) byServer.set(srv, [])+ byServer.get(srv)!.push(tool)+ }++ for (const name of uncached) {+ const serverTools = byServer.get(name) ?? []+ this.toolCache.set(name, { tools: serverTools, expiresAt: now + CACHE_TTL_MS })+ result.push(...serverTools)+ }+ } catch {+ // partial failure — tools for uncached servers are omitted+ }+ }++ return result+ }++ private filterDisabled(tools: MCPTool[], disabledKeys: string[]): MCPTool[] {+ if (disabledKeys.length === 0) return tools+ return tools.filter((tool) => {+ const key = `${(tool as { server?: string }).server ?? 'unknown'}::${tool.name}`+ return !disabledKeys.includes(key)+ })+ }+}++// Shared across all CustomChatTransport instances within the same session.+export const mcpOrchestrator = new MCPOrchestrator()