Skip to content

The agent that grows with you

feat(desktop): paste-anything MCP server import

Teknium1e54e052273e
diff --git a/apps/desktop/src/app/skills/mcp-tab.tsx b/apps/desktop/src/app/skills/mcp-tab.tsx
index 36dfce46fa7..2064b57419a 100644
--- a/apps/desktop/src/app/skills/mcp-tab.tsx
+++ b/apps/desktop/src/app/skills/mcp-tab.tsx
@@ -10,8 +10,10 @@ import { Button } from '@/components/ui/button'
import { Codicon } from '@/components/ui/codicon'
import { ErrorBanner } from '@/components/ui/error-state'
import { Input } from '@/components/ui/input'
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { Switch } from '@/components/ui/switch'
import { TextTab } from '@/components/ui/text-tab'
+import { Textarea } from '@/components/ui/textarea'
import { Tip } from '@/components/ui/tooltip'
import {
authMcpServer,
@@ -32,6 +34,7 @@ import { compactNumber } from '@/lib/format'
import { brandFor, brandGlyphStyle } from '@/lib/mcp-brands'
import { estimateServerTokens, serverUsageCount } from '@/lib/mcp-cost'
import { completeMcpDesktopOAuth } from '@/lib/mcp-dashboard-oauth'
+import { type McpImportEntry, parseMcpImport } from '@/lib/mcp-import'
import { NEEDS_AUTH_RE, PROBE_TTL_MS, probeCache, probeKey, serverFingerprint } from '@/lib/mcp-probe-cache'
import { countEnabledTools, isToolEnabled, toggleToolInServer } from '@/lib/mcp-tool-filter'
import { cn } from '@/lib/utils'
@@ -925,6 +928,53 @@ export function McpTab({ gateway, profile }: { gateway: HermesGateway | null; pr
}
}
+ // Paste-anything import: merge parsed entries into the draft exactly like
+ // addServer seeds its starter — dirty draft, unique keys, focus the first
+ // new block. Saving stays an explicit step, so the user can fix placeholder
+ // env values (YOUR_KEY, …) in the editor first.
+ const importServers = (entries: McpImportEntry[]) => {
+ if (profilePending || entries.length === 0) {
+ return
+ }
+
+ let base: McpServers
+
+ try {
+ base = parseServersDoc(draft)
+ } catch {
+ base = { ...servers }
+ }
+
+ let firstKey: null | string = null
+
+ for (const entry of entries) {
+ let key = entry.name
+
+ for (let i = 2; key in base; i++) {
+ key = `${entry.name}-${i}`
+ }
+
+ base = { ...base, [key]: entry.config }
+ firstKey ??= key
+ }
+
+ const nextDraft = wrapDoc(base)
+ setDraft(nextDraft)
+ setDirty(true)
+ setDocVersion(version => version + 1)
+
+ if (firstKey) {
+ const from = nextDraft.indexOf(`"${firstKey}"`)
+
+ if (from >= 0) {
+ requestAnimationFrame(() => {
+ editorApi.current?.setCursor(from + 1)
+ setCursor(from + 1)
+ })
+ }
+ }
+ }
+
const saveDoc = async () => {
if (profilePending) {
return
@@ -1041,7 +1091,8 @@ export function McpTab({ gateway, profile }: { gateway: HermesGateway | null; pr
lands on the exact line the sort link occupies in the
Skills/Tools views. */}
<div className="mb-1 flex h-6 shrink-0 items-center pl-2 pr-1">
- <span className="text-[0.72rem] font-medium text-(--ui-text-tertiary)">{m.tabServers}</span>
+ <span className="flex-1 text-[0.72rem] font-medium text-(--ui-text-tertiary)">{m.tabServers}</span>
+ <McpImportButton disabled={profilePending} onImport={importServers} />
</div>
{names.length === 0 ? (
<PanelEmpty
@@ -1398,6 +1449,92 @@ function ServerIconActions({
)
}
+// Paste-anything import: a compact popover on the Servers header. Paste any
+// README shape — mcp.json snippet, npx/docker command line, `claude mcp add`,
+// a bare URL, or a Cursor deeplink — see the inferred name + config, then
+// merge it into the editor draft (unsaved, like the "+" starter entry).
+function McpImportButton({
+ disabled,
+ onImport
+}: {
+ disabled: boolean
+ onImport: (entries: McpImportEntry[]) => void
+}) {
+ const { t } = useI18n()
+ const m = t.settings.mcp
+ const [open, setOpen] = useState(false)
+ const [text, setText] = useState('')
+
+ const entries = useMemo(() => parseMcpImport(text), [text])
+
+ const reset = () => {
+ setText('')
+ }
+
+ const confirm = () => {
+ if (!entries) {
+ return
+ }
+
+ onImport(entries)
+ setOpen(false)
+ reset()
+ }
+
+ return (
+ <Popover
+ onOpenChange={next => {
+ setOpen(next)
+
+ if (!next) {
+ reset()
+ }
+ }}
+ open={open}
+ >
+ <PopoverTrigger asChild>
+ <Button className="h-5 px-1 text-[0.68rem]" disabled={disabled} size="xs" variant="text">
+ <Codicon name="clippy" size="0.75rem" />
+ {m.importButton}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="end" className="w-80">
+ <div className="flex flex-col gap-2">
+ <Textarea
+ aria-label={m.importButton}
+ autoFocus
+ className="max-h-40 min-h-20 font-mono text-[0.68rem]"
+ onChange={event => setText(event.currentTarget.value)}
+ placeholder={m.importPlaceholder}
+ value={text}
+ />
+ {entries ? (
+ <div className="flex max-h-40 flex-col gap-1 overflow-y-auto">
+ {entries.map((entry, index) => (
+ <div className="rounded-md bg-(--ui-bg-tertiary) px-2 py-1.5" key={`${entry.name}-${index}`}>
+ <span className="block truncate text-[0.72rem] font-medium text-foreground/85">{entry.name}</span>
+ <span className="block truncate font-mono text-[0.62rem] text-muted-foreground/60">
+ {typeof entry.config.url === 'string'
+ ? entry.config.url
+ : [entry.config.command, ...((entry.config.args as string[]) ?? [])].join(' ')}
+ </span>
+ </div>
+ ))}
+ </div>
+ ) : (
+ text.trim() && <p className="px-0.5 text-[0.62rem] text-muted-foreground/60">{m.importNoMatch}</p>
+ )}
+ <div className="flex justify-end">
+ <Button disabled={!entries} onClick={confirm} size="xs">
+ {entries && entries.length > 1 ? m.importConfirmMany(entries.length) : m.importConfirm}
+ </Button>
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+ )
+}
+
// Small gray attribute chip (transport / auth / needs-build), matching the
// catalog's flat row treatment.
function CatalogTag({ children }: { children: string }) {
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index 5f1c492e175..21441305db6 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -922,7 +922,12 @@ export const en: Translations = {
deepLinkErrorConfig: 'The link\u2019s config is not valid base64-encoded JSON.',
deepLinkErrorShape: 'The config must be a JSON object with a string `url` or `command` field.',
deepLinkErrorUrl: 'Only http:// and https:// server URLs are allowed.',
- deepLinkErrorTooLarge: 'The config payload exceeds the 32KB limit.'
+ deepLinkErrorTooLarge: 'The config payload exceeds the 32KB limit.',
+ importButton: 'Import',
+ importPlaceholder: 'Paste an mcp.json snippet, npx/docker command, claude mcp add line, URL, or Cursor link…',
+ importNoMatch: 'No server config recognized in the pasted text.',
+ importConfirm: 'Add to mcp.json',
+ importConfirmMany: count => `Add ${count} servers to mcp.json`
},
model: {
loading: 'Loading model configuration...',
diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts
index 301365c73f4..a8e2401cfe5 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -903,7 +903,12 @@ export const ja = defineLocale({
deepLinkErrorShape:
'設定は文字列の `url` または `command` フィールドを持つ JSON オブジェクトである必要があります。',
deepLinkErrorUrl: 'サーバー URL は http:// と https:// のみ許可されます。',
- deepLinkErrorTooLarge: '設定ペイロードが 32KB の上限を超えています。'
+ deepLinkErrorTooLarge: '設定ペイロードが 32KB の上限を超えています。',
+ importButton: 'インポート',
+ importPlaceholder: 'mcp.json スニペット、npx/docker コマンド、claude mcp add 行、URL、Cursor リンクを貼り付け…',
+ importNoMatch: '貼り付けたテキストからサーバー設定を認識できませんでした。',
+ importConfirm: 'mcp.json に追加',
+ importConfirmMany: count => `${count} 件のサーバーを mcp.json に追加`
},
model: {
loading: 'モデル設定を読み込み中...',
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index a3814aeec9c..597c41b0b74 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -793,7 +793,12 @@ export interface Translations {
deepLinkErrorConfig: string
deepLinkErrorShape: string
deepLinkErrorUrl: string
- deepLinkErrorTooLarge: string
+ deepLinkErrorTooLarge: string,
+ importButton: string
+ importPlaceholder: string
+ importNoMatch: string
+ importConfirm: string
+ importConfirmMany: (count: number) => string
}
model: {
loading: string
diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.ts
index f140697477c..32c2ec0871c 100644
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@ -873,7 +873,12 @@ export const zhHant = defineLocale({
deepLinkErrorConfig: '連結中的設定不是有效的 base64 編碼 JSON。',
deepLinkErrorShape: '設定必須是包含字串 `url` 或 `command` 欄位的 JSON 物件。',
deepLinkErrorUrl: '僅允許 http:// 和 https:// 伺服器網址。',
- deepLinkErrorTooLarge: '設定內容超過 32KB 上限。'
+ deepLinkErrorTooLarge: '設定內容超過 32KB 上限。',
+ importButton: '匯入',
+ importPlaceholder: '貼上 mcp.json 片段、npx/docker 指令、claude mcp add 指令、URL 或 Cursor 連結…',
+ importNoMatch: '貼上的文字中未識別到伺服器設定。',
+ importConfirm: '加入 mcp.json',
+ importConfirmMany: count => `將 ${count} 個伺服器加入 mcp.json`
},
model: {
loading: '正在載入模型設定...',
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index 334053018a7..1918b16bb8c 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -1120,7 +1120,12 @@ export const zh: Translations = {
deepLinkErrorConfig: '链接中的配置不是有效的 base64 编码 JSON。',
deepLinkErrorShape: '配置必须是包含字符串 `url` 或 `command` 字段的 JSON 对象。',
deepLinkErrorUrl: '仅允许 http:// 和 https:// 服务器地址。',
- deepLinkErrorTooLarge: '配置负载超过 32KB 上限。'
+ deepLinkErrorTooLarge: '配置负载超过 32KB 上限。',
+ importButton: '导入',
+ importPlaceholder: '粘贴 mcp.json 片段、npx/docker 命令、claude mcp add 命令、URL 或 Cursor 链接…',
+ importNoMatch: '粘贴的文本中未识别到服务器配置。',
+ importConfirm: '添加到 mcp.json',
+ importConfirmMany: count => `添加 ${count} 个服务器到 mcp.json`
},
model: {
loading: '正在加载模型配置...',
diff --git a/apps/desktop/src/lib/mcp-import.test.ts b/apps/desktop/src/lib/mcp-import.test.ts
new file mode 100644
index 00000000000..bf45ae19d72
--- /dev/null
+++ b/apps/desktop/src/lib/mcp-import.test.ts
@@ -0,0 +1,199 @@
+import { describe, expect, it } from 'vitest'
+
+import { parseMcpImport } from './mcp-import'
+
+describe('parseMcpImport', () => {
+ describe('mcp.json snippets', () => {
+ it('parses an mcpServers-wrapped document', () => {
+ const text = JSON.stringify({
+ mcpServers: {
+ filesystem: { args: ['-y', '@modelcontextprotocol/server-filesystem', '/tmp'], command: 'npx' },
+ linear: { url: 'https://mcp.linear.app/sse' }
+ }
+ })
+
+ expect(parseMcpImport(text)).toEqual([
+ {
+ config: { args: ['-y', '@modelcontextprotocol/server-filesystem', '/tmp'], command: 'npx' },
+ name: 'filesystem'
+ },
+ { config: { url: 'https://mcp.linear.app/sse' }, name: 'linear' }
+ ])
+ })
+
+ it('parses a bare name→config map and normalizes the Cursor/Claude type field', () => {
+ const text = JSON.stringify({ context7: { type: 'http', url: 'https://mcp.context7.com/mcp' } })
+
+ expect(parseMcpImport(text)).toEqual([
+ { config: { transport: 'http', url: 'https://mcp.context7.com/mcp' }, name: 'context7' }
+ ])
+ })
+
+ it('infers a name for a single unnamed server object', () => {
+ const text = JSON.stringify({ args: ['-y', '@modelcontextprotocol/server-github'], command: 'npx' })
+
+ expect(parseMcpImport(text)).toEqual([
+ { config: { args: ['-y', '@modelcontextprotocol/server-github'], command: 'npx' }, name: 'github' }
+ ])
+ })
+
+ it('rejects JSON whose values are not server-shaped', () => {
+ expect(parseMcpImport('{"a": 1, "b": "two"}')).toBeNull()
+ expect(parseMcpImport('[1, 2, 3]')).toBeNull()
+ expect(parseMcpImport('{}')).toBeNull()
+ })
+ })
+
+ describe('bare command lines', () => {
+ it('parses an npx line and names it after the package basename', () => {
+ expect(parseMcpImport('npx -y @modelcontextprotocol/server-filesystem /path/to/dir')).toEqual([
+ {
+ config: { args: ['-y', '@modelcontextprotocol/server-filesystem', '/path/to/dir'], command: 'npx' },
+ name: 'filesystem'
+ }
+ ])
+ })
+
+ it('strips version pins when inferring the name', () => {
+ expect(parseMcpImport('npx -y @upstash/context7-mcp@latest')).toEqual([
+ { config: { args: ['-y', '@upstash/context7-mcp@latest'], command: 'npx' }, name: 'context7' }
+ ])
+ })
+
+ it('parses a uvx line', () => {
+ expect(parseMcpImport('uvx mcp-server-fetch')).toEqual([
+ { config: { args: ['mcp-server-fetch'], command: 'uvx' }, name: 'fetch' }
+ ])
+ })
+
+ it('parses a node line and names it after the script', () => {
+ expect(parseMcpImport('node ./servers/weather.js --port 3010')).toEqual([
+ { config: { args: ['./servers/weather.js', '--port', '3010'], command: 'node' }, name: 'weather' }
+ ])
+ })
+
+ it('parses a docker run line, keeping placeholder env values verbatim', () => {
+ expect(parseMcpImport('docker run -i --rm -e GITHUB_TOKEN=YOUR_KEY mcp/github')).toEqual([
+ {
+ config: { args: ['run', '-i', '--rm', '-e', 'GITHUB_TOKEN=YOUR_KEY', 'mcp/github'], command: 'docker' },
+ name: 'github'
+ }
+ ])
+ })
+
+ it('honors quoted arguments', () => {
+ expect(parseMcpImport('npx -y @modelcontextprotocol/server-filesystem "/My Files/docs"')).toEqual([
+ {
+ config: { args: ['-y', '@modelcontextprotocol/server-filesystem', '/My Files/docs'], command: 'npx' },
+ name: 'filesystem'
+ }
+ ])
+ })
+
+ it('parses multiple command lines into multiple entries', () => {
+ expect(parseMcpImport('uvx mcp-server-fetch\nnpx -y @modelcontextprotocol/server-memory')).toEqual([
+ { config: { args: ['mcp-server-fetch'], command: 'uvx' }, name: 'fetch' },
+ { config: { args: ['-y', '@modelcontextprotocol/server-memory'], command: 'npx' }, name: 'memory' }
+ ])
+ })
+ })
+
+ describe('claude mcp add lines', () => {
+ it('parses a stdio add with env and a -- separator', () => {
+ expect(parseMcpImport('claude mcp add airtable -e AIRTABLE_API_KEY=YOUR_KEY -- npx -y airtable-mcp-server')).toEqual(
+ [
+ {
+ config: {
+ args: ['-y', 'airtable-mcp-server'],
+ command: 'npx',
+ env: { AIRTABLE_API_KEY: 'YOUR_KEY' }
+ },
+ name: 'airtable'
+ }
+ ]
+ )
+ })
+
+ it('parses a stdio add without a -- separator', () => {
+ expect(parseMcpImport('claude mcp add linear npx -y mcp-remote https://mcp.linear.app/sse')).toEqual([
+ {
+ config: { args: ['-y', 'mcp-remote', 'https://mcp.linear.app/sse'], command: 'npx' },
+ name: 'linear'
+ }
+ ])
+ })
+
+ it('parses an http transport add pointing at a URL', () => {
+ expect(parseMcpImport('claude mcp add --transport http context7 https://mcp.context7.com/mcp')).toEqual([
+ { config: { transport: 'http', url: 'https://mcp.context7.com/mcp' }, name: 'context7' }
+ ])
+ })
+
+ it('parses an sse add with a header', () => {
+ expect(
+ parseMcpImport('claude mcp add --transport sse api -H "Authorization: Bearer TOKEN_HERE" https://api.example.com/sse')
+ ).toEqual([
+ {
+ config: {
+ headers: { Authorization: 'Bearer TOKEN_HERE' },
+ transport: 'sse',
+ url: 'https://api.example.com/sse'
+ },
+ name: 'api'
+ }
+ ])
+ })
+
+ it('rejects an add with no command or URL', () => {
+ expect(parseMcpImport('claude mcp add lonely')).toBeNull()
+ })
+ })
+
+ describe('bare URLs', () => {
+ it('parses an https URL and names it from the hostname', () => {
+ expect(parseMcpImport('https://mcp.linear.app/sse')).toEqual([
+ { config: { url: 'https://mcp.linear.app/sse' }, name: 'linear' }
+ ])
+ })
+
+ it('handles single-label hosts', () => {
+ expect(parseMcpImport('http://localhost:8080/mcp')).toEqual([
+ { config: { url: 'http://localhost:8080/mcp' }, name: 'localhost' }
+ ])
+ })
+ })
+
+ describe('cursor deeplinks', () => {
+ it('decodes the base64 config payload', () => {
+ const config = { args: ['-y', '@upstash/context7-mcp'], command: 'npx' }
+ const link = `cursor://anysphere.cursor-deeplink/mcp/install?name=context7&config=${btoa(JSON.stringify(config))}`
+
+ expect(parseMcpImport(link)).toEqual([{ config, name: 'context7' }])
+ })
+
+ it('normalizes a type field inside the payload', () => {
+ const config = { type: 'sse', url: 'https://mcp.example.com/sse' }
+ const link = `cursor://anysphere.cursor-deeplink/mcp/install?name=example&config=${btoa(JSON.stringify(config))}`
+
+ expect(parseMcpImport(link)).toEqual([
+ { config: { transport: 'sse', url: 'https://mcp.example.com/sse' }, name: 'example' }
+ ])
+ })
+
+ it('rejects deeplinks with an invalid payload', () => {
+ expect(parseMcpImport('cursor://anysphere.cursor-deeplink/mcp/install?name=x&config=!!!notbase64!!!')).toBeNull()
+ expect(parseMcpImport('cursor://anysphere.cursor-deeplink/mcp/install?name=x')).toBeNull()
+ })
+ })
+
+ describe('garbage input', () => {
+ it('returns null for prose, empty text, and unknown commands', () => {
+ expect(parseMcpImport('')).toBeNull()
+ expect(parseMcpImport(' \n ')).toBeNull()
+ expect(parseMcpImport('hello world this is not a config')).toBeNull()
+ expect(parseMcpImport('rm -rf /')).toBeNull()
+ expect(parseMcpImport('ftp://example.com/thing')).toBeNull()
+ expect(parseMcpImport('"unterminated quote npx foo')).toBeNull()
+ })
+ })
+})
diff --git a/apps/desktop/src/lib/mcp-import.ts b/apps/desktop/src/lib/mcp-import.ts
new file mode 100644
index 00000000000..7b83460b01d
--- /dev/null
+++ b/apps/desktop/src/lib/mcp-import.ts
@@ -0,0 +1,446 @@
+// Paste-anything MCP import: turns whatever a README tells the user to copy —
+// an mcp.json snippet, a bare `npx`/`docker` command, a `claude mcp add` line,
+// a plain server URL, or a Cursor install deeplink — into named mcp.json
+// entries. Pure and side-effect free; the MCP tab merges the result into the
+// editor draft. Returns null when nothing recognizable is in the text.
+
+export interface McpImportEntry {
+ config: Record<string, unknown>
+ name: string
+}
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ !!value && typeof value === 'object' && !Array.isArray(value)
+
+const isServerShape = (value: Record<string, unknown>) =>
+ typeof value.command === 'string' || typeof value.url === 'string'
+
+// Cursor/Claude write `type`; Hermes reads `transport` (same normalization the
+// MCP tab applies to pasted JSON).
+function normalizeEntry(entry: Record<string, unknown>): Record<string, unknown> {
+ if (typeof entry.type === 'string' && entry.transport === undefined) {
+ const { type, ...rest } = entry
+
+ return { ...rest, transport: type }
+ }
+
+ return entry
+}
+
+const URL_RE = /^https?:\/\/\S+$/i
+
+// "mcp.linear.app" → "linear": drop generic front labels, keep the brand one.
+function nameFromUrl(raw: string): string {
+ try {
+ const labels = new URL(raw).hostname.split('.').filter(Boolean)
+
+ while (labels.length > 1 && ['api', 'mcp', 'www'].includes(labels[0])) {
+ labels.shift()
+ }
+
+ return labels[0] || 'server'
+ } catch {
+ return 'server'
+ }
+}
+
+// "@modelcontextprotocol/server-filesystem@latest" → "filesystem".
+function cleanupName(base: string): string {
+ const stripped = base
+ .replace(/\.(cjs|js|mjs|py|ts)$/i, '')
+ .replace(/^(mcp-server-|server-|mcp-)/, '')
+ .replace(/(-mcp-server|-mcp|-server)$/, '')
+
+ return stripped || base
+}
+
+function packageBasename(spec: string): string {
+ // uvx-style version pins ("pkg==1.0"), then npm-style ("pkg@latest",
+ // "@scope/[email protected]" — the scope's leading @ is at index 0 and survives).
+ let bare = spec.split('==')[0]
+ const at = bare.lastIndexOf('@')
+
+ if (at > 0) {
+ bare = bare.slice(0, at)
+ }
+
+ return cleanupName(bare.split('/').pop() ?? bare)
+}
+
+// Shell-ish tokenizer: whitespace-split with single/double quotes (and
+// backslash escapes inside double quotes). Null on an unterminated quote.
+function tokenize(line: string): null | string[] {
+ const tokens: string[] = []
+ let current = ''
+ let sawQuote = false
+ let quote: '"' | "'" | null = null
+
+ for (let i = 0; i < line.length; i++) {
+ const ch = line[i]
+
+ if (quote) {
+ if (ch === quote) {
+ quote = null
+ } else if (ch === '\\' && quote === '"' && i + 1 < line.length) {
+ current += line[++i]
+ } else {
+ current += ch
+ }
+ } else if (ch === '"' || ch === "'") {
+ quote = ch
+ sawQuote = true
+ } else if (/\s/.test(ch)) {
+ if (current || sawQuote) {
+ tokens.push(current)
+ current = ''
+ sawQuote = false
+ }
+ } else {
+ current += ch
+ }
+ }
+
+ if (quote) {
+ return null
+ }
+
+ if (current || sawQuote) {
+ tokens.push(current)
+ }
+
+ return tokens
+}
+
+const STDIO_COMMANDS = new Set(['bunx', 'docker', 'node', 'npx', 'uvx'])
+
+// docker flags that consume the following token (so the image isn't mistaken
+// for a flag value or vice versa).
+const DOCKER_VALUE_FLAGS = new Set([
+ '--entrypoint',
+ '--env',
+ '--label',
+ '--mount',
+ '--name',
+ '--network',
+ '--platform',
+ '--publish',
+ '--pull',
+ '--user',
+ '--volume',
+ '--workdir',
+ '-e',
+ '-l',
+ '-p',
+ '-u',
+ '-v',
+ '-w'
+])
+
+function inferCommandName(command: string, args: string[]): string {
+ if (command === 'docker') {
+ let i = args[0] === 'run' ? 1 : 0
+
+ for (; i < args.length; i++) {
+ const arg = args[i]
+
+ if (arg.startsWith('-')) {
+ if (DOCKER_VALUE_FLAGS.has(arg)) {
+ i++
+ }
+
+ continue
+ }
+
+ // Image ref: strip registry/repo path and the :tag.
+ return cleanupName((arg.split('/').pop() ?? arg).split(':')[0])
+ }
+
+ return 'docker'
+ }
+
+ if (command === 'node') {
+ const script = args.find(arg => !arg.startsWith('-'))
+
+ return script ? cleanupName(script.split(/[/\\]/).pop() ?? script) : 'node'
+ }
+
+ // npx / bunx / uvx: the first positional is the package spec.
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i]
+
+ if (arg.startsWith('-')) {
+ if (arg === '--from' || arg === '--package' || arg === '-p') {
+ i++
+ }
+
+ continue
+ }
+
+ return packageBasename(arg)
+ }
+
+ return command
+}
+
+function fromCommandLine(tokens: string[]): McpImportEntry | null {
+ const command = tokens[0]
+
+ if (!STDIO_COMMANDS.has(command)) {
+ return null
+ }
+
+ return {
+ config: { args: tokens.slice(1), command },
+ name: inferCommandName(command, tokens.slice(1))
+ }
+}
+
+// `claude mcp add NAME [--transport http|sse] [-e K=V]... [--] CMD ARGS...`
+// and `claude mcp add NAME URL`. Everything after the first positional
+// following NAME (or after `--`) is the command verbatim.
+function fromClaudeAdd(tokens: string[]): McpImportEntry | null {
+ let name: null | string = null
+ let transport: null | string = null
+ let rest: null | string[] = null
+ const env: Record<string, string> = {}
+ const headers: Record<string, string> = {}
+
+ for (let i = 3; i < tokens.length; i++) {
+ const token = tokens[i]
+
+ if (token === '--') {
+ rest = tokens.slice(i + 1)
+
+ break
+ }
+
+ if (token === '--transport' || token === '-t') {
+ transport = tokens[++i] ?? null
+
+ continue
+ }
+
+ if (token === '--env' || token === '-e') {
+ const pair = tokens[++i] ?? ''
+ const eq = pair.indexOf('=')
+
+ if (eq > 0) {
+ env[pair.slice(0, eq)] = pair.slice(eq + 1)
+ }
+
+ continue
+ }
+
+ if (token === '--header' || token === '-H') {
+ const pair = tokens[++i] ?? ''
+ const colon = pair.indexOf(':')
+
+ if (colon > 0) {
+ headers[pair.slice(0, colon).trim()] = pair.slice(colon + 1).trim()
+ }
+
+ continue
+ }
+
+ if (token === '--scope' || token === '-s') {
+ i++
+
+ continue
+ }
+
+ if (token.startsWith('-')) {
+ continue
+ }
+
+ if (!name) {
+ name = token
+
+ continue
+ }
+
+ // First non-flag token after the name starts the command (no `--` given).
+ rest = tokens.slice(i)
+
+ break
+ }
+
+ if (!name || !rest || rest.length === 0) {
+ return null
+ }
+
+ if (rest.length === 1 && URL_RE.test(rest[0])) {
+ const config: Record<string, unknown> = { url: rest[0] }
+
+ if (transport) {
+ config.transport = transport
+ }
+
+ if (Object.keys(headers).length > 0) {
+ config.headers = headers
+ }
+
+ return { config, name }
+ }
+
+ const config: Record<string, unknown> = { args: rest.slice(1), command: rest[0] }
+
+ if (Object.keys(env).length > 0) {
+ // Placeholder values (YOUR_KEY, xxx, TOKEN_HERE) are kept verbatim — the
+ // user replaces them in the JSON editor.
+ config.env = env
+ }
+
+ return { config, name }
+}
+
+// cursor://anysphere.cursor-deeplink/mcp/install?name=X&config=<base64 JSON>
+function fromCursorDeeplink(text: string): McpImportEntry[] | null {
+ const match = /^cursor:\/\/anysphere\.cursor-deeplink\/mcp\/install\?(.+)$/i.exec(text)
+
+ if (!match) {
+ return null
+ }
+
+ const params = new URLSearchParams(match[1])
+ const name = params.get('name')
+ const encoded = params.get('config')
+
+ if (!name || !encoded) {
+ return null
+ }
+
+ try {
+ const config = JSON.parse(atob(encoded)) as unknown
+
+ if (!isRecord(config) || !isServerShape(config)) {
+ return null
+ }
+
+ return [{ config: normalizeEntry(config), name }]
+ } catch {
+ return null
+ }
+}
+
+function inferNameFromConfig(config: Record<string, unknown>): string {
+ if (typeof config.url === 'string') {
+ return nameFromUrl(config.url)
+ }
+
+ if (typeof config.command === 'string') {
+ const args = Array.isArray(config.args) ? config.args.filter((a): a is string => typeof a === 'string') : []
+
+ return inferCommandName(config.command, args)
+ }
+
+ return 'server'
+}
+
+// mcp.json snippets: `{"mcpServers": {...}}`, a bare name→config map, or a
+// single unnamed server object (name inferred from its command/url).
+function fromJson(text: string): McpImportEntry[] | null {
+ let parsed: unknown
+
+ try {
+ parsed = JSON.parse(text)
+ } catch {
+ return null
+ }
+
+ if (!isRecord(parsed)) {
+ return null
+ }
+
+ if (isServerShape(parsed)) {
+ const config = normalizeEntry(parsed)
+
+ return [{ config, name: inferNameFromConfig(config) }]
+ }
+
+ const wrapper = parsed.mcpServers ?? parsed.mcp_servers
+ const map = isRecord(wrapper) ? wrapper : parsed
+ const entries = Object.entries(map)
+
+ if (entries.length === 0) {
+ return null
+ }
+
+ const out: McpImportEntry[] = []
+
+ for (const [name, entry] of entries) {
+ if (!isRecord(entry) || !isServerShape(entry)) {
+ return null
+ }
+
+ out.push({ config: normalizeEntry(entry), name })
+ }
+
+ return out
+}
+
+function parseLine(line: string): McpImportEntry[] | null {
+ if (URL_RE.test(line)) {
+ return [{ config: { url: line }, name: nameFromUrl(line) }]
+ }
+
+ const tokens = tokenize(line)
+
+ if (!tokens || tokens.length === 0) {
+ return null
+ }
+
+ if (tokens[0] === 'claude' && tokens[1] === 'mcp' && tokens[2] === 'add') {
+ const entry = fromClaudeAdd(tokens)
+
+ return entry ? [entry] : null
+ }
+
+ const entry = fromCommandLine(tokens)
+
+ return entry ? [entry] : null
+}
+
+/**
+ * Parse any pasted MCP server description into named mcp.json entries.
+ * Returns null when the text doesn't contain a recognizable server config.
+ */
+export function parseMcpImport(text: string): McpImportEntry[] | null {
+ const trimmed = text.trim()
+
+ if (!trimmed) {
+ return null
+ }
+
+ const deeplink = fromCursorDeeplink(trimmed)
+
+ if (deeplink) {
+ return deeplink
+ }
+
+ const json = fromJson(trimmed)
+
+ if (json) {
+ return json
+ }
+
+ // Command / URL territory: fold shell line continuations, then parse each
+ // remaining line independently (a README block can list several commands).
+ const folded = trimmed.replace(/\\\r?\n/g, ' ')
+ const results: McpImportEntry[] = []
+
+ for (const line of folded.split('\n')) {
+ const clean = line.trim()
+
+ if (!clean) {
+ continue
+ }
+
+ const entries = parseLine(clean)
+
+ if (entries) {
+ results.push(...entries)
+ }
+ }
+
+ return results.length > 0 ? results : null
+}