Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

fix(mcp): keep !!js values and hidden fields when editing or copying a server (#1184)

Zuyang Liubbeba1c527e6
diff --git a/packages/dsh-tauri-extension/src/host/server/routes/mcp/copy/post.ts b/packages/dsh-tauri-extension/src/host/server/routes/mcp/copy/post.ts
index 822193ee..19824b94 100644
--- a/packages/dsh-tauri-extension/src/host/server/routes/mcp/copy/post.ts
+++ b/packages/dsh-tauri-extension/src/host/server/routes/mcp/copy/post.ts
@@ -2,7 +2,7 @@ import type { ExtensionRouteDeps } from '../../index.types'
import { getServerOptions } from 'dsh-h3/utils'
import { defineEventHandler, readBody } from 'h3'
import { mcp } from '../../../../service/mcp'
-import { mcpRowToInput, mcpScopeDir, normalizeMcpScope } from '../../../../service/mcp.utils'
+import { mcpScopeDir, normalizeMcpScope } from '../../../../service/mcp.utils'
interface McpCopyBody { id?: unknown, scope?: unknown, toScope?: unknown }
@@ -16,16 +16,12 @@ export default defineEventHandler(async (event) => {
const id = body.id
try {
const sourceDir = mcpScopeDir(normalizeMcpScope(body.scope), deps.profileDirPath)
- const source = mcp.peek(sourceDir).find(item => item.id === id)
- if (source === undefined) {
+ const scope = normalizeMcpScope(body.toScope)
+ const createdId = mcp.copy(sourceDir, mcpScopeDir(scope, deps.profileDirPath), id)
+ if (createdId === undefined) {
event.res.status = 404
return { error: 'server row not found' }
}
- const scope = normalizeMcpScope(body.toScope)
- const createdId = mcp.save(
- mcpScopeDir(scope, deps.profileDirPath),
- mcpRowToInput(source),
- )
return { ok: true, id: createdId, scope, restartNeeded: !deps.hotReload() }
}
catch (error) {
diff --git a/packages/dsh-tauri-extension/src/host/service/mcp.ts b/packages/dsh-tauri-extension/src/host/service/mcp.ts
index fdc698e1..b1de6a52 100644
--- a/packages/dsh-tauri-extension/src/host/service/mcp.ts
+++ b/packages/dsh-tauri-extension/src/host/service/mcp.ts
@@ -1,9 +1,9 @@
-import type { YAMLMap } from 'yaml'
+import type { Document, YAMLMap } from 'yaml'
import type { McpCheckOptions, McpCheckResult, McpInput, McpListResult, McpRow, McpRowView } from './mcp.types'
import { existsSync } from 'node:fs'
import process from 'node:process'
import { defineService, DSH_HOME } from 'dsh-tauri'
-import { compact, isEmpty } from 'lodash-es'
+import { compact } from 'lodash-es'
import { join } from 'pathe'
import { MCP_PLUGIN, PATCH_FILE_NAME } from '../config/constants'
import { mcpAuth } from './mcp-auth'
@@ -12,12 +12,12 @@ import {
loadPatch,
managedInsert,
mcpRowItems,
- normalizeStdioCommand,
readRows,
rowSeq,
savePatch,
takenIds,
toNode,
+ updateRow,
} from './mcp.utils'
const MCP_CHECK_TIMEOUT_MS = 5_000
@@ -59,50 +59,35 @@ export const mcp = defineService({
const existing = inputId !== ''
? mcpRowItems(doc).find(({ node }) => String(node.get('id') ?? '') === inputId)
: undefined
-
- let id = inputId !== '' ? inputId : `mcp-${input.serverName}`
- if (existing === undefined) {
- const taken = takenIds(doc)
- let suffix = 2
- while (taken.has(id))
- id = `mcp-${input.serverName}-${suffix++}`
- }
-
- const stdio = normalizeStdioCommand(input.command ?? '', input.args)
- const config: Record<string, unknown> = input.transport === 'stdio'
- ? {
- serverName: input.serverName,
- transport: input.transport,
- command: stdio.command,
- ...(!isEmpty(stdio.args) ? { args: stdio.args } : {}),
- ...(!isEmpty(input.env) ? { env: input.env } : {}),
- ...(!isEmpty(input.cwd) ? { cwd: input.cwd } : {}),
- }
- : {
- serverName: input.serverName,
- transport: input.transport,
- url: input.url,
- ...(!isEmpty(input.headers) ? { headers: input.headers } : {}),
- }
- const row: Record<string, unknown> = { id, name: MCP_PLUGIN, config }
- if (input.disabled === true)
- row.disabled = true
-
- const node = toNode<YAMLMap>(row)
- if (existing === undefined) {
- list.add(node)
- }
- else if (existing.list !== undefined) {
- existing.list.items.splice(existing.list.items.indexOf(existing.node), 1, node)
- }
- else {
- rowSeq(doc).items.splice(rowSeq(doc).items.indexOf(existing.node), 1, node)
+ if (existing !== undefined) {
+ updateRow(doc, existing.node, input)
+ savePatch(dirPath, doc)
+ return inputId
}
+ const id = freeId(doc, inputId !== '' ? inputId : `mcp-${input.serverName}`, input.serverName)
+ const node = toNode<YAMLMap>({ id, name: MCP_PLUGIN })
+ updateRow(doc, node, input)
+ list.add(node)
savePatch(dirPath, doc)
return id
},
+ copy(sourceDirPath: string, targetDirPath: string, id: string): string | undefined {
+ const source = mcpRowItems(loadPatch(sourceDirPath)).find(({ node }) => String(node.get('id') ?? '') === id)
+ if (source === undefined)
+ return undefined
+ const doc = loadPatch(targetDirPath)
+ const list = managedInsert(doc)
+ const node = source.node.clone() as YAMLMap
+ const serverName = String(node.getIn(['config', 'serverName']) ?? '')
+ const copyId = freeId(doc, `mcp-${serverName}`, serverName)
+ node.set('id', copyId)
+ list.add(node)
+ savePatch(targetDirPath, doc)
+ return copyId
+ },
+
remove(dirPath: string, id: string): boolean {
const doc = loadPatch(dirPath)
managedInsert(doc)
@@ -152,6 +137,15 @@ export const mcp = defineService({
// --- internal ---
+function freeId(doc: Document, preferred: string, serverName: string): string {
+ const taken = takenIds(doc)
+ let id = preferred
+ let suffix = 2
+ while (taken.has(id))
+ id = `mcp-${serverName}-${suffix++}`
+ return id
+}
+
function resolveCommandOnPath(command: string, pathEnv: string, platform: string = process.platform): boolean {
if (command.includes('/') || command.includes('\\'))
return existsSync(command)
diff --git a/packages/dsh-tauri-extension/src/host/service/mcp.utils.test.ts b/packages/dsh-tauri-extension/src/host/service/mcp.utils.test.ts
index 29cb3924..a33f2570 100644
--- a/packages/dsh-tauri-extension/src/host/service/mcp.utils.test.ts
+++ b/packages/dsh-tauri-extension/src/host/service/mcp.utils.test.ts
@@ -1,10 +1,62 @@
+import type { McpInput } from './mcp.types'
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
+import { parseDocument } from 'yaml'
import { mcp } from './mcp'
import { normalizeStdioCommand, splitCommandLine } from './mcp.utils'
+const HAND_EDITED = `- insert:
+ - id: mcp-github
+ name: '@deepseek-ai/dsh-mcp-client'
+ disabled: true
+ config:
+ serverName: github
+ transport: stdio
+ command: npx
+ args: [-y, '@modelcontextprotocol/server-github']
+ cwd: /srv/github
+ env:
+ GITHUB_TOKEN: !!js process.env.GITHUB_TOKEN
+ PORT: 3000
+ timeout: 30000
+`
+
+const GITHUB_ROW = {
+ id: 'mcp-github',
+ name: '@deepseek-ai/dsh-mcp-client',
+ disabled: true,
+ config: {
+ serverName: 'github',
+ transport: 'stdio',
+ command: 'npx',
+ args: ['-y', '@modelcontextprotocol/server-github'],
+ cwd: '/srv/github',
+ env: { GITHUB_TOKEN: 'process.env.GITHUB_TOKEN', PORT: 3000 },
+ timeout: 30000,
+ },
+}
+
+function patchDir(content: string): string {
+ const dir = mkdtempSync(join(tmpdir(), 'dsh-mcp-row-'))
+ writeFileSync(join(dir, 'cordis.patch.yml'), content)
+ return dir
+}
+
+function readPatch(dir: string): string {
+ return readFileSync(join(dir, 'cordis.patch.yml'), 'utf8')
+}
+
+function savedRows(dir: string): unknown[] {
+ return parseDocument(readPatch(dir)).toJS()[0].insert
+}
+
+function editorInput(dir: string): McpInput {
+ const [row] = mcp.peek(dir)
+ return { id: row.id, serverName: row.serverName, transport: row.transport, command: row.command, args: row.args ?? [], env: row.env ?? {} }
+}
+
describe('splitCommandLine', () => {
it('keeps quoted segments intact', () => {
expect(splitCommandLine('"C:/Program Files/node.exe" --experimental')).toEqual(['C:/Program Files/node.exe', '--experimental'])
@@ -59,4 +111,64 @@ describe('mcp.save', () => {
expect(patch).not.toContain('npx -y @heroui')
expect(patch).toContain('@heroui/react-mcp@latest')
})
+
+ it('keeps !!js values an edit left unchanged', () => {
+ const dir = patchDir(HAND_EDITED)
+ mcp.save(dir, editorInput(dir))
+ expect(readPatch(dir)).toContain('GITHUB_TOKEN: !!js process.env.GITHUB_TOKEN')
+ })
+
+ it('keeps the row fields the editor does not show', () => {
+ const dir = patchDir(HAND_EDITED)
+ mcp.save(dir, editorInput(dir))
+ expect(savedRows(dir)).toEqual([GITHUB_ROW])
+ })
+
+ it('saves an edited value as plain text', () => {
+ const dir = patchDir(HAND_EDITED)
+ mcp.save(dir, { ...editorInput(dir), env: { GITHUB_TOKEN: 'ghp_literal', PORT: '3000' } })
+ expect(readPatch(dir)).toContain('GITHUB_TOKEN: ghp_literal')
+ })
+
+ it('applies env keys added or removed in the editor', () => {
+ const dir = patchDir(HAND_EDITED)
+ mcp.save(dir, { ...editorInput(dir), env: { GITHUB_TOKEN: 'process.env.GITHUB_TOKEN', MODE: 'dev' } })
+ expect(savedRows(dir)).toEqual([
+ { ...GITHUB_ROW, config: { ...GITHUB_ROW.config, env: { GITHUB_TOKEN: 'process.env.GITHUB_TOKEN', MODE: 'dev' } } },
+ ])
+ })
+
+ it('drops stdio-only fields when an edit switches to http', () => {
+ const dir = patchDir(HAND_EDITED)
+ mcp.save(dir, { id: 'mcp-github', serverName: 'github', transport: 'streamable-http', url: 'https://mcp.example.test/mcp', headers: {} })
+ expect(savedRows(dir)).toEqual([
+ { ...GITHUB_ROW, config: { serverName: 'github', transport: 'streamable-http', url: 'https://mcp.example.test/mcp', timeout: 30000 } },
+ ])
+ })
+})
+
+describe('mcp.peek', () => {
+ it('lists non-string env values as text', () => {
+ expect(mcp.peek(patchDir(HAND_EDITED))[0].env).toEqual({ GITHUB_TOKEN: 'process.env.GITHUB_TOKEN', PORT: '3000' })
+ })
+})
+
+describe('mcp.copy', () => {
+ it('copies a row to another scope as it is written', () => {
+ const source = patchDir(HAND_EDITED)
+ const target = mkdtempSync(join(tmpdir(), 'dsh-mcp-copy-'))
+ expect(mcp.copy(source, target, 'mcp-github')).toBe('mcp-github')
+ expect(readPatch(target)).toContain('GITHUB_TOKEN: !!js process.env.GITHUB_TOKEN')
+ expect(savedRows(target)).toEqual([GITHUB_ROW])
+ })
+
+ it('gives the copy a free id when the source id is taken', () => {
+ const dir = patchDir(HAND_EDITED)
+ expect(mcp.copy(dir, dir, 'mcp-github')).toBe('mcp-github-2')
+ expect(savedRows(dir)).toEqual([GITHUB_ROW, { ...GITHUB_ROW, id: 'mcp-github-2' }])
+ })
+
+ it('returns undefined when the source row is missing', () => {
+ expect(mcp.copy(patchDir(HAND_EDITED), mkdtempSync(join(tmpdir(), 'dsh-mcp-copy-')), 'mcp-missing')).toBeUndefined()
+ })
})
diff --git a/packages/dsh-tauri-extension/src/host/service/mcp.utils.ts b/packages/dsh-tauri-extension/src/host/service/mcp.utils.ts
index 3a0a3aad..960c83d0 100644
--- a/packages/dsh-tauri-extension/src/host/service/mcp.utils.ts
+++ b/packages/dsh-tauri-extension/src/host/service/mcp.utils.ts
@@ -2,9 +2,9 @@ import type { YAMLMap, YAMLSeq } from 'yaml'
import type { McpInput, McpRow, McpScope } from './mcp.types'
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { DSH_HOME } from 'dsh-tauri'
-import { compact, every, isObject, isString, isUndefined, omitBy } from 'lodash-es'
+import { compact, isEmpty, isObject, isPlainObject, isString, mapValues } from 'lodash-es'
import { join } from 'pathe'
-import { Document, parseDocument } from 'yaml'
+import { Document, isMap, isNode, isScalar, isSeq, parseDocument } from 'yaml'
import { MCP_PLUGIN, PATCH_FILE_NAME } from '../config/constants'
const SERVER_NAME_RE = /^[\w-]{1,32}$/
@@ -52,20 +52,6 @@ export function mcpScopeDir(scope: McpScope, profileDirPath: string): string {
return scope === 'global' ? DSH_HOME : profileDirPath
}
-export function mcpRowToInput(row: McpRow): McpInput {
- const detail: Record<string, unknown> = row.transport === 'stdio'
- ? { args: row.args, env: row.env, cwd: row.cwd }
- : { headers: row.headers }
- return {
- id: '',
- serverName: row.serverName,
- transport: row.transport,
- disabled: row.disabled,
- ...(row.transport === 'stdio' ? { command: row.command } : { url: row.url }),
- ...omitBy(detail, isUndefined),
- }
-}
-
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 _ -'
@@ -166,6 +152,23 @@ export function readRows(dirPath: string): McpRow[] {
return mcpRowItems(doc).map(({ node }) => rowToMcp(doc, node))
}
+/** 原地改写已有行:只写表单管的字段,值没变的节点原样保留(`!!js` 标签、表单外的字段不丢)。 */
+export function updateRow(doc: Document, row: YAMLMap, input: McpInput): void {
+ const current = row.get('config', true)
+ const config = isMap(current) ? current : toNode<YAMLMap>({})
+ for (const [key, value] of Object.entries(formConfig(input))) {
+ if (isEmpty(value))
+ config.delete(key)
+ else
+ config.set(key, keepUnchanged(doc, config.get(key, true), value))
+ }
+ row.set('config', config)
+ if (input.disabled === true)
+ row.set('disabled', true)
+ else if (input.disabled === false)
+ row.delete('disabled')
+}
+
// --- internal ---
function assertPatchParses(path: string, doc: Document): void {
@@ -183,10 +186,60 @@ function isSeqNode(value: unknown): value is YAMLSeq<YAMLMap> {
return typeof value === 'object' && value !== null && Array.isArray((value as YAMLSeq).items)
}
-function isStringMap(value: unknown): value is Record<string, string> {
- if (!isObject(value) || Array.isArray(value))
- return false
- return every(value, isString)
+function valueText(value: unknown): string {
+ return isString(value) ? value : JSON.stringify(value)
+}
+
+function textMap(value: unknown): Record<string, string> | undefined {
+ return isPlainObject(value) ? mapValues(value as Record<string, unknown>, valueText) : undefined
+}
+
+function formConfig(input: McpInput): Record<string, unknown> {
+ if (input.transport !== 'stdio') {
+ return {
+ serverName: input.serverName,
+ transport: input.transport,
+ url: input.url,
+ headers: input.headers,
+ command: undefined,
+ args: undefined,
+ env: undefined,
+ cwd: undefined,
+ }
+ }
+ const stdio = normalizeStdioCommand(input.command ?? '', input.args)
+ return {
+ serverName: input.serverName,
+ transport: input.transport,
+ command: stdio.command,
+ args: stdio.args,
+ env: input.env,
+ ...(input.cwd !== undefined ? { cwd: input.cwd } : {}),
+ url: undefined,
+ headers: undefined,
+ }
+}
+
+function keepUnchanged(doc: Document, current: unknown, next: unknown): unknown {
+ if (Array.isArray(next)) {
+ const items: unknown[] = isSeq(current) ? current.items : []
+ const kept = next.map((value, index) => keepUnchanged(doc, items[index], value))
+ return kept.length === items.length && kept.every((item, index) => item === items[index])
+ ? current
+ : toNode(kept)
+ }
+ if (isPlainObject(next)) {
+ const map = isMap(current) ? current : toNode<YAMLMap>({})
+ const keys = Object.keys(next as Record<string, unknown>)
+ for (const pair of [...map.items]) {
+ if (!keys.includes(String(isScalar(pair.key) ? pair.key.value : pair.key)))
+ map.delete(pair.key)
+ }
+ for (const [key, value] of Object.entries(next as Record<string, unknown>))
+ map.set(key, keepUnchanged(doc, map.get(key, true), value))
+ return map
+ }
+ return isNode(current) && valueText(current.toJS(doc)) === next ? current : toNode(next)
}
function rowToMcp(doc: Document, item: YAMLMap): McpRow {
@@ -194,16 +247,18 @@ function rowToMcp(doc: Document, item: YAMLMap): McpRow {
const plain = (isObject(configNode) && typeof (configNode as { toJS?: unknown }).toJS === 'function'
? (configNode as { toJS: (document: Document) => unknown }).toJS(doc)
: {}) as Record<string, unknown>
+ const env = textMap(plain.env)
+ const headers = textMap(plain.headers)
return {
id: String(item.get('id') ?? ''),
serverName: String(plain.serverName ?? ''),
transport: plain.transport === 'streamable-http' ? 'streamable-http' : 'stdio',
disabled: item.get('disabled') === true,
...(typeof plain.command === 'string' && plain.command !== '' ? { command: plain.command } : {}),
- ...(Array.isArray(plain.args) ? { args: plain.args.map(String) } : {}),
- ...(isStringMap(plain.env) ? { env: plain.env } : {}),
+ ...(Array.isArray(plain.args) ? { args: plain.args.map(valueText) } : {}),
+ ...(env !== undefined ? { env } : {}),
...(typeof plain.cwd === 'string' && plain.cwd !== '' ? { cwd: plain.cwd } : {}),
...(typeof plain.url === 'string' && plain.url !== '' ? { url: plain.url } : {}),
- ...(isStringMap(plain.headers) ? { headers: plain.headers } : {}),
+ ...(headers !== undefined ? { headers } : {}),
}
}