From 41ab8037064188352c2f6c41bcaec74a393c1d3f Mon Sep 17 00:00:00 2001 From: Jordan Simonovski Date: Mon, 16 Nov 2026 17:03:56 +1100 Subject: [PATCH 1/3] feat(cli): name, team and agent choices for hdx mcp install hdx mcp install --name adds the MCP server under a chosen name, so a second ClickStack instance no longer overwrites the first. When the key belongs to more than one team the installer asks which team the server should query and pins it with x-hdx-team. When more than one agent is detected it asks which to set up. HDX-6024 --- .changeset/mcp-install-name.md | 10 ++ MCP.md | 3 + packages/cli/README.md | 11 ++ packages/cli/src/__tests__/mcpInstall.test.ts | 145 +++++++++++++++++- packages/cli/src/cli.tsx | 20 ++- packages/cli/src/mcp/Choice.tsx | 62 ++++++++ packages/cli/src/mcp/McpInstallPrompt.tsx | 73 +++++++-- packages/cli/src/mcp/install.ts | 118 ++++++++++---- 8 files changed, 398 insertions(+), 44 deletions(-) create mode 100644 .changeset/mcp-install-name.md create mode 100644 packages/cli/src/mcp/Choice.tsx diff --git a/.changeset/mcp-install-name.md b/.changeset/mcp-install-name.md new file mode 100644 index 0000000000..5c6c756e86 --- /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 team the server should query, and +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..57e4cdec36 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -222,6 +222,10 @@ 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 team the server should +query (Enter keeps the default). 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 +233,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..42be18d6a2 100644 --- a/packages/cli/src/__tests__/mcpInstall.test.ts +++ b/packages/cli/src/__tests__/mcpInstall.test.ts @@ -11,13 +11,20 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { + isValidServerName, + listTeams, + mcpClients, mcpUrl, 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 +47,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 +88,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 +133,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 +165,99 @@ 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('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('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 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..9827a15108 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; diff --git a/packages/cli/src/mcp/Choice.tsx b/packages/cli/src/mcp/Choice.tsx new file mode 100644 index 0000000000..246ce1985a --- /dev/null +++ b/packages/cli/src/mcp/Choice.tsx @@ -0,0 +1,62 @@ +import React, { useState } from 'react'; +import { Box, Text, useInput } from 'ink'; + +/** + * Arrow-key list. Single choice submits the highlighted item on Enter; with + * `multi`, Space toggles items and Enter submits the checked ones. + */ +export default function Choice({ + title, + items, + label, + initial = 0, + multi = false, + onSubmit, + onCancel, +}: { + title: string; + items: T[]; + label: (item: T) => string; + initial?: number; + multi?: boolean; + onSubmit: (chosen: T[]) => void; + onCancel: () => void; +}) { + const [cursor, setCursor] = useState(initial); + const [checked, setChecked] = useState(() => items.map(() => true)); + + 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 (multi && input === ' ') { + setChecked(c => c.map((on, i) => (i === cursor ? !on : on))); + } + if (key.return) { + const chosen = multi + ? items.filter((_, i) => checked[i]) + : [items[cursor]]; + if (chosen.length > 0) onSubmit(chosen); + } + if (key.escape) onCancel(); + }); + + return ( + + {title} + {items.map((item, i) => ( + + {i === cursor ? '▸ ' : ' '} + {multi && (checked[i] ? '[x] ' : '[ ] ')} + {label(item)} + + ))} + + + {multi ? 'Space to toggle, Enter to continue' : 'Enter to select'}, Esc + to cancel + + + ); +} diff --git a/packages/cli/src/mcp/McpInstallPrompt.tsx b/packages/cli/src/mcp/McpInstallPrompt.tsx index a368355613..53cd23a0eb 100644 --- a/packages/cli/src/mcp/McpInstallPrompt.tsx +++ b/packages/cli/src/mcp/McpInstallPrompt.tsx @@ -3,9 +3,12 @@ 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, verifyKey, } from '@/mcp/install'; @@ -16,19 +19,21 @@ export interface InstallResult { 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 +42,10 @@ export default function McpInstallPrompt({ const [appUrl, setAppUrl] = useState(initialAppUrl ?? ''); const [key, setKey] = useState(''); const [identity, setIdentity] = useState(null); + const [teams, setTeams] = useState([]); + const [team, setTeam] = useState(null); + const [teamsFailed, setTeamsFailed] = useState(false); + const [chosen, setChosen] = useState(clients); const [error, setError] = useState(null); const finish = (results: InstallResult[] | null) => { @@ -47,9 +56,9 @@ export default function McpInstallPrompt({ useInput( (input, inkKey) => { if (inkKey.return || input.toLowerCase() === 'y') { - const server = { url: mcpUrl(appUrl), key }; + const server = { name, url: mcpUrl(appUrl), key, teamId: team?.id }; finish( - clients.map(client => { + chosen.map(client => { try { client.install(server); return { client }; @@ -68,6 +77,8 @@ export default function McpInstallPrompt({ { isActive: step === 'confirm' }, ); + const afterTeam: Step = clients.length > 1 ? 'agents' : 'confirm'; + const submitAppUrl = () => { const trimmed = appUrl.trim().replace(/\/+$/, ''); if (!isValidUrl(trimmed)) { @@ -88,7 +99,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 +156,43 @@ 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={Math.max( + 0, + teams.findIndex(t => t.isCurrent), + )} + onSubmit={([picked]) => { + setTeam(picked); + setStep(afterTeam); + }} + onCancel={() => finish(null)} + /> + )} + + {step === 'agents' && ( + c.label} + onSubmit={picked => { + setChosen(picked); + setStep('confirm'); + }} + onCancel={() => finish(null)} + /> + )} + {step === 'confirm' && identity && ( @@ -151,8 +203,11 @@ export default function McpInstallPrompt({ . - Add the ClickStack MCP server to: - {clients.map(c => ( + + Add the ClickStack MCP server as "{name}" + {team && ` for team ${team.name}`} to: + + {chosen.map(c => ( - {c.label} ))} diff --git a/packages/cli/src/mcp/install.ts b/packages/cli/src/mcp/install.ts index c2db869ace..8f80db6a8a 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 { @@ -66,18 +81,64 @@ 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 } = JSON.parse(message); + // An unknown tool comes back as an error result, not an HTTP error. + if (!result || result.isError) return []; + const { teams } = JSON.parse(result.content[0].text); + return (teams as McpTeam[]).filter( + t => typeof t.id === 'string' && typeof t.name === 'string', + ); +} + 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 +155,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 +170,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 = new RegExp(`^\\[mcp_servers\\.${server.name}(\\.|\\])`); const kept: string[] = []; let skipping = false; // shortcut: line-based table removal, no TOML parser. Fine for tables we @@ -125,9 +186,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`); } @@ -170,17 +233,14 @@ export function mcpClients( label: 'Claude Code', location: 'Claude Code user config (~/.claude.json)', detect: () => onPath('claude'), - install: ({ url, key }) => { + 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 +249,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}`, + ]), ]); }, }, @@ -208,10 +270,10 @@ export function mcpClients( label: 'Cursor', location: cursorConfig, detect: () => fs.existsSync(path.dirname(cursorConfig)), - install: ({ url, key }) => - upsertJsonServer(cursorConfig, 'mcpServers', { - url, - headers: authHeaders(key), + install: server => + upsertJsonServer(cursorConfig, 'mcpServers', server.name, { + url: server.url, + headers: serverHeaders(server), }), }, { @@ -219,11 +281,11 @@ export function mcpClients( label: 'VS Code', location: vscodeConfig, detect: () => fs.existsSync(vscodeDir), - install: ({ url, key }) => - upsertJsonServer(vscodeConfig, 'servers', { + install: server => + upsertJsonServer(vscodeConfig, 'servers', server.name, { type: 'http', - url, - headers: authHeaders(key), + url: server.url, + headers: serverHeaders(server), }), }, ]; From da6ca9d3a555d922b149d16d57835130b666e4bc Mon Sep 17 00:00:00 2001 From: Jordan Simonovski Date: Mon, 16 Nov 2026 17:06:02 +1100 Subject: [PATCH 2/3] feat(cli): add an MCP server per team in hdx mcp install The team step is now multi-select. Enter keeps the default team under the given name; picking several teams adds one entry per team named -. HDX-6024 --- .changeset/mcp-install-name.md | 6 ++-- packages/cli/README.md | 5 +-- packages/cli/src/__tests__/mcpInstall.test.ts | 28 +++++++++++++++ packages/cli/src/mcp/Choice.tsx | 5 ++- packages/cli/src/mcp/McpInstallPrompt.tsx | 35 +++++++++++-------- packages/cli/src/mcp/install.ts | 30 +++++++++++++++- 6 files changed, 88 insertions(+), 21 deletions(-) diff --git a/.changeset/mcp-install-name.md b/.changeset/mcp-install-name.md index 5c6c756e86..97c11c4bee 100644 --- a/.changeset/mcp-install-name.md +++ b/.changeset/mcp-install-name.md @@ -5,6 +5,6 @@ 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 team the server should query, and -when it finds more than one agent it asks which to set up. +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/packages/cli/README.md b/packages/cli/README.md index 57e4cdec36..21c975c739 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -222,8 +222,9 @@ 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 team the server should -query (Enter keeps the default). If it finds more than one agent, it asks which +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 diff --git a/packages/cli/src/__tests__/mcpInstall.test.ts b/packages/cli/src/__tests__/mcpInstall.test.ts index 42be18d6a2..9b07d4639c 100644 --- a/packages/cli/src/__tests__/mcpInstall.test.ts +++ b/packages/cli/src/__tests__/mcpInstall.test.ts @@ -15,6 +15,7 @@ import { listTeams, mcpClients, mcpUrl, + teamServers, upsertCodexServer, upsertJsonServer, verifyKey, @@ -198,6 +199,33 @@ describe('mcpClients', () => { }); }); +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); diff --git a/packages/cli/src/mcp/Choice.tsx b/packages/cli/src/mcp/Choice.tsx index 246ce1985a..9932b5c400 100644 --- a/packages/cli/src/mcp/Choice.tsx +++ b/packages/cli/src/mcp/Choice.tsx @@ -11,6 +11,7 @@ export default function Choice({ label, initial = 0, multi = false, + isChecked = () => true, onSubmit, onCancel, }: { @@ -19,11 +20,13 @@ export default function Choice({ label: (item: T) => string; initial?: number; multi?: boolean; + /** Which items start ticked in a `multi` list. Defaults to all. */ + isChecked?: (item: T) => boolean; onSubmit: (chosen: T[]) => void; onCancel: () => void; }) { const [cursor, setCursor] = useState(initial); - const [checked, setChecked] = useState(() => items.map(() => true)); + const [checked, setChecked] = useState(() => items.map(isChecked)); useInput((input, key) => { if (key.upArrow || input === 'k') setCursor(c => Math.max(0, c - 1)); diff --git a/packages/cli/src/mcp/McpInstallPrompt.tsx b/packages/cli/src/mcp/McpInstallPrompt.tsx index 53cd23a0eb..4feb492460 100644 --- a/packages/cli/src/mcp/McpInstallPrompt.tsx +++ b/packages/cli/src/mcp/McpInstallPrompt.tsx @@ -10,6 +10,7 @@ import { type McpClient, type McpTeam, mcpUrl, + teamServers, verifyKey, } from '@/mcp/install'; import { isValidUrl } from '@/utils/url'; @@ -43,7 +44,7 @@ export default function McpInstallPrompt({ const [key, setKey] = useState(''); const [identity, setIdentity] = useState(null); const [teams, setTeams] = useState([]); - const [team, setTeam] = useState(null); + const [picked, setPicked] = useState([]); const [teamsFailed, setTeamsFailed] = useState(false); const [chosen, setChosen] = useState(clients); const [error, setError] = useState(null); @@ -56,11 +57,10 @@ export default function McpInstallPrompt({ useInput( (input, inkKey) => { if (inkKey.return || input.toLowerCase() === 'y') { - const server = { name, url: mcpUrl(appUrl), key, teamId: team?.id }; finish( chosen.map(client => { try { - client.install(server); + servers.forEach(server => client.install(server)); return { client }; } catch (e) { return { @@ -77,6 +77,9 @@ 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 = () => { @@ -164,15 +167,14 @@ export default function McpInstallPrompt({ {step === 'team' && ( (t.isCurrent ? `${t.name} (default)` : t.name)} - initial={Math.max( - 0, - teams.findIndex(t => t.isCurrent), - )} - onSubmit={([picked]) => { - setTeam(picked); + initial={teams.indexOf(defaultTeam)} + isChecked={t => t === defaultTeam} + onSubmit={chosenTeams => { + setPicked(chosenTeams); setStep(afterTeam); }} onCancel={() => finish(null)} @@ -203,10 +205,15 @@ export default function McpInstallPrompt({ . - - Add the ClickStack MCP server as "{name}" - {team && ` for team ${team.name}`} to: - + Add the ClickStack MCP server as: + {servers.map((s, i) => ( + + {' '} + - {s.name} + {picked[i] && ` (team ${picked[i].name})`} + + ))} + to: {chosen.map(c => ( - {c.label} ))} diff --git a/packages/cli/src/mcp/install.ts b/packages/cli/src/mcp/install.ts index 8f80db6a8a..50b78fda44 100644 --- a/packages/cli/src/mcp/install.ts +++ b/packages/cli/src/mcp/install.ts @@ -118,11 +118,39 @@ export async function listTeams( // An unknown tool comes back as an error result, not an HTTP error. if (!result || result.isError) return []; 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' && typeof t.name === 'string', + 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; } From e7de7b33cdb7c53de76d92b5495f3ad3ff4acd39 Mon Sep 17 00:00:00 2001 From: Jordan Simonovski Date: Mon, 16 Nov 2026 17:12:52 +1100 Subject: [PATCH 3/3] fix(cli): address review comments on hdx mcp install - A clickstack_list_teams tool error other than an unknown tool is now a failed listing, with the warning shown, not an empty team list. - The confirm step says when an entry name already exists in an agent's config, so a per-team name that clashes with another install is visible. - Results are reported per entry, so a failure partway through several team entries shows which ones were written. - The picker says to select at least one when Enter is pressed with nothing ticked, and is multi-select only. --- packages/cli/src/__tests__/mcpInstall.test.ts | 20 +++++++ packages/cli/src/cli.tsx | 6 +-- packages/cli/src/mcp/Choice.tsx | 26 ++++----- packages/cli/src/mcp/McpInstallPrompt.tsx | 53 +++++++++++------- packages/cli/src/mcp/install.ts | 54 +++++++++++++++++-- 5 files changed, 116 insertions(+), 43 deletions(-) diff --git a/packages/cli/src/__tests__/mcpInstall.test.ts b/packages/cli/src/__tests__/mcpInstall.test.ts index 9b07d4639c..abf6482554 100644 --- a/packages/cli/src/__tests__/mcpInstall.test.ts +++ b/packages/cli/src/__tests__/mcpInstall.test.ts @@ -189,6 +189,19 @@ describe('mcpClients', () => { ).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( @@ -280,6 +293,13 @@ describe('listTeams', () => { 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/); diff --git a/packages/cli/src/cli.tsx b/packages/cli/src/cli.tsx index 9827a15108..8b03de624d 100644 --- a/packages/cli/src/cli.tsx +++ b/packages/cli/src/cli.tsx @@ -608,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 index 9932b5c400..0012af7675 100644 --- a/packages/cli/src/mcp/Choice.tsx +++ b/packages/cli/src/mcp/Choice.tsx @@ -1,16 +1,12 @@ import React, { useState } from 'react'; import { Box, Text, useInput } from 'ink'; -/** - * Arrow-key list. Single choice submits the highlighted item on Enter; with - * `multi`, Space toggles items and Enter submits the checked ones. - */ +/** Arrow-key checklist. Space toggles items and Enter submits the ticked ones. */ export default function Choice({ title, items, label, initial = 0, - multi = false, isChecked = () => true, onSubmit, onCancel, @@ -19,28 +15,28 @@ export default function Choice({ items: T[]; label: (item: T) => string; initial?: number; - multi?: boolean; - /** Which items start ticked in a `multi` list. Defaults to all. */ + /** 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 (multi && input === ' ') { + if (input === ' ') { + setNoneTicked(false); setChecked(c => c.map((on, i) => (i === cursor ? !on : on))); } if (key.return) { - const chosen = multi - ? items.filter((_, i) => checked[i]) - : [items[cursor]]; + const chosen = items.filter((_, i) => checked[i]); if (chosen.length > 0) onSubmit(chosen); + else setNoneTicked(true); } if (key.escape) onCancel(); }); @@ -51,15 +47,13 @@ export default function Choice({ {items.map((item, i) => ( {i === cursor ? '▸ ' : ' '} - {multi && (checked[i] ? '[x] ' : '[ ] ')} + {checked[i] ? '[x] ' : '[ ] '} {label(item)} ))} - - {multi ? 'Space to toggle, Enter to continue' : 'Enter to select'}, Esc - to cancel - + {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 4feb492460..eb798fa250 100644 --- a/packages/cli/src/mcp/McpInstallPrompt.tsx +++ b/packages/cli/src/mcp/McpInstallPrompt.tsx @@ -17,6 +17,8 @@ import { isValidUrl } from '@/utils/url'; export interface InstallResult { client: McpClient; + /** Server entry name this result is for. */ + name: string; error?: string; } @@ -58,17 +60,20 @@ export default function McpInstallPrompt({ (input, inkKey) => { if (inkKey.return || input.toLowerCase() === 'y') { finish( - chosen.map(client => { - try { - servers.forEach(server => 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); @@ -167,7 +172,6 @@ export default function McpInstallPrompt({ {step === 'team' && ( (t.isCurrent ? `${t.name} (default)` : t.name)} @@ -183,7 +187,6 @@ export default function McpInstallPrompt({ {step === 'agents' && ( c.label} @@ -206,13 +209,23 @@ export default function McpInstallPrompt({ Add the ClickStack MCP server as: - {servers.map((s, i) => ( - - {' '} - - {s.name} - {picked[i] && ` (team ${picked[i].name})`} - - ))} + {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 50b78fda44..c3ba6538f9 100644 --- a/packages/cli/src/mcp/install.ts +++ b/packages/cli/src/mcp/install.ts @@ -33,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; } @@ -114,9 +116,22 @@ export async function listTeams( .split('\n') .find(line => line.startsWith('data:')) ?.slice(5) ?? text; - const { result } = JSON.parse(message); - // An unknown tool comes back as an error result, not an HTTP error. - if (!result || result.isError) return []; + 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( @@ -201,7 +216,7 @@ function tomlString(value: string): string { /** 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\\.${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 @@ -237,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) { @@ -261,6 +292,13 @@ export function mcpClients( label: 'Claude Code', location: 'Claude Code user config (~/.claude.json)', detect: () => onPath('claude'), + 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 @@ -291,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), }, { @@ -298,6 +342,7 @@ export function mcpClients( label: 'Cursor', location: cursorConfig, detect: () => fs.existsSync(path.dirname(cursorConfig)), + has: name => hasKey(readJsonObject(cursorConfig).mcpServers, name), install: server => upsertJsonServer(cursorConfig, 'mcpServers', server.name, { url: server.url, @@ -309,6 +354,7 @@ export function mcpClients( label: 'VS Code', location: vscodeConfig, detect: () => fs.existsSync(vscodeDir), + has: name => hasKey(readJsonObject(vscodeConfig).servers, name), install: server => upsertJsonServer(vscodeConfig, 'servers', server.name, { type: 'http',