Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/mcp-install-name.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@hyperdx/cli': patch
---

feat(cli): `hdx mcp install` can keep several ClickStack servers side by side

`--name <server-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.
3 changes: 3 additions & 0 deletions MCP.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ The key stays out of your shell history and agent chats.
npx @hyperdx/cli mcp install --app-url <your-hyperdx-url>
```

The entry is named `clickstack`, and running the command again replaces it. Pass
`--name <server-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,
Expand Down
12 changes: 12 additions & 0 deletions packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,13 +222,25 @@ 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 `<name>-<team>`. 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
```

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
Expand Down
193 changes: 187 additions & 6 deletions packages/cli/src/__tests__/mcpInstall.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand All @@ -40,38 +48,48 @@ 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/,
);
});

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');
Expand Down Expand Up @@ -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);
Expand All @@ -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(() => {
Expand Down
26 changes: 22 additions & 4 deletions packages/cli/src/cli.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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` -------------
Expand Down Expand Up @@ -554,7 +558,20 @@ mcp
'Add the ClickStack MCP server to Claude Code, Codex, Cursor, and VS Code',
)
.option('-a, --app-url <url>', 'ClickStack app URL')
.option(
'-n, --name <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',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — --name error message leaves out the leading-character rule, so _staging is rejected with a message that says underscores are allowed

Make the message match isValidServerName: e.g. '--name must start with a letter or number and contain only letters, numbers, hyphens, and underscores.'

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

),
);
process.exit(1);
}
if (!process.stdin.isTTY) {
_origError(
chalk.red(
Expand All @@ -577,6 +594,7 @@ mcp
const { waitUntilExit } = render(
<McpInstallPrompt
initialAppUrl={resolveServer(opts.appUrl)}
name={opts.name}
clients={clients}
onDone={r => {
results = r;
Expand All @@ -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`),
);
}
Expand Down
Loading
Loading