Skip to content

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.

fix(mcp): no ghost server when a connect is removed or repeated mid-handshake

purple814e5ebfdc00
diff --git a/src/components/settings/MCPServerSettings.tsx b/src/components/settings/MCPServerSettings.tsx
index a19d5ed0..e8a9a2f0 100644
--- a/src/components/settings/MCPServerSettings.tsx
+++ b/src/components/settings/MCPServerSettings.tsx
@@ -14,10 +14,29 @@ import type { MCPExternalClient } from '../../api/mcp/external-client'
// Active client instances (lazy-loaded to avoid Tauri import in dev mode)
const clients = new Map<string, MCPExternalClient>()
+/**
+ * Connects still in flight, one per server. A connect takes as long as the
+ * server needs for its handshake (an npx server installs first), and during
+ * that time the row can be removed, disconnected or connected again. Before
+ * this map the only guard was one `connecting` value for the whole panel:
+ * a second Connect on the same row spawned a second process whose client
+ * overwrote the first in `clients`, and a Remove found no client yet, so the
+ * handshake finished afterwards and registered the tools of a server that
+ * no longer existed, with its process running and no row left to stop it.
+ * The entry is the attempt itself: whoever ends it (Remove, Disconnect, an
+ * edit) deletes it, and the connect, once its handshake returns, sees that
+ * it is no longer current and takes its own client down instead of
+ * registering anything.
+ */
+interface ConnectAttempt { client: MCPExternalClient | null }
+const inFlight = new Map<string, ConnectAttempt>()
+
export function MCPServerSettings() {
const { servers, connectedServers, serverTools, addServer, updateServer, removeServer, setConnected, setServerTools, clearServerTools } = useMCPStore()
const [showAddForm, setShowAddForm] = useState(false)
- const [connecting, setConnecting] = useState<string | null>(null)
+ const [connecting, setConnecting] = useState<string[]>(() => [...inFlight.keys()])
+ const markConnecting = (id: string, on: boolean) =>
+ setConnecting((ids) => (on ? [...ids.filter((x) => x !== id), id] : ids.filter((x) => x !== id)))
const [error, setError] = useState<string | null>(null)
// Add form state. `editingId` entscheidet, ob Speichern anlegt oder aendert.
@@ -64,7 +83,7 @@ export function MCPServerSettings() {
// Ein laufender Server traegt noch den alten Befehl. Ihn stehen zu
// lassen waere die schlimmere Haelfte des Fehlers: die Zeile zeigte
// dann den neuen Befehl, waehrend der alte Prozess weiterlaeuft.
- if (connectedServers.includes(editingId)) await handleDisconnect(editingId)
+ if (connectedServers.includes(editingId) || inFlight.has(editingId)) await handleDisconnect(editingId)
updateServer(editingId, felder)
} else {
addServer({ id: uuid(), ...felder, enabled: true })
@@ -73,23 +92,46 @@ export function MCPServerSettings() {
}
const handleConnect = async (server: MCPServerConfig) => {
- setConnecting(server.id)
+ // One connect per server: a second click while the first is still in its
+ // handshake would start a second process.
+ if (inFlight.has(server.id) || clients.has(server.id)) return
+ const attempt: ConnectAttempt = { client: null }
+ inFlight.set(server.id, attempt)
+ const current = () =>
+ inFlight.get(server.id) === attempt && useMCPStore.getState().servers.some((s) => s.id === server.id)
+ markConnecting(server.id, true)
setError(null)
try {
const { MCPExternalClient } = await import('../../api/mcp/external-client')
+ if (!current()) return
// A server process can die on its own (crash, OOM kill, a bad config it
// quits on). Before this the panel stayed green and its tools stayed in
// the registry, so the model kept being offered a terminal that was not
// there and every call failed with "Not connected" until the app closed.
const client = new MCPExternalClient(server, {
onExit: (id) => {
+ if (clients.get(id) !== client) return
toolRegistry.unregisterServer(id)
setConnected(id, false)
clearServerTools(id)
clients.delete(id)
},
})
- const tools = await client.connect()
+ attempt.client = client
+ let tools: Awaited<ReturnType<MCPExternalClient['connect']>>
+ try {
+ tools = await client.connect()
+ } catch (err) {
+ // A connect that was called off fails on purpose; that is no error.
+ if (current()) throw err
+ return
+ }
+ // Removed, disconnected or edited while the handshake ran: this client
+ // is nobody's any more. Stop its process and register nothing.
+ if (!current()) {
+ await client.disconnect().catch(() => {})
+ return
+ }
clients.set(server.id, client)
setConnected(server.id, true)
setServerTools(server.id, tools)
@@ -106,15 +148,24 @@ export function MCPServerSettings() {
} catch (err) {
setError(err instanceof Error ? err.message : String(err))
} finally {
- setConnecting(null)
+ if (inFlight.get(server.id) === attempt) inFlight.delete(server.id)
+ markConnecting(server.id, false)
}
}
const handleDisconnect = async (id: string) => {
+ // A connect still in its handshake is called off: its process is stopped
+ // now, and the connect sees it is no longer current when it returns.
+ const attempt = inFlight.get(id)
+ if (attempt) {
+ inFlight.delete(id)
+ markConnecting(id, false)
+ await attempt.client?.disconnect().catch(() => {})
+ }
const client = clients.get(id)
if (client) {
- await client.disconnect()
clients.delete(id)
+ await client.disconnect()
}
toolRegistry.unregisterServer(id)
setConnected(id, false)
@@ -136,7 +187,7 @@ export function MCPServerSettings() {
{servers.map((server) => {
const isConnected = connectedServers.includes(server.id)
const tools = serverTools[server.id] || []
- const isLoading = connecting === server.id
+ const isLoading = connecting.includes(server.id)
return (
<div
diff --git a/src/components/settings/__tests__/mcp-connect-in-flight.test.tsx b/src/components/settings/__tests__/mcp-connect-in-flight.test.tsx
new file mode 100644
index 00000000..d0c9a73a
--- /dev/null
+++ b/src/components/settings/__tests__/mcp-connect-in-flight.test.tsx
@@ -0,0 +1,122 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * Settings, Agent, MCP Servers (Jaeger B, B3): a server whose handshake is
+ * still running can be removed or connected a second time. Both left a ghost:
+ * after Remove the handshake finished anyway and registered the tools of a
+ * server that no longer existed, with its process running; a second Connect
+ * started a second process, and Disconnect then stopped only one of them.
+ *
+ * Run: npx vitest run src/components/settings/__tests__/mcp-connect-in-flight.test.tsx
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { createElement } from 'react'
+import { render, screen, cleanup, fireEvent, act } from '@testing-library/react'
+import type { MCPServerConfig, MCPToolDefinition } from '../../../api/mcp/types'
+
+interface FakeClient {
+ id: string
+ disconnected: boolean
+ resolve: () => void
+}
+const started: FakeClient[] = []
+
+vi.mock('../../../api/mcp/external-client', () => ({
+ MCPExternalClient: class {
+ private config: MCPServerConfig
+ private fake: FakeClient
+ constructor(config: MCPServerConfig) {
+ this.config = config
+ this.fake = { id: config.id, disconnected: false, resolve: () => {} }
+ started.push(this.fake)
+ }
+ connect(): Promise<MCPToolDefinition[]> {
+ return new Promise((resolve) => {
+ this.fake.resolve = () => resolve([{
+ name: `${this.config.id}_ping`, description: 'ping', inputSchema: { type: 'object', properties: {} },
+ category: 'workflow', source: 'external', serverId: this.config.id,
+ } as MCPToolDefinition])
+ })
+ }
+ async disconnect() { this.fake.disconnected = true }
+ async callTool() { return '' }
+ },
+}))
+
+const { MCPServerSettings } = await import('../MCPServerSettings')
+const { useMCPStore } = await import('../../../stores/mcpStore')
+const { toolRegistry } = await import('../../../api/mcp')
+
+const server = (id: string): MCPServerConfig => ({ id, name: id, command: 'npx', args: ['slow'], enabled: true })
+const row = (name: string) => screen.getByText(name).closest('div.px-3') as HTMLElement
+const button = (name: string, title: string) => row(name).querySelector(`button[title="${title}"]`) as HTMLButtonElement
+const flush = () => act(async () => { for (let i = 0; i < 10; i++) await Promise.resolve() })
+const registered = () => toolRegistry.getAll().map((t) => t.name)
+
+beforeEach(() => {
+ started.length = 0
+ // Ids are fresh per test: the panel keeps its clients at module level.
+ useMCPStore.setState({ servers: [server('s7'), server('s8'), server('s9')], connectedServers: [], serverTools: {} })
+})
+afterEach(async () => {
+ cleanup()
+ for (const id of ['s7', 's8', 's9']) toolRegistry.unregisterServer(id)
+})
+
+describe('MCP connect while a handshake is still running', () => {
+ it('Remove during Connecting stops the process and registers nothing', async () => {
+ render(createElement(MCPServerSettings))
+ fireEvent.click(button('s8', 'Connect'))
+ await flush()
+ expect(started).toHaveLength(1)
+
+ fireEvent.click(button('s8', 'Remove server'))
+ await flush()
+ started[0].resolve()
+ await flush()
+
+ expect(useMCPStore.getState().servers.map((s) => s.id)).toEqual(['s7', 's9'])
+ expect(useMCPStore.getState().connectedServers).not.toContain('s8')
+ expect(useMCPStore.getState().serverTools.s8).toBeUndefined()
+ expect(registered()).not.toContain('s8_ping')
+ expect(started[0].disconnected).toBe(true)
+ })
+
+ it('a second Connect on the same row while the first runs starts no second process', async () => {
+ render(createElement(MCPServerSettings))
+ fireEvent.click(button('s8', 'Connect'))
+ await flush()
+ fireEvent.click(button('s9', 'Connect'))
+ await flush()
+ // The s8 row is still connecting; a click there must not start anything.
+ fireEvent.click(button('s8', 'Connect'))
+ await flush()
+ expect(started.map((c) => c.id)).toEqual(['s8', 's9'])
+
+ for (const c of started) c.resolve()
+ await flush()
+ expect(useMCPStore.getState().connectedServers).toEqual(expect.arrayContaining(['s8', 's9']))
+
+ fireEvent.click(button('s8', 'Disconnect'))
+ await flush()
+ expect(started.filter((c) => c.id === 's8').every((c) => c.disconnected)).toBe(true)
+ expect(registered()).not.toContain('s8_ping')
+ expect(registered()).toContain('s9_ping')
+ })
+
+ it('an edit during Connecting calls the connect off', async () => {
+ render(createElement(MCPServerSettings))
+ fireEvent.click(button('s7', 'Connect'))
+ await flush()
+ // The Connect button is busy, so the way in is an edit of the row, which
+ // disconnects first; Remove is covered above.
+ fireEvent.click(button('s7', 'Edit server'))
+ fireEvent.click(screen.getByText('Save Changes'))
+ await flush()
+ started[0].resolve()
+ await flush()
+ expect(started[0].disconnected).toBe(true)
+ expect(useMCPStore.getState().connectedServers).not.toContain('s7')
+ expect(registered()).not.toContain('s7_ping')
+ })
+})