DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(panel-extension): sync MCP capabilities
hairyf60267cde2956
diff --git a/packages/dsh-tauri-panel-extension/src/client/apis/index.ts b/packages/dsh-tauri-panel-extension/src/client/apis/index.tsindex 64933b5e..74faad10 100644--- a/packages/dsh-tauri-panel-extension/src/client/apis/index.ts+++ b/packages/dsh-tauri-panel-extension/src/client/apis/index.ts@@ -54,6 +54,11 @@ export function postMcpSave(body: Record<string, unknown>): Promise<Types.McpSavreturn fetch(`${baseURL}/mcp/save`, { method: 'POST', body })}+/** @method post 检查 MCP 服务器连通性。 */+export function postMcpCheck(body: { id: string }): Promise<Types.McpConnectivityResponse> {+ return fetch(`${baseURL}/mcp/check`, { method: 'POST', body })+}+/** @method post 启用/禁用 MCP 服务器。 */export function postMcpToggle(body: Types.PostMcpToggleBody): Promise<Types.ActionResult> {return fetch(`${baseURL}/mcp/toggle`, { method: 'POST', body })diff --git a/packages/dsh-tauri-panel-extension/src/client/apis/index.type.ts b/packages/dsh-tauri-panel-extension/src/client/apis/index.type.tsindex da7d613a..ec5c8373 100644--- a/packages/dsh-tauri-panel-extension/src/client/apis/index.type.ts+++ b/packages/dsh-tauri-panel-extension/src/client/apis/index.type.ts@@ -27,6 +27,15 @@ export interface McpSaveResponse {/** GET /mcp 响应。 */export interface McpListResponse {servers: McpRow[]+ global?: McpRow[]+ profile?: McpRow[]+}++/** POST /mcp/check connectivity response. */+export interface McpConnectivityResponse {+ ok: boolean+ latencyMs?: number+ error?: string}/** GET /import/scan 响应。 */diff --git a/packages/dsh-tauri-panel-extension/src/client/components/mcp-tab.tsx b/packages/dsh-tauri-panel-extension/src/client/components/mcp-tab.tsxindex 08e7284a..dbe06d6c 100644--- a/packages/dsh-tauri-panel-extension/src/client/components/mcp-tab.tsx+++ b/packages/dsh-tauri-panel-extension/src/client/components/mcp-tab.tsx@@ -13,7 +13,7 @@ import type { McpEditorMode, McpEditorState, McpImportItem, McpRow, McpTabPropsimport { Button, Modal, StateDot } from '@deepseek-ai/dsh-client-ui-primitives'import { ArrowRotateRight, Icon, PlugConnection, useMountStyle } from 'dsh-tauri-ui/client'import { useEffect, useState } from 'react'-import { getMcp, getMcpImportScan, postMcpImportApply, postMcpRemove, postMcpSave, postMcpToggle } from '../apis'+import { getMcp, getMcpImportScan, postMcpCheck, postMcpImportApply, postMcpRemove, postMcpSave, postMcpToggle } from '../apis'import { MCP_RESTART_INITIAL_DELAY_MS, MCP_RESTART_POLL_INTERVAL_MS, MCP_RESTART_TIMEOUT_MS, MCP_TAB_STYLE_ID } from '../constants'import { useTimers } from '../hooks/use-timers'import { handlePostMcpRestart, isMcpDesktop } from '../service/handle-post-mcp-restart'@@ -39,6 +39,8 @@ export function McpTab({ t }: McpTabProps): ReactElement {const [editorMode, setEditorMode] = useState<McpEditorMode>('json')const [pasteJson, setPasteJson] = useState('')const [pasteError, setPasteError] = useState<string | null>(null)+ const [scope, setScope] = useState<'all' | 'global' | 'profile'>('all')+ const [checking, setChecking] = useState<string | null>(null)const { later } = useTimers()useEffect(() => {@@ -101,6 +103,18 @@ export function McpTab({ t }: McpTabProps): ReactElement {}}+ const checkConnectivity = async (row: McpRow): Promise<void> => {+ setChecking(row.id)+ try {+ const result = await postMcpCheck({ id: row.id })+ setOutcome({ ok: result.ok, text: result.ok ? `${t('connectivityOk')}${result.latencyMs ? ` (${result.latencyMs}ms)` : ''}` : `${t('connectivityFailed')}: ${result.error ?? ''}` })+ }+ catch (error) {+ setOutcome({ ok: false, text: `${t('connectivityFailed')}: ${String(error)}` })+ }+ finally { setChecking(null) }+ }+const reloadList = (showPending: boolean): void => {setReload(value => value + 1)if (showPending)@@ -320,6 +334,7 @@ export function McpTab({ t }: McpTabProps): ReactElement {<div className="dshp-extension__list-head"><h3>{t('mcpTab')}</h3>{servers !== null && <span className="dshp-extension__count">{servers.length}</span>}+ <select aria-label={t('scope')} value={scope} onChange={event => setScope(event.target.value as typeof scope)}><option value="all">{t('scopeAll')}</option><option value="global">{t('global')}</option><option value="profile">{t('profile')}</option></select><span className="dshp-extension__spacer" /><button type="button" className="dshp-extension__refresh" aria-label={t('view')} title={t('view')} disabled={busy} onClick={() => setReload(value => value + 1)}><Icon as={ArrowRotateRight} />@@ -330,19 +345,20 @@ export function McpTab({ t }: McpTabProps): ReactElement {{servers !== null && servers.length === 0 && <p className="dshp-extension__empty">{t('emptyMcp')}</p>}{servers !== null && servers.length > 0 && (<ul className="dshp-extension__cards">- {servers.map(row => (+ {servers.filter(row => scope === 'all' || (row.layer ?? 'profile') === scope).map(row => (<li className="dshp-extension__card" key={row.id}><div className="dshp-extension__card-top"><strong className="dshp-extension__card-title" title={row.id}>{row.serverName}</strong>+ <span className="dshp-extension__tag" data-kind={(row.scope ?? row.layer) === 'global' ? 'source' : undefined}>{(row.scope ?? row.layer) === 'global' ? t('scopeGlobal') : t('scopeProfile')}</span><span className="dshp-extension__tag">{row.transport}</span><span className="dshp-extension__tag" data-kind={row.disabled ? 'off' : undefined}>{row.disabled ? t('disabled') : t('enabled')}</span></div><p className="dshp-extension__card-desc">{row.transport === 'stdio' ? `${row.command ?? ''} ${(row.args ?? []).join(' ')}` : row.url ?? ''}</p>- <div className="dshp-extension__card-row">+ {row.shadowed === true && <p className="dshp-extension__form-error">{t('shadowedByGlobal')}</p>}\n {row.globalError !== undefined && <p className="dshp-extension__form-error">{row.globalError}</p>}\n <div className="dshp-extension__card-row"><span className="dshp-extension__spacer" />- <Button variant="ghost" size="sm" disabled={busy} onClick={() => void doToggle(row)}>{t('toggle')}</Button>+ <Button variant="ghost" size="sm" disabled={busy || checking === row.id} onClick={() => void checkConnectivity(row)}>{checking === row.id ? t('checkRunning') : t('checkLabel')}</Button>\n <Button variant="ghost" size="sm" disabled={busy} onClick={() => void doToggle(row)}>{t('toggle')}</Button><Button variant="ghost" size="sm" disabled={busy} onClick={() => openEdit(row)}>{t('edit')}</Button><Button variant="ghost" size="sm" disabled={busy} onClick={() => setConfirmId(row.id)}>{t('delete')}</Button></div>diff --git a/packages/dsh-tauri-panel-extension/src/client/locales/index.ts b/packages/dsh-tauri-panel-extension/src/client/locales/index.tsindex a34d4483..151e53fe 100644--- a/packages/dsh-tauri-panel-extension/src/client/locales/index.ts+++ b/packages/dsh-tauri-panel-extension/src/client/locales/index.ts@@ -101,6 +101,7 @@ const zh: Record<string, string> = {formatPaste: '粘贴 JSON 配置(mcpServers 包装或单条目均可)',formatFill: '解析并切换到表单',pasteTransportMismatch: '该行传输方式已锁定,与粘贴配置不一致。',+ scope: '范围', scopeAll: '全部', global: '全局', profile: 'Profile', shadowed: '已覆盖', globalError: '全局错误', connectivityOk: '连接成功', connectivityFailed: '连接失败',}const en: Record<string, string> = {diff --git a/packages/dsh-tauri-panel-extension/src/client/types/mcp.ts b/packages/dsh-tauri-panel-extension/src/client/types/mcp.tsindex c0e76b95..edd97ae1 100644--- a/packages/dsh-tauri-panel-extension/src/client/types/mcp.ts+++ b/packages/dsh-tauri-panel-extension/src/client/types/mcp.ts@@ -4,6 +4,11 @@ import type { Translate } from './protocol'export interface McpRow {id: string+ /** Configuration layer; global rows are inherited and read-only by default. */+ layer?: 'global' | 'profile'+ shadowed?: boolean+ globalError?: string+ scope?: 'global' | 'profile'serverName: stringtransport: 'stdio' | 'streamable-http'disabled: boolean@@ -16,7 +21,7 @@ export interface McpRow {}export interface ImportedServerView {- agent: 'claude-code' | 'codex'+ agent: 'claude-code' | 'codex' | 'cursor' | 'gemini'name: stringtransport: 'stdio' | 'streamable-http'command?: stringdiff --git a/packages/dsh-tauri-panel-extension/src/client/utils/mcp.ts b/packages/dsh-tauri-panel-extension/src/client/utils/mcp.tsindex eb4e22c7..44b5b6f6 100644--- a/packages/dsh-tauri-panel-extension/src/client/utils/mcp.ts+++ b/packages/dsh-tauri-panel-extension/src/client/utils/mcp.ts@@ -7,8 +7,8 @@ import type { McpImportItem, ParsedMcpJson } from '../types'/** Group import candidates by source agent, known agents first. */export function importGroups(items: McpImportItem[]): Array<{ agent: string, label: string, items: Array<{ item: McpImportItem, index: number }> }> {- const label = (agent: string): string => agent === 'claude-code' ? 'Claude Code' : agent === 'codex' ? 'Codex' : agent- const order = ['claude-code', 'codex']+ const label = (agent: string): string => agent === 'claude-code' ? 'Claude Code' : agent === 'codex' ? 'Codex' : agent === 'cursor' ? 'Cursor' : agent === 'gemini' ? 'Gemini CLI' : agent+ const order = ['claude-code', 'codex', 'cursor', 'gemini']const agents = [...new Set(items.map(item => item.server.agent))].sort((a, b) => {const rank = (agent: string): number => {diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/index.ts b/packages/dsh-tauri-panel-extension/src/host/routes/index.tsindex 97a05b82..3c0bce61 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/index.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/index.ts@@ -9,6 +9,7 @@import type { PanelExtensionHost, RouteRegistrar } from '../types/index.ts'import { withConnectionAuth } from 'dsh-tauri'+import { dirname } from 'pathe'import { PLUGIN_NAME } from '../../shared/constants.ts'import { registerMcpRoutes } from './mcp.ts'import { registerRepositoryRoutes } from './repositories.ts'@@ -30,7 +31,11 @@ export function mountPanelExtensionRoutes(host: PanelExtensionHost, config: Paneconst disposers = [...registerSkillRoutes(register, host, { remountProvider: config.remountProvider }),- ...registerMcpRoutes(register, { profileDirPath: config.profileDirPath }),+ ...registerMcpRoutes(register, {+ profileDirPath: config.profileDirPath,+ // profileDirPath is always <DSH_HOME>/profiles/<profile>.+ dshHomePath: dirname(dirname(config.profileDirPath)),+ }),...registerRepositoryRoutes(register, { remountProvider: config.remountProvider }),...registerRestartRoute(register),]diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/mcp.ts b/packages/dsh-tauri-panel-extension/src/host/routes/mcp.tsindex a645b539..6aea0868 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/mcp.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/mcp.ts@@ -6,16 +6,17 @@*/import type { IncomingMessage, ServerResponse } from 'node:http'-import type { McpInput } from '../service/mcp.ts'+import type { McpInput, McpScope } from '../service/mcp.ts'import type { RouteRegistrar } from '../types/index.ts'import { readJsonBody, sameOrigin, sendJson } from 'dsh-tauri'import { API_PREFIX } from '../../shared/constants.ts'import { scanAllMcp } from '../service/agents.ts'-import { listMcp, removeMcp, setMcpDisabled, upsertMcp, validateMcpInput } from '../service/mcp.ts'+import { checkMcpRow, listMcp, listMcpScoped, mcpRowToInput, mcpScopeDir, removeMcp, setMcpDisabled, upsertMcp, validateMcpInput } from '../service/mcp.ts'/** MCP route module 的配置片:profile patch 目录。 */export interface McpRoutesConfig {profileDirPath: string+ dshHomePath: string}export function registerMcpRoutes(@@ -23,6 +24,8 @@ export function registerMcpRoutes(config: McpRoutesConfig,): Array<() => void> {const disposers: Array<() => void> = []+ const readScope = (value: unknown): McpScope => value === 'global' ? 'global' : 'profile'+ const scopeDir = (value: unknown): string => mcpScopeDir(readScope(value), config.profileDirPath, config.dshHomePath)disposers.push(register({kind: 'exact',@@ -33,7 +36,8 @@ export function registerMcpRoutes(response.end()return}- sendJson(response, 200, { servers: listMcp(config.profileDirPath), restartNeeded: true })+ const listing = listMcpScoped(config.profileDirPath, config.dshHomePath)+ sendJson(response, 200, { ...listing, restartNeeded: true })},}))@@ -51,13 +55,13 @@ export function registerMcpRoutes(return}try {- const input = (await readJsonBody(request)) as McpInput+ const input = (await readJsonBody(request)) as McpInput & { scope?: unknown }const invalid = validateMcpInput(input)if (invalid !== null) {sendJson(response, 400, { error: invalid })return}- const id = upsertMcp(config.profileDirPath, input)+ const id = upsertMcp(scopeDir(input.scope), input)sendJson(response, 200, { ok: true, id, restartNeeded: true })}catch (error) {@@ -80,12 +84,12 @@ export function registerMcpRoutes(return}try {- const body = (await readJsonBody(request)) as { id?: unknown, disabled?: unknown }+ const body = (await readJsonBody(request)) as { id?: unknown, disabled?: unknown, scope?: unknown }if (typeof body.id !== 'string' || typeof body.disabled !== 'boolean') {sendJson(response, 400, { error: 'id and disabled are required' })return}- const ok = setMcpDisabled(config.profileDirPath, body.id, body.disabled)+ const ok = setMcpDisabled(scopeDir(body.scope), body.id, body.disabled)sendJson(response, ok ? 200 : 404, ok ? { ok: true, restartNeeded: true } : { error: 'server row not found' })}catch (error) {@@ -108,12 +112,12 @@ export function registerMcpRoutes(return}try {- const body = (await readJsonBody(request)) as { id?: unknown }+ const body = (await readJsonBody(request)) as { id?: unknown, scope?: unknown }if (typeof body.id !== 'string') {sendJson(response, 400, { error: 'id is required' })return}- const ok = removeMcp(config.profileDirPath, body.id)+ const ok = removeMcp(scopeDir(body.scope), body.id)sendJson(response, ok ? 200 : 404, ok ? { ok: true, restartNeeded: true } : { error: 'server row not found' })}catch (error) {@@ -135,7 +139,7 @@ export function registerMcpRoutes(sendJson(response, 200, {servers: scanAllMcp(),// Profile serverNames, so the browser can grey out existing ones.- existing: listMcp(config.profileDirPath).map(row => row.serverName),+ existing: listMcpScoped(config.profileDirPath, config.dshHomePath).servers.map(row => row.serverName),})}catch (error) {@@ -158,7 +162,7 @@ export function registerMcpRoutes(return}try {- const body = (await readJsonBody(request)) as { items?: unknown }+ const body = (await readJsonBody(request)) as { items?: unknown, scope?: unknown }const wanted = new Set((Array.isArray(body.items) ? body.items : []).filter((item): item is { agent: string, name: string } =>@@ -169,7 +173,7 @@ export function registerMcpRoutes(for (const server of scanAllMcp()) {if (!wanted.has(`${server.agent}/${server.name}`))continue- const existing = listMcp(config.profileDirPath).some(row => row.serverName === server.name)+ const existing = listMcpScoped(config.profileDirPath, config.dshHomePath).servers.some(row => row.serverName === server.name)if (existing) {results.push({ name: server.name, ok: false, error: 'already in profile' })continue@@ -187,7 +191,7 @@ export function registerMcpRoutes(results.push({ name: server.name, ok: false, error: invalid })continue}- upsertMcp(config.profileDirPath, input)+ upsertMcp(scopeDir(body.scope), input)results.push({ name: server.name, ok: true })}sendJson(response, 200, { ok: results.every(item => item.ok), results, restartNeeded: true })@@ -198,5 +202,35 @@ export function registerMcpRoutes(},}))+ disposers.push(register({+ kind: 'exact', path: `${API_PREFIX}/mcp/check`,+ handler: async (request: IncomingMessage, response: ServerResponse) => {+ if (request.method !== 'POST') { response.writeHead(405, { allow: 'POST' }); response.end(); return }+ if (!sameOrigin(request)) { sendJson(response, 403, { error: 'untrusted origin' }); return }+ try {+ const body = (await readJsonBody(request)) as { id?: unknown, scope?: unknown }+ if (typeof body.id !== 'string') { sendJson(response, 400, { error: 'id is required' }); return }+ const row = listMcp(scopeDir(body.scope)).find(item => item.id === body.id)+ if (row === undefined) { sendJson(response, 404, { error: 'server row not found' }); return }+ sendJson(response, 200, await checkMcpRow(row))+ } catch (error) { sendJson(response, 500, { error: error instanceof Error ? error.message : String(error) }) }+ },+ }))+ disposers.push(register({+ kind: 'exact', path: `${API_PREFIX}/mcp/copy`,+ handler: async (request: IncomingMessage, response: ServerResponse) => {+ if (request.method !== 'POST') { response.writeHead(405, { allow: 'POST' }); response.end(); return }+ if (!sameOrigin(request)) { sendJson(response, 403, { error: 'untrusted origin' }); return }+ try {+ const body = (await readJsonBody(request)) as { id?: unknown, scope?: unknown, toScope?: unknown }+ if (typeof body.id !== 'string') { sendJson(response, 400, { error: 'id is required' }); return }+ const source = listMcp(scopeDir(body.scope)).find(item => item.id === body.id)+ if (source === undefined) { sendJson(response, 404, { error: 'server row not found' }); return }+ const scope = readScope(body.toScope)+ const id = upsertMcp(mcpScopeDir(scope, config.profileDirPath, config.dshHomePath), mcpRowToInput(source))+ sendJson(response, 200, { ok: true, id, scope, restartNeeded: true })+ } catch (error) { sendJson(response, 500, { error: error instanceof Error ? error.message : String(error) }) }+ },+ }))return disposers}diff --git a/packages/dsh-tauri-panel-extension/src/host/service/agents.ts b/packages/dsh-tauri-panel-extension/src/host/service/agents.tsindex 25e5718c..1b6dae9f 100644--- a/packages/dsh-tauri-panel-extension/src/host/service/agents.ts+++ b/packages/dsh-tauri-panel-extension/src/host/service/agents.ts@@ -1,18 +1,19 @@/*** Foreign-agent config readers: MCP servers from Claude Code (~/.claude.json,- * ~/.claude/settings.json) and Codex (~/.codex/config.toml). Pure reads of+ * ~/.claude/settings.json), Codex (~/.codex/config.toml), Cursor+ * (~/.cursor/mcp.json) and Gemini CLI (~/.gemini/settings.json). Pure reads of* well-known paths; anything missing or malformed yields an empty list.*/-import type { McpTransport } from './mcp.ts'import { existsSync, readFileSync } from 'node:fs'import { homedir } from 'node:os'import { join } from 'pathe'import { parse as parseToml } from 'smol-toml'+import type { McpTransport } from './mcp.ts'/** One MCP server discovered in a foreign agent's config. */export interface ImportedServer {- agent: 'claude-code' | 'codex'+ agent: 'claude-code' | 'codex' | 'cursor' | 'gemini'name: stringtransport: McpTransportcommand?: string@@ -24,48 +25,38 @@ export interface ImportedServer {/** Keep only string-valued entries of a record (configs may hold numbers). */function stringEntries(value: unknown): Record<string, string> | undefined {- if (typeof value !== 'object' || value === null || Array.isArray(value))- return undefined+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefinedconst out: Record<string, string> = {}for (const [key, entry] of Object.entries(value)) {- if (typeof entry === 'string')- out[key] = entry+ if (typeof entry === 'string') out[key] = entry}return Object.keys(out).length > 0 ? out : undefined}function stringArray(value: unknown): string[] | undefined {- if (!Array.isArray(value))- return undefined+ if (!Array.isArray(value)) return undefinedconst out = value.filter((entry): entry is string => typeof entry === 'string')return out.length > 0 ? out : undefined}-/** Map one Claude mcpServers entry; returns null for unsupported shapes (sse). */-function mapClaudeEntry(name: string, entry: unknown): ImportedServer | null {- if (typeof entry !== 'object' || entry === null)- return null+/** Map one mcpServers entry (Claude / Cursor share the shape); null for unsupported shapes (sse). */+function mapMcpServersEntry(agent: ImportedServer['agent'], name: string, entry: unknown): ImportedServer | null {+ if (typeof entry !== 'object' || entry === null) return nullconst record = entry as Record<string, unknown>const type = typeof record.type === 'string' ? record.type : 'stdio'if (type === 'stdio' || (type === 'stdio' && record.command !== undefined)) {- if (typeof record.command !== 'string' || record.command === '')- return null+ if (typeof record.command !== 'string' || record.command === '') return nullreturn {- agent: 'claude-code',- name,- transport: 'stdio',+ agent, name, transport: 'stdio',command: record.command,args: stringArray(record.args),env: stringEntries(record.env),}}if (type === 'http' || type === 'streamable-http') {- if (typeof record.url !== 'string' || record.url === '')- return null+ if (typeof record.url !== 'string' || record.url === '') return nullreturn {- agent: 'claude-code',- name,- transport: 'streamable-http',+ agent, name, transport: 'streamable-http',url: record.url,headers: stringEntries(record.headers),}@@ -78,23 +69,70 @@ function mapClaudeEntry(name: string, entry: unknown): ImportedServer | null {export function scanClaudeMcp(home: string = homedir()): ImportedServer[] {const merged: Record<string, unknown> = {}for (const file of [join(home, '.claude', 'settings.json'), join(home, '.claude.json')]) {- if (!existsSync(file))- continue+ if (!existsSync(file)) continuetry {const parsed = JSON.parse(readFileSync(file, 'utf8')) as { mcpServers?: unknown }if (typeof parsed.mcpServers === 'object' && parsed.mcpServers !== null) {Object.assign(merged, parsed.mcpServers)}- }- catch {+ } catch {// Broken or partial config: skip the file, keep earlier merges.}}const out: ImportedServer[] = []for (const [name, entry] of Object.entries(merged)) {- const mapped = mapClaudeEntry(name, entry)- if (mapped !== null)- out.push(mapped)+ const mapped = mapMcpServersEntry('claude-code', name, entry)+ if (mapped !== null) out.push(mapped)+ }+ return out+}++/** MCP servers from Cursor's ~/.cursor/mcp.json (mcpServers, Claude-shaped). */+export function scanCursorMcp(home: string = homedir()): ImportedServer[] {+ const file = join(home, '.cursor', 'mcp.json')+ if (!existsSync(file)) return []+ let parsed: { mcpServers?: unknown }+ try {+ parsed = JSON.parse(readFileSync(file, 'utf8')) as { mcpServers?: unknown }+ } catch {+ return []+ }+ if (typeof parsed.mcpServers !== 'object' || parsed.mcpServers === null) return []+ const out: ImportedServer[] = []+ for (const [name, entry] of Object.entries(parsed.mcpServers)) {+ const mapped = mapMcpServersEntry('cursor', name, entry)+ if (mapped !== null) out.push(mapped)+ }+ return out+}++/** MCP servers from Gemini CLI's ~/.gemini/settings.json (mcpServers; httpUrl+ * keys map to streamable-http, plain `url` marks SSE and is skipped). */+export function scanGeminiMcp(home: string = homedir()): ImportedServer[] {+ const file = join(home, '.gemini', 'settings.json')+ if (!existsSync(file)) return []+ let parsed: { mcpServers?: unknown }+ try {+ parsed = JSON.parse(readFileSync(file, 'utf8')) as { mcpServers?: unknown }+ } catch {+ return []+ }+ if (typeof parsed.mcpServers !== 'object' || parsed.mcpServers === null) return []+ const out: ImportedServer[] = []+ for (const [name, entry] of Object.entries(parsed.mcpServers)) {+ if (typeof entry !== 'object' || entry === null) continue+ const record = entry as Record<string, unknown>+ if (typeof record.command === 'string' && record.command !== '') {+ out.push({+ agent: 'gemini', name, transport: 'stdio',+ command: record.command,+ args: stringArray(record.args),+ env: stringEntries(record.env),+ })+ } else if (typeof record.httpUrl === 'string' && record.httpUrl !== '') {+ out.push({ agent: 'gemini', name, transport: 'streamable-http', url: record.httpUrl })+ }+ // `url`-only entries are SSE endpoints, which dsh's client cannot speak.}return out}@@ -102,34 +140,27 @@ export function scanClaudeMcp(home: string = homedir()): ImportedServer[] {/** MCP servers from Codex's config.toml ([mcp_servers.<name>] tables). */export function scanCodexMcp(home: string = homedir()): ImportedServer[] {const file = join(home, '.codex', 'config.toml')- if (!existsSync(file))- return []+ if (!existsSync(file)) return []let root: Record<string, unknown>try {root = parseToml(readFileSync(file, 'utf8')) as Record<string, unknown>- }- catch {+ } catch {return []}const table = root.mcp_servers- if (typeof table !== 'object' || table === null)- return []+ if (typeof table !== 'object' || table === null) return []const out: ImportedServer[] = []for (const [name, entry] of Object.entries(table)) {- if (typeof entry !== 'object' || entry === null)- continue+ if (typeof entry !== 'object' || entry === null) continueconst record = entry as Record<string, unknown>if (typeof record.command === 'string' && record.command !== '') {out.push({- agent: 'codex',- name,- transport: 'stdio',+ agent: 'codex', name, transport: 'stdio',command: record.command,args: stringArray(record.args),env: stringEntries(record.env),})- }- else if (typeof record.url === 'string' && record.url !== '') {+ } else if (typeof record.url === 'string' && record.url !== '') {out.push({ agent: 'codex', name, transport: 'streamable-http', url: record.url })}}@@ -139,11 +170,10 @@ export function scanCodexMcp(home: string = homedir()): ImportedServer[] {/** All foreign-agent MCP servers, deduplicated by (agent, name). */export function scanAllMcp(home: string = homedir()): ImportedServer[] {const seen = new Set<string>()- return [...scanClaudeMcp(home), ...scanCodexMcp(home)]- .filter((server) => {+ return [...scanClaudeMcp(home), ...scanCodexMcp(home), ...scanCursorMcp(home), ...scanGeminiMcp(home)]+ .filter(server => {const key = `${server.agent}/${server.name}`- if (seen.has(key))- return false+ if (seen.has(key)) return falseseen.add(key)return true})diff --git a/packages/dsh-tauri-panel-extension/src/host/service/mcp.ts b/packages/dsh-tauri-panel-extension/src/host/service/mcp.tsindex 9466e7ee..bc11245f 100644--- a/packages/dsh-tauri-panel-extension/src/host/service/mcp.ts+++ b/packages/dsh-tauri-panel-extension/src/host/service/mcp.ts@@ -10,21 +10,29 @@* list. Managed rows therefore always sit inside one insert entry, and any* legacy bare rows (written before this contract was understood) are* absorbed into it on the next write.+ *+ * Rows live in one of two patch layers: the profile's own+ * `cordis.patch.yml`, or the machine-wide `$DSH_HOME/cordis.patch.yml`+ * (dsh composes it over every profile, after the profile layer — a home row+ * with the same id wins). The primitives below address one layer via the+ * directory holding its `cordis.patch.yml`; `listMcpScoped` merges both.*/-import type { YAMLMap, YAMLSeq } from 'yaml'import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'import { join } from 'pathe'-import { Document, parseDocument } from 'yaml'+import { parseDocument, Document, type YAMLMap, type YAMLSeq } from 'yaml'/** The plugin every managed row instantiates. */export const MCP_PLUGIN = '@deepseek-ai/dsh-mcp-client'/** MCP serverName grammar (dsh-mcp-client's contract). */-export const SERVER_NAME_RE = /^[\w-]{1,32}$/+export const SERVER_NAME_RE = /^[A-Za-z0-9_-]{1,32}$//** Transport choices the client supports. */export type McpTransport = 'stdio' | 'streamable-http'+/** Which patch layer a row lives in. */+export type McpScope = 'global' | 'profile'+/** One managed row, as shown to the browser. */export interface McpRow {id: string@@ -39,25 +47,56 @@ export interface McpRow {headers?: Record<string, string>}+/** One row tagged with its layer. */+export interface McpRowView extends McpRow {+ scope: McpScope+ /** Profile rows only: a global row with the same id composes after this one and wins. */+ shadowed?: boolean+}++/** Merged listing across both patch layers. */+export interface McpListResult {+ servers: McpRowView[]+ /** The home layer exists but could not be read; its rows are not shown. */+ globalError?: string+}+/** Write request for one server row (id empty = create). */export type McpInput = Omit<McpRow, 'disabled'> & { disabled?: boolean }-/** Load the profile patch as a YAML document; `[]` for a missing file. */-function loadPatch(profileDirPath: string): Document {- const path = join(profileDirPath, 'cordis.patch.yml')+/**+ * Refuse to touch a patch file the parser could not fully read. parseDocument+ * parks syntax errors in doc.errors (it does not throw), and the failure only+ * resurfaces at String(doc) as the internals-leaking "Document with errors+ * cannot be stringified". Nothing gets written either way, but the banner must+ * say what is actually wrong and which file to fix.+ */+function assertPatchParses(path: string, doc: Document): void {+ if (doc.errors.length === 0) return+ const at = String(doc.errors[0].message).split('\n', 1)[0]+ const total = doc.errors.length > 1 ? `, +${doc.errors.length - 1} more` : ''+ throw new Error(+ `配置文件 ${path} 存在 YAML 语法错误(${at}${total}),未写入任何内容,请修复该文件后重试`+ + ` / YAML syntax error in the patch file (${at}${total}); nothing was written — fix it and retry`,+ )+}++/** Load one layer's patch (`<dirPath>/cordis.patch.yml`) as a YAML document; `[]` for a missing file. */+function loadPatch(dirPath: string): Document {+ const path = join(dirPath, 'cordis.patch.yml')const text = existsSync(path) ? readFileSync(path, 'utf8') : '[]'const doc = parseDocument(text)+ assertPatchParses(path, doc)const contents = doc.contents as YAMLSeq | null// The default-empty file parses as a flow `[]`; the patch layer is// human-edited block YAML, so flip the flag before anything appends.- if (contents !== null && contents.flow === true && contents.items.length === 0)- contents.flow = false+ if (contents !== null && contents.flow === true && contents.items.length === 0) contents.flow = falsereturn doc}-function savePatch(profileDirPath: string, doc: Document): void {- mkdirSync(profileDirPath, { recursive: true })- writeFileSync(join(profileDirPath, 'cordis.patch.yml'), String(doc), 'utf8')+function savePatch(dirPath: string, doc: Document): void {+ mkdirSync(dirPath, { recursive: true })+ writeFileSync(join(dirPath, 'cordis.patch.yml'), String(doc), 'utf8')}/** Wrap a plain value into a YAML node (yaml v2 exposes no standalone createNode). */@@ -81,8 +120,7 @@ function isSeqNode(value: unknown): value is YAMLSeq<YAMLMap> {/** A patch entry's insert list when it is the anonymous create form. */function insertListOf(item: YAMLMap): YAMLSeq<YAMLMap> | undefined {- if (item.has('id'))- return undefined+ if (item.has('id')) return undefinedconst node = item.get('insert')return isSeqNode(node) ? node : undefined}@@ -91,12 +129,10 @@ function insertListOf(item: YAMLMap): YAMLSeq<YAMLMap> | undefined {function mcpRowItems(doc: Document): { node: YAMLMap, list?: YAMLSeq<YAMLMap> }[] {const found: { node: YAMLMap, list?: YAMLSeq<YAMLMap> }[] = []for (const item of rowSeq(doc).items ?? []) {- if (item.get('name') === MCP_PLUGIN)- found.push({ node: item })+ if (item.get('name') === MCP_PLUGIN) found.push({ node: item })const list = insertListOf(item)for (const row of list?.items ?? []) {- if (row.get('name') === MCP_PLUGIN)- found.push({ node: row, list })+ if (row.get('name') === MCP_PLUGIN) found.push({ node: row, list })}}return found@@ -107,7 +143,7 @@ function rowToMcp(doc: Document, item: YAMLMap): McpRow {// config is a YAMLMap node — materialize it before property access.const configNode = item.get('config') as unknownconst plain = (typeof configNode === 'object' && configNode !== null && typeof (configNode as { toJS?: unknown }).toJS === 'function'- ? (configNode as { toJS: (document: Document) => unknown }).toJS(doc)+ ? (configNode as { toJS(document: Document): unknown }).toJS(doc): {}) as Record<string, unknown>return {id: String(item.get('id') ?? ''),@@ -124,8 +160,7 @@ function rowToMcp(doc: Document, item: YAMLMap): McpRow {}function isStringMap(value: unknown): value is Record<string, string> {- if (typeof value !== 'object' || value === null || Array.isArray(value))- return false+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return falsereturn Object.values(value).every(entry => typeof entry === 'string')}@@ -140,11 +175,9 @@ function managedInsert(doc: Document): YAMLSeq<YAMLMap> {const bare: YAMLMap[] = []let target: YAMLSeq<YAMLMap> | undefinedfor (const item of seq.items ?? []) {- if (item.get('name') === MCP_PLUGIN)- bare.push(item)+ if (item.get('name') === MCP_PLUGIN) bare.push(item)const list = insertListOf(item)- if (list !== undefined && list.items.some(row => row.get('name') === MCP_PLUGIN))- target ??= list+ if (list !== undefined && list.items.some(row => row.get('name') === MCP_PLUGIN)) target ??= list}if (target === undefined) {const entry = toNode<YAMLMap>({ insert: [] })@@ -164,45 +197,76 @@ function takenIds(doc: Document): Set<string> {const taken = new Set<string>()for (const item of rowSeq(doc).items ?? []) {const id = String(item.get('id') ?? '')- if (id !== '')- taken.add(id)+ if (id !== '') taken.add(id)for (const row of insertListOf(item)?.items ?? []) {const rowId = String(row.get('id') ?? '')- if (rowId !== '')- taken.add(rowId)+ if (rowId !== '') taken.add(rowId)}}return taken}-/** Read every mcp-client row in the profile layer. */-export function listMcp(profileDirPath: string): McpRow[] {- const doc = loadPatch(profileDirPath)+/** Read every mcp-client row in one patch layer (`<dirPath>/cordis.patch.yml`). */+export function listMcp(dirPath: string): McpRow[] {+ const doc = loadPatch(dirPath)return mcpRowItems(doc).map(({ node }) => rowToMcp(doc, node))}+/**+ * Merge both patch layers for the browser: global rows first (dsh composes+ * them after the profile layer, so they win), profile rows tagged `shadowed`+ * when a global row claims the same id. A broken home layer must not take+ * the whole page down — its read failure degrades to `globalError` and the+ * profile layer still lists (the assertPatchParses message names the file+ * and the parser location, which is what the banner shows).+ */+export function listMcpScoped(profileDirPath: string, dshHomePath: string): McpListResult {+ let globalRows: McpRow[] = []+ let globalError: string | undefined+ if (existsSync(join(dshHomePath, 'cordis.patch.yml'))) {+ try {+ globalRows = listMcp(dshHomePath)+ } catch (error) {+ globalError = error instanceof Error ? error.message : String(error)+ }+ }+ const globalIds = new Set(globalRows.map(row => row.id).filter(id => id !== ''))+ return {+ servers: [+ ...globalRows.map((row): McpRowView => ({ ...row, scope: 'global' })),+ ...listMcp(profileDirPath).map((row): McpRowView => ({+ ...row,+ scope: 'profile',+ ...(globalIds.has(row.id) ? { shadowed: true } : {}),+ })),+ ],+ ...(globalError !== undefined ? { globalError } : {}),+ }+}++/** Resolve a write target: the layer's directory holding its cordis.patch.yml. */+export function mcpScopeDir(scope: McpScope, profileDirPath: string, dshHomePath: string): string {+ return scope === 'global' ? dshHomePath : profileDirPath+}+/** Validate one write request; returns the rejection reason or null. */export function validateMcpInput(input: McpInput): string | null {- if (!SERVER_NAME_RE.test(input.serverName))- return 'serverName must be 1-32 chars of A-Z a-z 0-9 _ -'+ if (!SERVER_NAME_RE.test(input.serverName)) return 'serverName must be 1-32 chars of A-Z a-z 0-9 _ -'// The route casts raw JSON to McpInput; a create request may omit `id`.const id = input.id ?? ''- if (id.includes('/') || id.includes('..'))- return 'invalid id'+ if (id.includes('/') || id.includes('..')) return 'invalid id'if (input.transport === 'stdio') {- if (input.command === undefined || input.command.trim() === '')- return 'stdio transport requires a command'- }- else if (input.url === undefined || !/^https?:\/\//.test(input.url)) {+ if (input.command === undefined || input.command.trim() === '') return 'stdio transport requires a command'+ } else if (input.url === undefined || !/^https?:\/\//.test(input.url)) {return 'http transport requires an http(s) url'}return null}/** Add or replace one server row. Returns the (possibly deduplicated) id. */-export function upsertMcp(profileDirPath: string, input: McpInput): string {+export function upsertMcp(dirPath: string, input: McpInput): string {const inputId = input.id ?? ''- const doc = loadPatch(profileDirPath)+ const doc = loadPatch(dirPath)const list = managedInsert(doc)const existing = inputId !== ''@@ -232,46 +296,40 @@ export function upsertMcp(profileDirPath: string, input: McpInput): string {...(input.headers !== undefined && Object.keys(input.headers).length > 0 ? { headers: input.headers } : {}),}const row: Record<string, unknown> = { id, name: MCP_PLUGIN, config }- if (input.disabled === true)- row.disabled = true+ if (input.disabled === true) row.disabled = trueconst node = toNode<YAMLMap>(row)if (existing === undefined) {list.add(node)- }- else if (existing.list !== undefined) {+ } else if (existing.list !== undefined) {existing.list.items.splice(existing.list.items.indexOf(existing.node), 1, node)- }- else {+ } else {// Bare rows were absorbed above; reaching here means a foreign-shaped row.rowSeq(doc).items.splice(rowSeq(doc).items.indexOf(existing.node), 1, node)}- savePatch(profileDirPath, doc)+ savePatch(dirPath, doc)return id}/** Flip one row's disabled flag (absent = enabled). Returns false when missing. */-export function setMcpDisabled(profileDirPath: string, id: string, disabled: boolean): boolean {- const doc = loadPatch(profileDirPath)+export function setMcpDisabled(dirPath: string, id: string, disabled: boolean): boolean {+ const doc = loadPatch(dirPath)managedInsert(doc)const hit = mcpRowItems(doc).find(({ node }) => String(node.get('id') ?? '') === id)- if (hit === undefined)- return false- if (disabled)- hit.node.set('disabled', true)+ if (hit === undefined) return false+ if (disabled) hit.node.set('disabled', true)else hit.node.delete('disabled')- savePatch(profileDirPath, doc)+ savePatch(dirPath, doc)return true}/** Remove one server row. Returns false when missing. */-export function removeMcp(profileDirPath: string, id: string): boolean {- const doc = loadPatch(profileDirPath)+export function removeMcp(dirPath: string, id: string): boolean {+ const doc = loadPatch(dirPath)managedInsert(doc)const hit = mcpRowItems(doc).find(({ node }) => String(node.get('id') ?? '') === id)- if (hit === undefined || hit.list === undefined)- return false+ if (hit === undefined || hit.list === undefined) return falsehit.list.items.splice(hit.list.items.indexOf(hit.node), 1)// An insert entry left with no rows is dead weight; drop it when the@@ -282,6 +340,84 @@ export function removeMcp(profileDirPath: string, id: string): boolean {seq.items.splice(seq.items.indexOf(owner), 1)}- savePatch(profileDirPath, doc)+ savePatch(dirPath, doc)return true}++/** Rebuild a create request from an existing row (id emptied; identity fields+ * carried over) — used to copy a row into the other patch layer. */+export function mcpRowToInput(row: McpRow): McpInput {+ return {+ id: '',+ serverName: row.serverName,+ transport: row.transport,+ disabled: row.disabled,+ ...(row.transport === 'stdio'+ ? {+ command: row.command,+ ...(row.args !== undefined ? { args: row.args } : {}),+ ...(row.env !== undefined ? { env: row.env } : {}),+ ...(row.cwd !== undefined ? { cwd: row.cwd } : {}),+ }+ : {+ url: row.url,+ ...(row.headers !== undefined ? { headers: row.headers } : {}),+ }),+ }+}++/**+ * Whether a stdio command would resolve at spawn time: a bare name is looked+ * up in the PATH entries (with the Windows executable extensions), anything+ * with a path separator must exist as given. Pure filesystem reads — no+ * process is spawned, so no console-window or side-effect concerns.+ */+export function resolveCommandOnPath(command: string, pathEnv: string, platform: string = process.platform): boolean {+ if (command.includes('/') || command.includes('\\')) return existsSync(command)+ const exts = platform === 'win32' ? ['', '.com', '.exe', '.bat', '.cmd'] : ['']+ const separator = platform === 'win32' ? ';' : ':'+ for (const rawDir of pathEnv.split(separator)) {+ const dir = rawDir.trim().replace(/^"|"$/g, '')+ if (dir === '') continue+ for (const ext of exts) {+ if (existsSync(join(dir, command + ext))) return true+ }+ }+ return false+}++/** Outcome of a connectivity check, as the browser renders it. */+export interface McpCheckResult {+ ok: boolean+ /** Short technical detail for the hint line ("HTTP 200", "not found on PATH"). */+ detail?: string+}++/**+ * Probe one server row without starting it: stdio rows are validated against+ * the PATH (a spawn would leave console windows and side effects behind),+ * streamable-http rows get a short GET — any HTTP status proves reachability,+ * since MCP endpoints legitimately answer 405 to plain GETs.+ */+export async function checkMcpRow(row: McpRow, options: { timeoutMs?: number; pathEnv?: string; platform?: string } = {}): Promise<McpCheckResult> {+ const pathEnv = options.pathEnv ?? process.env.PATH ?? ''+ if (row.transport === 'stdio') {+ const command = row.command ?? ''+ if (command === '') return { ok: false, detail: 'row has no command' }+ return resolveCommandOnPath(command, pathEnv, options.platform)+ ? { ok: true, detail: command }+ : { ok: false, detail: `${command} not found on PATH` }+ }+ if (row.url === undefined || !/^https?:\/\//.test(row.url)) return { ok: false, detail: 'row has no http url' }+ try {+ const response = await fetch(row.url, {+ headers: { accept: 'application/json, text/event-stream' },+ signal: AbortSignal.timeout(options.timeoutMs ?? 5000),+ })+ return { ok: true, detail: `HTTP ${response.status}` }+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error)+ const cause = (error as { cause?: { code?: unknown } }).cause?.code+ return { ok: false, detail: cause !== undefined ? String(cause) : message }+ }+}