The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(mcp): every external MCP server failed to connect
purple396e85ddf4fb
diff --git a/src/api/mcp/__tests__/external-client.test.ts b/src/api/mcp/__tests__/external-client.test.tsnew file mode 100644index 00000000..94f6d18b--- /dev/null+++ b/src/api/mcp/__tests__/external-client.test.ts@@ -0,0 +1,239 @@+/**+ * MCPExternalClient against a stand-in for @tauri-apps/plugin-shell that+ * mirrors the real API exactly: the Command carries stdout/stderr/close, and+ * ONLY the Child returned by spawn() has write() and kill().+ *+ * The client used to keep the Command and reach for `command.stdin.write`,+ * which is undefined there — so the initialize handshake threw on the very+ * first request and every external MCP server failed to connect with+ * "Cannot read properties of undefined (reading 'write')". The fake below+ * makes that a hard failure again: touching `stdin` throws.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { MCPExternalClient } from '../external-client'+import type { MCPServerConfig } from '../types'++class Emitter {+ private handlers: Record<string, ((data: any) => void)[]> = {}+ on(event: string, fn: (data: any) => void) {+ ;(this.handlers[event] ||= []).push(fn)+ }+ emit(event: string, data?: any) {+ for (const fn of this.handlers[event] || []) fn(data)+ }+}++/** Server behaviour a single test wants: id/method → response line. */+type Responder = (req: any) => string | null++let lastServer: FakeServer | null = null+let killCount = 0++class FakeChild {+ server: FakeServer+ constructor(server: FakeServer) {+ this.server = server+ }+ async write(data: string) {+ this.server.receive(data)+ }+ async kill() {+ killCount+++ this.server.killed = true+ }+}++class FakeServer extends Emitter {+ stdout = new Emitter()+ stderr = new Emitter()+ killed = false+ spawned = false+ written: string[] = []+ /** Set `stdin` so any code reading it fails the way the real API would. */+ get stdin(): never {+ throw new Error('the real Command has no stdin — write() lives on the Child')+ }+ constructor() {+ super()+ lastServer = this+ }+ async spawn() {+ this.spawned = true+ return new FakeChild(this)+ }+ receive(data: string) {+ this.written.push(data)+ for (const line of data.split('\n')) {+ if (!line.trim()) continue+ const out = responder(JSON.parse(line))+ // Tauri's line reader hands the newline through with the line.+ if (out !== null) this.stdout.emit('data', out + '\n')+ }+ }+}++let responder: Responder = () => null++vi.mock('@tauri-apps/plugin-shell', () => ({+ Command: {+ create: (_cmd: string, _args?: string[], _opts?: unknown) => new FakeServer(),+ },+}))++const config: MCPServerConfig = {+ id: 'srv-1',+ name: 'weather',+ command: 'npx',+ args: ['-y', 'weather-mcp'],+ enabled: true,+}++/** A well-behaved MCP server: handshake, one tool, echoing tools/call. */+const goodServer: Responder = (req) => {+ if (req.method === 'initialize') {+ return JSON.stringify({ jsonrpc: '2.0', id: req.id, result: { protocolVersion: '2024-11-05' } })+ }+ if (req.method === 'tools/list') {+ return JSON.stringify({+ jsonrpc: '2.0',+ id: req.id,+ result: { tools: [{ name: 'get_forecast', description: 'forecast', inputSchema: { type: 'object', properties: { city: { type: 'string' } } } }] },+ })+ }+ if (req.method === 'tools/call') {+ return JSON.stringify({+ jsonrpc: '2.0',+ id: req.id,+ result: { content: [{ type: 'text', text: `sunny in ${req.params.arguments.city}` }] },+ })+ }+ return null+}++beforeEach(() => {+ responder = goodServer+ lastServer = null+ killCount = 0+})++/** connect() dynamically imports the shell plugin, so the fake appears a few+ * ticks in. Wait for the condition instead of guessing a tick count. */+async function until(cond: () => boolean, what: string) {+ for (let i = 0; i < 100; i++) {+ if (cond()) return+ await new Promise((r) => setTimeout(r, 0))+ }+ throw new Error(`timed out waiting for ${what}`)+}++const serverStarted = () => until(() => lastServer !== null, 'the server to spawn')+const wroteRequests = (n: number) => until(() => (lastServer?.written.length ?? 0) >= n, `${n} requests`)++describe('connecting to an external server', () => {+ it('completes the handshake and returns the discovered tools', async () => {+ const client = new MCPExternalClient(config)+ const tools = await client.connect()++ expect(tools).toHaveLength(1)+ expect(tools[0]).toMatchObject({ name: 'get_forecast', source: 'external', serverId: 'srv-1' })+ expect(client.isConnected()).toBe(true)+ })++ it('writes the JSON-RPC requests through the child, newline-framed', async () => {+ const client = new MCPExternalClient(config)+ await client.connect()++ expect(lastServer!.written).toHaveLength(2)+ for (const msg of lastServer!.written) expect(msg.endsWith('\n')).toBe(true)+ expect(JSON.parse(lastServer!.written[0]).method).toBe('initialize')+ expect(JSON.parse(lastServer!.written[1]).method).toBe('tools/list')+ })++ it('calls a tool and flattens the content array', async () => {+ const client = new MCPExternalClient(config)+ await client.connect()++ expect(await client.callTool('get_forecast', { city: 'Berlin' })).toBe('sunny in Berlin')+ })++ it('surfaces a JSON-RPC error as a rejection', async () => {+ const client = new MCPExternalClient(config)+ await client.connect()+ responder = (req) => JSON.stringify({ jsonrpc: '2.0', id: req.id, error: { code: -32602, message: 'unknown city' } })++ await expect(client.callTool('get_forecast', { city: 'Atlantis' })).rejects.toThrow('unknown city')+ })++ it('refuses to call a tool before connecting', async () => {+ await expect(new MCPExternalClient(config).callTool('get_forecast', {})).rejects.toThrow('Not connected')+ })+})++describe('a server that misbehaves does not leave a process behind', () => {+ it('kills the child when the handshake is refused', async () => {+ responder = (req) =>+ req.method === 'initialize'+ ? JSON.stringify({ jsonrpc: '2.0', id: req.id, error: { code: -32600, message: 'nope' } })+ : null++ const client = new MCPExternalClient(config)+ await expect(client.connect()).rejects.toThrow(/Failed to connect to MCP server "weather".*nope/)+ // The caller never receives a client it could disconnect, so connect has+ // to clean up after itself or the server process stays alive forever.+ expect(lastServer!.spawned).toBe(true)+ expect(killCount).toBe(1)+ expect(client.isConnected()).toBe(false)+ })++ it('fails every pending request when the process exits', async () => {+ responder = (req) => (req.method === 'initialize' ? JSON.stringify({ jsonrpc: '2.0', id: req.id, result: {} }) : null)+ const client = new MCPExternalClient(config)+ const connecting = client.connect()+ // tools/list gets no answer; the process dies instead.+ await wroteRequests(2)+ lastServer!.emit('close')++ await expect(connecting).rejects.toThrow(/Server process exited/)+ expect(client.isConnected()).toBe(false)+ })+})++describe('response framing', () => {+ it('reassembles a response split across two stdout events', async () => {+ responder = () => null+ const client = new MCPExternalClient(config)+ const connecting = client.connect()+ await wroteRequests(1)+ const server = lastServer!+ const id = JSON.parse(server.written[0]).id+ server.stdout.emit('data', `{"jsonrpc":"2.0","id":${id},"resu`)+ server.stdout.emit('data', 'lt":{"ok":true}}\n')+ // The handshake resolved; tools/list is now outstanding, so answer it too.+ await wroteRequests(2)+ const listId = JSON.parse(server.written[1]).id+ server.stdout.emit('data', `{"jsonrpc":"2.0","id":${listId},"result":{"tools":[]}}\n`)++ await expect(connecting).resolves.toEqual([])+ })++ it('ignores non-JSON chatter on stdout', async () => {+ const client = new MCPExternalClient(config)+ const connecting = client.connect()+ await serverStarted()+ lastServer!.stdout.emit('data', 'Debugger listening on ws://127.0.0.1:9229\n')++ await expect(connecting).resolves.toHaveLength(1)+ })+})++describe('disconnect', () => {+ it('kills the child and refuses further calls', async () => {+ const client = new MCPExternalClient(config)+ await client.connect()+ await client.disconnect()++ expect(killCount).toBe(1)+ expect(client.isConnected()).toBe(false)+ await expect(client.callTool('get_forecast', {})).rejects.toThrow('Not connected')+ })+})diff --git a/src/api/mcp/external-client.ts b/src/api/mcp/external-client.tsindex 99a5110e..85841dd8 100644--- a/src/api/mcp/external-client.ts+++ b/src/api/mcp/external-client.ts@@ -24,11 +24,21 @@ interface JsonRpcResponse {}export class MCPExternalClient {- private process: any = null+ /** The Command — owns the stdout/stderr/close events. */+ private command: any = null+ /**+ * The Child that spawn() hands back — owns stdin and kill(). These live on+ * two different objects in @tauri-apps/plugin-shell, and keeping only the+ * Command meant `stdin.write` hit undefined on the very first request: every+ * external server failed to connect with "Cannot read properties of+ * undefined (reading 'write')".+ */+ private child: any = nullprivate requestId = 0private pendingRequests = new Map<number, {resolve: (value: any) => voidreject: (error: Error) => void+ timer: ReturnType<typeof setTimeout>}>()private outputBuffer = ''private connected = false@@ -49,26 +59,27 @@ export class MCPExternalClient {// to their .cmd shim here.const resolvedCommand = resolveCommandForPlatform(this.config.command)- this.process = Command.create(resolvedCommand, this.config.args, {+ this.command = Command.create(resolvedCommand, this.config.args, {env: this.config.env,})// Handle stdout — parse JSON-RPC responses- this.process.stdout.on('data', (data: string) => {+ this.command.stdout.on('data', (data: string) => {this.outputBuffer += datathis.processBuffer()})- this.process.stderr.on('data', (data: string) => {+ this.command.stderr.on('data', (data: string) => {log.warn(`[MCP:${this.config.name}] stderr`, { data })})- this.process.on('close', () => {+ this.command.on('close', () => {this.connected = false+ this.child = nullthis.rejectAllPending('Server process exited')})- await this.process.spawn()+ this.child = await this.command.spawn()this.connected = true// Initialize the MCP connection@@ -92,6 +103,13 @@ export class MCPExternalClient {return tools} catch (err) {this.connected = false+ // A failure after spawn (handshake refused, tools/list timed out) leaves+ // the server process running with nobody holding a handle to it — the+ // caller never gets a client it could disconnect. Take it down here.+ if (this.child) {+ try { await this.child.kill() } catch { /* already gone */ }+ this.child = null+ }throw new Error(`Failed to connect to MCP server "${this.config.name}": ${err instanceof Error ? err.message : String(err)}`)}}@@ -117,14 +135,15 @@ export class MCPExternalClient {async disconnect() {this.connected = falsethis.rejectAllPending('Disconnecting')- if (this.process) {+ if (this.child) {try {- await this.process.kill()+ await this.child.kill()} catch {// Process may already be dead}- this.process = null+ this.child = null}+ this.command = null}isConnected() {@@ -135,6 +154,10 @@ export class MCPExternalClient {private sendRequest(method: string, params?: any): Promise<any> {return new Promise((resolve, reject) => {+ if (!this.child) {+ reject(new Error('Not connected'))+ return+ }const id = ++this.requestIdconst request: JsonRpcRequest = {jsonrpc: '2.0',@@ -143,18 +166,23 @@ export class MCPExternalClient {params,}- this.pendingRequests.set(id, { resolve, reject })-- const msg = JSON.stringify(request) + '\n'- this.process.stdin.write(msg)-- // Timeout after 30 seconds- setTimeout(() => {- if (this.pendingRequests.has(id)) {- this.pendingRequests.delete(id)+ const timer = setTimeout(() => {+ if (this.pendingRequests.delete(id)) {reject(new Error(`Request ${method} timed out`))}}, 30000)++ this.pendingRequests.set(id, { resolve, reject, timer })++ // Child.write is async: a failed write has to fail the request instead+ // of becoming an unhandled rejection and letting it sit for 30 s.+ const msg = JSON.stringify(request) + '\n'+ Promise.resolve(this.child.write(msg)).catch((err: unknown) => {+ if (this.pendingRequests.delete(id)) {+ clearTimeout(timer)+ reject(err instanceof Error ? err : new Error(String(err)))+ }+ })})}@@ -170,6 +198,7 @@ export class MCPExternalClient {const pending = this.pendingRequests.get(response.id)if (pending) {this.pendingRequests.delete(response.id)+ clearTimeout(pending.timer)if (response.error) {pending.reject(new Error(response.error.message))} else {@@ -183,9 +212,11 @@ export class MCPExternalClient {}private rejectAllPending(reason: string) {- for (const [id, { reject }] of this.pendingRequests) {+ const pending = [...this.pendingRequests.values()]+ this.pendingRequests.clear()+ for (const { reject, timer } of pending) {+ clearTimeout(timer)reject(new Error(reason))- this.pendingRequests.delete(id)}}}