Skip to content
Merged
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
267 changes: 261 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,22 @@ import * as os from 'node:os';
import * as path from 'node:path';

import {
installAll,
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 +49,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 +135,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 +167,219 @@ 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('installAll', () => {
it('writes every server to every client and reports each entry', () => {
const calls: string[] = [];
const client = (id: string, failOn?: string) =>
({
id,
install: (s: { name: string; teamId?: string }) => {
if (s.name === failOn) throw new Error('disk full');
calls.push(`${id}:${s.name}:${s.teamId}`);
},
}) as unknown as ReturnType<typeof mcpClients>[number];
const servers = teamServers(server, [
{ id: 'a', name: 'Demo', isCurrent: true },
{ id: 'b', name: 'Prod', isCurrent: false },
]);
const results = installAll(
[client('cursor'), client('codex', 'clickstack-demo')],
servers,
);
expect(calls).toEqual([
'cursor:clickstack-demo:a',
'cursor:clickstack-prod:b',
'codex:clickstack-prod:b',
]);
expect(results.map(r => [r.client.id, r.name, r.error])).toEqual([
['cursor', 'clickstack-demo', undefined],
['cursor', 'clickstack-prod', undefined],
['codex', 'clickstack-demo', 'disk full'],
['codex', 'clickstack-prod', undefined],
]);
});
});

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 clickstack_list_teams 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 clickstack_list_teams not found',
'user not found',
),
);
await expect(listTeams('https://example.com', 'k')).rejects.toThrow(
/user not found/,
);
});

const rpcError = (message: string) =>
`event: message\ndata: ${JSON.stringify({
jsonrpc: '2.0',
id: 1,
error: { code: -32602, message },
})}\n\n`;

it('reads a JSON-RPC unknown-tool error as no team listing', async () => {
respondText(rpcError('Tool clickstack_list_teams not found'));
await expect(listTeams('https://example.com', 'k')).resolves.toEqual([]);
});

it('throws on any other JSON-RPC error', async () => {
respondText(rpcError('Invalid arguments'));
await expect(listTeams('https://example.com', 'k')).rejects.toThrow(
/Invalid arguments/,
);
});

it('skips other SSE messages and throws on a malformed team list', async () => {
const notice = `event: message\ndata: ${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/message' })}\n\n`;
const teams = [{ id: 'a', name: 'Demo', isCurrent: true }];
respondText(notice + sse(JSON.stringify({ teams })));
await expect(listTeams('https://example.com', 'k')).resolves.toEqual(teams);
respondText(sse('not json'));
await expect(listTeams('https://example.com', 'k')).rejects.toThrow(
/unexpected team list/,
);
});

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
Loading
Loading