Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat: implement MCP tool routing structured LLM step in the orchestrator

dataCenter4305f4b2093908f
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index 834b9ae1a..f1d8e6fcf 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -57,6 +57,24 @@ export type ServiceHub = {
}
}
+/** Text from the most recent user message (for MCP server routing). */
+function extractLatestUserText(messages: UIMessage[]): string {
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const m = messages[i]
+ if (m.role !== 'user') continue
+ const parts = Array.isArray(m.parts) ? m.parts : []
+ const chunks: string[] = []
+ for (const p of parts) {
+ if (p.type === 'text' && typeof (p as { text?: string }).text === 'string') {
+ const t = (p as { text: string }).text.trim()
+ if (t) chunks.push(t)
+ }
+ }
+ if (chunks.length > 0) return chunks.join('\n')
+ }
+ return ''
+}
+
/**
* Wraps a UIMessageChunk stream so that when the first `text-start` chunk
* arrives, a `text-delta` carrying `prefixText` is immediately injected into
@@ -151,7 +169,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
* Filters out disabled tools based on thread settings
* @private
*/
- async refreshTools() {
+ async refreshTools(abortSignal?: AbortSignal) {
if (!this.serviceHub) {
this.tools = {}
return
@@ -246,7 +264,11 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
mcpService.getToolsForServers!(names),
getServerSummaries: () => mcpService.getServerSummaries!(),
},
- disabledToolKeys
+ disabledToolKeys,
+ {
+ routerModel: this.model,
+ abortSignal,
+ }
)
} else {
mcpTools = await mcpService.getTools()
@@ -299,9 +321,6 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
messageId: string | undefined
} & ChatRequestOptions
): Promise<ReadableStream<UIMessageChunk>> {
- // Ensure tools updated before sending messages
- await this.refreshTools()
-
// Capture the effective provider name early so the Anthropic serial
// tool-use repair later uses the same value that was used to create the
// model, even if the user switches provider mid-request.
@@ -309,33 +328,36 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
const providerId = useModelProvider.getState().selectedProvider
const effectiveProviderName = providerId
const provider = useModelProvider.getState().getProviderByName(providerId)
- if (this.serviceHub && modelId && provider) {
- try {
- const updatedProvider = useModelProvider
- .getState()
- .getProviderByName(providerId)
-
- // Get assistant parameters from current assistant
- const currentAssistant = useAssistant.getState().currentAssistant
- const inferenceParams = currentAssistant?.parameters
-
- // Create the model using the factory
- // For llamacpp provider, startModel is called internally in ModelFactory.createLlamaCppModel
- this.model = await ModelFactory.createModel(
- modelId,
- updatedProvider ?? provider,
- inferenceParams ?? {}
- )
- } catch (error) {
- console.error('Failed to create model:', error)
- throw new Error(
- `Failed to create model: ${error instanceof Error ? error.message : JSON.stringify(error)}`
- )
- }
- } else {
+ if (!this.serviceHub || !modelId || !provider) {
throw new Error('ServiceHub not initialized or model/provider missing.')
}
+ this.lastUserMessage = extractLatestUserText(options.messages)
+
+ try {
+ const updatedProvider = useModelProvider
+ .getState()
+ .getProviderByName(providerId)
+
+ const currentAssistant = useAssistant.getState().currentAssistant
+ const inferenceParams = currentAssistant?.parameters
+
+ // Create the model before refreshing tools so the MCP orchestrator can run
+ // structured LLM routing when many servers are connected.
+ this.model = await ModelFactory.createModel(
+ modelId,
+ updatedProvider ?? provider,
+ inferenceParams ?? {}
+ )
+ } catch (error) {
+ console.error('Failed to create model:', error)
+ throw new Error(
+ `Failed to create model: ${error instanceof Error ? error.message : JSON.stringify(error)}`
+ )
+ }
+
+ await this.refreshTools(options.abortSignal)
+
// Fix for Anthropic serial tool-use (error 400): when an assistant message
// contains tool parts interleaved with text parts (serial tool calls),
// split it into separate messages so convertToModelMessages produces the
diff --git a/web-app/src/lib/mcp-orchestrator/__tests__/mcp-router-llm-orchestrator.test.ts b/web-app/src/lib/mcp-orchestrator/__tests__/mcp-router-llm-orchestrator.test.ts
new file mode 100644
index 000000000..1fb17f723
--- /dev/null
+++ b/web-app/src/lib/mcp-orchestrator/__tests__/mcp-router-llm-orchestrator.test.ts
@@ -0,0 +1,109 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { MCPOrchestrator } from '../mcp-orchestrator'
+import type { MCPServiceLike } from '../mcp-orchestrator'
+import type { ServerSummary } from '@/services/mcp/types'
+import * as mcpRouterLlm from '../mcp-router-llm'
+
+vi.mock('../mcp-router-llm', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../mcp-router-llm')>()
+ return {
+ ...actual,
+ selectServersWithLlm: vi.fn(),
+ }
+})
+
+const manySummaries: ServerSummary[] = [
+ { name: 'filesystem', capabilities: ['filesystem'], description: 'files' },
+ { name: 'browser', capabilities: ['web'], description: 'web' },
+ { name: 'database', capabilities: ['database'], description: 'sql' },
+ { name: 'calendar', capabilities: ['calendar'], description: 'events' },
+ { name: 'email', capabilities: ['email'], description: 'mail' },
+ { name: 'code', capabilities: ['code'], description: 'git' },
+]
+
+function makeService(overrides: Partial<MCPServiceLike> = {}): MCPServiceLike {
+ return {
+ getTools: vi.fn().mockResolvedValue([]),
+ getToolsForServers: vi.fn().mockResolvedValue([]),
+ getServerSummaries: vi.fn().mockResolvedValue([]),
+ ...overrides,
+ }
+}
+
+describe('MCPOrchestrator LLM routing', () => {
+ let orchestrator: MCPOrchestrator
+
+ beforeEach(() => {
+ orchestrator = new MCPOrchestrator()
+ vi.mocked(mcpRouterLlm.selectServersWithLlm).mockReset()
+ })
+
+ afterEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('uses LLM server list when the model returns non-empty selection', async () => {
+ vi.mocked(mcpRouterLlm.selectServersWithLlm).mockResolvedValue(['email', 'calendar'])
+
+ const mockTools = [{ name: 'send', description: '', inputSchema: {}, server: 'email' }]
+ const service = makeService({
+ getServerSummaries: vi.fn().mockResolvedValue(manySummaries),
+ getToolsForServers: vi.fn().mockResolvedValue(mockTools),
+ })
+
+ const fakeModel = { specificationVersion: 'v2', provider: 'x', modelId: 'y' } as const
+
+ await orchestrator.getRelevantTools('schedule a meeting and email invites', service, [], {
+ routerModel: fakeModel as never,
+ })
+
+ expect(mcpRouterLlm.selectServersWithLlm).toHaveBeenCalled()
+ const calledWith = (service.getToolsForServers as ReturnType<typeof vi.fn>).mock.calls[0][0] as string[]
+ expect(calledWith).toEqual(['email', 'calendar'])
+ })
+
+ it('falls back to keyword routing when LLM returns empty', async () => {
+ vi.mocked(mcpRouterLlm.selectServersWithLlm).mockResolvedValue([])
+
+ const service = makeService({
+ getServerSummaries: vi.fn().mockResolvedValue(manySummaries),
+ getToolsForServers: vi.fn().mockResolvedValue([]),
+ })
+
+ const fakeModel = { specificationVersion: 'v2', provider: 'x', modelId: 'y' } as const
+
+ await orchestrator.getRelevantTools('read the file from disk', service, [], {
+ routerModel: fakeModel as never,
+ })
+
+ expect(mcpRouterLlm.selectServersWithLlm).toHaveBeenCalled()
+ const calledWith = (service.getToolsForServers as ReturnType<typeof vi.fn>).mock.calls[0][0] as string[]
+ expect(calledWith).toContain('filesystem')
+ })
+
+ it('does not call the LLM without a router model', async () => {
+ const service = makeService({
+ getServerSummaries: vi.fn().mockResolvedValue(manySummaries),
+ getToolsForServers: vi.fn().mockResolvedValue([]),
+ })
+
+ await orchestrator.getRelevantTools('read the file from disk', service, [])
+
+ expect(mcpRouterLlm.selectServersWithLlm).not.toHaveBeenCalled()
+ })
+
+ it('does not call the LLM when the user message is blank', async () => {
+ const service = makeService({
+ getServerSummaries: vi.fn().mockResolvedValue(manySummaries),
+ getToolsForServers: vi.fn().mockResolvedValue([]),
+ })
+
+ const fakeModel = { specificationVersion: 'v2', provider: 'x', modelId: 'y' } as const
+
+ await orchestrator.getRelevantTools(' ', service, [], {
+ routerModel: fakeModel as never,
+ })
+
+ expect(mcpRouterLlm.selectServersWithLlm).not.toHaveBeenCalled()
+ })
+})
diff --git a/web-app/src/lib/mcp-orchestrator/index.ts b/web-app/src/lib/mcp-orchestrator/index.ts
index ad70ff49b..0bc11787e 100644
--- a/web-app/src/lib/mcp-orchestrator/index.ts
+++ b/web-app/src/lib/mcp-orchestrator/index.ts
@@ -1,3 +1,4 @@
export { classifyIntent, tokenize, ROUTING_THRESHOLD, MAX_ROUTED_SERVERS } from './intent-classifier'
+export { MCP_ROUTER_TIMEOUT_MS, selectServersWithLlm } from './mcp-router-llm'
export { MCPOrchestrator, mcpOrchestrator } from './mcp-orchestrator'
-export type { MCPServiceLike } from './mcp-orchestrator'
+export type { GetRelevantToolsOptions, MCPServiceLike } from './mcp-orchestrator'
diff --git a/web-app/src/lib/mcp-orchestrator/mcp-orchestrator.ts b/web-app/src/lib/mcp-orchestrator/mcp-orchestrator.ts
index 3a7a26d12..091a5f9ea 100644
--- a/web-app/src/lib/mcp-orchestrator/mcp-orchestrator.ts
+++ b/web-app/src/lib/mcp-orchestrator/mcp-orchestrator.ts
@@ -1,6 +1,8 @@
+import type { LanguageModel } from 'ai'
import type { MCPTool } from '@/types/completion'
import type { ServerSummary } from '@/services/mcp/types'
import { classifyIntent, ROUTING_THRESHOLD } from './intent-classifier'
+import { selectServersWithLlm } from './mcp-router-llm'
export interface MCPServiceLike {
getTools(): Promise<MCPTool[]>
@@ -8,6 +10,12 @@ export interface MCPServiceLike {
getServerSummaries(): Promise<ServerSummary[]>
}
+export interface GetRelevantToolsOptions {
+ /** When set (e.g. chat model), used for structured server selection above the routing threshold. */
+ routerModel?: LanguageModel | null
+ abortSignal?: AbortSignal
+}
+
interface CacheEntry {
tools: MCPTool[]
expiresAt: number
@@ -25,7 +33,8 @@ export class MCPOrchestrator {
async getRelevantTools(
userMessage: string,
service: MCPServiceLike,
- disabledKeys: string[]
+ disabledKeys: string[],
+ options?: GetRelevantToolsOptions
): Promise<MCPTool[]> {
const summaries = await this.fetchSummaries(service)
@@ -34,7 +43,22 @@ export class MCPOrchestrator {
return this.filterDisabled(tools, disabledKeys)
}
- const selectedNames = classifyIntent(userMessage, summaries)
+ const keywordNames = classifyIntent(userMessage, summaries)
+ let selectedNames = keywordNames
+
+ const routerModel = options?.routerModel
+ if (routerModel && userMessage.trim()) {
+ const llmNames = await selectServersWithLlm(
+ userMessage,
+ summaries,
+ routerModel,
+ options.abortSignal
+ )
+ if (llmNames.length > 0) {
+ selectedNames = llmNames
+ }
+ }
+
const tools = await this.fetchToolsForServers(selectedNames, service)
return this.filterDisabled(tools, disabledKeys)
}
diff --git a/web-app/src/lib/mcp-orchestrator/mcp-router-llm.ts b/web-app/src/lib/mcp-orchestrator/mcp-router-llm.ts
new file mode 100644
index 000000000..0ad2eb8ad
--- /dev/null
+++ b/web-app/src/lib/mcp-orchestrator/mcp-router-llm.ts
@@ -0,0 +1,56 @@
+import { generateObject, type LanguageModel } from 'ai'
+import { z } from 'zod'
+import type { ServerSummary } from '@/services/mcp/types'
+import { MAX_ROUTED_SERVERS } from './intent-classifier'
+
+const routerSchema = z.object({
+ selectedServers: z.array(z.string()),
+})
+
+export const MCP_ROUTER_TIMEOUT_MS = 3_500
+
+/**
+ * Uses a small structured LLM call to pick MCP server names relevant to the user message.
+ * Returns an empty array on timeout, abort, or error so the caller can fall back to keyword routing.
+ */
+export async function selectServersWithLlm(
+ userMessage: string,
+ summaries: ServerSummary[],
+ model: LanguageModel,
+ abortSignal?: AbortSignal
+): Promise<string[]> {
+ const allowed = new Set(summaries.map((s) => s.name))
+ const lines = summaries.map(
+ (s) =>
+ `- ${s.name}: ${s.description || '(no description)'} [capabilities: ${s.capabilities.length ? s.capabilities.join(', ') : 'none'}]`
+ )
+ const system = `You choose which MCP servers are relevant to the user's latest message. Output only via the structured schema. Only use server names from the list. Pick at most ${MAX_ROUTED_SERVERS} servers. If none apply, return an empty selectedServers array.`
+
+ const routerAbort = new AbortController()
+ const onParentAbort = () => routerAbort.abort()
+ if (abortSignal) {
+ if (abortSignal.aborted) routerAbort.abort()
+ else abortSignal.addEventListener('abort', onParentAbort, { once: true })
+ }
+ const timeoutId = setTimeout(() => routerAbort.abort(), MCP_ROUTER_TIMEOUT_MS)
+
+ try {
+ const { object } = await generateObject({
+ model,
+ schema: routerSchema,
+ schemaName: 'MCPRouterSelection',
+ system,
+ prompt: `Servers:\n${lines.join('\n')}\n\nUser message:\n${userMessage}`,
+ temperature: 0,
+ maxOutputTokens: 256,
+ abortSignal: routerAbort.signal,
+ })
+ const names = object.selectedServers.filter((n) => allowed.has(n))
+ return [...new Set(names)].slice(0, MAX_ROUTED_SERVERS)
+ } catch {
+ return []
+ } finally {
+ clearTimeout(timeoutId)
+ abortSignal?.removeEventListener('abort', onParentAbort)
+ }
+}