diff --git a/.changeset/mcp-install-name.md b/.changeset/mcp-install-name.md new file mode 100644 index 0000000000..97c11c4bee --- /dev/null +++ b/.changeset/mcp-install-name.md @@ -0,0 +1,10 @@ +--- +'@hyperdx/cli': patch +--- + +feat(cli): `hdx mcp install` can keep several ClickStack servers side by side + +`--name ` adds the MCP server under a name you choose, so a second +ClickStack instance no longer overwrites the first. When the key belongs to more +than one team, the installer asks which teams to add a server for and adds one +entry per team. When it finds more than one agent it asks which to set up. diff --git a/MCP.md b/MCP.md index 8f88349434..b5b070344d 100644 --- a/MCP.md +++ b/MCP.md @@ -48,6 +48,9 @@ The key stays out of your shell history and agent chats. npx @hyperdx/cli mcp install --app-url ``` +The entry is named `clickstack`, and running the command again replaces it. Pass +`--name ` to add a second instance under its own name instead. + ### Claude Code `read -rs` waits for you to paste the key and press Enter, without echoing it, diff --git a/packages/cli/README.md b/packages/cli/README.md index 7d3f6da7a7..21c975c739 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -222,6 +222,11 @@ Codex, Cursor, and VS Code. It asks for a personal access key or an organization API key with hidden input and checks it before changing any config, so the key stays out of shell history and agent chats. +If the key belongs to more than one team, it asks which teams to add a server +for (Enter keeps the default team). Picking several adds one entry per team, +named `-`. If it finds more than one agent, it asks which +to set up (Enter keeps all of them). + ```bash npx @hyperdx/cli mcp install -a https://your-hyperdx.example ``` @@ -229,6 +234,13 @@ npx @hyperdx/cli mcp install -a https://your-hyperdx.example The key is stored in plain text in each agent's user config, which the command lists when it finishes. Running it again replaces the existing entry. +The entry is named `clickstack`. To keep more than one ClickStack instance side +by side, give each its own name: + +```bash +npx @hyperdx/cli mcp install -a https://staging.example --name clickstack-staging +``` + ### `hdx upload-sourcemaps` — Source maps Upload JavaScript source maps to HyperDX for stack trace de-obfuscation. Run it diff --git a/packages/cli/src/__tests__/mcpInstall.test.ts b/packages/cli/src/__tests__/mcpInstall.test.ts index f86f227b98..abf6482554 100644 --- a/packages/cli/src/__tests__/mcpInstall.test.ts +++ b/packages/cli/src/__tests__/mcpInstall.test.ts @@ -11,13 +11,21 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { + isValidServerName, + listTeams, + mcpClients, mcpUrl, + teamServers, upsertCodexServer, upsertJsonServer, verifyKey, } from '@/mcp/install'; -const server = { url: 'https://example.com/api/mcp', key: 'hdx_org_abc' }; +const server = { + name: 'clickstack', + url: 'https://example.com/api/mcp', + key: 'hdx_org_abc', +}; let dir: string; beforeEach(() => { @@ -40,30 +48,40 @@ describe('upsertJsonServer', () => { file, JSON.stringify({ theme: 'dark', mcpServers: { other: { url: 'x' } } }), ); - upsertJsonServer(file, 'mcpServers', { url: server.url }); + upsertJsonServer(file, 'mcpServers', 'clickstack', { url: server.url }); expect(JSON.parse(fs.readFileSync(file, 'utf-8'))).toEqual({ theme: 'dark', mcpServers: { other: { url: 'x' }, clickstack: { url: server.url } }, }); }); + it('keeps an entry installed under another name', () => { + const file = path.join(dir, 'mcp.json'); + upsertJsonServer(file, 'mcpServers', 'clickstack', { url: 'a' }); + upsertJsonServer(file, 'mcpServers', 'clickstack-staging', { url: 'b' }); + expect(JSON.parse(fs.readFileSync(file, 'utf-8')).mcpServers).toEqual({ + clickstack: { url: 'a' }, + 'clickstack-staging': { url: 'b' }, + }); + }); + it('creates the file and its directory with owner-only permissions', () => { const file = path.join(dir, 'nested', 'mcp.json'); - upsertJsonServer(file, 'servers', { url: server.url }); + upsertJsonServer(file, 'servers', 'clickstack', { url: server.url }); expect(fs.statSync(file).mode & 0o777).toBe(0o600); }); it('tightens an existing config to owner-only before writing the key', () => { const file = path.join(dir, 'mcp.json'); fs.writeFileSync(file, '{}', { mode: 0o644 }); - upsertJsonServer(file, 'servers', { url: server.url }); + upsertJsonServer(file, 'servers', 'clickstack', { url: server.url }); expect(fs.statSync(file).mode & 0o777).toBe(0o600); }); it('refuses JSON that is not an object', () => { const file = path.join(dir, 'mcp.json'); fs.writeFileSync(file, 'null'); - expect(() => upsertJsonServer(file, 'servers', {})).toThrow( + expect(() => upsertJsonServer(file, 'servers', 'clickstack', {})).toThrow( /Could not parse/, ); }); @@ -71,7 +89,7 @@ describe('upsertJsonServer', () => { it('refuses to rewrite a file it cannot parse', () => { const file = path.join(dir, 'mcp.json'); fs.writeFileSync(file, '{ // comment\n "servers": {} }'); - expect(() => upsertJsonServer(file, 'servers', {})).toThrow( + expect(() => upsertJsonServer(file, 'servers', 'clickstack', {})).toThrow( /Could not parse/, ); expect(fs.readFileSync(file, 'utf-8')).toContain('// comment'); @@ -116,6 +134,29 @@ describe('upsertCodexServer', () => { ).toBe(true); }); + it('keeps a table installed under a name that shares a prefix', () => { + const file = path.join(dir, 'config.toml'); + upsertCodexServer(file, { ...server, name: 'clickstack-staging' }); + upsertCodexServer(file, { ...server, url: 'https://prd/api/mcp' }); + upsertCodexServer(file, { ...server, url: 'https://prd2/api/mcp' }); + const out = fs.readFileSync(file, 'utf-8'); + expect(out).toContain( + '[mcp_servers.clickstack-staging]\nurl = "https://example.com/api/mcp"', + ); + expect(out).toContain( + '[mcp_servers.clickstack]\nurl = "https://prd2/api/mcp"', + ); + expect(out).not.toContain('https://prd/'); + }); + + it('writes the team header when a team was chosen', () => { + const file = path.join(dir, 'config.toml'); + upsertCodexServer(file, { ...server, teamId: 't1' }); + expect(fs.readFileSync(file, 'utf-8')).toContain( + 'http_headers = { Authorization = "Bearer hdx_org_abc", x-hdx-team = "t1" }', + ); + }); + it('creates the config when Codex has none yet', () => { const file = path.join(dir, '.codex', 'config.toml'); upsertCodexServer(file, server); @@ -125,6 +166,146 @@ describe('upsertCodexServer', () => { }); }); +describe('mcpClients', () => { + const readJson = (file: string) => JSON.parse(fs.readFileSync(file, 'utf-8')); + const install = (id: string, teamId?: string) => + mcpClients(dir, 'linux') + .find(c => c.id === id)! + .install({ ...server, name: 'clickstack-prd', teamId }); + + it('writes the team header for Cursor and VS Code', () => { + install('cursor', 't1'); + install('vscode', 't1'); + const headers = { Authorization: 'Bearer hdx_org_abc', 'x-hdx-team': 't1' }; + expect( + readJson(path.join(dir, '.cursor', 'mcp.json')).mcpServers[ + 'clickstack-prd' + ].headers, + ).toEqual(headers); + expect( + readJson(path.join(dir, '.config', 'Code', 'User', 'mcp.json')).servers[ + 'clickstack-prd' + ].headers, + ).toEqual(headers); + }); + + it('reports an entry as present only once it is installed', () => { + const has = (id: string, name: string) => + mcpClients(dir, 'linux') + .find(c => c.id === id)! + .has(name); + for (const id of ['cursor', 'vscode', 'codex']) { + expect(has(id, 'clickstack-prd')).toBe(false); + install(id); + expect(has(id, 'clickstack-prd')).toBe(true); + expect(has(id, 'clickstack')).toBe(false); + } + }); + + it('writes no team header when no team was chosen', () => { + install('cursor'); + expect( + readJson(path.join(dir, '.cursor', 'mcp.json')).mcpServers[ + 'clickstack-prd' + ].headers, + ).toEqual({ Authorization: 'Bearer hdx_org_abc' }); + }); +}); + +describe('teamServers', () => { + const team = (id: string, name: string) => ({ id, name, isCurrent: false }); + + it('keeps the name for one team and for no team', () => { + expect(teamServers(server, [])).toEqual([{ ...server, teamId: undefined }]); + expect(teamServers(server, [team('a', 'Demo')])).toEqual([ + { ...server, teamId: 'a' }, + ]); + }); + + it('names one entry per team, falling back to the id on a clash', () => { + expect( + teamServers(server, [ + team('a', 'Prod EU'), + team('b', 'Demo!'), + team('c', 'demo'), + team('d', '***'), + ]).map(s => [s.name, s.teamId]), + ).toEqual([ + ['clickstack-prod-eu', 'a'], + ['clickstack-b', 'b'], + ['clickstack-c', 'c'], + ['clickstack-d', 'd'], + ]); + }); +}); + +describe('isValidServerName', () => { + it('rejects names that would break a TOML table header', () => { + expect(isValidServerName('clickstack-prd_2')).toBe(true); + expect(isValidServerName('a.b')).toBe(false); + expect(isValidServerName('a]')).toBe(false); + expect(isValidServerName('-h')).toBe(false); + expect(isValidServerName('')).toBe(false); + }); +}); + +describe('listTeams', () => { + const realFetch = globalThis.fetch; + afterEach(() => { + globalThis.fetch = realFetch; + }); + const respondText = (text: string, status = 200) => { + const fetchMock = jest.fn(async (_url: string, _init?: RequestInit) => { + return new Response(text, { status }); + }); + globalThis.fetch = fetchMock as unknown as typeof fetch; + return fetchMock; + }; + const sse = (toolText: string) => + `event: message\ndata: ${JSON.stringify({ + jsonrpc: '2.0', + id: 1, + result: { content: [{ type: 'text', text: toolText }] }, + })}\n\n`; + const toolError = `event: message\ndata: ${JSON.stringify({ + jsonrpc: '2.0', + id: 1, + result: { + isError: true, + content: [{ type: 'text', text: 'MCP error -32602: Tool not found' }], + }, + })}\n\n`; + + it('reads teams from the MCP endpoint', async () => { + const teams = [ + { id: 'a', name: 'Demo', isCurrent: true }, + { id: 'b', name: 'Prod', isCurrent: false }, + ]; + const fetchMock = respondText(sse(JSON.stringify({ teams }))); + await expect(listTeams('https://example.com/', 'k')).resolves.toEqual( + teams, + ); + expect(fetchMock.mock.calls[0][0]).toBe('https://example.com/api/mcp'); + }); + + it('returns no teams when the server has no team listing', async () => { + respondText(toolError); + await expect(listTeams('https://example.com', 'k')).resolves.toEqual([]); + }); + + it('throws when the tool exists but fails', async () => { + respondText(toolError.replace('Tool not found', 'database timeout')); + await expect(listTeams('https://example.com', 'k')).rejects.toThrow( + /database timeout/, + ); + }); + + it('throws when the listing failed, so it is not read as one team', async () => { + respondText('Too many requests', 429); + await expect(listTeams('https://example.com', 'k')).rejects.toThrow(/429/); + }); +}); + describe('verifyKey', () => { const realFetch = globalThis.fetch; afterEach(() => { diff --git a/packages/cli/src/cli.tsx b/packages/cli/src/cli.tsx index 8061522254..8b03de624d 100644 --- a/packages/cli/src/cli.tsx +++ b/packages/cli/src/cli.tsx @@ -32,7 +32,11 @@ import { clearSession, loadSession, setActiveTeam } from '@/utils/config'; import { parseTimeValue } from '@/utils/editor'; import { isValidUrl } from '@/utils/url'; import { uploadSourcemaps } from '@/sourcemaps'; -import { mcpClients } from '@/mcp/install'; +import { + DEFAULT_MCP_SERVER_NAME, + isValidServerName, + mcpClients, +} from '@/mcp/install'; import McpInstallPrompt, { type InstallResult } from '@/mcp/McpInstallPrompt'; // ---- Standalone interactive login for `hdx auth login` ------------- @@ -554,7 +558,20 @@ mcp 'Add the ClickStack MCP server to Claude Code, Codex, Cursor, and VS Code', ) .option('-a, --app-url ', 'ClickStack app URL') + .option( + '-n, --name ', + 'Server name in the agent configs. Use a different name per ClickStack instance to keep several side by side', + DEFAULT_MCP_SERVER_NAME, + ) .action(async opts => { + if (!isValidServerName(opts.name)) { + _origError( + chalk.red( + '--name can only contain letters, numbers, hyphens, and underscores.\n', + ), + ); + process.exit(1); + } if (!process.stdin.isTTY) { _origError( chalk.red( @@ -577,6 +594,7 @@ mcp const { waitUntilExit } = render( { results = r; @@ -590,11 +608,11 @@ mcp process.stdout.write('Cancelled. No configs were changed.\n'); return; } - for (const { client, error } of done) { + for (const { client, name, error } of done) { process.stdout.write( error - ? chalk.red(`✗ ${client.label}: ${error}\n`) - : chalk.green(`✓ ${client.label}`) + + ? chalk.red(`✗ ${client.label}: ${name}: ${error}\n`) + : chalk.green(`✓ ${client.label}: ${name}`) + chalk.dim(` (key stored in ${client.location})\n`), ); } diff --git a/packages/cli/src/mcp/Choice.tsx b/packages/cli/src/mcp/Choice.tsx new file mode 100644 index 0000000000..0012af7675 --- /dev/null +++ b/packages/cli/src/mcp/Choice.tsx @@ -0,0 +1,59 @@ +import React, { useState } from 'react'; +import { Box, Text, useInput } from 'ink'; + +/** Arrow-key checklist. Space toggles items and Enter submits the ticked ones. */ +export default function Choice({ + title, + items, + label, + initial = 0, + isChecked = () => true, + onSubmit, + onCancel, +}: { + title: string; + items: T[]; + label: (item: T) => string; + initial?: number; + /** Which items start ticked. Defaults to all. */ + isChecked?: (item: T) => boolean; + onSubmit: (chosen: T[]) => void; + onCancel: () => void; +}) { + const [cursor, setCursor] = useState(initial); + const [checked, setChecked] = useState(() => items.map(isChecked)); + const [noneTicked, setNoneTicked] = useState(false); + + useInput((input, key) => { + if (key.upArrow || input === 'k') setCursor(c => Math.max(0, c - 1)); + if (key.downArrow || input === 'j') { + setCursor(c => Math.min(items.length - 1, c + 1)); + } + if (input === ' ') { + setNoneTicked(false); + setChecked(c => c.map((on, i) => (i === cursor ? !on : on))); + } + if (key.return) { + const chosen = items.filter((_, i) => checked[i]); + if (chosen.length > 0) onSubmit(chosen); + else setNoneTicked(true); + } + if (key.escape) onCancel(); + }); + + return ( + + {title} + {items.map((item, i) => ( + + {i === cursor ? '▸ ' : ' '} + {checked[i] ? '[x] ' : '[ ] '} + {label(item)} + + ))} + + {noneTicked && Select at least one.} + Space to toggle, Enter to continue, Esc to cancel + + ); +} diff --git a/packages/cli/src/mcp/McpInstallPrompt.tsx b/packages/cli/src/mcp/McpInstallPrompt.tsx index a368355613..eb798fa250 100644 --- a/packages/cli/src/mcp/McpInstallPrompt.tsx +++ b/packages/cli/src/mcp/McpInstallPrompt.tsx @@ -3,32 +3,40 @@ import { Box, Text, useApp, useInput } from 'ink'; import TextInput from 'ink-text-input'; import Spinner from 'ink-spinner'; +import Choice from '@/mcp/Choice'; import { type KeyIdentity, + listTeams, type McpClient, + type McpTeam, mcpUrl, + teamServers, verifyKey, } from '@/mcp/install'; import { isValidUrl } from '@/utils/url'; export interface InstallResult { client: McpClient; + /** Server entry name this result is for. */ + name: string; error?: string; } -type Step = 'appUrl' | 'key' | 'checking' | 'confirm'; +type Step = 'appUrl' | 'key' | 'checking' | 'team' | 'agents' | 'confirm'; /** - * Collects the app URL and API key, checks the key, then asks before writing - * any client config. Calls `onDone` with the results, or with null if the - * user cancels. + * Collects the app URL and API key, checks the key, offers a team and agent + * choice when there is more than one, then asks before writing any config. + * Calls `onDone` with the results, or with null if the user cancels. */ export default function McpInstallPrompt({ initialAppUrl, + name, clients, onDone, }: { initialAppUrl?: string; + name: string; clients: McpClient[]; onDone: (results: InstallResult[] | null) => void; }) { @@ -37,6 +45,10 @@ export default function McpInstallPrompt({ const [appUrl, setAppUrl] = useState(initialAppUrl ?? ''); const [key, setKey] = useState(''); const [identity, setIdentity] = useState(null); + const [teams, setTeams] = useState([]); + const [picked, setPicked] = useState([]); + const [teamsFailed, setTeamsFailed] = useState(false); + const [chosen, setChosen] = useState(clients); const [error, setError] = useState(null); const finish = (results: InstallResult[] | null) => { @@ -47,19 +59,21 @@ export default function McpInstallPrompt({ useInput( (input, inkKey) => { if (inkKey.return || input.toLowerCase() === 'y') { - const server = { url: mcpUrl(appUrl), key }; finish( - clients.map(client => { - try { - client.install(server); - return { client }; - } catch (e) { - return { - client, - error: e instanceof Error ? e.message : String(e), - }; - } - }), + chosen.flatMap(client => + servers.map(server => { + try { + client.install(server); + return { client, name: server.name }; + } catch (e) { + return { + client, + name: server.name, + error: e instanceof Error ? e.message : String(e), + }; + } + }), + ), ); } else if (inkKey.escape || input.toLowerCase() === 'n') { finish(null); @@ -68,6 +82,11 @@ export default function McpInstallPrompt({ { isActive: step === 'confirm' }, ); + const servers = teamServers({ name, url: mcpUrl(appUrl), key }, picked); + // Enter must always keep one team, even if the server marks none as current. + const defaultTeam = teams.find(t => t.isCurrent) ?? teams[0]; + const afterTeam: Step = clients.length > 1 ? 'agents' : 'confirm'; + const submitAppUrl = () => { const trimmed = appUrl.trim().replace(/\/+$/, ''); if (!isValidUrl(trimmed)) { @@ -88,7 +107,11 @@ export default function McpInstallPrompt({ setStep('checking'); try { setIdentity(await verifyKey(appUrl, cleaned)); - setStep('confirm'); + // A failed listing must not block the install or look like one team. + const found = await listTeams(appUrl, cleaned).catch(() => null); + setTeamsFailed(found == null); + setTeams(found ?? []); + setStep(found && found.length > 1 ? 'team' : afterTeam); } catch (e) { setError(e instanceof Error ? e.message : String(e)); setKey(''); @@ -141,6 +164,40 @@ export default function McpInstallPrompt({ )} + {teamsFailed && step !== 'key' && ( + + Could not list teams. The server will use the key's default team. + + )} + + {step === 'team' && ( + (t.isCurrent ? `${t.name} (default)` : t.name)} + initial={teams.indexOf(defaultTeam)} + isChecked={t => t === defaultTeam} + onSubmit={chosenTeams => { + setPicked(chosenTeams); + setStep(afterTeam); + }} + onCancel={() => finish(null)} + /> + )} + + {step === 'agents' && ( + c.label} + onSubmit={picked => { + setChosen(picked); + setStep('confirm'); + }} + onCancel={() => finish(null)} + /> + )} + {step === 'confirm' && identity && ( @@ -151,8 +208,26 @@ export default function McpInstallPrompt({ . - Add the ClickStack MCP server to: - {clients.map(c => ( + Add the ClickStack MCP server as: + {servers.map((s, i) => { + const replaced = chosen.filter(c => c.has(s.name)); + return ( + + {' '} + - {s.name} + {picked[i] && ` (team ${picked[i].name})`} + {replaced.length > 0 && ( + + {' '} + replaces the existing entry in{' '} + {replaced.map(c => c.label).join(', ')} + + )} + + ); + })} + to: + {chosen.map(c => ( - {c.label} ))} diff --git a/packages/cli/src/mcp/install.ts b/packages/cli/src/mcp/install.ts index c2db869ace..c3ba6538f9 100644 --- a/packages/cli/src/mcp/install.ts +++ b/packages/cli/src/mcp/install.ts @@ -5,11 +5,26 @@ import * as path from 'node:path'; // Same server name the Team Settings snippets use, so a reinstall replaces // an entry added by hand instead of adding a second one. -const MCP_SERVER_NAME = 'clickstack'; +export const DEFAULT_MCP_SERVER_NAME = 'clickstack'; + +// The name is a TOML bare key in Codex's config and a `claude mcp add` +// argument, where a leading hyphen would read as a flag. +export function isValidServerName(name: string): boolean { + return /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(name); +} export interface McpServer { + name: string; url: string; key: string; + /** Sent as `x-hdx-team`. Unset means the key's default team. */ + teamId?: string; +} + +export interface McpTeam { + id: string; + name: string; + isCurrent: boolean; } export interface McpClient { @@ -18,6 +33,8 @@ export interface McpClient { /** Where the key ends up, shown to the user after install. */ location: string; detect: () => boolean; + /** Whether an entry with this name is already configured. */ + has: (name: string) => boolean; install: (server: McpServer) => void; } @@ -66,18 +83,105 @@ export async function verifyKey( }; } +/** + * Teams the key can act on, read from the MCP server's own + * `clickstack_list_teams` tool. Empty when the server has no such tool + * (single-team deployments), so the caller skips the team choice. Throws when + * the listing itself failed, so that is not mistaken for a single team. + */ +export async function listTeams( + appUrl: string, + key: string, +): Promise { + const res = await fetch(mcpUrl(appUrl), { + method: 'POST', + headers: { + Authorization: `Bearer ${key}`, + 'Content-Type': 'application/json', + Accept: 'application/json, text/event-stream', + }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { name: 'clickstack_list_teams', arguments: {} }, + }), + signal: AbortSignal.timeout(15_000), + }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + const text = await res.text(); + // The endpoint answers with a one-message SSE stream. + const message = + text + .split('\n') + .find(line => line.startsWith('data:')) + ?.slice(5) ?? text; + const { result, error } = JSON.parse(message); + // Only an unknown tool means "no team listing". The SDK reports it as an + // error result (or a -32601/-32602 error); any other error is a failure. + const failure: string | undefined = result?.isError + ? String(result.content?.[0]?.text ?? 'tool error') + : error + ? String(error.message ?? 'error') + : undefined; + if (failure != null) { + const unknownTool = + /tool .*not found/i.test(failure) || + error?.code === -32601 || + error?.code === -32602; + if (unknownTool) return []; + throw new Error(failure); + } + const { teams } = JSON.parse(result.content[0].text); + // The id ends up in a header value and, with several teams, a server name. + return (teams as McpTeam[]).filter( + t => + typeof t.id === 'string' && + isValidServerName(t.id) && + typeof t.name === 'string', + ); +} + +/** + * One server per chosen team. A single team (or none) keeps the server's + * name; several teams get `-` each. + */ +export function teamServers(server: McpServer, teams: McpTeam[]): McpServer[] { + if (teams.length <= 1) return [{ ...server, teamId: teams[0]?.id }]; + const slugs = teams.map(t => + t.name + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''), + ); + return teams.map((t, i) => { + const slug = slugs[i]; + // Use the id when the name has no usable characters or two teams share it. + const unique = slug && slugs.indexOf(slug) === slugs.lastIndexOf(slug); + return { + ...server, + name: `${server.name}-${unique ? slug : t.id}`, + teamId: t.id, + }; + }); +} + function onPath(command: string): boolean { return !spawnSync(command, ['--version'], { stdio: 'ignore' }).error; } -function authHeaders(key: string) { - return { Authorization: `Bearer ${key}` }; +function serverHeaders({ key, teamId }: McpServer): Record { + return { + Authorization: `Bearer ${key}`, + ...(teamId ? { 'x-hdx-team': teamId } : {}), + }; } -/** Sets `.` in a JSON config, keeping everything else. */ +/** Sets `.` in a JSON config, keeping everything else. */ export function upsertJsonServer( file: string, topKey: string, + name: string, entry: Record, ): void { let config: Record = {}; @@ -94,7 +198,7 @@ export function upsertJsonServer( config = parsed as Record; } const servers = (config[topKey] ?? {}) as Record; - config[topKey] = { ...servers, [MCP_SERVER_NAME]: entry }; + config[topKey] = { ...servers, [name]: entry }; writePrivate(file, `${JSON.stringify(config, null, 2)}\n`); } @@ -109,10 +213,10 @@ function tomlString(value: string): string { return JSON.stringify(value); } -/** Replaces the `[mcp_servers.clickstack]` table (and its subtables) in Codex's config.toml. */ +/** Replaces the `[mcp_servers.]` table (and its subtables) in Codex's config.toml. */ export function upsertCodexServer(file: string, server: McpServer): void { const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf-8') : ''; - const header = new RegExp(`^\\[mcp_servers\\.${MCP_SERVER_NAME}(\\.|\\])`); + const header = codexTableHeader(server.name); const kept: string[] = []; let skipping = false; // shortcut: line-based table removal, no TOML parser. Fine for tables we @@ -125,9 +229,11 @@ export function upsertCodexServer(file: string, server: McpServer): void { } const body = kept.join('\n').trimEnd(); const table = [ - `[mcp_servers.${MCP_SERVER_NAME}]`, + `[mcp_servers.${server.name}]`, `url = ${tomlString(server.url)}`, - `http_headers = { Authorization = ${tomlString(`Bearer ${server.key}`)} }`, + `http_headers = { ${Object.entries(serverHeaders(server)) + .map(([k, v]) => `${k} = ${tomlString(v)}`) + .join(', ')} }`, ].join('\n'); writePrivate(file, `${body ? `${body}\n\n` : ''}${table}\n`); } @@ -146,6 +252,22 @@ function vscodeUserDir(home: string, platform: NodeJS.Platform): string { return path.join(home, '.config', 'Code', 'User'); } +function readJsonObject(file: string): Record { + try { + return JSON.parse(fs.readFileSync(file, 'utf-8')) ?? {}; + } catch { + return {}; + } +} + +function hasKey(servers: unknown, name: string): boolean { + return servers != null && Object.hasOwn(servers, name); +} + +function codexTableHeader(name: string): RegExp { + return new RegExp(`^\\[mcp_servers\\.${name}(\\.|\\])`); +} + function runClaude(args: string[]): void { const res = spawnSync('claude', args, { encoding: 'utf-8' }); if (res.error || res.status !== 0) { @@ -170,17 +292,21 @@ export function mcpClients( label: 'Claude Code', location: 'Claude Code user config (~/.claude.json)', detect: () => onPath('claude'), - install: ({ url, key }) => { + has: name => { + const config = readJsonObject(path.join(home, '.claude.json')); + return ( + hasKey(config.mcpServers, name) || + hasKey(config.projects?.[process.cwd()]?.mcpServers, name) + ); + }, + install: server => { + const { name, url } = server; // `mcp add` refuses to overwrite, so drop any earlier entry first. A // local-scope entry for this directory would also shadow the new one. for (const scope of ['local', 'user']) { - spawnSync( - 'claude', - ['mcp', 'remove', '--scope', scope, MCP_SERVER_NAME], - { - stdio: 'ignore', - }, - ); + spawnSync('claude', ['mcp', 'remove', '--scope', scope, name], { + stdio: 'ignore', + }); } runClaude([ 'mcp', @@ -189,10 +315,12 @@ export function mcpClients( 'user', '--transport', 'http', - MCP_SERVER_NAME, + name, url, - '--header', - `Authorization: Bearer ${key}`, + ...Object.entries(serverHeaders(server)).flatMap(([k, v]) => [ + '--header', + `${k}: ${v}`, + ]), ]); }, }, @@ -201,6 +329,12 @@ export function mcpClients( label: 'Codex', location: codexConfig, detect: () => fs.existsSync(path.dirname(codexConfig)) || onPath('codex'), + has: name => + fs.existsSync(codexConfig) && + fs + .readFileSync(codexConfig, 'utf-8') + .split('\n') + .some(line => codexTableHeader(name).test(line.trim())), install: server => upsertCodexServer(codexConfig, server), }, { @@ -208,10 +342,11 @@ export function mcpClients( label: 'Cursor', location: cursorConfig, detect: () => fs.existsSync(path.dirname(cursorConfig)), - install: ({ url, key }) => - upsertJsonServer(cursorConfig, 'mcpServers', { - url, - headers: authHeaders(key), + has: name => hasKey(readJsonObject(cursorConfig).mcpServers, name), + install: server => + upsertJsonServer(cursorConfig, 'mcpServers', server.name, { + url: server.url, + headers: serverHeaders(server), }), }, { @@ -219,11 +354,12 @@ export function mcpClients( label: 'VS Code', location: vscodeConfig, detect: () => fs.existsSync(vscodeDir), - install: ({ url, key }) => - upsertJsonServer(vscodeConfig, 'servers', { + has: name => hasKey(readJsonObject(vscodeConfig).servers, name), + install: server => + upsertJsonServer(vscodeConfig, 'servers', server.name, { type: 'http', - url, - headers: authHeaders(key), + url: server.url, + headers: serverHeaders(server), }), }, ];